diff options
author | Adam <Adam@anope.org> | 2012-11-22 00:50:33 -0500 |
---|---|---|
committer | Adam <Adam@anope.org> | 2012-11-22 00:50:33 -0500 |
commit | d33a0f75a5c0c584fbb7cc0076da36d494f39494 (patch) | |
tree | 7b2274cc833c793c0f5595660cbd4d715de52ffd | |
parent | 368d469631763e9c8bf399980d0ac7c5b5664d39 (diff) |
Pretty large coding style cleanup, in source doc
cleanup, and allow protocol mods to depend on each
other
303 files changed, 7854 insertions, 9362 deletions
diff --git a/include/access.h b/include/access.h index 558dbeb5c..918dd7be6 100644 --- a/include/access.h +++ b/include/access.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef ACCESS_H @@ -25,19 +24,25 @@ enum ACCESS_FOUNDER = 10001 }; +/* A privilege, probably configured using a privilege{} block. Most + * commands require specific privileges to be executed. The AccessProvider + * backing each ChanAccess determines whether that ChanAccess has a given + * privilege. + */ struct CoreExport Privilege { Anope::string name; Anope::string desc; + /* Rank relative to other privileges */ int rank; - Privilege(const Anope::string &n, const Anope::string &d, int r); + Privilege(const Anope::string &name, const Anope::string &desc, int rank); bool operator==(const Privilege &other) const; }; class CoreExport PrivilegeManager { - static std::vector<Privilege> privs; + static std::vector<Privilege> Privileges; public: static void AddPrivilege(Privilege p); static void RemovePrivilege(Privilege &p); @@ -46,25 +51,34 @@ class CoreExport PrivilegeManager static void ClearPrivileges(); }; - +/* A provider of access. Only used for creating ChanAccesses, as + * they contain pure virtual functions. + */ class CoreExport AccessProvider : public Service { public: - AccessProvider(Module *o, const Anope::string &n); + AccessProvider(Module *owner, const Anope::string &name); virtual ~AccessProvider(); + + /** Creates a new ChanAccess entry using this provider. + * @return The new entry + */ virtual ChanAccess *Create() = 0; private: - static std::list<AccessProvider *> providers; + static std::list<AccessProvider *> Providers; public: static const std::list<AccessProvider *>& GetProviders(); }; +/* Represents one entry of an access list on a channel. */ class CoreExport ChanAccess : public Serializable { public: + /* The provider that created this access entry */ AccessProvider *provider; - serialize_obj<ChannelInfo> ci; + /* Channel this access entry is on */ + Serialize::Reference<ChannelInfo> ci; Anope::string mask; Anope::string creator; time_t last_seen; @@ -73,29 +87,69 @@ class CoreExport ChanAccess : public Serializable ChanAccess(AccessProvider *p); virtual ~ChanAccess(); - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); + /** Check if this access entry matches the given user or account + * @param u The user + * @param nc The account + */ virtual bool Matches(const User *u, const NickCore *nc) const; + + /** Check if this access entry has the given privilege. + * @param name The privilege name + */ virtual bool HasPriv(const Anope::string &name) const = 0; - virtual Anope::string Serialize() const = 0; - virtual void Unserialize(const Anope::string &data) = 0; + /** Serialize the access given by this access entry into a human + * readable form. chanserv/access will return a number, chanserv/xop + * will be AOP, SOP, etc. + */ + virtual Anope::string AccessSerialize() const = 0; + + /** Unserialize this access entry from the given data. This data + * will be fetched from AccessSerialize. + */ + virtual void AccessUnserialize(const Anope::string &data) = 0; + + /* Comparison operators to other Access entries */ bool operator>(const ChanAccess &other) const; bool operator<(const ChanAccess &other) const; bool operator>=(const ChanAccess &other) const; bool operator<=(const ChanAccess &other) const; }; +/* A group of access entries. This is used commonly, for example with ChannelInfo::AccessFor, + * to show what access a user has on a channel because users can match multiple access entries. + */ class CoreExport AccessGroup : public std::vector<ChanAccess *> { public: + /* Channel these access entries are on */ const ChannelInfo *ci; + /* Account these entries affect, if any */ const NickCore *nc; - bool SuperAdmin, Founder; + /* super_admin always gets all privs. founder is a special case where ci->founder == nc */ + bool super_admin, founder; + AccessGroup(); + + /** Check if this access group has a certain privilege. Eg, it + * will check every ChanAccess entry of this group for any that + * has the given privilege. + * @param priv The privilege + * @return true if any entry has the given privilege + */ bool HasPriv(const Anope::string &priv) const; + + /** Get the "highest" access entry from this group of entries. + * The highest entry is determined by the entry that has the privilege + * with the highest rank (see Privilege::rank). + * @return The "highest" entry + */ const ChanAccess *Highest() const; + + /* Comparison operators to other AccessGroups */ bool operator>(const AccessGroup &other) const; bool operator<(const AccessGroup &other) const; bool operator>=(const AccessGroup &other) const; diff --git a/include/account.h b/include/account.h index 8ed1f06a4..a45bf8c90 100644 --- a/include/account.h +++ b/include/account.h @@ -7,8 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. - * - * + * */ #ifndef ACCOUNT_H @@ -23,10 +22,8 @@ typedef Anope::hash_map<NickAlias *> nickalias_map; typedef Anope::hash_map<NickCore *> nickcore_map; -extern CoreExport serialize_checker<nickalias_map> NickAliasList; -extern CoreExport serialize_checker<nickcore_map> NickCoreList; - -/* NickServ nickname structures. */ +extern CoreExport Serialize::Checker<nickalias_map> NickAliasList; +extern CoreExport Serialize::Checker<nickcore_map> NickCoreList; /** Flags set on NickAliases */ @@ -50,10 +47,6 @@ enum NickNameFlag NS_END }; -const Anope::string NickNameFlagStrings[] = { - "BEGIN", "NO_EXPIRE", "HELD", "COLLIDED", "" -}; - /** Flags set on NickCores */ enum NickCoreFlag @@ -101,40 +94,36 @@ enum NickCoreFlag NI_END }; -const Anope::string NickCoreFlagStrings[] = { - "BEGIN", "KILLPROTECT", "SECURE", "MSG", "MEMO_HARDMAX", "MEMO_SIGNON", "MEMO_RECEIVE", - "PRIVATE", "HIDE_EMAIL", "HIDE_MASK", "HIDE_QUIT", "KILL_QUICK", "KILL_IMMED", - "MEMO_MAIL", "HIDE_STATUS", "SUSPENDED", "AUTOOP", "UNCONFIRMED", "STATS", "" -}; - -/* It matters that Base is here before Extensible (it is inherited by Serializable) */ -class CoreExport NickAlias : public Serializable, public Extensible, public Flags<NickNameFlag, NS_END> +/* A registered nickname. + * It matters that Base is here before Extensible (it is inherited by Serializable) + */ +class CoreExport NickAlias : public Serializable, public Extensible, public Flags<NickNameFlag> { Anope::string vhost_ident, vhost_host, vhost_creator; time_t vhost_created; public: - /** Default constructor + Anope::string nick; + Anope::string last_quit; + Anope::string last_realname; + /* Last usermask this nick was seen on, eg user@host */ + Anope::string last_usermask; + /* Last uncloaked usermask, requires nickserv/auspex to see */ + Anope::string last_realhost; + time_t time_registered; + time_t last_seen; + /* Account this nick is tied to. Multiple nicks can be tied to a single account. */ + Serialize::Reference<NickCore> nc; + + /** Constructor * @param nickname The nick * @param nickcore The nickcore for this nick */ NickAlias(const Anope::string &nickname, NickCore *nickcore); - - /** Default destructor - */ ~NickAlias(); - Anope::string nick; /* Nickname */ - Anope::string last_quit; /* Last quit message */ - Anope::string last_realname; /* Last realname */ - Anope::string last_usermask; /* Last usermask */ - Anope::string last_realhost; /* Last uncloaked usermask, requires nickserv/auspex to see */ - time_t time_registered; /* When the nick was registered */ - time_t last_seen; /* When it was seen online for the last time */ - serialize_obj<NickCore> nc; /* I'm an alias of this */ - - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); /** Release a nick * See the comment in users.cpp @@ -184,41 +173,67 @@ class CoreExport NickAlias : public Serializable, public Extensible, public Flag * @return the time it was created */ time_t GetVhostCreated() const; + + /** Finds a registered nick + * @param nick The nick to lookup + * @return the nick, if found + */ + static NickAlias *Find(const Anope::string &nick); }; -/* It matters that Base is here before Extensible (it is inherited by Serializable) */ -class CoreExport NickCore : public Serializable, public Extensible, public Flags<NickCoreFlag, NI_END> +/* A registered account. Each account must have a NickAlias with the same nick as the + * account's display. + * It matters that Base is here before Extensible (it is inherited by Serializable) + */ +class CoreExport NickCore : public Serializable, public Extensible, public Flags<NickCoreFlag> { public: - /** Default constructor - * @param display The display nick - */ - NickCore(const Anope::string &nickdisplay); + /* Name of the account. Find(display)->nc == this. */ + Anope::string display; + /* User password in form of hashm:data */ + Anope::string pass; + Anope::string email; + /* Greet associated with the account, sometimes sent when the user joins a channel */ + Anope::string greet; + /* Locale name of the language of the user. Empty means default language */ + Anope::string language; + /* Access list, contains user@host masks of users who get certain privileges based + * on if NI_SECURE is set and what (if any) kill protection is enabled. */ + std::vector<Anope::string> access; + /* SSL certificate list. Users who have a matching certificate may be automatically logged in */ + std::vector<Anope::string> cert; + MemoInfo memos; - /** Default destructor + /* Nicknames registered that are grouped to this account. + * for n in aliases, n->nc == this. */ - ~NickCore(); - - std::list<User *> Users; - - Anope::string display; /* How the nick is displayed */ - Anope::string pass; /* Password of the nicks */ - Anope::string email; /* E-mail associated to the nick */ - Anope::string greet; /* Greet associated to the nick */ - Anope::string language; /* Language name */ - std::vector<Anope::string> access; /* Access list, vector of strings */ - std::vector<Anope::string> cert; /* ssl certificate list, vector of strings */ - MemoInfo memos; + std::list<Serialize::Reference<NickAlias> > aliases; + /* Set if this user is a services operattor. o->ot must exist. */ Oper *o; /* Unsaved data */ - uint16_t channelcount; /* Number of channels currently registered */ - time_t lastmail; /* Last time this nick record got a mail */ - std::list<serialize_obj<NickAlias> > aliases; /* List of aliases */ - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + /* Number of channels registered by this account */ + uint16_t channelcount; + /* Last time an email was sent to this user */ + time_t lastmail; + /* Users online now logged into this account */ + std::list<User *> users; + + /** Constructor + * @param display The display nick + */ + NickCore(const Anope::string &nickdisplay); + ~NickCore(); + + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); + + /** Changes the display for this account + * @param na The new display, must be grouped to this account. + */ + void SetDisplay(const NickAlias *na); /** Checks whether this account is a services oper or not. * @return True if this account is a services oper, false otherwise. @@ -265,6 +280,14 @@ class CoreExport NickCore : public Serializable, public Extensible, public Flags */ void ClearAccess(); + /** Is the given user on this accounts access list? + * + * @param u The user + * + * @return true if the user is on the access list + */ + bool IsOnAccess(const User *u) const; + /** Add an entry to the nick's certificate list * * @param entry The fingerprint to add to the cert list @@ -304,10 +327,21 @@ class CoreExport NickCore : public Serializable, public Extensible, public Flags * Deletes all the memory allocated in the certificate list vector and then clears the vector. */ void ClearCert(); + + /** Finds an account + * @param nick The account name to find + * @return The account, if it exists + */ + static NickCore* Find(const Anope::string &nick); }; +/* A request to check if an account/password is valid. These can exist for + * extended periods of time due to some authentication modules take. + */ class CoreExport IdentifyRequest { + /* Owner of this request, used to cleanup requests if a module is unloaded + * while a reqyest us pending */ Module *owner; Anope::string account; Anope::string password; @@ -316,35 +350,47 @@ class CoreExport IdentifyRequest bool dispatched; bool success; - static std::set<IdentifyRequest *> requests; + static std::set<IdentifyRequest *> Requests; protected: IdentifyRequest(Module *o, const Anope::string &acc, const Anope::string &pass); virtual ~IdentifyRequest(); public: + /* One of these is called when the request goes through */ virtual void OnSuccess() = 0; virtual void OnFail() = 0; const Anope::string &GetAccount() const { return account; } const Anope::string &GetPassword() const { return password; } - /* Hold this request. Once held it must be Release()d later on */ + /* Holds this request. When a request is held it must be Released later + * for the request to complete. Multiple modules may hold a request at any time, + * but the request is not complete until every module has released it. If you do not + * require holding this (eg, your password check is done in this thread and immediately) + * then you don't need to hold the request before Successing it. + * @param m The module holding this request + */ void Hold(Module *m); + + /** Releases a held request + * @param m The module releaseing the hold + */ void Release(Module *m); + /** Called by modules when this IdentifyRequest has successeded successfully. + * If this request is behind held it must still be Released after calling this. + * @param m The module confirming authentication + */ void Success(Module *m); + /** Used to either finalize this request or marks + * it as dispatched and begins waiting for the module(s) + * that have holds to finish. + */ void Dispatch(); static void ModuleUnload(Module *m); }; -extern CoreExport void change_core_display(NickCore *nc); -extern CoreExport void change_core_display(NickCore *nc, const Anope::string &newdisplay); - -extern CoreExport NickAlias *findnick(const Anope::string &nick); -extern CoreExport NickCore *findcore(const Anope::string &nick); -extern CoreExport bool is_on_access(const User *u, const NickCore *nc); - #endif // ACCOUNT_H diff --git a/include/anope.h b/include/anope.h index b6033b15c..2dda6cf76 100644 --- a/include/anope.h +++ b/include/anope.h @@ -1,4 +1,5 @@ /* + * * (C) 2003-2012 Anope Team * Contact us at team@anope.org * @@ -6,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef ANOPE_H @@ -304,11 +306,52 @@ namespace Anope static const char *const compiled = __TIME__ " " __DATE__; + /** The time Anope started. + */ + extern time_t StartTime; + + /** The value to return from main() + */ + extern int ReturnValue; + extern bool Quitting; + extern bool Restarting; + extern Anope::string QuitReason; + /** The current system time, which is pretty close to being accurate. * Use this unless you need very specific time checks */ extern CoreExport time_t CurTime; + /** The debug level we are running at. + */ + extern int Debug; + + /** Other comand line options. + */ + extern bool ReadOnly, NoFork, NoThird, NoExpire, ProtocolDebug; + + /** The root of the services installation. Usually ~/services + */ + extern Anope::string ServicesDir; + + /** Services binary name (eg services) + */ + extern Anope::string ServicesBin; + + /** Various directory paths. These can be set at runtime by command line args + */ + extern Anope::string ConfigDir; + extern Anope::string DataDir; + extern Anope::string ModuleDir; + extern Anope::string LocaleDir; + extern Anope::string LogDir; + + /** The uplink we are currently connected to + */ + extern int CurrentUplink; + + /** Various methods to determine the Anope version running + */ extern CoreExport string Version(); extern CoreExport string VersionShort(); extern CoreExport string VersionBuildString(); @@ -316,6 +359,29 @@ namespace Anope extern CoreExport int VersionMinor(); extern CoreExport int VersionPatch(); + /** Determines if we are still attached to the terminal, and can print + * messages to the user via stderr/stdout. + * @return true if still attached + */ + extern bool AtTerm(); + + /** Used to "fork" the process and go into the background during initial startup + * while we are AtTerm(). The actual fork is not done here, but earlier, and this + * simply notifys the parent via kill() to exit(). + */ + extern void Fork(); + + /** One of the first functions called, does general initialization such as reading + * command line args, loading the configuration, doing the initial fork() if necessary, + * initializating language support, loading modules, and loading databases. + * @throws CoreException if something bad went wrong + */ + extern void Init(int ac, char **av); + + /** Calls the save database event + */ + extern void SaveDatabases(); + /** Check whether two strings match. * @param str The string to check against the pattern (e.g. foobar) * @param mask The pattern to check (e.g. foo*bar) @@ -350,6 +416,20 @@ namespace Anope */ extern CoreExport void B64Decode(const string &src, string &target); + /** Encrypts what is in 'src' to 'dest' + * @param src The source string to encrypt + * @param dest The destination where the encrypted string is placed + */ + extern void Encrypt(const Anope::string &src, Anope::string &dest); + + /** Decrypts what is in 'src' to 'dest'. + * @param src The source string to decrypt + * @param dest The destination where the decrypted string is placed + * @return true if decryption was successful. This is usually not the case + * as most encryption methods we use are one way. + */ + extern bool Decrypt(const Anope::string &src, Anope::string &dest); + /** Returns a sequence of data formatted as the format argument specifies. ** After the format parameter, the function expects at least as many ** additional arguments as specified in format. @@ -368,6 +448,48 @@ namespace Anope * @return An error message */ extern CoreExport const string LastError(); + + /** Determines if a path is a file + */ + extern bool IsFile(const Anope::string &file); + + /** Converts a string into seconds + * @param s The string, eg 3d + * @return The time represented by the string, eg 259,200 + */ + extern time_t DoTime(const Anope::string &s); + + /** Retrieves a human readable string representing the time in seconds + * @param seconds The time on seconds, eg 60 + * @param nc The account to use langauge settings for to translate this string, if applicable + * @return A human readable string, eg "1 minute" + */ + extern Anope::string Duration(time_t seconds, const NickCore *nc = NULL); + + /** Generates a human readable string of type "expires in ..." + * @param expires time in seconds + * @param nc The account to use langauge settings for to translate this string, if applicable + * @return A human readable string, eg "expires in 5 days" + */ + extern Anope::string Expires(time_t seconds, const NickCore *nc = NULL); + + /** Converts a time in seconds (epoch) to a human readable format. + * @param t The time + * @param nc The account to use langauge settings for to translate this string, if applicable + * @param short_output If true, the output is just a date (eg, "Apr 12 20:18:22 2009 MSD"), else it includes the date and how long ago/from now that date is, (eg "Apr 12 20:18:22 2009 MSD (1313 days, 9 hours, 32 minutes ago)" + */ + extern Anope::string strftime(time_t t, const NickCore *nc = NULL, bool short_output = false); + + /** Normalize buffer, stripping control characters and colors + * @param A string to be parsed for control and color codes + * @return A string stripped of control and color codes + */ + extern Anope::string NormalizeBuffer(const Anope::string &); + + /** Main processing routine. Parses the message and takes the appropriate action. + * @param Raw message from the uplink + */ + extern void Process(const Anope::string &); } /** sepstream allows for splitting token seperated lists. @@ -394,23 +516,52 @@ class CoreExport sepstream /** Create a sepstream and fill it with the provided data */ sepstream(const Anope::string &source, char seperator); - virtual ~sepstream() { } /** Fetch the next token from the stream * @param token The next token from the stream is placed here * @return True if tokens still remain, false if there are none left */ - virtual bool GetToken(Anope::string &token); + bool GetToken(Anope::string &token); + + /** Gets token number 'num' from the stream + * @param token The token is placed here + * @param num The token number to featch + * @return True if the token was able to be detched + */ + bool GetToken(Anope::string &token, int num); + + /** Gets every token from this stream + * @param token Tokens are pushed back here + */ + template<typename T> void GetTokens(T& token) + { + token.clear(); + Anope::string t; + while (this->GetToken(t)) + token.push_back(t); + } + + /** Gets token number 'num' from the stream and all remaining tokens. + * @param token The token is placed here + * @param num The token number to featch + * @return True if the token was able to be detched + */ + bool GetTokenRemainder(Anope::string &token, int num); + + /** Determines the number of tokens in this stream. + * @return The number of tokens in this stream + */ + int NumTokens(); /** Fetch the entire remaining stream, without tokenizing * @return The remaining part of the stream */ - virtual const Anope::string GetRemaining(); + const Anope::string GetRemaining(); /** Returns true if the end of the stream has been reached * @return True if the end of the stream has been reached, otherwise false */ - virtual bool StreamEnd(); + bool StreamEnd(); }; /** A derived form of sepstream, which seperates on commas @@ -478,14 +629,6 @@ class CoreException : public std::exception } }; -class FatalException : public CoreException -{ - public: - FatalException(const Anope::string &reason = "") : CoreException(reason) { } - - virtual ~FatalException() throw() { } -}; - class ModuleException : public CoreException { public: @@ -600,39 +743,43 @@ template<typename T, typename O> inline T anope_dynamic_reinterpret_cast(O ptr) /** Class with the ability to keep flags on items, they should extend from this * where T is an enum. */ -template<typename T, size_t Size = 32> class Flags +template<typename T> class Flags { - protected: - std::bitset<Size> Flag_Values; - const Anope::string *Flag_Strings; + std::vector<bool> flags_values; + static const Anope::string *flags_strings; public: - Flags() : Flag_Strings(NULL) { } - Flags(const Anope::string *flag_strings) : Flag_Strings(flag_strings) { } - /** Add a flag to this item - * @param Value The flag + * @param value The flag */ - void SetFlag(T Value) + void SetFlag(T value) { - Flag_Values[Value] = true; + if (value < 0) + return; + + if (static_cast<unsigned>(value) >= flags_values.size()) + flags_values.resize(value + 1); + flags_values[value] = true; } /** Remove a flag from this item - * @param Value The flag + * @param value The flag */ - void UnsetFlag(T Value) + void UnsetFlag(T value) { - Flag_Values[Value] = false; + if (value >= 0 && static_cast<unsigned>(value) < flags_values.size()) + flags_values[value] = false; } /** Check if this item has a flag - * @param Value The flag + * @param value The flag * @return true or false */ - bool HasFlag(T Value) const + bool HasFlag(T value) const { - return Flag_Values.test(Value); + if (value >= 0 && static_cast<unsigned>(value) < flags_values.size()) + return flags_values[value]; + return false; } /** Check how many flags are set @@ -640,14 +787,23 @@ template<typename T, size_t Size = 32> class Flags */ size_t FlagCount() const { - return Flag_Values.count(); + size_t c = 0; + for (unsigned i = 0; i < flags_values.size(); ++i) + if (flags_values[i]) + ++c; + return c; } /** Unset all of the flags */ void ClearFlags() { - Flag_Values.reset(); + flags_values.clear(); + } + + static const Anope::string* GetFlagStrings() + { + return flags_strings; } Anope::string ToString() const @@ -675,9 +831,9 @@ template<typename T, size_t Size = 32> class Flags std::vector<Anope::string> ToVector() const { std::vector<Anope::string> ret; - for (unsigned i = 0; this->Flag_Strings && !this->Flag_Strings[i].empty(); ++i) + for (unsigned i = 0; this->flags_strings && !this->flags_strings[i].empty(); ++i) if (this->HasFlag(static_cast<T>(i))) - ret.push_back(this->Flag_Strings[i]); + ret.push_back(this->flags_strings[i]); return ret; } @@ -685,9 +841,9 @@ template<typename T, size_t Size = 32> class Flags { this->ClearFlags(); - for (unsigned i = 0; this->Flag_Strings && !this->Flag_Strings[i].empty(); ++i) + for (unsigned i = 0; this->flags_strings && !this->flags_strings[i].empty(); ++i) for (unsigned j = 0; j < strings.size(); ++j) - if (this->Flag_Strings[i] == strings[j]) + if (this->flags_strings[i] == strings[j]) this->SetFlag(static_cast<T>(i)); } }; diff --git a/include/base.h b/include/base.h index c09b97400..178bb1937 100644 --- a/include/base.h +++ b/include/base.h @@ -4,6 +4,7 @@ * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #ifndef BASE_H @@ -16,48 +17,57 @@ class CoreExport Base { /* References to this base class */ - std::set<dynamic_reference_base *> References; + std::set<ReferenceBase *> references; public: Base(); virtual ~Base(); - void AddReference(dynamic_reference_base *r); - void DelReference(dynamic_reference_base *r); + + /** Adds a reference to this object. Eg, when a Reference + * is created referring to this object this is called. It is used to + * cleanup references when this object is destructed. + */ + void AddReference(ReferenceBase *r); + + void DelReference(ReferenceBase *r); }; -class dynamic_reference_base +class ReferenceBase { protected: bool invalid; public: - dynamic_reference_base() : invalid(false) { } - dynamic_reference_base(const dynamic_reference_base &other) : invalid(other.invalid) { } - virtual ~dynamic_reference_base() { } + ReferenceBase() : invalid(false) { } + ReferenceBase(const ReferenceBase &other) : invalid(other.invalid) { } + virtual ~ReferenceBase() { } inline void Invalidate() { this->invalid = true; } }; +/** Used to hold pointers to objects that may be deleted. A Reference will + * no longer be valid once the object it refers is destructed. + */ template<typename T> -class dynamic_reference : public dynamic_reference_base +class Reference : public ReferenceBase { protected: T *ref; public: - dynamic_reference() : ref(NULL) + Reference() : ref(NULL) { } - dynamic_reference(T *obj) : ref(obj) + Reference(T *obj) : ref(obj) { if (ref) ref->AddReference(this); } - dynamic_reference(const dynamic_reference<T> &other) : dynamic_reference_base(other), ref(other.ref) + Reference(const Reference<T> &other) : ReferenceBase(other), ref(other.ref) { if (operator bool()) ref->AddReference(this); } - virtual ~dynamic_reference() + virtual ~Reference() { if (operator bool()) ref->DelReference(this); @@ -105,12 +115,12 @@ class dynamic_reference : public dynamic_reference_base this->ref->AddReference(this); } - inline bool operator<(const dynamic_reference<T> &other) const + inline bool operator<(const Reference<T> &other) const { return this < &other; } - inline bool operator==(const dynamic_reference<T> &other) + inline bool operator==(const Reference<T> &other) { if (!this->invalid) return this->ref == other; diff --git a/include/bots.h b/include/bots.h index 888e8d217..3d44d08dd 100644 --- a/include/bots.h +++ b/include/bots.h @@ -1,8 +1,10 @@ /* + * * Copyright (C) 2008-2011 Robin Burchell <w00t@inspircd.org> * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #ifndef BOTS_H @@ -16,7 +18,7 @@ typedef Anope::map<BotInfo *> botinfo_map; -extern CoreExport serialize_checker<botinfo_map> BotListByNick, BotListByUID; +extern CoreExport Serialize::Checker<botinfo_map> BotListByNick, BotListByUID; /** Flags settable on a bot */ @@ -24,8 +26,6 @@ enum BotFlag { BI_BEGIN, - /* This bot is a core bot. NickServ, ChanServ, etc */ - BI_CORE, /* This bot can only be assigned by IRCops */ BI_PRIVATE, /* This bot is defined in the config */ @@ -34,17 +34,21 @@ enum BotFlag BI_END }; -static const Anope::string BotFlagString[] = { "BEGIN", "CORE", "PRIVATE", "CONF", "" }; - -class CoreExport BotInfo : public User, public Flags<BotFlag, BI_END>, public Serializable +/* A service bot (NickServ, ChanServ, a BotServ bot, etc). */ +class CoreExport BotInfo : public User, public Flags<BotFlag>, public Serializable { public: - time_t created; /* Birth date ;) */ - time_t lastmsg; /* Last time we said something */ - CommandInfo::map commands; /* Commands, actual name to service name */ - Anope::string botmodes; /* Modes the bot should have as configured in service:modes */ - std::vector<Anope::string> botchannels; /* Channels the bot should be in as configured in service:channels */ - bool introduced; /* Whether or not this bot is introduced */ + time_t created; + /* Last time this bot said something (via privmsg) */ + time_t lastmsg; + /* Map of actual command names -> service name/permission required */ + CommandInfo::map commands; + /* Modes the bot should have as configured in service:modes */ + Anope::string botmodes; + /* Channels the bot should be in as configured in service:channels */ + std::vector<Anope::string> botchannels; + /* Whether or not this bot is introduced to the network */ + bool introduced; /** Create a new bot. * @param nick The nickname to assign to the bot. @@ -59,8 +63,8 @@ class CoreExport BotInfo : public User, public Flags<BotFlag, BI_END>, public Se */ virtual ~BotInfo(); - Serialize::Data serialize() const; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); void GenerateUID(); @@ -126,11 +130,13 @@ class CoreExport BotInfo : public User, public Flags<BotFlag, BI_END>, public Se * @return A struct containing service name and permission */ CommandInfo *GetCommand(const Anope::string &cname); -}; -extern CoreExport BotInfo *findbot(const Anope::string &nick); - -extern CoreExport void bot_raw_ban(User *requester, ChannelInfo *ci, const Anope::string &nick, const Anope::string &reason); -extern CoreExport void bot_raw_kick(User *requester, ChannelInfo *ci, const Anope::string &nick, const Anope::string &reason); + /** Find a bot by nick + * @param nick The nick + * @param nick_only True to only look by nick, and not by UID + * @return The bot, if it exists + */ + static BotInfo* Find(const Anope::string &nick, bool nick_only = false); +}; #endif // BOTS_H diff --git a/include/botserv.h b/include/botserv.h deleted file mode 100644 index e5ef2c8ba..000000000 --- a/include/botserv.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - * - * - */ - -#ifndef BOTSERV_H -#define BOTSERV_H - -#include "anope.h" - -/* BotServ SET flags */ -enum BotServFlag -{ - BS_BEGIN, - /* BotServ won't kick ops */ - BS_DONTKICKOPS, - /* BotServ won't kick voices */ - BS_DONTKICKVOICES, - /* BotServ bot accepts fantasy commands */ - BS_FANTASY, - /* BotServ should show greets */ - BS_GREET, - /* BotServ bots are not allowed to be in this channel */ - BS_NOBOT, - /* BotServ kicks for bolds */ - BS_KICK_BOLDS, - /* BotServ kicks for colors */ - BS_KICK_COLORS, - /* BOtServ kicks for reverses */ - BS_KICK_REVERSES, - /* BotServ kicks for underlines */ - BS_KICK_UNDERLINES, - /* BotServ kicks for badwords */ - BS_KICK_BADWORDS, - /* BotServ kicks for caps */ - BS_KICK_CAPS, - /* BotServ kicks for flood */ - BS_KICK_FLOOD, - /* BotServ kicks for repeating */ - BS_KICK_REPEAT, - /* BotServ kicks for italics */ - BS_KICK_ITALICS, - /* BotServ kicks for amsgs */ - BS_KICK_AMSGS, - BS_END -}; - -const Anope::string BotServFlagStrings[] = { - "BEGIN", "DONTKICKOPS", "DONTKICKVOICES", "FANTASY", "GREET", "NOBOT", - "KICK_BOLDs", "KICK_COLORS", "KICK_REVERSES", "KICK_UNDERLINES", "KICK_BADWORDS", "KICK_CAPS", - "KICK_FLOOD", "KICK_REPEAT", "KICK_ITALICS", "KICK_AMSGS", "MSG_PRIVMSG", "MSG_NOTICE", - "MSG_NOTICEOPS", "" -}; - -/* Indices for TTB (Times To Ban) */ -enum -{ - TTB_BOLDS, - TTB_COLORS, - TTB_REVERSES, - TTB_UNDERLINES, - TTB_BADWORDS, - TTB_CAPS, - TTB_FLOOD, - TTB_REPEAT, - TTB_ITALICS, - TTB_AMSGS, - TTB_SIZE -}; - -#endif // BOTSERV_H diff --git a/include/channels.h b/include/channels.h index 99ddf06b9..5cbea5ecc 100644 --- a/include/channels.h +++ b/include/channels.h @@ -4,6 +4,7 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ #ifndef CHANNELS_H @@ -18,10 +19,12 @@ typedef Anope::hash_map<Channel *> channel_map; extern CoreExport channel_map ChannelList; +/* A user container, there is one of these per user per channel. */ struct UserContainer : public Extensible { User *user; - ChannelStatus *Status; + /* Status the user has in the channel */ + ChannelStatus *status; UserContainer(User *u) : user(u) { } virtual ~UserContainer() { } @@ -39,9 +42,7 @@ enum ChannelFlag CH_SYNCING }; -const Anope::string ChannelFlagString[] = { "CH_INABIT", "CH_PERSIST", "CH_SYNCING", "" }; - -class CoreExport Channel : public virtual Base, public Extensible, public Flags<ChannelFlag, 3> +class CoreExport Channel : public Base, public Extensible, public Flags<ChannelFlag> { public: typedef std::multimap<ChannelModeName, Anope::string> ModeList; @@ -51,27 +52,27 @@ class CoreExport Channel : public virtual Base, public Extensible, public Flags< ModeList modes; public: - /** Default constructor - * @param name The channel name - * @param ts The time the channel was created - */ - Channel(const Anope::string &nname, time_t ts = Anope::CurTime); - - /** Default destructor - */ - ~Channel(); - - Anope::string name; /* Channel name */ - serialize_obj<ChannelInfo> ci; /* Corresponding ChannelInfo */ - time_t creation_time; /* When channel was created */ - - /* List of users in the channel */ + /* Channel name */ + Anope::string name; + /* Set if this channel is registered. ci->c == this. Contains information relevant to the registered channel */ + Serialize::Reference<ChannelInfo> ci; + /* When the channel was created */ + time_t creation_time; + + /* Users in the channel */ CUserList users; - Anope::string topic; /* Current topic of the channel */ - Anope::string topic_setter; /* Who set the topic */ - time_t topic_ts; /* The timestamp associated with the topic. Not necessarually anywhere close to Anope::CurTime */ - time_t topic_time; /* The actual time the topic was set, probably close to Anope::CurTime */ + /* Current topic of the channel */ + Anope::string topic; + /* Who set the topic */ + Anope::string topic_setter; + /* The timestamp associated with the topic. Not necessarually anywhere close to Anope::CurTime. + * This is the time the topic was *originally set*. When we restore the topic we want to change the TS back + * to this, but we can only do this on certain IRCds. + */ + time_t topic_ts; + /* The actual time the topic was set, probably close to Anope::CurTime */ + time_t topic_time; time_t server_modetime; /* Time of last server MODE */ time_t chanserv_modetime; /* Time of last check_modes() */ @@ -79,6 +80,16 @@ class CoreExport Channel : public virtual Base, public Extensible, public Flags< int16_t chanserv_modecount; /* Number of check_mode()'s this sec */ int16_t bouncy_modes; /* Did we fail to set modes here? */ + /** Constructor + * @param name The channel name + * @param ts The time the channel was created + */ + Channel(const Anope::string &nname, time_t ts = Anope::CurTime); + + /** Destructor + */ + ~Channel(); + /** Call if we need to unset all modes and clear all user status (internally). * Only useful if we get a SJOIN with a TS older than what we have here */ @@ -94,8 +105,9 @@ class CoreExport Channel : public virtual Base, public Extensible, public Flags< /** Join a user internally to the channel * @param u The user + * @return The UserContainer for the user */ - void JoinUser(User *u); + UserContainer* JoinUser(User *u); /** Remove a user internally from the channel * @param u The user @@ -118,94 +130,101 @@ class CoreExport Channel : public virtual Base, public Extensible, public Flags< /** Check if a user has a status on a channel * Use the overloaded function for ChannelModeStatus* to check for no status * @param u The user - * @param Name The Mode name, eg CMODE_OP, CMODE_VOICE + * @param name The mode name, eg CMODE_OP, CMODE_VOICE * @return true or false */ - bool HasUserStatus(const User *u, ChannelModeName Name) const; + bool HasUserStatus(const User *u, ChannelModeName name) const; /** See if a channel has a mode - * @param Name The mode name + * @param name The mode name * @return The number of modes set * @param param The optional mode param */ - size_t HasMode(ChannelModeName Name, const Anope::string ¶m = ""); + size_t HasMode(ChannelModeName name, const Anope::string ¶m = ""); /** Get a list of modes on a channel - * @param Name A mode name to get the list of + * @param name A mode name to get the list of * @return a pair of iterators for the beginning and end of the list */ - std::pair<ModeList::iterator, ModeList::iterator> GetModeList(ChannelModeName Name); + std::pair<ModeList::iterator, ModeList::iterator> GetModeList(ChannelModeName name); /** Set a mode internally on a channel, this is not sent out to the IRCd * @param setter The setter * @param cm The mode * @param param The param - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void SetModeInternal(MessageSource &source, ChannelMode *cm, const Anope::string ¶m = "", bool EnforceMLock = true); + void SetModeInternal(MessageSource &source, ChannelMode *cm, const Anope::string ¶m = "", bool enforce_mlock = true); /** Remove a mode internally on a channel, this is not sent out to the IRCd * @param setter The Setter * @param cm The mode * @param param The param - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void RemoveModeInternal(MessageSource &source, ChannelMode *cm, const Anope::string ¶m = "", bool EnforceMLock = true); + void RemoveModeInternal(MessageSource &source, ChannelMode *cm, const Anope::string ¶m = "", bool enforce_mlock = true); /** Set a mode on a channel * @param bi The client setting the modes * @param cm The mode * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void SetMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m = "", bool EnforceMLock = true); + void SetMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m = "", bool enforce_mlock = true); /** * Set a mode on a channel * @param bi The client setting the modes - * @param Name The mode name + * @param name The mode name * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void SetMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m = "", bool EnforceMLock = true); + void SetMode(BotInfo *bi, ChannelModeName name, const Anope::string ¶m = "", bool enforce_mlock = true); /** Remove a mode from a channel * @param bi The client setting the modes * @param cm The mode * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void RemoveMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m = "", bool EnforceMLock = true); + void RemoveMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m = "", bool enforce_mlock = true); /** * Remove a mode from a channel * @param bi The client setting the modes - * @param Name The mode name + * @param name The mode name * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock + * @param enforce_mlock true if mlocks should be enforced, false to override mlock */ - void RemoveMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m = "", bool EnforceMLock = true); + void RemoveMode(BotInfo *bi, ChannelModeName name, const Anope::string ¶m = "", bool enforce_mlock = true); - /** Get a param from the channel - * @param Name The mode - * @param Target a string to put the param into - * @return true on success + /** Get a modes parameter for the channel + * @param name The mode + * @param target a string to put the param into + * @return true if the parameter was fetched, false if on error (mode not set) etc. */ - bool GetParam(ChannelModeName Name, Anope::string &Target) const; + bool GetParam(ChannelModeName name, Anope::string &target) const; /** Set a string of modes on the channel * @param bi The client setting the modes - * @param EnforceMLock Should mlock be enforced on this mode change + * @param enforce_mlock Should mlock be enforced on this mode change * @param cmodes The modes to set */ - void SetModes(BotInfo *bi, bool EnforceMLock, const char *cmodes, ...); + void SetModes(BotInfo *bi, bool enforce_mlock, const char *cmodes, ...); /** Set a string of modes internally on a channel * @param source The setter * @param mode the modes - * @param EnforceMLock true to enforce mlock + * @param enforce_mlock true to enforce mlock + */ + void SetModesInternal(MessageSource &source, const Anope::string &mode, time_t ts = 0, bool enforce_mlock = true); + + /** Does the given user match the given list? (CMODE_BAN, CMODE_EXCEPT, etc, a list mode) + * @param u The user + * @param list The mode of the list to check (eg CMODE_BAN) + * @return true if the user matches the list */ - void SetModesInternal(MessageSource &source, const Anope::string &mode, time_t ts = 0, bool EnforceMLock = true); + bool MatchesList(User *u, ChannelModeName list); /** Kick a user from a channel internally * @param source The sender of the kick @@ -246,12 +265,26 @@ class CoreExport Channel : public virtual Base, public Extensible, public Flags< /** Hold the channel open using ChanServ */ void Hold(); -}; -extern CoreExport Channel *findchan(const Anope::string &chan); + /** Set the correct modes, or remove the ones granted without permission, + * for the specified user. + * @param user The user to give/remove modes to/from + * @param give_modes if true modes may be given to the user + * @param check_noop if true, CI_NOAUTOOP is checked before giving modes + */ + void SetCorrectModes(User *u, bool give_mode, bool check_noop); -extern CoreExport User *nc_on_chan(Channel *c, const NickCore *nc); + /** Unbans a user from this channel. + * @param u The user to unban + * @param full Whether or not to match using the user's real host and IP + */ + void Unban(const User *u, bool full = false); -extern CoreExport void chan_set_correct_modes(const User *user, Channel *c, int give_modes, bool check_noop); + /** Finds a channel + * @param name The channel to find + * @return The channel, if found + */ + static Channel* Find(const Anope::string &name); +}; #endif // CHANNELS_H diff --git a/include/commands.h b/include/commands.h index 333d6882a..5c8664147 100644 --- a/include/commands.h +++ b/include/commands.h @@ -22,20 +22,20 @@ enum CommandFlag CFLAG_STRIP_CHANNEL }; -const Anope::string CommandFlagStrings[] = { - "CFLAG_ALLOW_UNREGISTERED", - "CFLAG_STRIP_CHANNEL", - "" -}; - +/* Used in BotInfo::commands */ struct CommandInfo { typedef Anope::map<CommandInfo> map; + /* Service name of the command */ Anope::string name; + /* Permission required to execute the command */ Anope::string permission; }; +/* Where the replies from commands go to. User inheits from this and is the normal + * source of a CommandReply + */ struct CommandReply { virtual void SendMessage(const BotInfo *source, const Anope::string &msg) = 0; @@ -47,16 +47,16 @@ class CoreExport CommandSource /* The nick executing the command */ Anope::string nick; /* User executing the command, may be NULL */ - dynamic_reference<User> u; + Reference<User> u; public: /* The account executing the command */ - dynamic_reference<NickCore> nc; + Reference<NickCore> nc; /* Where the reply should go */ CommandReply *reply; /* Channel the command was executed on (fantasy) */ - dynamic_reference<Channel> c; + Reference<Channel> c; /* The service this command is on */ - dynamic_reference<BotInfo> service; + Reference<BotInfo> service; /* The actual name of the command being executed */ Anope::string command; /* The permission of the command being executed */ @@ -88,9 +88,9 @@ class CoreExport Command : public Service, public Flags<CommandFlag> public: /* Maximum paramaters accepted by this command */ - size_t MaxParams; + size_t max_params; /* Minimum parameters required to use this command */ - size_t MinParams; + size_t min_params; /* Module which owns us */ Module *module; diff --git a/include/config.h b/include/config.h index 86a232485..ad772033d 100644 --- a/include/config.h +++ b/include/config.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef CONFIG_H @@ -207,23 +206,6 @@ typedef bool (*MultiValidator)(ServerConfig *, const Anope::string &, const Anop */ typedef bool (*MultiNotify)(ServerConfig *, const Anope::string &); -bool ValidateNotEmpty(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateNotZero(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateEmailReg(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidatePort(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateGuestPrefix(ServerConfig *conf, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateBantype(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data); -bool ValidateChanServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateMemoServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateBotServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateHostServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateLimitSessions(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateOperServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateGlobal(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateNickLen(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data); -bool ValidateMail(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); -bool ValidateGlobalOnCycle(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data); - /** Represents a configuration file */ class ConfigurationFile @@ -463,8 +445,6 @@ class CoreExport ServerConfig bool UseServerSideTopicLock; /* Default botmodes on channels, defaults to ao */ Anope::string BotModes; - /* THe actual modes */ - ChannelStatus BotModeList; /* How long to wait between connection attempts */ int RetryWait; /* If services should hide unprivileged commands */ @@ -517,7 +497,7 @@ class CoreExport ServerConfig /* Don't allow nicks to use /ns group to regroup nicks */ bool NSNoGroupChange; /* Default flags for newly registered nicks */ - Flags<NickCoreFlag, NI_END> NSDefFlags; + Flags<NickCoreFlag> NSDefFlags; /* All languages Anope is aware about */ Anope::string Languages; /* Default language used by services */ @@ -578,7 +558,7 @@ class CoreExport ServerConfig /* Core ChanServ modules */ Anope::string ChanCoreModules; /* Default flags for newly registered channels */ - Flags<ChannelInfoFlag, CI_END> CSDefFlags; + Flags<ChannelInfoFlag> CSDefFlags; /* Max number of channels a user can own */ unsigned CSMaxReg; /* Time before a channel expires */ @@ -741,7 +721,7 @@ class ConfigException : public CoreException #define CONF_FILE_NOT_FOUND 0x000200 /** Allows reading of values from configuration files - * This class allows a module to read from either the main configuration file (inspircd.conf) or from + * This class allows a module to read from either the main configuration file (services.conf) or from * a module-specified configuration file. It may either be instantiated with one parameter or none. * Constructing the class using one parameter allows you to specify a path to your own configuration * file, otherwise, inspircd.conf is read. @@ -836,7 +816,7 @@ class CoreExport ConfigReader int EnumerateValues(const Anope::string &, int); }; -extern ConfigurationFile services_conf; +extern ConfigurationFile ServicesConf; extern CoreExport ServerConfig *Config; #endif // CONFIG_H diff --git a/include/defs.h b/include/defs.h index ed6795142..437f0f08d 100644 --- a/include/defs.h +++ b/include/defs.h @@ -23,21 +23,21 @@ class ClientSocket; class Command; class CommandSource; class ConnectionSocket; -class DNSPacket; -class dynamic_reference_base; +namespace DNS { class Packet; } class Entry; class IdentifyRequest; class InfoFormatter; +class IRCDProto; class ListenSocket; class Log; class LogInfo; class Memo; -class Message; class MessageSource; class Module; class NickAlias; class NickCore; class OperType; +class ReferenceBase; class Regex; class Serializable; class Server; @@ -48,7 +48,7 @@ class User; class XLine; class XLineManager; struct BadWord; -struct DNSQuery; +namespace DNS { struct Query; } struct Exception; struct MemoInfo; struct ModeLock; diff --git a/include/dns.h b/include/dns.h index 64067107b..fee9da8a9 100644 --- a/include/dns.h +++ b/include/dns.h @@ -8,260 +8,271 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ - + #ifndef DNS_H #define DNS_H #include "sockets.h" #include "timers.h" -#include "extern.h" #include "config.h" - -/** Valid query types - */ -enum QueryType -{ - /* Nothing */ - DNS_QUERY_NONE, - /* A simple A lookup */ - DNS_QUERY_A = 1, - /* An authoritative name server */ - DNS_QUERY_NS = 2, - /* A CNAME lookup */ - DNS_QUERY_CNAME = 5, - /* Start of a zone of authority */ - DNS_QUERY_SOA = 6, - /* Reverse DNS lookup */ - DNS_QUERY_PTR = 12, - /* IPv6 AAAA lookup */ - DNS_QUERY_AAAA = 28, - /* Zone transfer */ - DNS_QUERY_AXFR = 252 -}; - -/** Flags that can be AND'd into DNSPacket::flags to receive certain values - */ -enum -{ - DNS_QUERYFLAGS_QR = 0x8000, - DNS_QUERYFLAGS_OPCODE = 0x7800, - DNS_QUERYFLAGS_AA = 0x400, - DBS_QUERYFLAGS_TC = 0x200, - DNS_QUERYFLAGS_RD = 0x100, - DNS_QUERYFLAGS_RA = 0x80, - DNS_QUERYFLAGS_Z = 0x70, - DNS_QUERYFLAGS_RCODE = 0xF -}; - -enum DNSError -{ - DNS_ERROR_NONE, - DNS_ERROR_UNKNOWN, - DNS_ERROR_UNLOADED, - DNS_ERROR_TIMEOUT, - DNS_ERROR_NOT_AN_ANSWER, - DNS_ERROR_NONSTANDARD_QUERY, - DNS_ERROR_FORMAT_ERROR, - DNS_ERROR_SERVER_FAILURE, - DNS_ERROR_DOMAIN_NOT_FOUND, - DNS_ERROR_NOT_IMPLEMENTED, - DNS_ERROR_REFUSED, - DNS_ERROR_NO_RECORDS, - DNS_ERROR_INVALIDTYPE -}; - - -struct CoreExport Question -{ - Anope::string name; - QueryType type; - unsigned short qclass; - - Question(); - Question(const Anope::string &, QueryType, unsigned short = 1); -}; - -struct CoreExport ResourceRecord : public Question -{ - unsigned int ttl; - Anope::string rdata; - time_t created; - - ResourceRecord(const Anope::string &, QueryType, unsigned short = 1); - ResourceRecord(const Question &); -}; - -struct CoreExport DNSQuery -{ - std::vector<Question> questions; - std::vector<ResourceRecord> answers, authorities, additional; - DNSError error; - - DNSQuery(); - DNSQuery(const Question &q); -}; - -/** The request - */ -class CoreExport DNSRequest : public Timer, public Question -{ - /* Use result cache if available */ - bool use_cache; - - public: - /* Request id */ - unsigned short id; - /* Creator of this request */ - Module *creator; - - DNSRequest(const Anope::string &addr, QueryType qt, bool cache = false, Module *c = NULL); - - virtual ~DNSRequest(); - - void Process(); - - virtual void OnLookupComplete(const DNSQuery *r) = 0; - - virtual void OnError(const DNSQuery *r); - void Tick(time_t) anope_override; -}; - -/** A full packet sent or recieved to/from the nameserver - */ -class DNSPacket : public DNSQuery +namespace DNS { - static const int DNS_POINTER = 0xC0; - static const int DNS_LABEL = 0x3F; - - void PackName(unsigned char *output, unsigned short output_size, unsigned short &pos, const Anope::string &name); - Anope::string UnpackName(const unsigned char *input, unsigned short input_size, unsigned short &pos); - Question UnpackQuestion(const unsigned char *input, unsigned short input_size, unsigned short &pos); - ResourceRecord UnpackResourceRecord(const unsigned char *input, unsigned short input_size, unsigned short &poss); - public: - static const int HEADER_LENGTH = 12; - - /* Source or destination of the packet */ - sockaddrs addr; - /* ID for this packet */ - unsigned short id; - /* Flags on the packet */ - unsigned short flags; - - DNSPacket(sockaddrs *a); - void Fill(const unsigned char *input, const unsigned short len); - unsigned short Pack(unsigned char *output, unsigned short output_size); -}; - -/** DNS manager - */ -class CoreExport DNSManager : public Timer -{ - class ReplySocket : public virtual Socket + /** Valid query types + */ + enum QueryType + { + /* Nothing */ + QUERY_NONE, + /* A simple A lookup */ + QUERY_A = 1, + /* An authoritative name server */ + QUERY_NS = 2, + /* A CNAME lookup */ + QUERY_CNAME = 5, + /* Start of a zone of authority */ + QUERY_SOA = 6, + /* Reverse DNS lookup */ + QUERY_PTR = 12, + /* IPv6 AAAA lookup */ + QUERY_AAAA = 28, + /* Zone transfer */ + QUERY_AXFR = 252 + }; + + /** Flags that can be AND'd into DNSPacket::flags to receive certain values + */ + enum { + QUERYFLAGS_QR = 0x8000, + QUERYFLAGS_OPCODE = 0x7800, + QUERYFLAGS_AA = 0x400, + QUERYFLAGS_TC = 0x200, + QUERYFLAGS_RD = 0x100, + QUERYFLAGS_RA = 0x80, + QUERYFLAGS_Z = 0x70, + QUERYFLAGS_RCODE = 0xF + }; + + enum Error + { + ERROR_NONE, + ERROR_UNKNOWN, + ERROR_UNLOADED, + ERROR_TIMEOUT, + ERROR_NOT_AN_ANSWER, + ERROR_NONSTANDARD_QUERY, + ERROR_FORMAT_ERROR, + ERROR_SERVER_FAILURE, + ERROR_DOMAIN_NOT_FOUND, + ERROR_NOT_IMPLEMENTED, + ERROR_REFUSED, + ERROR_NO_RECORDS, + ERROR_INVALIDTYPE + }; + + + struct CoreExport Question + { + Anope::string name; + QueryType type; + unsigned short qclass; + + Question(); + Question(const Anope::string &, QueryType, unsigned short = 1); + }; + + struct CoreExport ResourceRecord : public Question + { + unsigned int ttl; + Anope::string rdata; + time_t created; + + ResourceRecord(const Anope::string &, QueryType, unsigned short = 1); + ResourceRecord(const Question &); + }; + + struct CoreExport Query + { + std::vector<Question> questions; + std::vector<ResourceRecord> answers, authorities, additional; + Error error; + + Query(); + Query(const Question &q); + }; + + /** A DNS query. + */ + class CoreExport Request : public Timer, public Question + { + /* Use result cache if available */ + bool use_cache; + public: - virtual ~ReplySocket() { } - virtual void Reply(DNSPacket *p) = 0; + /* Request id */ + unsigned short id; + /* Creator of this request */ + Module *creator; + + Request(const Anope::string &addr, QueryType qt, bool cache = false, Module *c = NULL); + virtual ~Request(); + + void Process(); + + /** Called when this request succeeds + * @param r The query sent back from the nameserver + */ + virtual void OnLookupComplete(const Query *r) = 0; + + /** Called when this request fails or times out. + * @param r The query sent back from the nameserver, check the error code. + */ + virtual void OnError(const Query *r); + + /** Used to time out the query, Calls OnError and lets the TimerManager + * delete this request. + */ + void Tick(time_t) anope_override; }; - - /* Listens for TCP requests */ - class TCPSocket : public ListenSocket + + /** A full packet sent or recieved to/from the nameserver + */ + class Packet : public Query { - /* A TCP client */ - class Client : public ClientSocket, public Timer, public ReplySocket + static const int POINTER = 0xC0; + static const int LABEL = 0x3F; + + void PackName(unsigned char *output, unsigned short output_size, unsigned short &pos, const Anope::string &name); + Anope::string UnpackName(const unsigned char *input, unsigned short input_size, unsigned short &pos); + + Question UnpackQuestion(const unsigned char *input, unsigned short input_size, unsigned short &pos); + ResourceRecord UnpackResourceRecord(const unsigned char *input, unsigned short input_size, unsigned short &poss); + public: + static const int HEADER_LENGTH = 12; + + /* Source or destination of the packet */ + sockaddrs addr; + /* ID for this packet */ + unsigned short id; + /* Flags on the packet */ + unsigned short flags; + + Packet(sockaddrs *a); + void Fill(const unsigned char *input, const unsigned short len); + unsigned short Pack(unsigned char *output, unsigned short output_size); + }; + + /** DNS manager + */ + class CoreExport Manager : public Timer + { + class ReplySocket : public virtual Socket { - TCPSocket *tcpsock; - DNSPacket *packet; - unsigned char packet_buffer[524]; - int length; - public: - Client(TCPSocket *ls, int fd, const sockaddrs &addr); - ~Client(); - - /* Times out after a few seconds */ - void Tick(time_t) anope_override { } - void Reply(DNSPacket *p) anope_override; + virtual ~ReplySocket() { } + virtual void Reply(Packet *p) = 0; + }; + + /* Listens for TCP requests */ + class TCPSocket : public ListenSocket + { + /* A TCP client */ + class Client : public ClientSocket, public Timer, public ReplySocket + { + TCPSocket *tcpsock; + Packet *packet; + unsigned char packet_buffer[524]; + int length; + + public: + Client(TCPSocket *ls, int fd, const sockaddrs &addr); + ~Client(); + + /* Times out after a few seconds */ + void Tick(time_t) anope_override { } + void Reply(Packet *p) anope_override; + bool ProcessRead() anope_override; + bool ProcessWrite() anope_override; + }; + + public: + TCPSocket(const Anope::string &ip, int port); + + ClientSocket *OnAccept(int fd, const sockaddrs &addr) anope_override; + }; + + /* Listens for UDP requests */ + class UDPSocket : public ReplySocket + { + std::deque<Packet *> packets; + public: + + UDPSocket(const Anope::string &ip, int port); + ~UDPSocket(); + + void Reply(Packet *p) anope_override; + + std::deque<Packet *>& GetPackets() { return packets; } + bool ProcessRead() anope_override; + bool ProcessWrite() anope_override; }; - - public: - TCPSocket(const Anope::string &ip, int port); - - ClientSocket *OnAccept(int fd, const sockaddrs &addr) anope_override; - }; - - /* Listens for UDP requests */ - class UDPSocket : public ReplySocket - { - std::deque<DNSPacket *> packets; + + typedef std::multimap<Anope::string, ResourceRecord, ci::less> cache_map; + cache_map cache; + + bool listen; + uint32_t serial; + public: - - UDPSocket(const Anope::string &ip, int port); - ~UDPSocket(); - - void Reply(DNSPacket *p) anope_override; - - std::deque<DNSPacket *>& GetPackets() { return packets; } - - bool ProcessRead() anope_override; - - bool ProcessWrite() anope_override; + TCPSocket *tcpsock; + UDPSocket *udpsock; + + sockaddrs addrs; + std::map<unsigned short, Request *> requests; + + Manager(const Anope::string &nameserver, const Anope::string &ip, int port); + ~Manager(); + + bool HandlePacket(ReplySocket *s, const unsigned char *const data, int len, sockaddrs *from); + + /** Add a record to the dns cache + * @param r The record + */ + void AddCache(Query &r); + + /** Check the DNS cache to see if request can be handled by a cached result + * @return true if a cached result was found. + */ + bool CheckCache(Request *request); + + /** Tick this timer, used to clear the DNS cache. + */ + void Tick(time_t now) anope_override; + + /** Cleanup all pending DNS queries for a module + * @param mod The module + */ + void Cleanup(Module *mod); + + void UpdateSerial(); + uint32_t GetSerial() const; + + /** Does a BLOCKING DNS query and returns the first IP. + * Only use this if you know what you are doing. Unless you specifically + * need a blocking query use the DNSRequest system + */ + static Query BlockingQuery(const Anope::string &mask, QueryType qt); }; - - typedef std::multimap<Anope::string, ResourceRecord, ci::less> cache_map; - cache_map cache; - - bool listen; - uint32_t serial; - - public: - TCPSocket *tcpsock; - UDPSocket *udpsock; - - sockaddrs addrs; - std::map<unsigned short, DNSRequest *> requests; - - DNSManager(const Anope::string &nameserver, const Anope::string &ip, int port); - ~DNSManager(); - - bool HandlePacket(ReplySocket *s, const unsigned char *const data, int len, sockaddrs *from); - - /** Add a record to the dns cache - * @param r The record - */ - void AddCache(DNSQuery &r); - - /** Check the DNS cache to see if request can be handled by a cached result - * @return true if a cached result was found. - */ - bool CheckCache(DNSRequest *request); - - /** Tick this timer, used to clear the DNS cache. - */ - void Tick(time_t now) anope_override; - - /** Cleanup all pending DNS queries for a module - * @param mod The module - */ - void Cleanup(Module *mod); - - void UpdateSerial(); - uint32_t GetSerial() const; - - /** Does a BLOCKING DNS query and returns the first IP. - * Only use this if you know what you are doing. Unless you specifically - * need a blocking query use the DNSRequest system - */ - static DNSQuery BlockingQuery(const Anope::string &mask, QueryType qt); -}; - -extern CoreExport DNSManager *DNSEngine; - + + extern CoreExport Manager *Engine; + +} // namespace DNS + #endif // DNS_H - - + + diff --git a/include/extensible.h b/include/extensible.h index 6db4cf112..493dc20cf 100644 --- a/include/extensible.h +++ b/include/extensible.h @@ -1,7 +1,10 @@ /* - * Copyright (C) 2008-2012 Anope Team <team@anope.org> + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ #ifndef EXTENSIBLE_H @@ -9,19 +12,28 @@ #include "anope.h" +/* All items added to Extensible must inherit from this. + */ class CoreExport ExtensibleItem { public: - ExtensibleItem(); - virtual ~ExtensibleItem(); - virtual void OnDelete(); + virtual ~ExtensibleItem() { } + + /* Called when this ExtensibleItem is being deleted. This should + * clean up things (eg, delete this;) if necessary. + */ + virtual void OnDelete() { delete this; } }; +/** Common class used to Extensible::Extend non-pointers from, as it doesn't delete + * itself when removed. Eg, obj->Extend(key, new ExtensibleItemClass<Anope::string>(value)); + */ template<typename T> struct CoreExport ExtensibleItemClass : T, ExtensibleItem { ExtensibleItemClass(const T& t) : T(t) { } }; +/* Used to attach arbitrary objects to this object using unique keys */ class CoreExport Extensible { private: @@ -33,7 +45,7 @@ class CoreExport Extensible */ Extensible() { } - /** Default destructor, deletes all of the extensible items in this object + /** Destructor, deletes all of the extensible items in this object * then clears the map */ virtual ~Extensible() diff --git a/include/extern.h b/include/extern.h deleted file mode 100644 index e8a47c209..000000000 --- a/include/extern.h +++ /dev/null @@ -1,108 +0,0 @@ -/* Prototypes and external variable declarations. - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -#ifndef EXTERN_H -#define EXTERN_H - -#include "modes.h" - -#define E extern CoreExport -#define EI extern DllExport - - -/**** actions.c ****/ - -E bool bad_password(User *u); -E void common_unban(const ChannelInfo *ci, User *u, bool full = false); - -/**** encrypt.c ****/ - -E void enc_encrypt(const Anope::string &src, Anope::string &dest); -E bool enc_decrypt(const Anope::string &src, Anope::string &dest); - -/**** init.c ****/ - -E Anope::string conf_dir, db_dir, modules_dir, locale_dir, log_dir; - -E void introduce_user(const Anope::string &user); -E bool GetCommandLineArgument(const Anope::string &name, char shortname = 0); -E bool GetCommandLineArgument(const Anope::string &name, char shortname, Anope::string ¶m); -E bool AtTerm(); -E void Fork(); -E void Init(int ac, char **av); - -/**** language.cpp ****/ - -E std::vector<Anope::string> languages; -E std::vector<Anope::string> domains; -E void InitLanguages(); -E const char *translate(const char *string); -E const char *translate(User *u, const char *string); -E const char *translate(const NickCore *nc, const char *string); -E const char *anope_gettext(const char *lang, const char *string); - -/**** main.c ****/ - -E Anope::string services_dir; -E Anope::string services_bin; -E int debug; -E bool readonly; -E bool nofork; -E bool nothird; -E bool noexpire; -E bool protocoldebug; - -E bool quitting; -E int return_code; -E bool restarting; -E Anope::string quitmsg; -E time_t start_time; - -E int CurrentUplink; - -E void save_databases(); -E void sighandler(int signum); - -/**** misc.c ****/ - -E bool IsFile(const Anope::string &filename); - -E time_t dotime(const Anope::string &s); -E Anope::string duration(const time_t &seconds, const NickCore *nc = NULL); -E Anope::string expire_left(const NickCore *nc, time_t expires); -E Anope::string do_strftime(const time_t &t, const NickCore *nc = NULL, bool short_output = false); -E bool IsValidIdent(const Anope::string &ident); -E bool IsValidHost(const Anope::string &host); - -E Anope::string myStrGetToken(const Anope::string &str, char dilim, int token_number); -E Anope::string myStrGetTokenRemainder(const Anope::string &str, char dilim, int token_number); -E int myNumToken(const Anope::string &str, char dilim); -E bool nickIsServices(const Anope::string &nick, bool bot); - -E std::list<Anope::string> BuildStringList(const Anope::string &, char = ' '); -E std::vector<Anope::string> BuildStringVector(const Anope::string &, char = ' '); - -E bool str_is_wildcard(const Anope::string &str); -E bool str_is_pure_wildcard(const Anope::string &str); -E Anope::string normalizeBuffer(const Anope::string &); - -/**** modes.cpp ****/ - -/* Number of generic modes we support */ -E unsigned GenericChannelModes, GenericUserModes; -E std::multimap<ChannelModeName, ModeLock *> def_mode_locks; -E void SetDefaultMLock(ServerConfig *config); - -/**** process.c ****/ - -E void process(const Anope::string &buf); - -#endif /* EXTERN_H */ diff --git a/include/hashcomp.h b/include/hashcomp.h index 9f9be9793..74258151a 100644 --- a/include/hashcomp.h +++ b/include/hashcomp.h @@ -1,13 +1,10 @@ /* + * * Copyright (C) 2002-2011 InspIRCd Development Team * Copyright (C) 2009-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. * - * These classes have been copied from InspIRCd and modified - * for use in Anope. - * - * */ #ifndef HASHCOMP_H @@ -28,13 +25,15 @@ namespace Anope { class string; + /* Casemap in use by Anope. ci::string's comparation functions use this (and thus Anope::string) */ extern std::locale casemap; - template<typename charT> - class ascii_ctype : public std::ctype<charT> + /* ASCII case insensitive ctype. */ + template<typename char_type> + class ascii_ctype : public std::ctype<char_type> { public: - charT do_toupper(charT c) const anope_override + char_type do_toupper(char_type c) const anope_override { if (c >= 'a' && c <= 'z') return c - 32; @@ -42,7 +41,7 @@ namespace Anope return c; } - charT do_tolower(charT c) const anope_override + char_type do_tolower(char_type c) const anope_override { if (c >= 'A' && c <= 'Z') return c + 32; @@ -51,29 +50,30 @@ namespace Anope } }; - template<typename charT> - class rfc1459_ctype : public ascii_ctype<charT> + /* rfc1459 case insensitive ctype, { = [, } = ], and | = \ */ + template<typename char_type> + class rfc1459_ctype : public ascii_ctype<char_type> { public: - charT do_toupper(charT c) const anope_override + char_type do_toupper(char_type c) const anope_override { if (c == '{' || c == '}' || c == '|') return c - 32; else - return ascii_ctype<charT>::do_toupper(c); + return ascii_ctype<char_type>::do_toupper(c); } - charT do_tolower(charT c) const anope_override + char_type do_tolower(char_type c) const anope_override { if (c == '[' || c == ']' || c == '\\') return c + 32; else - return ascii_ctype<charT>::do_tolower(c); + return ascii_ctype<char_type>::do_tolower(c); } }; } -/** The ci namespace contains a number of helper classes. +/** The ci namespace contains a number of helper classes relevant to case insensitive strings. */ namespace ci { diff --git a/include/language.h b/include/language.h index f48d9ce2d..eeb23af02 100644 --- a/include/language.h +++ b/include/language.h @@ -1,11 +1,67 @@ -/* Commonly used language strings +/* * * (C) 2008-2012 Anope Team * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ +namespace Language +{ + + /* Languages we support as configured in services.conf. They are + * added to this list if we detect a language exists in the correct + * location for each language. + */ + extern std::vector<Anope::string> Languages; + + /* Domains to search when looking for translations other than the + * default "anope domain. This is used by modules who add their own + * language files (and thus domains) to Anope. If a module is loaded + * and we detect a language file exists for at least one of the supported + * languages for the module, then we add the module's domain (its name) + * here. + * + * When strings are translated they are checked against all domains. + */ + extern std::vector<Anope::string> Domains; + + /** Initialize the language system. Finds valid language files and + * populates the Languages list. + */ + extern void InitLanguages(); + + /** Translates a string to the default language. + * @param string A string to translate + * @return The translated string if found, else the original string. + */ + extern const char *Translate(const char *string); + + /** Translates a string to the language of the given user. + * @param u The user to transate the string for + * @param string A string to translate + * @return The translated string if found, else the original string. + */ + extern const char *Translate(User *u, const char *string); + + /** Translates a string to the language of the given account. + * @param nc The account to translate the string for + * @param string A string to translate + * @return The translated string if count, else the original string + */ + extern const char *Translate(const NickCore *nc, const char *string); + + /** Translatesa string to the given language. + * @param lang The language to trnalsate to + * @param string The string to translate + * @return The translated string if found, else the original string. + */ + extern const char *Translate(const char *lang, const char *string); + +} // namespace Language + +/* Commonly used language strings */ #define MORE_INFO _("\002%s%s HELP %s\002 for more information.") #define BAD_USERHOST_MASK _("Mask must be in the form \037user\037@\037host\037.") #define BAD_EXPIRY_TIME _("Invalid expiry time.") diff --git a/include/lists.h b/include/lists.h index 841faf7a9..94d03aa4b 100644 --- a/include/lists.h +++ b/include/lists.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef LISTS_H @@ -48,9 +47,9 @@ class CoreExport NumberList void Process(); /** Called with a number from the list - * @param Number The number + * @param number The number */ - virtual void HandleNumber(unsigned Number); + virtual void HandleNumber(unsigned number); /** Called when there is an error with the numbered list * Return false to immediatly stop processing the list and return @@ -71,9 +70,9 @@ class CoreExport ListFormatter std::vector<Anope::string> columns; std::vector<ListEntry> entries; public: - ListFormatter &addColumn(const Anope::string &name); - void addEntry(const ListEntry &entry); - bool isEmpty() const; + ListFormatter &AddColumn(const Anope::string &name); + void AddEntry(const ListEntry &entry); + bool IsEmpty() const; void Process(std::vector<Anope::string> &); }; diff --git a/include/logger.h b/include/logger.h index 5df81a5bc..1f674467a 100644 --- a/include/logger.h +++ b/include/logger.h @@ -18,8 +18,13 @@ enum LogType { + /* Used whenever an administrator uses an administrative comand */ LOG_ADMIN, + /* Used whenever an administrator overides something, such as adding + * access to a channel where they don't have permission to. + */ LOG_OVERRIDE, + /* Any other command usage */ LOG_COMMAND, LOG_SERVER, LOG_CHANNEL, @@ -37,30 +42,37 @@ enum LogType struct LogFile { Anope::string filename; - - public: std::ofstream stream; LogFile(const Anope::string &name); Anope::string GetName() const; }; - +/* Represents a single log message */ class CoreExport Log { public: + /* Bot that should log this message */ const BotInfo *bi; + /* For commands, the user executing the command */ Anope::string nick; + /* For commands, the user executing the command, but might not always exist */ const User *u; + /* For commands, the account executing teh command, but will not always exist */ const NickCore *nc; + /* For commands, the command being executed */ Command *c; + /* Used for LOG_CHANNEL */ Channel *chan; + /* For commands, the channel the command was executed on, will not always exist */ const ChannelInfo *ci; + /* For LOG_SERVER */ Server *s; + /* For LOG_MODULE */ Module *m; - LogType Type; - Anope::string Category; - std::list<Anope::string> Sources; + LogType type; + Anope::string category; + std::list<Anope::string> sources; std::stringstream buf; @@ -93,22 +105,23 @@ class CoreExport Log } }; +/* Configured in the configuration file, actually does the message logging */ class CoreExport LogInfo { public: - std::list<Anope::string> Targets; - std::map<Anope::string, LogFile *> Logfiles; - std::list<Anope::string> Sources; - int LogAge; - std::list<Anope::string> Admin; - std::list<Anope::string> Override; - std::list<Anope::string> Commands; - std::list<Anope::string> Servers; - std::list<Anope::string> Users; - std::list<Anope::string> Channels; - std::list<Anope::string> Normal; - bool RawIO; - bool Debug; + std::list<Anope::string> targets; + std::map<Anope::string, LogFile *> logfiles; + std::list<Anope::string> sources; + int log_age; + std::list<Anope::string> admin; + std::list<Anope::string> override; + std::list<Anope::string> commands; + std::list<Anope::string> servers; + std::list<Anope::string> users; + std::list<Anope::string> channels; + std::list<Anope::string> normal; + bool raw_io; + bool debug; LogInfo(int logage, bool rawio, bool debug); @@ -118,6 +131,7 @@ class CoreExport LogInfo bool HasType(LogType ltype, const Anope::string &type) const; + /* Logs the message l if configured to */ void ProcessMessage(const Log *l); }; diff --git a/include/mail.h b/include/mail.h index 493002637..2b513c849 100644 --- a/include/mail.h +++ b/include/mail.h @@ -18,28 +18,41 @@ #include "threadengine.h" #include "serialize.h" -extern CoreExport bool Mail(User *u, NickCore *nc, const BotInfo *service, const Anope::string &subject, const Anope::string &message); -extern CoreExport bool Mail(NickCore *nc, const Anope::string &subject, const Anope::string &message); -extern CoreExport bool MailValidate(const Anope::string &email); - -class MailThread : public Thread +namespace Mail { - private: - Anope::string SendMailPath; - Anope::string SendFrom; - Anope::string MailTo; - Anope::string Addr; - Anope::string Subject; - Anope::string Message; - bool DontQuoteAddresses; - - bool Success; - public: - MailThread(const Anope::string &smpath, const Anope::string &sf, const Anope::string &mailto, const Anope::string &addr, const Anope::string &subject, const Anope::string &message); - - ~MailThread(); - - void Run(); -}; + extern CoreExport bool Send(User *from, NickCore *to, const BotInfo *service, const Anope::string &subject, const Anope::string &message); + extern CoreExport bool Send(NickCore *to, const Anope::string &subject, const Anope::string &message); + extern CoreExport bool Validate(const Anope::string &email); + + /* A email message being sent */ + class Message : public Thread + { + private: + Anope::string sendmail_path; + Anope::string send_from; + Anope::string mail_to; + Anope::string addr; + Anope::string subject; + Anope::string message; + bool dont_quote_addresses; + + bool success; + public: + /** Construct this message. Once constructed call Thread::Start to launch the mail sending. + * @param sf Config->SendFrom + * @param mailto Name of person being mailed (u->nick, nc->display, etc) + * @param addr Destination address to mail + * @param subject Message subject + * @param message The actual message + */ + Message(const Anope::string &sf, const Anope::string &mailto, const Anope::string &addr, const Anope::string &subject, const Anope::string &message); + + ~Message(); + + /* Called from within the thread to actually send the mail */ + void Run() anope_override; + }; + +} // namespace Mail #endif // MAIL_H diff --git a/include/memo.h b/include/memo.h index 1879f89b3..9fdbb3cab 100644 --- a/include/memo.h +++ b/include/memo.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef MEMO_H @@ -27,30 +26,28 @@ enum MemoFlag MF_RECEIPT }; -const Anope::string MemoFlagStrings[] = { - "MF_UNREAD", "MF_RECEIPT", "" -}; - -/* Memo info structures. Since both nicknames and channels can have memos, - * we encapsulate memo data in a MemoList to make it easier to handle. */ class CoreExport Memo : public Flags<MemoFlag>, public Serializable { public: Memo(); - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); Anope::string owner; - time_t time; /* When it was sent */ + /* When it was sent */ + time_t time; Anope::string sender; Anope::string text; }; +/* Memo info structures. Since both nicknames and channels can have memos, + * we encapsulate memo data in a MemoInfo to make it easier to handle. + */ struct CoreExport MemoInfo { int16_t memomax; - serialize_checker<std::vector<Memo *> > memos; + Serialize::Checker<std::vector<Memo *> > memos; std::vector<Anope::string> ignores; MemoInfo(); diff --git a/include/messages.h b/include/messages.h index 1a577ae85..1ef9638ff 100644 --- a/include/messages.h +++ b/include/messages.h @@ -1,126 +1,161 @@ +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + #include "protocol.h" - + /* Common IRCD messages. * Protocol modules may chose to include some, none, or all of these handlers * as they see fit. */ - -struct CoreExport CoreIRCDMessageAway : IRCDMessage -{ - CoreIRCDMessageAway(const Anope::string &mname = "AWAY") : IRCDMessage(mname, 0) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageCapab : IRCDMessage -{ - CoreIRCDMessageCapab(const Anope::string &mname = "CAPAB") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageError : IRCDMessage -{ - CoreIRCDMessageError(const Anope::string &mname = "ERROR") : IRCDMessage(mname, 1) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageJoin : IRCDMessage -{ - CoreIRCDMessageJoin(const Anope::string &mname = "JOIN") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageKick : IRCDMessage -{ - CoreIRCDMessageKick(const Anope::string &mname = "KICK") : IRCDMessage(mname, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageKill : IRCDMessage -{ - CoreIRCDMessageKill(const Anope::string &mname = "KILL") : IRCDMessage(mname, 2) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageMOTD : IRCDMessage -{ - CoreIRCDMessageMOTD(const Anope::string &mname = "MOTD") : IRCDMessage(mname, 1) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessagePart : IRCDMessage -{ - CoreIRCDMessagePart(const Anope::string &mname = "PART") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessagePing : IRCDMessage -{ - CoreIRCDMessagePing(const Anope::string &mname = "PING") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessagePrivmsg : IRCDMessage -{ - CoreIRCDMessagePrivmsg(const Anope::string &mname = "PRIVMSG") : IRCDMessage(mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageQuit : IRCDMessage -{ - CoreIRCDMessageQuit(const Anope::string &mname = "QUIT") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageSQuit : IRCDMessage -{ - CoreIRCDMessageSQuit(const Anope::string &mname = "SQUIT") : IRCDMessage(mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageStats : IRCDMessage -{ - CoreIRCDMessageStats(const Anope::string &mname = "STATS") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageTime : IRCDMessage -{ - CoreIRCDMessageTime(const Anope::string &mname = "TIME") : IRCDMessage(mname, 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageTopic : IRCDMessage -{ - CoreIRCDMessageTopic(const Anope::string &mname = "TOPIC") : IRCDMessage(mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageVersion : IRCDMessage -{ - CoreIRCDMessageVersion(const Anope::string &mname = "VERSION") : IRCDMessage(mname, 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - -struct CoreExport CoreIRCDMessageWhois : IRCDMessage -{ - CoreIRCDMessageWhois(const Anope::string &mname = "WHOIS") : IRCDMessage(mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; -}; - + +namespace Message +{ + + struct CoreExport Away : IRCDMessage + { + Away(Module *creator, const Anope::string &mname = "AWAY") : IRCDMessage(creator, mname, 0) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Capab : IRCDMessage + { + Capab(Module *creator, const Anope::string &mname = "CAPAB") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Error : IRCDMessage + { + Error(Module *creator, const Anope::string &mname = "ERROR") : IRCDMessage(creator, mname, 1) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Join : IRCDMessage + { + Join(Module *creator, const Anope::string &mname = "JOIN") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + + typedef std::pair<ChannelStatus, User *> SJoinUser; + + /** Handle a SJOIN. + * @param source The source of the SJOIN + * @param chan The channel the users are joining to + * @param ts The TS for the channel + * @param modes The modes sent with the SJOIN, if any + * @param users The users and their status, if any + */ + static void SJoin(MessageSource &source, const Anope::string &chan, time_t ts, const Anope::string &modes, const std::list<SJoinUser> &users); + }; + + struct CoreExport Kick : IRCDMessage + { + Kick(Module *creator, const Anope::string &mname = "KICK") : IRCDMessage(creator, mname, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Kill : IRCDMessage + { + Kill(Module *creator, const Anope::string &mname = "KILL") : IRCDMessage(creator, mname, 2) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Mode : IRCDMessage + { + Mode(Module *creator, const Anope::string &mname = "MODE") : IRCDMessage(creator, mname, 2) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport MOTD : IRCDMessage + { + MOTD(Module *creator, const Anope::string &mname = "MOTD") : IRCDMessage(creator, mname, 1) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Part : IRCDMessage + { + Part(Module *creator, const Anope::string &mname = "PART") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Ping : IRCDMessage + { + Ping(Module *creator, const Anope::string &mname = "PPING") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Privmsg : IRCDMessage + { + Privmsg(Module *creator, const Anope::string &mname = "PRIVMSG") : IRCDMessage(creator, mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Quit : IRCDMessage + { + Quit(Module *creator, const Anope::string &mname = "QUIT") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport SQuit : IRCDMessage + { + SQuit(Module *creator, const Anope::string &mname = "SQUIT") : IRCDMessage(creator, mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Stats : IRCDMessage + { + Stats(Module *creator, const Anope::string &mname = "STATS") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Time : IRCDMessage + { + Time(Module *creator, const Anope::string &mname = "TIME") : IRCDMessage(creator, mname, 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Topic : IRCDMessage + { + Topic(Module *creator, const Anope::string &mname = "TOPIC") : IRCDMessage(creator, mname, 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Version : IRCDMessage + { + Version(Module *creator, const Anope::string &mname = "VERSION") : IRCDMessage(creator, mname, 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + + struct CoreExport Whois : IRCDMessage + { + Whois(Module *creator, const Anope::string &mname = "WHOIS") : IRCDMessage(creator, mname, 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override; + }; + +} // namespace Message + diff --git a/include/modes.h b/include/modes.h index 1bd928ed1..b38ef3dc1 100644 --- a/include/modes.h +++ b/include/modes.h @@ -27,18 +27,6 @@ enum UserModeName UMODE_END }; -const Anope::string UserModeNameStrings[] = { - "UMODE_BEGIN", - - "UMODE_SERV_ADMIN", "UMODE_BOT", "UMODE_CO_ADMIN", "UMODE_FILTER", "UMODE_HIDEOPER", "UMODE_NETADMIN", - "UMODE_REGPRIV", "UMODE_PROTECTED", "UMODE_NOCTCP", "UMODE_WEBTV", "UMODE_WEBIRC", "UMODE_WHOIS", "UMODE_ADMIN", "UMODE_DEAF", - "UMODE_GLOBOPS", "UMODE_HELPOP", "UMODE_INVIS", "UMODE_OPER", "UMODE_PRIV", "UMODE_GOD", "UMODE_REGISTERED", - "UMODE_SNOMASK", "UMODE_VHOST", "UMODE_WALLOPS", "UMODE_CLOAK", "UMODE_SSL", "UMODE_SOFTCALLERID", "UMODE_CALLERID", - "UMODE_COMMONCHANS", "UMODE_HIDDEN", "UMODE_STRIPCOLOR", "UMODE_INVISIBLE_OPER", "UMODE_RESTRICTED", "UMODE_HIDEIDLE", - - "" -}; - /** All of the valid channel mode names */ enum ChannelModeName @@ -64,29 +52,6 @@ enum ChannelModeName CMODE_END }; -const Anope::string ChannelModeNameStrings[] = { - "CMODE_BEGIN", - - /* Channel modes */ - "CMODE_BLOCKCOLOR", "CMODE_FLOOD", "CMODE_INVITE", "CMODE_KEY", "CMODE_LIMIT", "CMODE_MODERATED", "CMODE_NOEXTERNAL", - "CMODE_PRIVATE", "CMODE_REGISTERED", "CMODE_SECRET", "CMODE_TOPIC", "CMODE_AUDITORIUM", "CMODE_SSL", "CMODE_ADMINONLY", - "CMODE_NOCTCP", "CMODE_FILTER", "CMODE_NOKNOCK", "CMODE_REDIRECT", "CMODE_REGMODERATED", "CMODE_NONICK", "CMODE_OPERONLY", - "CMODE_NOKICK", "CMODE_REGISTEREDONLY", "CMODE_STRIPCOLOR", "CMODE_NONOTICE", "CMODE_NOINVITE", "CMODE_ALLINVITE", - "CMODE_BLOCKCAPS", "CMODE_PERM", "CMODE_NICKFLOOD", "CMODE_JOINFLOOD", "CMODE_DELAYEDJOIN", "CMODE_NOREJOIN", - "CMODE_BANDWIDTH", - - /* b/e/I */ - "CMODE_BAN", "CMODE_EXCEPT", - "CMODE_INVITEOVERRIDE", - - /* v/h/o/a/q */ - "CMODE_VOICE", "CMODE_HALFOP", "CMODE_OP", - "CMODE_PROTECT", "CMODE_OWNER", - - "" -}; - - /** The different types of modes */ enum ModeType @@ -105,9 +70,7 @@ enum ModeType */ enum ModeClass { - /* Channel mode */ MC_CHANNEL, - /* User mode */ MC_USER }; @@ -116,22 +79,19 @@ enum ModeClass class CoreExport Mode : public Base { public: - /* Class of mode this is */ - ModeClass Class; - /* Mode char for this */ - char ModeChar; - /* Type of mode this is */ - ModeType Type; - - /** Default constructor - * @param mClass The type of mode this is - * @param modeChar The mode char + /* Class of mode this is (user/channel) */ + ModeClass mclass; + /* Mode char for this, eg 'b' */ + char mchar; + /* Type of mode this is, eg MODE_LIST */ + ModeType type; + + /** constructor + * @param mclass The type of mode this is + * @param mc The mode char * @param type The mode type */ - Mode(ModeClass mClass, char modeChar, ModeType type); - - /** Default destructor - */ + Mode(ModeClass mclass, char mc, ModeType type); virtual ~Mode(); }; @@ -141,16 +101,13 @@ class CoreExport UserMode : public Mode { public: /* Mode name */ - UserModeName Name; - - /** Default constructor - * @param nName The mode name - * @param modeChar The mode char - */ - UserMode(UserModeName mName, char modeChar); + UserModeName name; - /** Default destructor + /** constructor + * @param name The mode name + * @param mc The mode char */ + UserMode(UserModeName name, char mc); virtual ~UserMode(); /** Returns the mode name as a string @@ -161,11 +118,11 @@ class CoreExport UserMode : public Mode class CoreExport UserModeParam : public UserMode { public: - /** Default constructor - * @param mName The mode name - * @param modeChar The mode char + /** constructor + * @param name The mode name + * @param mc The mode char */ - UserModeParam(UserModeName mName, char modeChar); + UserModeParam(UserModeName name, char mc); /** Check if the param is valid * @param value The param @@ -180,16 +137,13 @@ class CoreExport ChannelMode : public Mode { public: /* Mode name */ - ChannelModeName Name; + ChannelModeName name; - /** Default constructor - * @param mName The mode name - * @param modeChar The mode char - */ - ChannelMode(ChannelModeName mName, char modeChar); - - /** Default destructor + /** constructor + * @param name The mode name + * @param mc The mode char */ + ChannelMode(ChannelModeName name, char mc); virtual ~ChannelMode(); /** Can a user set this mode, used for mlock @@ -209,13 +163,13 @@ class CoreExport ChannelMode : public Mode class CoreExport ChannelModeList : public ChannelMode { public: - /** Default constructor - * @param mName The mode name - * @param modeChar The mode char + /** constructor + * @param name The mode name + * @param mc The mode char */ - ChannelModeList(ChannelModeName mName, char modeChar); + ChannelModeList(ChannelModeName name, char mc); - /** Default destructor + /** destructor */ virtual ~ChannelModeList(); @@ -251,19 +205,19 @@ class CoreExport ChannelModeList : public ChannelMode class CoreExport ChannelModeParam : public ChannelMode { public: - /** Default constructor - * @param mName The mode name - * @param modeChar The mode char - * @param MinusArg true if this mode sends no arg when unsetting + /** constructor + * @param name The mode name + * @param mc The mode char + * @param minus_no_arg true if this mode sends no arg when unsetting */ - ChannelModeParam(ChannelModeName mName, char modeChar, bool MinusArg = false); + ChannelModeParam(ChannelModeName name, char mc, bool minus_no_arg = false); - /** Default destructor + /** destructor */ virtual ~ChannelModeParam(); /* Should we send an arg when unsetting this mode? */ - bool MinusNoArg; + bool minus_no_arg; /** Is the param valid * @param value The param @@ -284,25 +238,33 @@ class CoreExport ChannelModeStatus : public ChannelMode */ unsigned short Level; - /** Default constructor - * @param mName The mode name - * @param modeChar The mode char + /** constructor + * @param name The mode name + * @param mc The mode char * @param mSymbol The symbol for the mode, eg @ % * @param mLevel A level for the mode, which is usually determined by the PREFIX capab */ - ChannelModeStatus(ChannelModeName mName, char modeChar, char mSymbol, unsigned short mLevel = 0); + ChannelModeStatus(ChannelModeName name, char mc, char mSymbol, unsigned short mLevel = 0); - /** Default destructor + /** destructor */ virtual ~ChannelModeStatus(); }; +/* The status a user has on a channel (+v, +h, +o) etc */ +class CoreExport ChannelStatus : public Flags<ChannelModeName> +{ + public: + Anope::string BuildCharPrefixList() const; + Anope::string BuildModePrefixList() const; +}; + /** Channel mode +k (key) */ class CoreExport ChannelModeKey : public ChannelModeParam { public: - ChannelModeKey(char modeChar) : ChannelModeParam(CMODE_KEY, modeChar) { } + ChannelModeKey(char mc) : ChannelModeParam(CMODE_KEY, mc) { } bool IsValid(const Anope::string &value) const anope_override; }; @@ -313,7 +275,7 @@ class CoreExport ChannelModeKey : public ChannelModeParam class CoreExport ChannelModeAdmin : public ChannelMode { public: - ChannelModeAdmin(char modeChar) : ChannelMode(CMODE_ADMINONLY, modeChar) { } + ChannelModeAdmin(char mc) : ChannelMode(CMODE_ADMINONLY, mc) { } /* Opers only */ bool CanSet(User *u) const anope_override; @@ -325,7 +287,7 @@ class CoreExport ChannelModeAdmin : public ChannelMode class CoreExport ChannelModeOper : public ChannelMode { public: - ChannelModeOper(char modeChar) : ChannelMode(CMODE_OPERONLY, modeChar) { } + ChannelModeOper(char mc) : ChannelMode(CMODE_OPERONLY, mc) { } /* Opers only */ bool CanSet(User *u) const anope_override; @@ -337,7 +299,7 @@ class CoreExport ChannelModeOper : public ChannelMode class CoreExport ChannelModeRegistered : public ChannelMode { public: - ChannelModeRegistered(char modeChar) : ChannelMode(CMODE_REGISTERED, modeChar) { } + ChannelModeRegistered(char mc) : ChannelMode(CMODE_REGISTERED, mc) { } /* No one mlocks +r */ bool CanSet(User *u) const anope_override; @@ -355,17 +317,17 @@ class StackerInfo /** Add a mode to this object * @param mode The mode - * @param Set true if setting, false if unsetting - * @param Param The param for the mode + * @param set true if setting, false if unsetting + * @param param The param for the mode */ - void AddMode(Mode *mode, bool Set, const Anope::string &Param); + void AddMode(Mode *mode, bool set, const Anope::string ¶m); }; -/** This is mode manager +/** This is the mode manager * It contains functions for adding modes to Anope so Anope can track them * and do things such as MLOCK. * This also contains a mode stacker that will combine multiple modes and set - * them on a channel all at once + * them on a channel or user at once */ class CoreExport ModeManager { @@ -385,6 +347,13 @@ class CoreExport ModeManager static std::vector<ChannelMode *> ChannelModes; static std::vector<UserMode *> UserModes; + /* Number of generic channel and user modes we are tracking */ + static unsigned GenericChannelModes, GenericUserModes; + /* Default channel mode lock */ + static std::multimap<ChannelModeName, ModeLock *> DefaultModeLocks; + /* Default modes bots have on channels */ + static ChannelStatus DefaultBotModes; + /** Add a user mode to Anope * @param um A UserMode or UserMode derived class * @return true on success, false on error @@ -397,29 +366,39 @@ class CoreExport ModeManager */ static bool AddChannelMode(ChannelMode *cm); + /** Remove a user mode from Anope + * @param um A UserMode to remove + */ + static void RemoveUserMode(UserMode *um); + + /** Remove a channel mode from Anope + * @param um A ChanneMode to remove + */ + static void RemoveChannelMode(ChannelMode *cm); + /** Find a channel mode - * @param Mode The mode + * @param mode The mode * @return The mode class */ - static ChannelMode *FindChannelModeByChar(char Mode); + static ChannelMode *FindChannelModeByChar(char mode); /** Find a user mode - * @param Mode The mode + * @param mode The mode * @return The mode class */ - static UserMode *FindUserModeByChar(char Mode); + static UserMode *FindUserModeByChar(char mode); /** Find a channel mode - * @param Mode The modename + * @param name The modename * @return The mode class */ - static ChannelMode *FindChannelModeByName(ChannelModeName Name); + static ChannelMode *FindChannelModeByName(ChannelModeName name); /** Find a user mode - * @param Mode The modename + * @param name The modename * @return The mode class */ - static UserMode *FindUserModeByName(UserModeName Name); + static UserMode *FindUserModeByName(UserModeName name); /** Find channel mode by string * @param name The mode name @@ -434,37 +413,44 @@ class CoreExport ModeManager static UserMode *FindUserModeByString(const Anope::string &name); /** Gets the channel mode char for a symbol (eg + returns v) - * @param Value The symbol + * @param symbol The symbol * @return The char */ - static char GetStatusChar(char Value); + static char GetStatusChar(char symbol); /** Add a mode to the stacker to be set on a channel * @param bi The client to set the modes from * @param c The channel * @param cm The channel mode - * @param Set true for setting, false for removing - * @param Param The param, if there is one + * @param set true for setting, false for removing + * @param param The param, if there is one */ - static void StackerAdd(const BotInfo *bi, Channel *c, ChannelMode *cm, bool Set, const Anope::string &Param = ""); + static void StackerAdd(const BotInfo *bi, Channel *c, ChannelMode *cm, bool set, const Anope::string ¶m = ""); /** Add a mode to the stacker to be set on a user * @param bi The client to set the modes from * @param u The user * @param um The user mode - * @param Set true for setting, false for removing + * @param set true for setting, false for removing * @param param The param, if there is one */ - static void StackerAdd(const BotInfo *bi, User *u, UserMode *um, bool Set, const Anope::string &Param = ""); + static void StackerAdd(const BotInfo *bi, User *u, UserMode *um, bool set, const Anope::string ¶m = ""); /** Process all of the modes in the stacker and send them to the IRCd to be set on channels/users */ static void ProcessModes(); - /** Delete a user or channel from the stacker + /** Delete a user, channel, or mode from the stacker */ static void StackerDel(User *u); static void StackerDel(Channel *c); + static void StackerDel(Mode *m); + + /** Updates the default mode locks and default bot modes + * @param config The configuration to read from. This is often called + * during a config reload. + */ + static void UpdateDefaultMLock(ServerConfig *config); }; /** Entry flags @@ -493,10 +479,10 @@ class CoreExport Entry : public Flags<EntryType> Anope::string nick, user, host; /** Constructor - * @param _host A full nick!ident@host/cidr mask * @param mode What mode this host is for - can be CMODE_BEGIN for unknown/no mode + * @param host A full nick!ident@host/cidr mask */ - Entry(ChannelModeName mode, const Anope::string &_host); + Entry(ChannelModeName mode, const Anope::string &host); /** Get the banned mask for this entry * @return The mask diff --git a/include/module.h b/include/module.h index bba901741..e6b63bdfb 100644 --- a/include/module.h +++ b/include/module.h @@ -18,13 +18,11 @@ #include "anope.h" #include "base.h" #include "bots.h" -#include "botserv.h" #include "channels.h" #include "commands.h" #include "config.h" #include "dns.h" #include "extensible.h" -#include "extern.h" #include "hashcomp.h" #include "language.h" #include "lists.h" @@ -34,7 +32,6 @@ #include "messages.h" #include "modes.h" #include "modules.h" -#include "oper.h" #include "opertype.h" #include "protocol.h" #include "regexpr.h" @@ -50,9 +47,14 @@ #include "timers.h" #include "uplink.h" #include "users.h" +#include "xline.h" +#include "chanserv.h" +#include "botserv.h" #include "global.h" +#include "hostserv.h" #include "memoserv.h" #include "nickserv.h" +#include "operserv.h" #endif // MODULE_H diff --git a/include/modules.h b/include/modules.h index cdaf53fc0..e62ed8e36 100644 --- a/include/modules.h +++ b/include/modules.h @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "serialize.h" @@ -31,7 +32,7 @@ { \ return new x(modname, creator); \ } \ - BOOLEAN WINAPI DllMain(HINSTANCE, DWORD nReason, LPVOID) \ + BOOLEAN WINAPI DllMain(HINSTANCE, DWORD, LPVOID) \ { \ return TRUE; \ } \ @@ -120,7 +121,6 @@ enum EventReturn EVENT_ALLOW }; - enum ModuleReturn { MOD_ERR_OK, @@ -141,26 +141,23 @@ enum Priority { PRIORITY_FIRST, PRIORITY_DONTCARE, PRIORITY_LAST, PRIORITY_BEFOR /* Module types, in the order in which they are unloaded. The order these are in is IMPORTANT */ enum ModType { MT_BEGIN, THIRD, SUPPORTED, CORE, DATABASE, ENCRYPTION, PROTOCOL, MT_END }; -extern CoreExport std::list<Module *> Modules; - +/** Returned by Module::GetVersion, used to see what version of Anope + * a module is compiled against. + */ class ModuleVersion { private: - int Major; - int Minor; - int Patch; + int version_major; + int version_minor; + int version_patch; public: /** Constructor - * @param vMajor The major version numbber - * @param vMinor The minor version numbber - * @param vPatch The patch version numbber - */ - ModuleVersion(int vMajor, int vMinor, int vPatch); - - /** Destructor + * @param major The major version numbber + * @param minor The minor version numbber + * @param patch The patch version numbber */ - virtual ~ModuleVersion(); + ModuleVersion(int major, int minor, int patch); /** Get the major version of Anope this was built against * @return The major version @@ -200,7 +197,7 @@ class CoreExport Module : public Extensible /** Callbacks used in this module */ - std::list<CallBack *> CallBacks; + std::list<CallBack *> callbacks; /** Handle for this module, obtained from dlopen() */ @@ -259,6 +256,14 @@ class CoreExport Module : public Extensible */ ModuleVersion GetVersion() const; + /** Gets the IRCd protocol published by this module + */ + virtual IRCDProto *GetIRCDProto(); + + /* Everything below here are events. Modules must ModuleManager::Attach to these events + * before they will be called. + */ + /** Called when the ircd notifies that a user has been kicked from a channel. * @param c The channel the user has been kicked from. * @param target The user that has been kicked. @@ -290,7 +295,7 @@ class CoreExport Module : public Extensible * @param u The connecting user. * @param exempt set to true/is true if the user should be excepted from bans etc */ - virtual void OnUserConnect(dynamic_reference<User> &u, bool &exempt) { } + virtual void OnUserConnect(Reference<User> &u, bool &exempt) { } /** Called when a new server connects to the network. * @param s The server that has connected to the network @@ -649,9 +654,9 @@ class CoreExport Module : public Extensible * @param source The user requesting info * @param ci The channel the user is requesting info for * @param info Data to show the user requesting information - * @param ShowHidden true if we should show the user everything + * @param show_hidden true if we should show the user everything */ - virtual void OnChanInfo(CommandSource &source, ChannelInfo *ci, InfoFormatter &info, bool ShowHidden) { } + virtual void OnChanInfo(CommandSource &source, ChannelInfo *ci, InfoFormatter &info, bool show_hidden) { } /** Checks if access has the channel privilege 'priv'. * @param access THe access struct @@ -763,9 +768,9 @@ class CoreExport Module : public Extensible * @param source The user requesting info * @param na The nick the user is requesting info from * @param info Data to show the user requesting information - * @param ShowHidden true if we should show the user everything + * @param show_hidden true if we should show the user everything */ - virtual void OnNickInfo(CommandSource &source, NickAlias *na, InfoFormatter &info, bool ShowHidden) { } + virtual void OnNickInfo(CommandSource &source, NickAlias *na, InfoFormatter &info, bool show_hidden) { } /** Check whether a username and password is correct * @param u The user trying to identify, if applicable. @@ -824,32 +829,32 @@ class CoreExport Module : public Extensible /** Called when a mode is set on a channel * @param c The channel * @param setter The user or server that is setting the mode - * @param Name The mode name + * @param mname The mode name * @param param The mode param, if there is one * @return EVENT_STOP to make mlock/secureops etc checks not happen */ - virtual EventReturn OnChannelModeSet(Channel *c, MessageSource &setter, ChannelModeName Name, const Anope::string ¶m) { return EVENT_CONTINUE; } + virtual EventReturn OnChannelModeSet(Channel *c, MessageSource &setter, ChannelModeName mname, const Anope::string ¶m) { return EVENT_CONTINUE; } /** Called when a mode is unset on a channel * @param c The channel * @param setter The user or server that is unsetting the mode - * @param Name The mode name + * @param mname The mode name * @param param The mode param, if there is one * @return EVENT_STOP to make mlock/secureops etc checks not happen */ - virtual EventReturn OnChannelModeUnset(Channel *c, MessageSource &setter, ChannelModeName Name, const Anope::string ¶m) { return EVENT_CONTINUE; } + virtual EventReturn OnChannelModeUnset(Channel *c, MessageSource &setter, ChannelModeName mname, const Anope::string ¶m) { return EVENT_CONTINUE; } /** Called when a mode is set on a user * @param u The user - * @param Name The mode name + * @param mname The mode name */ - virtual void OnUserModeSet(User *u, UserModeName Name) { } + virtual void OnUserModeSet(User *u, UserModeName mname) { } /** Called when a mode is unset from a user * @param u The user - * @param Name The mode name + * @param mname The mode name */ - virtual void OnUserModeUnset(User *u, UserModeName Name) { } + virtual void OnUserModeUnset(User *u, UserModeName mname) { } /** Called when a channel mode is introducted into Anope * @param cm The mode @@ -921,7 +926,7 @@ class CoreExport Module : public Extensible * @param req The dns request * @param reply The reply that will be sent */ - virtual void OnDnsRequest(DNSPacket &req, DNSPacket *reply) { } + virtual void OnDnsRequest(DNS::Packet &req, DNS::Packet *reply) { } /** Called when a channels modes are being checked to see if they are allowed, * mostly to ensure mlock/+r are set. @@ -930,7 +935,7 @@ class CoreExport Module : public Extensible */ virtual EventReturn OnCheckModes(Channel *c) { return EVENT_CONTINUE; } - virtual void OnSerializeCheck(SerializeType *) { } + virtual void OnSerializeCheck(Serialize::Type *) { } virtual void OnSerializableConstruct(Serializable *) { } virtual void OnSerializableDestruct(Serializable *) { } virtual void OnSerializableUpdate(Serializable *) { } @@ -1012,6 +1017,10 @@ enum Implementation class CoreExport ModuleManager { public: + /** List of all modules loaded in Anope + */ + static CoreExport std::list<Module *> Modules; + /** Event handler hooks. * This needs to be public to be used by FOREACH_MOD and friends. */ @@ -1124,7 +1133,8 @@ class CoreExport ModuleManager static ModuleReturn DeleteModule(Module *m); }; -/** Class used for callbacks within modules +/** Class used for callbacks within modules. These are identical to Timers hwoever + * they will be cleaned up automatically when a module is unloaded, and Timers will not. */ class CoreExport CallBack : public Timer { diff --git a/include/opertype.h b/include/opertype.h index 4e3f01e28..ccba85141 100644 --- a/include/opertype.h +++ b/include/opertype.h @@ -3,6 +3,7 @@ * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #ifndef OPERTYPE_H @@ -11,15 +12,22 @@ #include "services.h" #include "account.h" +/* A services operator. Usually made by the configuration file, but not always. + * NickAlias::Find(name)->nc->o == this + */ struct CoreExport Oper { + /* The oper's nick */ Anope::string name; + /* The type of operator this operator is */ OperType *ot; + /* Whether the user must be an IRC operator (umode +o) to be considered a services operator */ bool require_oper; Anope::string password; Anope::string certfp; + /* True if this operator is set in the config */ bool config; - + /* Hosts allowed to use this operator block */ std::vector<Anope::string> hosts; Anope::string vhost; diff --git a/include/protocol.h b/include/protocol.h index 4da0b5b3a..ec7061d38 100644 --- a/include/protocol.h +++ b/include/protocol.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef PROTOCOL_H @@ -16,14 +15,17 @@ #include "services.h" #include "anope.h" +#include "service.h" +/* Encapsultes the IRCd protocol we are speaking. */ class CoreExport IRCDProto { Anope::string proto_name; - IRCDProto() { } protected: IRCDProto(const Anope::string &proto_name); + public: + virtual ~IRCDProto(); virtual void SendSVSKillInternal(const BotInfo *, User *, const Anope::string &); virtual void SendModeInternal(const BotInfo *, const Channel *, const Anope::string &); @@ -37,8 +39,6 @@ class CoreExport IRCDProto virtual void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf); virtual void SendCTCPInternal(const BotInfo *bi, const Anope::string &dest, const Anope::string &buf); virtual void SendNumericInternal(int numeric, const Anope::string &dest, const Anope::string &buf); - public: - virtual ~IRCDProto(); const Anope::string &GetProtocolName(); /* Modes used by default by our clients */ @@ -66,53 +66,135 @@ class CoreExport IRCDProto /* The maximum number of modes we are allowed to set with one MODE command */ unsigned MaxModes; - virtual void SendSVSNOOP(const Server *, bool) { } + /** Sets the server in NOOP mode. If NOOP mode is enabled, no users + * will be able to oper on the server. + * @param s The server + * @param mode Whether to turn NOOP on or off + */ + virtual void SendSVSNOOP(const Server *s, bool mode) { } + + /** Sets the topic on a channel + * @param bi The bot to set the topic from + * @param c The channel to set the topic on. The topic being set is Channel::topic + */ virtual void SendTopic(BotInfo *, Channel *); + + /** Sets a vhost on a user. + * @param u The user + * @param vident The ident to set + * @param vhost The vhost to set + */ + virtual void SendVhost(User *u, const Anope::string &vident, const Anope::string &vhost) { } virtual void SendVhostDel(User *) { } + + /** Sets an akill. This is a recursive function that can be called multiple times + * for the same xline, but for different users, if the xline is not one that can be + * enforced by the IRCd, such as a nick/user/host/realname combination ban. + * @param u The user affected by the akill, if known + * @param x The akill + */ virtual void SendAkill(User *, XLine *) = 0; virtual void SendAkillDel(const XLine *) = 0; + + /* Realname ban */ + virtual void SendSGLine(User *, const XLine *) { } + virtual void SendSGLineDel(const XLine *) { } + + /* IP ban */ + virtual void SendSZLine(User *u, const XLine *) { } + virtual void SendSZLineDel(const XLine *) { } + + /* Nick ban (and sometimes channel) */ + virtual void SendSQLine(User *, const XLine *x) { } + virtual void SendSQLineDel(const XLine *x) { } + + /** Kills a user + * @param source The client used to kill the user, if any + * @param user The user to be killed + * @param fmt Kill reason + */ virtual void SendSVSKill(const BotInfo *source, User *user, const char *fmt, ...); + virtual void SendMode(const BotInfo *bi, const Channel *dest, const char *fmt, ...); virtual void SendMode(const BotInfo *bi, const User *u, const char *fmt, ...); + + /** Introduces a client to the rest of the network + * @param u The client to introduce + */ virtual void SendClientIntroduction(const User *u) = 0; + virtual void SendKick(const BotInfo *bi, const Channel *chan, const User *user, const char *fmt, ...); + + /* Sends a message using SendPrivmsg or SendNotice, depending on the default message method. */ virtual void SendMessage(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); virtual void SendNotice(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); - virtual void SendAction(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); virtual void SendPrivmsg(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); + virtual void SendAction(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); + virtual void SendCTCP(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); + virtual void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) = 0; virtual void SendGlobalPrivmsg(const BotInfo *bi, const Server *desc, const Anope::string &msg) = 0; virtual void SendQuit(const User *u, const char *fmt, ...); virtual void SendPing(const Anope::string &servname, const Anope::string &who); virtual void SendPong(const Anope::string &servname, const Anope::string &who); - virtual void SendJoin(const User *, Channel *, const ChannelStatus *) = 0; - virtual void SendSQLineDel(const XLine *x) { } - virtual void SendInvite(const BotInfo *bi, const Channel *c, const User *u); + + /** Joins one of our users to a channel. + * @param u The user to join + * @param c The channel to join the user to + * @param status The status to set on the user after joining. This may or may not already internally + * be set on the user. This may include the modes in the join, but will usually place them on the mode + * stacker to be set "soon". + */ + virtual void SendJoin(const User *u, Channel *c, const ChannelStatus *status) = 0; virtual void SendPart(const BotInfo *bi, const Channel *chan, const char *fmt, ...); + + /** Force joins a user that isn't ours to a channel. + * @param bi The source of the message + * @param nick The user to join + * @param chan The channel to join the user to + * @param param Channel key? + */ + virtual void SendSVSJoin(const BotInfo *bi, const Anope::string &nick, const Anope::string &chan, const Anope::string ¶m) { } + + virtual void SendInvite(const BotInfo *bi, const Channel *c, const User *u); virtual void SendGlobops(const BotInfo *source, const char *fmt, ...); - virtual void SendSQLine(User *, const XLine *x) { } - virtual void SendSquit(Server *, const Anope::string &message); + + /** Sets oper flags on a user, currently only supported by Unreal + */ virtual void SendSVSO(const BotInfo *, const Anope::string &, const Anope::string &) { } - virtual void SendChangeBotNick(const BotInfo *bi, const Anope::string &newnick); + + /** Sends a nick change of one of our clients. + */ + virtual void SendNickChange(const User *u, const Anope::string &newnick); + + /** Forces a nick change of a user that isn't ours (SVSNICK) + */ virtual void SendForceNickChange(const User *u, const Anope::string &newnick, time_t when); - virtual void SendVhost(User *, const Anope::string &, const Anope::string &) { } + + /** Used to introduce ourselves to our uplink. Usually will SendServer(Me) and any other + * initial handshake requirements. + */ virtual void SendConnect() = 0; + + /** Called right before we begin our burst, after we have handshaked successfully with the uplink/ + * At this point none of our servesr, users, or channels exist on the uplink + */ + virtual void SendBOB() { } + virtual void SendEOB() { } + virtual void SendSVSHold(const Anope::string &) { } virtual void SendSVSHoldDel(const Anope::string &) { } - virtual void SendSGLineDel(const XLine *) { } - virtual void SendSZLineDel(const XLine *) { } - virtual void SendSZLine(User *u, const XLine *) { } - virtual void SendSGLine(User *, const XLine *) { } - virtual void SendCTCP(const BotInfo *bi, const Anope::string &dest, const char *fmt, ...); - virtual void SendSVSJoin(const BotInfo *bi, const Anope::string &, const Anope::string &, const Anope::string &) { } + virtual void SendSWhois(const BotInfo *bi, const Anope::string &, const Anope::string &) { } - virtual void SendBOB() { } - virtual void SendEOB() { } + + /** Introduces a server to the uplink + */ virtual void SendServer(const Server *) = 0; - virtual bool IsNickValid(const Anope::string &) { return true; } - virtual bool IsChannelValid(const Anope::string &); + virtual void SendSquit(Server *, const Anope::string &message); + virtual void SendNumeric(int numeric, const Anope::string &dest, const char *fmt, ...); + virtual void SendLogin(User *u) = 0; virtual void SendLogout(User *u) = 0; @@ -125,6 +207,11 @@ class CoreExport IRCDProto * Normally this is a simple +o, though some IRCds require us to send the oper type */ virtual void SendOper(User *u); + + virtual bool IsNickValid(const Anope::string &); + virtual bool IsChannelValid(const Anope::string &); + virtual bool IsIdentValid(const Anope::string &); + virtual bool IsHostValid(const Anope::string &); }; enum IRCDMessageFlag @@ -150,21 +237,16 @@ class CoreExport MessageSource Server *GetServer(); }; -class CoreExport IRCDMessage : public Flags<IRCDMessageFlag, 3> +class CoreExport IRCDMessage : public Flags<IRCDMessageFlag>, public Service { - static std::map<Anope::string, std::vector<IRCDMessage *> > messages; - Anope::string name; unsigned param_count; public: - static const std::vector<IRCDMessage *> *Find(const Anope::string &name); - - IRCDMessage(const Anope::string &n, unsigned p = 0); - ~IRCDMessage(); + IRCDMessage(Module *owner, const Anope::string &n, unsigned p = 0); unsigned GetParamCount() const; virtual bool Run(MessageSource &, const std::vector<Anope::string> ¶ms) = 0; }; -extern CoreExport IRCDProto *ircdproto; +extern CoreExport IRCDProto *IRCD; #endif // PROTOCOL_H diff --git a/include/regchannel.h b/include/regchannel.h index a692dda4a..9e01963b8 100644 --- a/include/regchannel.h +++ b/include/regchannel.h @@ -1,15 +1,15 @@ -/* Modular support +/* * * (C) 2008-2012 Anope Team * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ #ifndef REGCHANNEL_H #define REGCHANNEL_H -#include "botserv.h" #include "memo.h" #include "modes.h" #include "extensible.h" @@ -20,7 +20,7 @@ typedef Anope::hash_map<ChannelInfo *> registered_channel_map; -extern CoreExport serialize_checker<registered_channel_map> RegisteredChannelList; +extern CoreExport Serialize::Checker<registered_channel_map> RegisteredChannelList; /** Flags used for the ChannelInfo class */ @@ -68,10 +68,57 @@ enum ChannelInfoFlag CI_END }; -const Anope::string ChannelInfoFlagStrings[] = { - "BEGIN", "KEEPTOPIC", "SECUREOPS", "PRIVATE", "TOPICLOCK", "RESTRICTED", - "PEACE", "SECURE", "NO_EXPIRE", "MEMO_HARDMAX", "SECUREFOUNDER", - "SIGNKICK", "SIGNKICK_LEVEL", "SUSPENDED", "PERSIST", "STATS", "NOAUTOOP", "" +/* BotServ SET flags (ChannelInfo::botflags) */ +enum BotServFlag +{ + BS_BEGIN, + /* BotServ won't kick ops */ + BS_DONTKICKOPS, + /* BotServ won't kick voices */ + BS_DONTKICKVOICES, + /* BotServ bot accepts fantasy commands */ + BS_FANTASY, + /* BotServ should show greets */ + BS_GREET, + /* BotServ bots are not allowed to be in this channel */ + BS_NOBOT, + /* BotServ kicks for bolds */ + BS_KICK_BOLDS, + /* BotServ kicks for colors */ + BS_KICK_COLORS, + /* BOtServ kicks for reverses */ + BS_KICK_REVERSES, + /* BotServ kicks for underlines */ + BS_KICK_UNDERLINES, + /* BotServ kicks for badwords */ + BS_KICK_BADWORDS, + /* BotServ kicks for caps */ + BS_KICK_CAPS, + /* BotServ kicks for flood */ + BS_KICK_FLOOD, + /* BotServ kicks for repeating */ + BS_KICK_REPEAT, + /* BotServ kicks for italics */ + BS_KICK_ITALICS, + /* BotServ kicks for amsgs */ + BS_KICK_AMSGS, + BS_END +}; + +/* Indices for TTB (Times To Ban) */ +enum +{ + TTB_BOLDS, + TTB_COLORS, + TTB_REVERSES, + TTB_UNDERLINES, + TTB_BADWORDS, + TTB_CAPS, + TTB_FLOOD, + TTB_REPEAT, + TTB_ITALICS, + TTB_AMSGS, + TTB_SIZE }; /** Flags for badwords @@ -96,8 +143,8 @@ struct CoreExport BadWord : Serializable BadWordType type; BadWord() : Serializable("BadWord") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); }; /** Flags for auto kick @@ -108,31 +155,31 @@ enum AutoKickFlag AK_ISNICK }; -const Anope::string AutoKickFlagString[] = { "AK_ISNICK", "" }; - /* AutoKick data. */ class CoreExport AutoKick : public Flags<AutoKickFlag>, public Serializable { public: - AutoKick(); - serialize_obj<ChannelInfo> ci; - /* Only one of these can be in use */ + /* Channel this autokick is on */ + Serialize::Reference<ChannelInfo> ci; + + /* Only one of these can be in use. if HasFlag(AK_ISNICK) then nc is in use */ Anope::string mask; - serialize_obj<NickCore> nc; + Serialize::Reference<NickCore> nc; Anope::string reason; Anope::string creator; time_t addtime; time_t last_used; - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + AutoKick(); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); }; struct CoreExport ModeLock : Serializable { public: - serialize_obj<ChannelInfo> ci; + Serialize::Reference<ChannelInfo> ci; bool set; ChannelModeName name; Anope::string param; @@ -141,13 +188,13 @@ struct CoreExport ModeLock : Serializable ModeLock(ChannelInfo *ch, bool s, ChannelModeName n, const Anope::string &p, const Anope::string &se = "", time_t c = Anope::CurTime); - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); }; struct CoreExport LogSetting : Serializable { - serialize_obj<ChannelInfo> ci; + Serialize::Reference<ChannelInfo> ci; /* Our service name of the command */ Anope::string service_name; /* The name of the client the command is on */ @@ -159,67 +206,65 @@ struct CoreExport LogSetting : Serializable time_t created; LogSetting() : Serializable("LogSetting") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); }; /* It matters that Base is here before Extensible (it is inherited by Serializable) */ -class CoreExport ChannelInfo : public Serializable, public Extensible, public Flags<ChannelInfoFlag, CI_END> +class CoreExport ChannelInfo : public Serializable, public Extensible, public Flags<ChannelInfoFlag> { private: - serialize_obj<NickCore> founder; /* Channel founder */ - serialize_checker<std::vector<ChanAccess *> > access; /* List of authorized users */ - serialize_checker<std::vector<AutoKick *> > akick; /* List of users to kickban */ - serialize_checker<std::vector<BadWord *> > badwords; /* List of badwords */ + Serialize::Reference<NickCore> founder; /* Channel founder */ + Serialize::Checker<std::vector<ChanAccess *> > access; /* List of authorized users */ + Serialize::Checker<std::vector<AutoKick *> > akick; /* List of users to kickban */ + Serialize::Checker<std::vector<BadWord *> > badwords; /* List of badwords */ std::map<Anope::string, int16_t> levels; public: typedef std::multimap<ChannelModeName, ModeLock *> ModeList; - serialize_checker<ModeList> mode_locks; - serialize_checker<std::vector<LogSetting *> > log_settings; - - /** Default constructor - * @param chname The channel name - */ - ChannelInfo(const Anope::string &chname); - - /** Copy constructor - * @param ci The ChannelInfo to copy settings to - */ - ChannelInfo(const ChannelInfo &ci); - - /** Default destructor - */ - ~ChannelInfo(); + Serialize::Checker<ModeList> mode_locks; + Serialize::Checker<std::vector<LogSetting *> > log_settings; - Anope::string name; /* Channel name */ - serialize_obj<NickCore> successor; /* Who gets the channel if the founder nick is dropped or expires */ + Anope::string name; /* Channel name */ + Serialize::Reference<NickCore> successor; /* Who gets the channel if the founder nick is dropped or expires */ Anope::string desc; time_t time_registered; time_t last_used; - Anope::string last_topic; /* The last topic that was set on this channel */ - Anope::string last_topic_setter; /* Setter */ - time_t last_topic_time; /* Time */ + Anope::string last_topic; /* The last topic that was set on this channel */ + Anope::string last_topic_setter; /* Setter */ + time_t last_topic_time; /* Time */ int16_t bantype; MemoInfo memos; - Channel *c; /* Pointer to channel record (if channel is currently in use) */ + Channel *c; /* Pointer to channel, if the channel exists */ /* For BotServ */ - serialize_obj<BotInfo> bi; /* Bot used on this channel */ + Serialize::Reference<BotInfo> bi; /* Bot used on this channel */ Flags<BotServFlag> botflags; - int16_t ttb[TTB_SIZE]; /* Times to ban for each kicker */ + int16_t ttb[TTB_SIZE]; /* Times to ban for each kicker */ + + int16_t capsmin, capspercent; /* For CAPS kicker */ + int16_t floodlines, floodsecs; /* For FLOOD kicker */ + int16_t repeattimes; /* For REPEAT kicker */ - int16_t capsmin, capspercent; /* For CAPS kicker */ - int16_t floodlines, floodsecs; /* For FLOOD kicker */ - int16_t repeattimes; /* For REPEAT kicker */ + /** Constructor + * @param chname The channel name + */ + ChannelInfo(const Anope::string &chname); - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &); + /** Copy constructor + * @param ci The ChannelInfo to copy settings to + */ + ChannelInfo(const ChannelInfo &ci); + + ~ChannelInfo(); + + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &); /** Change the founder of the channek * @params nc The new founder @@ -440,11 +485,26 @@ class CoreExport ChannelInfo : public Serializable, public Extensible, public Fl /** Clear all privileges from the channel */ void ClearLevels(); + + /** Gets a ban mask for the given user based on the bantype + * of the channel. + * @param u The user + * @return A ban mask that affects the user + */ + Anope::string GetIdealBan(User *u) const; + + /** Finds a ChannelInfo + * @param name channel name to lookup + * @return the ChannelInfo associated with the channel + */ + static ChannelInfo* Find(const Anope::string &name); }; -extern CoreExport ChannelInfo *cs_findchan(const Anope::string &chan); +/** Is the user the real founder? + * @param user The user + * @param ci The channel + * @return true or false + */ extern CoreExport bool IsFounder(const User *user, const ChannelInfo *ci); -extern CoreExport void update_cs_lastseen(User *user, ChannelInfo *ci); -extern CoreExport int get_idealban(const ChannelInfo *ci, User *u, Anope::string &ret); #endif // REGCHANNEL_H diff --git a/include/serialize.h b/include/serialize.h index 53bd096de..8b8497c40 100644 --- a/include/serialize.h +++ b/include/serialize.h @@ -25,54 +25,65 @@ namespace Serialize DT_TEXT, DT_INT }; -} -class CoreExport stringstream : public std::stringstream -{ - private: - Serialize::DataType type; - unsigned _max; + class CoreExport stringstream : public std::stringstream + { + private: + Serialize::DataType type; + unsigned _max; - public: - stringstream(); - stringstream(const stringstream &ss); - Anope::string astr() const; + public: + stringstream(); + stringstream(const stringstream &ss); + Anope::string astr() const; - template<typename T> std::istream &operator>>(T &val) - { - std::istringstream is(this->str()); - is >> val; - return *this; - } - std::istream &operator>>(Anope::string &val); + template<typename T> std::istream &operator>>(T &val) + { + std::istringstream is(this->str()); + is >> val; + return *this; + } + std::istream &operator>>(Anope::string &val); - bool operator==(const stringstream &other) const; - bool operator!=(const stringstream &other) const; + bool operator==(const stringstream &other) const; + bool operator!=(const stringstream &other) const; - stringstream &setType(Serialize::DataType t); - Serialize::DataType getType() const; - stringstream &setMax(unsigned m); - unsigned getMax() const; -}; + stringstream &SetType(Serialize::DataType t); + Serialize::DataType GetType() const; + stringstream &SetMax(unsigned m); + unsigned GetMax() const; + }; -namespace Serialize -{ typedef std::map<Anope::string, stringstream> Data; -} -extern void RegisterTypes(); + extern void RegisterTypes(); -class SerializeType; + class Type; + template<typename T> class Checker; + template<typename T> class Reference; +} +/** A serialziable object. Serializable objects can be serialized into + * a map of stringstreams (Serialize::Data), and then reconstructed or + * updated later at any time. + */ class CoreExport Serializable : public virtual Base { private: - static std::list<Serializable *> *serializable_items; - SerializeType *s_type; + /* A list of every serializable item in Anope. + * Some of these are static and constructed at runtime, + * so this list must be on the heap, as it is not always + * constructed before other objects are if it isn't. + */ + static std::list<Serializable *> *SerializableItems; + /* The type of item this object is */ + Serialize::Type *s_type; private: - std::list<Serializable *>::iterator s_iter; // Iterator into serializable_items - + /* Iterator into serializable_items */ + std::list<Serializable *>::iterator s_iter; + /* The last serialized form of this object commited to the database */ Serialize::Data last_commit; + /* The last time this object was commited to the database */ time_t last_commit_time; Serializable(); @@ -85,10 +96,16 @@ class CoreExport Serializable : public virtual Base Serializable &operator=(const Serializable &); public: + /* Unique ID (per type, not globally) for this object */ unsigned int id; - void destroy(); + /* Destroys this object. This is effectively the same thing as + * delete, however it properly cleans up after this object. + */ + void Destroy(); + /** Marks the object as potentially being updated "soon". + */ void QueueUpdate(); bool IsCached(); @@ -97,27 +114,43 @@ class CoreExport Serializable : public virtual Base bool IsTSCached(); void UpdateTS(); - SerializeType* GetSerializableType() const; + /** Get the type of serializable object this is + * @return The serializable object type + */ + Serialize::Type* GetSerializableType() const; - virtual Serialize::Data serialize() const = 0; + virtual Serialize::Data Serialize() const = 0; static const std::list<Serializable *> &GetItems(); }; -class CoreExport SerializeType +/* A serializable type. There should be one of these classes for each type + * of class that inherits from Serialiable. Used for unserializing objects + * of this type, as it requires a function pointer to a static member function. + */ +class CoreExport Serialize::Type { typedef Serializable* (*unserialize_func)(Serializable *obj, Serialize::Data &); - static std::vector<Anope::string> type_order; - static std::map<Anope::string, SerializeType *> types; + static std::vector<Anope::string> TypeOrder; + static std::map<Anope::string, Serialize::Type *> Types; + /* The name of this type, should be a class name */ Anope::string name; unserialize_func unserialize; + /* Owner of this type. Used for placing objects of this type in separate databases + * based on what module, if any, owns it. + */ Module *owner; + /* The timesatmp for this type. All objects of this type are as up to date as + * this timestamp. if curtime == timestamp then we have the most up to date + * version of every object of this type. + */ time_t timestamp; public: + /* Map of Serializable::id to Serializable objects */ std::map<unsigned int, Serializable *> objects; /** Creates a new serializable type @@ -125,44 +158,67 @@ class CoreExport SerializeType * @param f Func to unserialize objects * @param owner Owner of this type. Leave NULL for the core. */ - SerializeType(const Anope::string &n, unserialize_func f, Module *owner = NULL); - ~SerializeType(); + Type(const Anope::string &n, unserialize_func f, Module *owner = NULL); + ~Type(); + /** Gets the name for this type + * @return The name, eg "NickAlias" + */ const Anope::string &GetName(); + /** Unserialized an object. + * @param obj NULL if this object doesn't yet exist. If this isn't NULL, instead + * update the contents of this object. + * @param data The data to unserialize + * @return The unserialized object. If obj != NULL this should be obj. + */ Serializable *Unserialize(Serializable *obj, Serialize::Data &data); + /** Check if this object type has any pending changes and update them. + */ void Check(); + /** Gets the timestamp for the object type. That is, the time we know + * all objects of this type are updated at least to. + */ time_t GetTimestamp() const; + + /** Bumps object type timestamp to current time + */ void UpdateTimestamp(); Module* GetOwner() const; - static SerializeType *Find(const Anope::string &name); + static Serialize::Type *Find(const Anope::string &name); static const std::vector<Anope::string> &GetTypeOrder(); }; +/** Should be used to hold lists and other objects of a specific type, + * but not a specific object. Used for ensuring that any access to + * this object type is always up to date. These are usually constructed + * at run time, before main is called, so no types are registered. This + * is why there are static Serialize::Type* variables in every function. + */ template<typename T> -class serialize_checker +class Serialize::Checker { Anope::string name; T obj; public: - serialize_checker(const Anope::string &n) : name(n) { } + Checker(const Anope::string &n) : name(n) { } inline const T* operator->() const { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return &this->obj; } inline T* operator->() { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return &this->obj; @@ -170,14 +226,14 @@ class serialize_checker inline const T& operator*() const { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return this->obj; } inline T& operator*() { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return this->obj; @@ -185,44 +241,50 @@ class serialize_checker inline operator const T&() const { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return this->obj; } inline operator T&() { - static SerializeType *type = SerializeType::Find(this->name); + static Serialize::Type *type = Serialize::Type::Find(this->name); if (type) type->Check(); return this->obj; } }; +/** Used to hold references to serializable objects. Reference should always be + * used when holding references to serializable objects for extended periods of time + * to ensure that the object it refers to it always up to date. This also behaves like + * Reference in that it will invalidate itself if the object it refers to is + * destructed. + */ template<typename T> -class serialize_obj : public dynamic_reference_base +class Serialize::Reference : public ReferenceBase { protected: T *ref; public: - serialize_obj() : ref(NULL) + Reference() : ref(NULL) { } - serialize_obj(T *obj) : ref(obj) + Reference(T *obj) : ref(obj) { if (obj) obj->AddReference(this); } - serialize_obj(const serialize_obj<T> &other) : ref(other.ref) + Reference(const Reference<T> &other) : ref(other.ref) { if (*this) this->ref->AddReference(this); } - ~serialize_obj() + ~Reference() { if (*this) this->ref->DelReference(this); diff --git a/include/servers.h b/include/servers.h index 339b4db19..216679cc0 100644 --- a/include/servers.h +++ b/include/servers.h @@ -1,3 +1,15 @@ +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + #ifndef SERVERS_H #define SERVERS_H @@ -5,13 +17,25 @@ #include "anope.h" #include "extensible.h" -/* Anope */ +/* Anope. We are at the top of the server tree, our uplink is + * almost always me->GetLinks()[0]. We never have an uplink. */ extern CoreExport Server *Me; -extern CoreExport const Anope::string ts6_uid_retrieve(); -extern CoreExport const Anope::string ts6_sid_retrieve(); +namespace Servers +{ + /* Retrieves the next free TS6 UID or SID */ + extern CoreExport const Anope::string TS6_UID_Retrieve(); + extern CoreExport const Anope::string TS6_SID_Retrieve(); + + /* Gets our uplink. Note we don't actually have an "uplink", this is just + * the only server whose uplink *is* Me that is not a juped server. + * @return Our uplink, or NULL if not uplinked to anything + */ + extern CoreExport Server* GetUplink(); -extern CoreExport std::set<Anope::string> Capab; + /* CAPAB/PROTOCTL given by the uplink */ + extern CoreExport std::set<Anope::string> Capab; +} /** Flags set on servers */ @@ -24,28 +48,26 @@ enum ServerFlag SERVER_JUPED }; -const Anope::string ServerFlagStrings[] = { "SERVER_NONE", "SERVER_SYNCING", "SERVER_JUPED", "" }; - /** Class representing a server */ class CoreExport Server : public Flags<ServerFlag>, public Extensible { private: /* Server name */ - Anope::string Name; + Anope::string name; /* Hops between services and server */ - unsigned int Hops; + unsigned int hops; /* Server description */ - Anope::string Description; + Anope::string description; /* Server ID */ - Anope::string SID; + Anope::string sid; /* Links for this server */ - std::vector<Server *> Links; + std::vector<Server *> links; /* Uplink for this server */ - Server *UplinkServer; + Server *uplink; /* Reason this server was quit */ - Anope::string QReason; + Anope::string quit_reason; public: /** Constructor @@ -65,7 +87,7 @@ class CoreExport Server : public Flags<ServerFlag>, public Extensible public: /* Number of users on the server */ - unsigned Users; + unsigned users; /** Delete this server with a reason * @param reason The reason @@ -125,7 +147,7 @@ class CoreExport Server : public Flags<ServerFlag>, public Extensible /** Finish syncing this server and optionally all links to it * @param SyncLinks True to sync the links for this server too (if any) */ - void Sync(bool SyncLinks); + void Sync(bool sync_links); /** Check if this server is synced * @return true or false diff --git a/include/service.h b/include/service.h index 95c650076..f2f553eb2 100644 --- a/include/service.h +++ b/include/service.h @@ -1,4 +1,5 @@ /* + * * (C) 2003-2012 Anope Team * Contact us at team@anope.org * @@ -6,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef SERVICE_H @@ -15,18 +17,34 @@ #include "anope.h" #include "modules.h" +/** Anything that inherits from this class can be referred to + * using ServiceReference. Any interfaces provided by modules, + * such as commands, use this. This is also used for modules + * that publish a service (m_ssl, etc). + */ class CoreExport Service : public virtual Base { - static std::map<Anope::string, std::map<Anope::string, Service *> > services; + static std::map<Anope::string, std::map<Anope::string, Service *> > Services; + static std::map<Anope::string, std::map<Anope::string, Anope::string> > Aliases; public: static Service *FindService(const Anope::string &t, const Anope::string &n) { - std::map<Anope::string, std::map<Anope::string, Service *> >::iterator it = services.find(t); - if (it != services.end()) + std::map<Anope::string, std::map<Anope::string, Service *> >::iterator it = Services.find(t); + if (it != Services.end()) { - std::map<Anope::string, Service *>::iterator it2 = it->second.find(n); - if (it2 != it->second.end()) - return it2->second; + Anope::string name = n; + + std::map<Anope::string, std::map<Anope::string, Anope::string> >::iterator it2 = Aliases.find(t); + if (it2 != Aliases.end()) + { + std::map<Anope::string, Anope::string>::iterator it3 = it2->second.find(n); + if (it3 != it2->second.end()) + name = it3->second; + } + + std::map<Anope::string, Service *>::iterator it4 = it->second.find(name); + if (it4 != it->second.end()) + return it4->second; } return NULL; @@ -35,15 +53,31 @@ class CoreExport Service : public virtual Base static std::vector<Anope::string> GetServiceKeys(const Anope::string &t) { std::vector<Anope::string> keys; - std::map<Anope::string, std::map<Anope::string, Service *> >::iterator it = services.find(t); - if (it != services.end()) + std::map<Anope::string, std::map<Anope::string, Service *> >::iterator it = Services.find(t); + if (it != Services.end()) for (std::map<Anope::string, Service *>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) keys.push_back(it2->first); return keys; } + static void AddAlias(const Anope::string &t, const Anope::string &n, const Anope::string &v) + { + std::map<Anope::string, Anope::string> &smap = Aliases[t]; + smap[n] = v; + } + + static void DelAlias(const Anope::string &t, const Anope::string &n) + { + std::map<Anope::string, Anope::string> &smap = Aliases[t]; + smap.erase(n); + if (smap.empty()) + Aliases.erase(t); + } + Module *owner; + /* Service type, which should be the class name (eg "Command") */ Anope::string type; + /* Service name, commands are usually named service/command */ Anope::string name; Service(Module *o, const Anope::string &t, const Anope::string &n) : owner(o), type(t), name(n) @@ -58,7 +92,7 @@ class CoreExport Service : public virtual Base void Register() { - std::map<Anope::string, Service *> &smap = services[this->type]; + std::map<Anope::string, Service *> &smap = Services[this->type]; if (smap.find(this->name) != smap.end()) throw ModuleException("Service " + this->type + " with name " + this->name + " already exists"); smap[this->name] = this; @@ -66,29 +100,32 @@ class CoreExport Service : public virtual Base void Unregister() { - std::map<Anope::string, Service *> &smap = services[this->type]; + std::map<Anope::string, Service *> &smap = Services[this->type]; smap.erase(this->name); if (smap.empty()) - services.erase(this->type); + Services.erase(this->type); } }; +/** Like Reference, but used to refer to Services. + */ template<typename T> -class service_reference : public dynamic_reference<T> +class ServiceReference : public Reference<T> { Anope::string type; Anope::string name; public: - service_reference() : dynamic_reference<T>(NULL) { } + ServiceReference() { } - service_reference(const Anope::string &t, const Anope::string &n) : dynamic_reference<T>(NULL), type(t), name(n) + ServiceReference(const Anope::string &t, const Anope::string &n) : type(t), name(n) { } inline void operator=(const Anope::string &n) { this->name = n; + this->invalid = true; } operator bool() anope_override @@ -100,6 +137,10 @@ class service_reference : public dynamic_reference<T> } if (!this->ref) { + /* This really could be dynamic_cast in every case, except for when a module + * creates its own service type (that other modules must include the header file + * for), as the core is not compiled with it so there is no RTTI for it. + */ this->ref = static_cast<T *>(Service::FindService(this->type, this->name)); if (this->ref) this->ref->AddReference(this); @@ -108,5 +149,20 @@ class service_reference : public dynamic_reference<T> } }; +class ServiceAlias +{ + Anope::string t, f; + public: + ServiceAlias(const Anope::string &type, const Anope::string &from, const Anope::string &to) : t(type), f(from) + { + Service::AddAlias(type, from, to); + } + + ~ServiceAlias() + { + Service::DelAlias(t, f); + } +}; + #endif // SERVICE_H diff --git a/include/services.h b/include/services.h index 4b21bac2a..0405206d2 100644 --- a/include/services.h +++ b/include/services.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef SERVICES_H @@ -66,13 +65,4 @@ # include "anope_windows.h" #endif -/** - * RFC: defination of a valid nick - * nickname = ( letter / special ) *8( letter / digit / special / "-" ) - * letter = %x41-5A / %x61-7A ; A-Z / a-z - * digit = %x30-39 ; 0-9 - * special = %x5B-60 / %x7B-7D ; "[", "]", "\", "`", "_", "^", "{", "|", "}" - **/ -#define isvalidnick(c) (isalnum(c) || ((c) >= '\x5B' && (c) <= '\x60') || ((c) >= '\x7B' && (c) <= '\x7D') || (c) == '-') - #endif // SERVICES_H diff --git a/include/signals.h b/include/signals.h index f057bdfee..771404f52 100644 --- a/include/signals.h +++ b/include/signals.h @@ -8,7 +8,6 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * */ #ifndef SIGNAL_H diff --git a/include/socketengine.h b/include/socketengine.h index 8effb79f1..5f4bc5980 100644 --- a/include/socketengine.h +++ b/include/socketengine.h @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef SOCKETENGINE_H @@ -17,7 +18,7 @@ class CoreExport SocketEngine { - static const int DefaultSize = 4; // Uplink, DNS, Signal handler, Mode stacker + static const int DefaultSize = 8; // Uplink, DNS, Signal handlers, Mode stacker public: /* Map of sockets */ static std::map<int, Socket *> Sockets; diff --git a/include/sockets.h b/include/sockets.h index 6fa6c4075..24c993d9e 100644 --- a/include/sockets.h +++ b/include/sockets.h @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef SOCKETS_H @@ -104,12 +105,12 @@ class CoreExport cidr class SocketException : public CoreException { public: - /** Default constructor for socket exceptions + /** Constructor for socket exceptions * @param message Error message */ SocketException(const Anope::string &message) : CoreException(message) { } - /** Default destructor + /** Destructor * @throws Nothing */ virtual ~SocketException() throw() { } @@ -126,9 +127,6 @@ enum SocketFlag SF_ACCEPTED }; -static const Anope::string SocketFlagStrings[] = { "SF_DEAD", "SF_WRITABLE", "SF_CONNECTING", "SF_CONNECTED", "SF_ACCEPTING", "SF_ACCEPTED", "" }; - - class CoreExport SocketIO { public: @@ -189,29 +187,29 @@ class CoreExport Socket : public Flags<SocketFlag> { protected: /* Socket FD */ - int Sock; + int sock; /* Is this an IPv6 socket? */ - bool IPv6; + bool ipv6; public: /* Sockaddrs for bind() (if it's bound) */ sockaddrs bindaddr; /* I/O functions used for this socket */ - SocketIO *IO; + SocketIO *io; /** Empty constructor, should not be called. */ Socket(); - /** Default constructor + /** Constructor, possibly creates the socket and adds it to the engine * @param sock The socket to use, -1 if we need to create our own * @param ipv6 true if using ipv6 * @param type The socket type, defaults to SOCK_STREAM */ Socket(int sock, bool ipv6 = false, int type = SOCK_STREAM); - /** Default destructor + /** Destructor, closes the socket and removes it from the engine */ virtual ~Socket(); @@ -225,7 +223,7 @@ class CoreExport Socket : public Flags<SocketFlag> */ bool IsIPv6() const; - /** Mark a socket as blockig + /** Mark a socket as blocking * @return true if the socket is now blocking */ bool SetBlocking(); @@ -266,19 +264,14 @@ class CoreExport BufferedSocket : public virtual Socket { protected: /* Things to be written to the socket */ - Anope::string WriteBuffer; + Anope::string write_buffer; /* Part of a message sent from the server, but not totally received */ - Anope::string extrabuf; - /* How much data was received from this socket */ - int RecvLen; + Anope::string extra_buf; + /* How much data was received from this socket on this recv() */ + int recv_len; public: - /** Constructor - */ BufferedSocket(); - - /** Default destructor - */ virtual ~BufferedSocket(); /** Called when there is something to be received for this socket @@ -330,15 +323,11 @@ class CoreExport BinarySocket : public virtual Socket ~DataBlock(); }; - std::deque<DataBlock *> WriteBuffer; + /* Data to be written out */ + std::deque<DataBlock *> write_buffer; public: - /** Constructor - */ BinarySocket(); - - /** Default destructor - */ virtual ~BinarySocket(); /** Called when there is something to be received for this socket @@ -376,9 +365,6 @@ class CoreExport ListenSocket : public virtual Socket * @param ipv6 true for ipv6 */ ListenSocket(const Anope::string &bindip, int port, bool ipv6); - - /** Destructor - */ virtual ~ListenSocket(); /** Process what has come in from the connection @@ -435,7 +421,7 @@ class CoreExport ClientSocket : public virtual Socket { public: /* Listen socket this connection came from */ - ListenSocket *LS; + ListenSocket *ls; /* Clients address */ sockaddrs clientaddr; @@ -469,19 +455,14 @@ class CoreExport Pipe : public Socket { public: /** The FD of the write pipe (if this isn't evenfd) - * this->Sock is the readfd + * this->sock is the readfd */ - int WritePipe; + int write_pipe; - /** Constructor - */ Pipe(); - - /** Destructor - */ ~Pipe(); - /** Called when data is to be read + /** Called when data is to be read, reads the data then calls OnNotify */ bool ProcessRead() anope_override; @@ -489,13 +470,13 @@ class CoreExport Pipe : public Socket */ void Notify(); - /** Overload to do something useful + /** Called after ProcessRead comes back from Notify(), overload to do something useful */ virtual void OnNotify() = 0; }; extern CoreExport uint32_t TotalRead; extern CoreExport uint32_t TotalWritten; -extern CoreExport SocketIO normalSocketIO; +extern CoreExport SocketIO NormalSocketIO; #endif // SOCKET_H diff --git a/include/threadengine.h b/include/threadengine.h index 5d1752a8f..7eebed22f 100644 --- a/include/threadengine.h +++ b/include/threadengine.h @@ -1,3 +1,15 @@ +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + #ifndef THREADENGINE_H #define THREADENGINE_H @@ -12,7 +24,7 @@ class CoreExport Thread : public Pipe, public Extensible public: /* Handle for this thread */ - pthread_t Handle; + pthread_t handle; /** Threads constructor */ diff --git a/include/timers.h b/include/timers.h index d5fc66fb0..d2597178b 100644 --- a/include/timers.h +++ b/include/timers.h @@ -4,8 +4,10 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. + * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef TIMERS_H @@ -33,14 +35,14 @@ class CoreExport Timer bool repeat; public: - /** Default constructor, initializes the triggering time + /** Constructor, initializes the triggering time * @param time_from_now The number of seconds from now to trigger the timer * @param now The time now * @param repeating Repeat this timer every time_from_now if this is true */ Timer(long time_from_now, time_t now = Anope::CurTime, bool repeating = false); - /** Default destructor, removes the timer from the list + /** Destructor, removes the timer from the list */ virtual ~Timer(); @@ -91,14 +93,14 @@ class CoreExport TimerManager static std::vector<Timer *> Timers; public: /** Add a timer to the list - * @param T A Timer derived class to add + * @param t A Timer derived class to add */ - static void AddTimer(Timer *T); + static void AddTimer(Timer *t); /** Deletes a timer - * @param T A Timer derived class to delete + * @param t A Timer derived class to delete */ - static void DelTimer(Timer *T); + static void DelTimer(Timer *t); /** Tick all pending timers * @param ctime The current time diff --git a/include/uplink.h b/include/uplink.h index 617a8aa1a..d635bd7d3 100644 --- a/include/uplink.h +++ b/include/uplink.h @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #ifndef UPLINK_H @@ -14,6 +15,12 @@ #include "sockets.h" +namespace Uplink +{ + extern void Connect(); +} + +/* This is the socket to our uplink */ class UplinkSocket : public ConnectionSocket, public BufferedSocket { public: @@ -22,10 +29,12 @@ class UplinkSocket : public ConnectionSocket, public BufferedSocket bool Read(const Anope::string &); void OnConnect(); void OnError(const Anope::string &); - + + /* A message sent over the uplink socket */ class CoreExport Message { private: + /* The source of the message, can be a server (Me), or any user (one of our bots) */ const Server *server; const User *user; std::stringstream buffer; diff --git a/include/users.h b/include/users.h index 17f3fac9f..ab7edeee3 100644 --- a/include/users.h +++ b/include/users.h @@ -1,8 +1,14 @@ /* - * Copyright (C) 2008-2011 Robin Burchell <w00t@inspircd.org> - * Copyright (C) 2008-2012 Anope Team <team@anope.org> + * + * (C) 2008-2011 Robin Burchell <w00t@inspircd.org> + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org * * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * */ #ifndef USERS_H @@ -19,18 +25,15 @@ typedef Anope::hash_map<User *> user_map; extern CoreExport user_map UserListByNick, UserListByUID; -class CoreExport ChannelStatus : public Flags<ChannelModeName, CMODE_END * 2> -{ - public: - ChannelStatus(); - Anope::string BuildCharPrefixList() const; - Anope::string BuildModePrefixList() const; -}; +extern CoreExport int OperCount; +extern CoreExport unsigned MaxUserCount; +extern CoreExport time_t MaxUserTime; +/* One per channel per user. Channel and status */ struct ChannelContainer { Channel *chan; - ChannelStatus *Status; + ChannelStatus *status; ChannelContainer(Channel *c) : chan(c) { } virtual ~ChannelContainer() { } @@ -38,7 +41,6 @@ struct ChannelContainer typedef std::list<ChannelContainer *> UChannelList; - /* Online user and channel data. */ class CoreExport User : public virtual Base, public Extensible, public CommandReply { @@ -46,36 +48,55 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe Anope::string vident; Anope::string ident; Anope::string uid; - bool OnAccess; /* If the user is on the access list of the nick theyre on */ - Flags<UserModeName, UMODE_END * 2> modes; /* Bitset of mode names the user has set on them */ - std::map<UserModeName, Anope::string> Params; /* Map of user modes and the params this user has */ - serialize_obj<NickCore> nc; /* NickCore account the user is currently loggged in as */ + /* If the user is on the access list of the nick theyre on */ + bool on_access; + /* Bitset of mode names the user has set on them */ + Flags<UserModeName> modes; + /* Map of user modes and the params this user has */ + std::map<UserModeName, Anope::string> mode_params; + /* NickCore account the user is currently loggged in as, if they are logged in */ + Serialize::Reference<NickCore> nc; + + /* # of invalid password attempts */ + unsigned short invalid_pw_count; + /* Time of last invalid password */ + time_t invalid_pw_time; + public: // XXX: exposing a tiny bit too much - Anope::string nick; /* User's current nick */ - - Anope::string host; /* User's real hostname */ - Anope::string vhost; /* User's virtual hostname */ - Anope::string chost; /* User's cloaked hostname */ - Anope::string realname; /* Realname */ - Anope::string fingerprint; /* SSL Fingerprint */ - Anope::string ip; /* User's IP */ - Server *server; /* Server user is connected to */ - time_t signon; /* When the user signed on. Set on connect and never modified. */ - time_t timestamp; /* Timestamp of the nick. Updated when the nick changes. */ - bool SuperAdmin; /* is SuperAdmin on or off? */ + /* User's current nick */ + Anope::string nick; + + /* User's real hostname */ + Anope::string host; + /* User's virtual hostname */ + Anope::string vhost; + /* User's cloaked hostname */ + Anope::string chost; + /* Realname */ + Anope::string realname; + /* SSL Fingerprint */ + Anope::string fingerprint; + /* User's IP */ + Anope::string ip; + /* Server user is connected to */ + Server *server; + /* When the user signed on. Set on connect and never modified. */ + time_t signon; + /* Timestamp of the nick. Updated when the nick changes. */ + time_t timestamp; + /* Is the user as super admin? */ + bool super_admin; /* Channels the user is in */ UChannelList chans; - unsigned short invalid_pw_count; /* # of invalid password attempts */ - time_t invalid_pw_time; /* Time of last invalid password */ - - time_t lastmemosend; /* Last time MS SEND command used */ - time_t lastnickreg; /* Last time NS REGISTER cmd used */ - time_t lastmail; /* Last time this user sent a mail */ - - /****************************************************************/ + /* Last time this user sent a memo command used */ + time_t lastmemosend; + /* Last time this user registered */ + time_t lastnickreg; + /* Last time this user sent an email */ + time_t lastmail; /** Create a new user object, initialising necessary fields and * adds it to the hash @@ -152,7 +173,7 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe */ const Anope::string &GetIdent() const; - /** Get the full mask ( nick!ident@realhost ) of a user + /** Get the full mask (nick!ident@realhost) of a user */ Anope::string GetMask() const; @@ -201,16 +222,16 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe virtual NickCore *Account() const; /** Check if the user is identified for their nick - * @param CheckNick True to check if the user is identified to the nickname they are on too + * @param check_nick True to check if the user is identified to the nickname they are on too * @return true or false */ - bool IsIdentified(bool CheckNick = false) const; + bool IsIdentified(bool check_nick = false) const; /** Check if the user is recognized for their nick (on the nicks access list) - * @param CheckSecure Only returns true if the user has secure off + * @param check_nick Only returns true if the user has secure off * @return true or false */ - bool IsRecognized(bool CheckSecure = true) const; + bool IsRecognized(bool check_nick = true) const; /** Check if the user is a services oper * @return true if they are an oper @@ -243,7 +264,7 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe * @param um The user mode * @param Param The param, if there is one */ - void SetModeInternal(UserMode *um, const Anope::string &Param = ""); + void SetModeInternal(UserMode *um, const Anope::string ¶m = ""); /** Remove a mode internally on the user, the IRCd is not informed * @param um The user mode @@ -255,14 +276,14 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe * @param um The user mode * @param Param Optional param for the mode */ - void SetMode(const BotInfo *bi, UserMode *um, const Anope::string &Param = ""); + void SetMode(const BotInfo *bi, UserMode *um, const Anope::string ¶m = ""); /** Set a mode on the user * @param bi The client setting the mode - * @param Name The mode name + * @param name The mode name * @param Param Optional param for the mode */ - void SetMode(const BotInfo *bi, UserModeName Name, const Anope::string &Param = ""); + void SetMode(const BotInfo *bi, UserModeName name, const Anope::string ¶m = ""); /** Remove a mode on the user * @param bi The client setting the mode @@ -272,9 +293,9 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe /** Remove a mode from the user * @param bi The client setting the mode - * @param Name The mode name + * @param name The mode name */ - void RemoveMode(const BotInfo *bi, UserModeName Name); + void RemoveMode(const BotInfo *bi, UserModeName name); /** Set a string of modes on a user * @param bi The client setting the modes @@ -316,16 +337,28 @@ class CoreExport User : public virtual Base, public Extensible, public CommandRe * @param reason The reason for the kill */ void KillInternal(const Anope::string &source, const Anope::string &reason); -}; - -extern CoreExport int32_t opcnt; -extern CoreExport uint32_t maxusercnt, usercnt; -extern CoreExport time_t maxusertime; -extern CoreExport User *finduser(const Anope::string &nick); + /* Returns a mask that will most likely match any address the + * user will have from that location. For IP addresses, wildcards the + * appropriate subnet mask (e.g. 35.1.1.1 -> 35.*; 128.2.1.1 -> 128.2.*); + * for named addresses, wildcards the leftmost part of the name unless the + * name only contains two parts. If the username begins with a ~, delete + * it. + */ + Anope::string Mask() const; -extern CoreExport bool matches_list(Channel *c, User *user, ChannelModeName mode); + /** Notes the usage of an incorrect password. If too many + * incorrect passwords are used the user might be killed. + * @return true if the user was killed + */ + bool BadPassword(); -extern CoreExport Anope::string create_mask(User *u); + /** Finds a user by nick, or possibly UID + * @param name The nick, or possibly UID, to lookup + * @param nick_only set to true to only look up by nick, not UID + * @return the user, if they exist + */ + static User* Find(const Anope::string &name, bool nick_only = false); +}; #endif // USERS_H diff --git a/include/oper.h b/include/xline.h index 6a18d3e2b..5d407d4ba 100644 --- a/include/oper.h +++ b/include/xline.h @@ -1,29 +1,31 @@ -/* OperServ support +/* * * (C) 2008-2012 Anope Team * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ -#ifndef OPER_H -#define OPER_H +#ifndef XLINE_H +#define XLINE_H #include "serialize.h" #include "service.h" +/* An Xline, eg, anything added with operserv/akill, or any of the operserv/sxline commands */ class CoreExport XLine : public Serializable { void InitRegex(); public: - Anope::string Mask; + Anope::string mask; Regex *regex; - Anope::string By; - time_t Created; - time_t Expires; - Anope::string Reason; + Anope::string by; + time_t created; + time_t expires; + Anope::string reason; XLineManager *manager; - Anope::string UID; + Anope::string id; XLine(const Anope::string &mask, const Anope::string &reason = "", const Anope::string &uid = ""); @@ -40,17 +42,18 @@ class CoreExport XLine : public Serializable bool HasNickOrReal() const; bool IsRegex() const; - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; +/* Managers XLines. There is one XLineManager per type of XLine. */ class CoreExport XLineManager : public Service { char type; /* List of XLines in this XLineManager */ - serialize_checker<std::vector<XLine *> > XLines; + Serialize::Checker<std::vector<XLine *> > xlines; /* Akills can have the same IDs, sometimes */ - static serialize_checker<std::multimap<Anope::string, XLine *, ci::less> > XLinesByUID; + static Serialize::Checker<std::multimap<Anope::string, XLine *, ci::less> > XLinesByUID; public: /* List of XLine managers we check users against in XLineManager::CheckAll */ static std::list<XLineManager *> XLineManagers; @@ -174,4 +177,4 @@ class CoreExport XLineManager : public Service virtual void SendDel(XLine *x) = 0; }; -#endif // OPER_H +#endif // XLINE_H diff --git a/modules/commands/bs_assign.cpp b/modules/commands/bs_assign.cpp index 874c40015..ac809b952 100644 --- a/modules/commands/bs_assign.cpp +++ b/modules/commands/bs_assign.cpp @@ -27,20 +27,20 @@ class CommandBSAssign : public Command const Anope::string &chan = params[0]; const Anope::string &nick = params[1]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(BOT_ASSIGN_READONLY); return; } - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); return; } - BotInfo *bi = findbot(nick); + BotInfo *bi = BotInfo::Find(nick, true); if (!bi) { source.Reply(BOT_DOES_NOT_EXIST, nick.c_str()); @@ -95,13 +95,13 @@ class CommandBSUnassign : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (readonly) + if (Anope::ReadOnly) { source.Reply(BOT_ASSIGN_READONLY); return; } - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/bs_badwords.cpp b/modules/commands/bs_badwords.cpp index ad7a49085..36a83b717 100644 --- a/modules/commands/bs_badwords.cpp +++ b/modules/commands/bs_badwords.cpp @@ -19,10 +19,10 @@ class BadwordsDelCallback : public NumberList CommandSource &source; ChannelInfo *ci; Command *c; - unsigned Deleted; + unsigned deleted; bool override; public: - BadwordsDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &list) : NumberList(list, true), source(_source), ci(_ci), c(_c), Deleted(0), override(false) + BadwordsDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &list) : NumberList(list, true), source(_source), ci(_ci), c(_c), deleted(0), override(false) { if (!source.AccessFor(ci).HasPriv("BADWORDS") && source.HasPriv("botserv/administration")) this->override = true; @@ -30,12 +30,12 @@ class BadwordsDelCallback : public NumberList ~BadwordsDelCallback() { - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on %s bad words list."), ci->name.c_str()); - else if (Deleted == 1) + else if (deleted == 1) source.Reply(_("Deleted 1 entry from %s bad words list."), ci->name.c_str()); else - source.Reply(_("Deleted %d entries from %s bad words list."), Deleted, ci->name.c_str()); + source.Reply(_("Deleted %d entries from %s bad words list."), deleted, ci->name.c_str()); } void HandleNumber(unsigned Number) anope_override @@ -44,7 +44,7 @@ class BadwordsDelCallback : public NumberList return; Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "DEL " << ci->GetBadWord(Number - 1)->word; - ++Deleted; + ++deleted; ci->EraseBadWord(Number - 1); } }; @@ -58,7 +58,7 @@ class CommandBSBadwords : public Command Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "LIST"; ListFormatter list; - list.addColumn("Number").addColumn("Word").addColumn("Type"); + list.AddColumn("Number").AddColumn("Word").AddColumn("Type"); if (!ci->GetBadWordCount()) { @@ -86,7 +86,7 @@ class CommandBSBadwords : public Command entry["Number"] = stringify(Number); entry["Word"] = bw->word; entry["Type"] = bw->type == BW_SINGLE ? "(SINGLE)" : (bw->type == BW_START ? "(START)" : (bw->type == BW_END ? "(END)" : "")); - this->list.addEntry(entry); + this->list.AddEntry(entry); } } nl_list(list, ci, word); @@ -105,11 +105,11 @@ class CommandBSBadwords : public Command entry["Number"] = stringify(i + 1); entry["Word"] = bw->word; entry["Type"] = bw->type == BW_SINGLE ? "(SINGLE)" : (bw->type == BW_START ? "(START)" : (bw->type == BW_END ? "(END)" : "")); - list.addEntry(entry); + list.AddEntry(entry); } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on %s badword list."), ci->name.c_str()); else { @@ -241,7 +241,7 @@ class CommandBSBadwords : public Command return; } - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -254,7 +254,7 @@ class CommandBSBadwords : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, channel bad words list modification is temporarily disabled.")); return; diff --git a/modules/commands/bs_bot.cpp b/modules/commands/bs_bot.cpp index de7fa1128..8246692d0 100644 --- a/modules/commands/bs_bot.cpp +++ b/modules/commands/bs_bot.cpp @@ -23,7 +23,7 @@ class CommandBSBot : public Command const Anope::string &host = params[3]; const Anope::string &real = params[4]; - if (findbot(nick)) + if (BotInfo::Find(nick, true)) { source.Reply(_("Bot \002%s\002 already exists."), nick.c_str()); return; @@ -47,46 +47,30 @@ class CommandBSBot : public Command return; } - /* Check the nick is valid re RFC 2812 */ - if (isdigit(nick[0]) || nick[0] == '-') + if (!IRCD->IsNickValid(nick)) { source.Reply(_("Bot Nicks may only contain valid nick characters.")); return; } - for (unsigned i = 0, end = nick.length(); i < end && i < Config->NickLen; ++i) - if (!isvalidnick(nick[i])) - { - source.Reply(_("Bot Nicks may only contain valid nick characters.")); - return; - } - - /* check for hardcored ircd forbidden nicks */ - if (!ircdproto->IsNickValid(nick)) + /* Check the host is valid */ + if (!IRCD->IsHostValid(host)) { - source.Reply(_("Bot Nicks may only contain valid nick characters.")); + source.Reply(_("Bot Hosts may only contain valid host characters.")); return; } - /* Check the host is valid */ - if (!IsValidHost(host)) + if (!IRCD->IsIdentValid(user)) { - source.Reply(_("Bot Hosts may only contain valid host characters.")); + source.Reply(_("Bot Idents may only contain valid characters.")); return; } - for (unsigned i = 0, end = user.length(); i < end && i < Config->UserLen; ++i) - if (!isalnum(user[i])) - { - source.Reply(_("Bot Idents may only contain valid characters."), Config->UserLen); - return; - } - /* We check whether the nick is registered, and inform the user * if so. You need to drop the nick manually before you can use * it as a bot nick from now on -GD */ - if (findnick(nick)) + if (NickAlias::Find(nick)) { source.Reply(NICK_ALREADY_REGISTERED, nick.c_str()); return; @@ -116,16 +100,16 @@ class CommandBSBot : public Command return; } - BotInfo *bi = findbot(oldnick); + BotInfo *bi = BotInfo::Find(oldnick, true); if (!bi) { source.Reply(BOT_DOES_NOT_EXIST, oldnick.c_str()); return; } - if (!oldnick.equals_ci(nick) && nickIsServices(oldnick, false)) + if (bi->HasFlag(BI_CONF)) { - source.Reply(BOT_DOES_NOT_EXIST, oldnick.c_str()); + source.Reply(_("Bot %s is not changable."), bi->nick.c_str()); return; } @@ -147,12 +131,6 @@ class CommandBSBot : public Command return; } - if (!oldnick.equals_ci(nick) && nickIsServices(nick, false)) - { - source.Reply(BOT_DOES_NOT_EXIST, oldnick.c_str()); - return; - } - /* Checks whether there *are* changes. * Case sensitive because we may want to change just the case. * And we must finally check that the nick is not already @@ -164,42 +142,25 @@ class CommandBSBot : public Command return; } - /* Check the nick is valid re RFC 2812 */ - if (isdigit(nick[0]) || nick[0] == '-') + if (!IRCD->IsNickValid(nick)) { source.Reply(_("Bot Nicks may only contain valid nick characters.")); return; } - for (unsigned i = 0, end = nick.length(); i < end && i < Config->NickLen; ++i) - if (!isvalidnick(nick[i])) - { - source.Reply(_("Bot Nicks may only contain valid nick characters.")); - return; - } - - /* check for hardcored ircd forbidden nicks */ - if (!ircdproto->IsNickValid(nick)) + if (!host.empty() && !IRCD->IsHostValid(host)) { - source.Reply(_("Bot Nicks may only contain valid nick characters.")); + source.Reply(_("Bot Hosts may only contain valid host characters.")); return; } - if (!host.empty() && !IsValidHost(host)) + if (!user.empty() && !IRCD->IsIdentValid(user)) { - source.Reply(_("Bot Hosts may only contain valid host characters.")); + source.Reply(_("Bot Idents may only contain valid characters."), Config->UserLen); return; } - if (!user.empty()) - for (unsigned i = 0, end = user.length(); i < end && i < Config->UserLen; ++i) - if (!isalnum(user[i])) - { - source.Reply(_("Bot Idents may only contain valid characters."), Config->UserLen); - return; - } - - if (!nick.equals_ci(bi->nick) && findbot(nick)) + if (!nick.equals_ci(bi->nick) && BotInfo::Find(nick, true)) { source.Reply(_("Bot \002%s\002 already exists."), nick.c_str()); return; @@ -211,7 +172,7 @@ class CommandBSBot : public Command * if so. You need to drop the nick manually before you can use * it as a bot nick from now on -GD */ - if (findnick(nick)) + if (NickAlias::Find(nick)) { source.Reply(NICK_ALREADY_REGISTERED, nick.c_str()); return; @@ -219,19 +180,17 @@ class CommandBSBot : public Command /* The new nick is really different, so we remove the Q line for the old nick. */ XLine x_del(bi->nick); - ircdproto->SendSQLineDel(&x_del); + IRCD->SendSQLineDel(&x_del); /* Add a Q line for the new nick */ XLine x(nick, "Reserved for services"); - ircdproto->SendSQLine(NULL, &x); + IRCD->SendSQLine(NULL, &x); } if (!user.empty()) - ircdproto->SendQuit(bi, "Quit: Be right back"); + IRCD->SendQuit(bi, "Quit: Be right back"); else - { - ircdproto->SendChangeBotNick(bi, nick); - } + IRCD->SendNickChange(bi, nick); if (!nick.equals_cs(bi->nick)) bi->SetNewNick(nick); @@ -245,7 +204,7 @@ class CommandBSBot : public Command if (!user.empty()) { - ircdproto->SendClientIntroduction(bi); + IRCD->SendClientIntroduction(bi); bi->RejoinAll(); } @@ -266,16 +225,16 @@ class CommandBSBot : public Command return; } - BotInfo *bi = findbot(nick); + BotInfo *bi = BotInfo::Find(nick, true); if (!bi) { source.Reply(BOT_DOES_NOT_EXIST, nick.c_str()); return; } - if (nickIsServices(nick, false)) + if (bi->HasFlag(BI_CONF)) { - source.Reply(BOT_DOES_NOT_EXIST, nick.c_str()); + source.Reply(_("Bot %s is not deletable."), bi->nick.c_str()); return; } @@ -284,7 +243,7 @@ class CommandBSBot : public Command Log(LOG_ADMIN, source, this) << "DEL " << bi->nick; source.Reply(_("Bot \002%s\002 has been deleted."), nick.c_str()); - bi->destroy(); + bi->Destroy(); return; } public: @@ -300,7 +259,7 @@ class CommandBSBot : public Command { const Anope::string &cmd = params[0]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, bot modification is temporarily disabled.")); return; diff --git a/modules/commands/bs_botlist.cpp b/modules/commands/bs_botlist.cpp index a4a7c2586..1cdd93c45 100644 --- a/modules/commands/bs_botlist.cpp +++ b/modules/commands/bs_botlist.cpp @@ -27,7 +27,7 @@ class CommandBSBotList : public Command unsigned count = 0; ListFormatter list; - list.addColumn("Nick").addColumn("Mask"); + list.AddColumn("Nick").AddColumn("Mask"); for (botinfo_map::const_iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) { @@ -39,7 +39,7 @@ class CommandBSBotList : public Command ListFormatter::ListEntry entry; entry["Nick"] = (bi->HasFlag(BI_PRIVATE) ? "* " : "") + bi->nick; entry["Mask"] = bi->GetIdent() + "@" + bi->host; - list.addEntry(entry); + list.AddEntry(entry); } } diff --git a/modules/commands/bs_control.cpp b/modules/commands/bs_control.cpp index 6957d0a78..3ee0401d6 100644 --- a/modules/commands/bs_control.cpp +++ b/modules/commands/bs_control.cpp @@ -26,7 +26,7 @@ class CommandBSSay : public Command { const Anope::string &text = params[1]; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -57,7 +57,7 @@ class CommandBSSay : public Command return; } - ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", text.c_str()); + IRCD->SendPrivmsg(ci->bi, ci->name, "%s", text.c_str()); ci->bi->lastmsg = Anope::CurTime; // XXX need a way to find if someone is overriding this @@ -88,7 +88,7 @@ class CommandBSAct : public Command { Anope::string message = params[1]; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -117,7 +117,7 @@ class CommandBSAct : public Command while ((i = message.find(1)) && i != Anope::string::npos) message.erase(i, 1); - ircdproto->SendAction(ci->bi, ci->name, "%s", message.c_str()); + IRCD->SendAction(ci->bi, ci->name, "%s", message.c_str()); ci->bi->lastmsg = Anope::CurTime; // XXX Need to be able to find if someone is overriding this. diff --git a/modules/commands/bs_info.cpp b/modules/commands/bs_info.cpp index 199b17e3e..a4312cea6 100644 --- a/modules/commands/bs_info.cpp +++ b/modules/commands/bs_info.cpp @@ -44,7 +44,7 @@ class CommandBSInfo : public Command { if (!buf.empty()) buf += ", "; - buf += translate(nc, option); + buf += Language::Translate(nc, option); } } @@ -59,7 +59,7 @@ class CommandBSInfo : public Command { const Anope::string &query = params[0]; - const BotInfo *bi = findbot(query); + const BotInfo *bi = BotInfo::Find(query, true); ChannelInfo *ci; InfoFormatter info(source.nc); @@ -68,7 +68,7 @@ class CommandBSInfo : public Command source.Reply(_("Information for bot \002%s\002:"), bi->nick.c_str()); info[_("Mask")] = bi->GetIdent() + "@" + bi->host; info[_("Real name")] = bi->realname; - info[_("Created")] = do_strftime(bi->created); + info[_("Created")] = Anope::strftime(bi->created); info[_("Options")] = bi->HasFlag(BI_PRIVATE) ? _("Private") : _("None"); info[_("Used on")] = stringify(bi->GetChannelCount()) + " channel(s)"; @@ -87,7 +87,7 @@ class CommandBSInfo : public Command } } - else if ((ci = cs_findchan(query))) + else if ((ci = ChannelInfo::Find(query))) { if (!source.AccessFor(ci).HasPriv("FOUNDER") && !source.HasPriv("botserv/administration")) { @@ -98,8 +98,8 @@ class CommandBSInfo : public Command source.Reply(CHAN_INFO_HEADER, ci->name.c_str()); info[_("Bot nick")] = ci->bi ? ci->bi->nick : "not assigned yet"; - Anope::string enabled = translate(source.nc, _("Enabled")); - Anope::string disabled = translate(source.nc, _("Disabled")); + Anope::string enabled = Language::Translate(source.nc, _("Enabled")); + Anope::string disabled = Language::Translate(source.nc, _("Disabled")); if (ci->botflags.HasFlag(BS_KICK_BADWORDS)) { diff --git a/modules/commands/bs_kick.cpp b/modules/commands/bs_kick.cpp index eeaccd5f9..3e569696e 100644 --- a/modules/commands/bs_kick.cpp +++ b/modules/commands/bs_kick.cpp @@ -30,9 +30,9 @@ class CommandBSKick : public Command const Anope::string &value = params[2]; const Anope::string &ttb = params.size() > 3 ? params[3] : ""; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); - if (readonly) + if (Anope::ReadOnly) source.Reply(_("Sorry, kicker configuration is temporarily disabled.")); else if (ci == NULL) source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -736,14 +736,12 @@ class BSKick : public Module /* Should not use == here because bd.ttb[ttbtype] could possibly be > ci->ttb[ttbtype] * if the TTB was changed after it was not set (0) before and the user had already been * kicked a few times. Bug #1056 - Adam */ - Anope::string mask; bd.ttb[ttbtype] = 0; - get_idealban(ci, u, mask); + Anope::string mask = ci->GetIdealBan(u); - if (ci->c) - ci->c->SetMode(NULL, CMODE_BAN, mask); + ci->c->SetMode(NULL, CMODE_BAN, mask); FOREACH_MOD(I_OnBotBan, OnBotBan(u, ci, mask)); } } @@ -756,7 +754,7 @@ class BSKick : public Module if (!ci || !ci->bi || !ci->c || !u || u->server->IsULined() || !ci->c->FindUser(u)) return; - Anope::string fmt = translate(u, message); + Anope::string fmt = Language::Translate(u, message); va_start(args, message); vsnprintf(buf, sizeof(buf), fmt.c_str(), args); va_end(args); @@ -895,7 +893,7 @@ class BSKick : public Module bool mustkick = false; /* Normalize the buffer */ - Anope::string nbuf = normalizeBuffer(realbuf); + Anope::string nbuf = Anope::NormalizeBuffer(realbuf); for (unsigned i = 0, end = ci->GetBadWordCount(); i < end; ++i) { diff --git a/modules/commands/bs_set.cpp b/modules/commands/bs_set.cpp index e169f3c83..6f458bec0 100644 --- a/modules/commands/bs_set.cpp +++ b/modules/commands/bs_set.cpp @@ -41,7 +41,7 @@ class CommandBSSet : public Command const CommandInfo &info = it->second; if (c_name.find_ci(this_name + " ") == 0) { - service_reference<Command> command("Command", info.name); + ServiceReference<Command> command("Command", info.name); if (command) { source.command = it->first; diff --git a/modules/commands/bs_set_dontkickops.cpp b/modules/commands/bs_set_dontkickops.cpp index 598dfdcea..5346074a6 100644 --- a/modules/commands/bs_set_dontkickops.cpp +++ b/modules/commands/bs_set_dontkickops.cpp @@ -24,7 +24,7 @@ class CommandBSSetDontKickOps : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -38,7 +38,7 @@ class CommandBSSetDontKickOps : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, bot option setting is temporarily disabled.")); return; diff --git a/modules/commands/bs_set_dontkickvoices.cpp b/modules/commands/bs_set_dontkickvoices.cpp index 05453296b..b4b0cd7ec 100644 --- a/modules/commands/bs_set_dontkickvoices.cpp +++ b/modules/commands/bs_set_dontkickvoices.cpp @@ -24,7 +24,7 @@ class CommandBSSetDontKickVoices : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -38,7 +38,7 @@ class CommandBSSetDontKickVoices : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, bot option setting is temporarily disabled.")); return; diff --git a/modules/commands/bs_set_fantasy.cpp b/modules/commands/bs_set_fantasy.cpp index 03bd40c70..29c722026 100644 --- a/modules/commands/bs_set_fantasy.cpp +++ b/modules/commands/bs_set_fantasy.cpp @@ -24,7 +24,7 @@ class CommandBSSetFantasy : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); const Anope::string &value = params[1]; if (ci == NULL) @@ -39,7 +39,7 @@ class CommandBSSetFantasy : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, bot option setting is temporarily disabled.")); return; diff --git a/modules/commands/bs_set_greet.cpp b/modules/commands/bs_set_greet.cpp index b74b0e5dd..ad5220203 100644 --- a/modules/commands/bs_set_greet.cpp +++ b/modules/commands/bs_set_greet.cpp @@ -24,7 +24,7 @@ class CommandBSSetGreet : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); const Anope::string &value = params[1]; if (ci == NULL) @@ -39,7 +39,7 @@ class CommandBSSetGreet : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, bot option setting is temporarily disabled.")); return; diff --git a/modules/commands/bs_set_nobot.cpp b/modules/commands/bs_set_nobot.cpp index 246864953..f3f749aa5 100644 --- a/modules/commands/bs_set_nobot.cpp +++ b/modules/commands/bs_set_nobot.cpp @@ -24,7 +24,7 @@ class CommandBSSetNoBot : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); const Anope::string &value = params[1]; if (ci == NULL) diff --git a/modules/commands/bs_set_private.cpp b/modules/commands/bs_set_private.cpp index 0cd055d00..920c97d37 100644 --- a/modules/commands/bs_set_private.cpp +++ b/modules/commands/bs_set_private.cpp @@ -24,7 +24,7 @@ class CommandBSSetPrivate : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - BotInfo *bi = findbot(params[0]); + BotInfo *bi = BotInfo::Find(params[0], true); const Anope::string &value = params[1]; if (bi == NULL) diff --git a/modules/commands/cs_access.cpp b/modules/commands/cs_access.cpp index 40414a336..ed6f4f7fa 100644 --- a/modules/commands/cs_access.cpp +++ b/modules/commands/cs_access.cpp @@ -36,12 +36,12 @@ class AccessChanAccess : public ChanAccess return this->ci->GetLevel(name) != ACCESS_INVALID && this->level >= this->ci->GetLevel(name); } - Anope::string Serialize() const + Anope::string AccessSerialize() const { return stringify(this->level); } - void Unserialize(const Anope::string &data) anope_override + void AccessUnserialize(const Anope::string &data) anope_override { this->level = convertTo<int>(data); } @@ -119,7 +119,7 @@ class CommandCSAccess : public Command bool override = false; - if ((!highest || *highest <= tmp_access) && !u_access.Founder) + if ((!highest || *highest <= tmp_access) && !u_access.founder) { if (source.HasPriv("chanserv/access/modify")) override = true; @@ -130,9 +130,9 @@ class CommandCSAccess : public Command } } - if (mask.find_first_of("!*@") == Anope::string::npos && !findnick(mask)) + if (mask.find_first_of("!*@") == Anope::string::npos && !NickAlias::Find(mask)) { - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ != NULL) mask = "*!*@" + targ->GetDisplayedHost(); else @@ -148,7 +148,7 @@ class CommandCSAccess : public Command if (mask.equals_ci(access->mask)) { /* Don't allow lowering from a level >= u_level */ - if ((!highest || *access >= *highest) && !u_access.Founder && !source.HasPriv("chanserv/access/modify")) + if ((!highest || *access >= *highest) && !u_access.founder && !source.HasPriv("chanserv/access/modify")) { source.Reply(ACCESS_DENIED); return; @@ -164,7 +164,7 @@ class CommandCSAccess : public Command return; } - service_reference<AccessProvider> provider("AccessProvider", "access/access"); + ServiceReference<AccessProvider> provider("AccessProvider", "access/access"); if (!provider) return; AccessChanAccess *access = anope_dynamic_static_cast<AccessChanAccess *>(provider->Create()); @@ -188,9 +188,9 @@ class CommandCSAccess : public Command { Anope::string mask = params[2]; - if (mask.find_first_of("!*@") == Anope::string::npos && !findnick(mask)) + if (mask.find_first_of("!*@") == Anope::string::npos && !NickAlias::Find(mask)) { - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ != NULL) mask = "*!*@" + targ->GetDisplayedHost(); else @@ -209,12 +209,12 @@ class CommandCSAccess : public Command CommandSource &source; ChannelInfo *ci; Command *c; - unsigned Deleted; + unsigned deleted; Anope::string Nicks; bool Denied; bool override; public: - AccessDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &numlist) : NumberList(numlist, true), source(_source), ci(_ci), c(_c), Deleted(0), Denied(false), override(false) + AccessDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &numlist) : NumberList(numlist, true), source(_source), ci(_ci), c(_c), deleted(0), Denied(false), override(false) { if (!source.AccessFor(ci).HasPriv("ACCESS_CHANGE") && source.HasPriv("chanserv/access/modify")) this->override = true; @@ -222,18 +222,18 @@ class CommandCSAccess : public Command ~AccessDelCallback() { - if (Denied && !Deleted) + if (Denied && !deleted) source.Reply(ACCESS_DENIED); - else if (!Deleted) + else if (!deleted) source.Reply(_("No matching entries on %s access list."), ci->name.c_str()); else { Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "to delete " << Nicks; - if (Deleted == 1) + if (deleted == 1) source.Reply(_("Deleted 1 entry from %s access list."), ci->name.c_str()); else - source.Reply(_("Deleted %d entries from %s access list."), Deleted, ci->name.c_str()); + source.Reply(_("Deleted %d entries from %s access list."), deleted, ci->name.c_str()); } } @@ -247,13 +247,13 @@ class CommandCSAccess : public Command AccessGroup u_access = source.AccessFor(ci); const ChanAccess *u_highest = u_access.Highest(); - if ((!u_highest || *u_highest <= *access) && !u_access.Founder && !this->override && !access->mask.equals_ci(source.nc->display)) + if ((!u_highest || *u_highest <= *access) && !u_access.founder && !this->override && !access->mask.equals_ci(source.nc->display)) { Denied = true; return; } - ++Deleted; + ++deleted; if (!Nicks.empty()) Nicks += ", " + access->mask; else @@ -277,12 +277,12 @@ class CommandCSAccess : public Command ChanAccess *access = ci->GetAccess(i - 1); if (mask.equals_ci(access->mask)) { - if (!access->mask.equals_ci(source.nc->display) && !u_access.Founder && (!highest || *highest <= *access) && !source.HasPriv("chanserv/access/modify")) + if (!access->mask.equals_ci(source.nc->display) && !u_access.founder && (!highest || *highest <= *access) && !source.HasPriv("chanserv/access/modify")) source.Reply(ACCESS_DENIED); else { source.Reply(_("\002%s\002 deleted from %s access list."), access->mask.c_str(), ci->name.c_str()); - bool override = !u_access.Founder && !u_access.HasPriv("ACCESS_CHANGE") && !access->mask.equals_ci(source.nc->display); + bool override = !u_access.founder && !u_access.HasPriv("ACCESS_CHANGE") && !access->mask.equals_ci(source.nc->display); Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to delete " << access->mask; FOREACH_MOD(I_OnAccessDel, OnAccessDel(ci, source, access)); @@ -333,7 +333,7 @@ class CommandCSAccess : public Command if (access->last_seen == 0) timebuf = "Never"; else - timebuf = do_strftime(access->last_seen, NULL, true); + timebuf = Anope::strftime(access->last_seen, NULL, true); } ListFormatter::ListEntry entry; @@ -342,7 +342,7 @@ class CommandCSAccess : public Command entry["Mask"] = access->mask; entry["By"] = access->creator; entry["Last seen"] = timebuf; - this->list.addEntry(entry); + this->list.AddEntry(entry); } } nl_list(list, ci, nick); @@ -367,7 +367,7 @@ class CommandCSAccess : public Command if (access->last_seen == 0) timebuf = "Never"; else - timebuf = do_strftime(access->last_seen, NULL, true); + timebuf = Anope::strftime(access->last_seen, NULL, true); } ListFormatter::ListEntry entry; @@ -376,11 +376,11 @@ class CommandCSAccess : public Command entry["Mask"] = access->mask; entry["By"] = access->creator; entry["Last seen"] = timebuf; - list.addEntry(entry); + list.AddEntry(entry); } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on %s access list."), ci->name.c_str()); else { @@ -407,7 +407,7 @@ class CommandCSAccess : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Level").addColumn("Mask"); + list.AddColumn("Number").AddColumn("Level").AddColumn("Mask"); this->ProcessList(source, ci, params, list); } @@ -420,7 +420,7 @@ class CommandCSAccess : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Level").addColumn("Mask").addColumn("By").addColumn("Last seen"); + list.AddColumn("Number").AddColumn("Level").AddColumn("Mask").AddColumn("By").AddColumn("Last seen"); this->ProcessList(source, ci, params, list); } @@ -460,7 +460,7 @@ class CommandCSAccess : public Command const Anope::string &nick = params.size() > 2 ? params[2] : ""; const Anope::string &s = params.size() > 3 ? params[3] : ""; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -480,7 +480,7 @@ class CommandCSAccess : public Command has_access = true; else if (is_del) { - const NickAlias *na = findnick(nick); + const NickAlias *na = NickAlias::Find(nick); if (na && na->nc == source.GetAccount()) has_access = true; } @@ -492,7 +492,7 @@ class CommandCSAccess : public Command this->OnSyntaxError(source, cmd); else if (!has_access) source.Reply(ACCESS_DENIED); - else if (readonly && !is_list) + else if (Anope::ReadOnly && !is_list) source.Reply(_("Sorry, channel access list modification is temporarily disabled.")); else if (cmd.equals_ci("ADD")) this->DoAdd(source, ci, params); @@ -652,7 +652,7 @@ class CommandCSLevels : public Command source.Reply(_("Access level settings for channel %s:"), ci->name.c_str()); ListFormatter list; - list.addColumn("Name").addColumn("Level"); + list.AddColumn("Name").AddColumn("Level"); const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); @@ -671,7 +671,7 @@ class CommandCSLevels : public Command else entry["Level"] = stringify(j); - list.addEntry(entry); + list.AddEntry(entry); } std::vector<Anope::string> replies; @@ -709,7 +709,7 @@ class CommandCSLevels : public Command const Anope::string &what = params.size() > 2 ? params[2] : ""; const Anope::string &s = params.size() > 3 ? params[3] : ""; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -744,7 +744,7 @@ class CommandCSLevels : public Command source.Reply(_("The following feature/function names are understood.")); ListFormatter list; - list.addColumn("Name").addColumn("Description"); + list.AddColumn("Name").AddColumn("Description"); const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); for (unsigned i = 0; i < privs.size(); ++i) @@ -752,8 +752,8 @@ class CommandCSLevels : public Command const Privilege &p = privs[i]; ListFormatter::ListEntry entry; entry["Name"] = p.name; - entry["Description"] = translate(source.nc, p.desc.c_str()); - list.addEntry(entry); + entry["Description"] = Language::Translate(source.nc, p.desc.c_str()); + list.AddEntry(entry); } std::vector<Anope::string> replies; diff --git a/modules/commands/cs_akick.cpp b/modules/commands/cs_akick.cpp index 1425d1636..29959bf32 100644 --- a/modules/commands/cs_akick.cpp +++ b/modules/commands/cs_akick.cpp @@ -52,7 +52,7 @@ class CommandCSAKick : public Command { Anope::string mask = params[2]; Anope::string reason = params.size() > 3 ? params[3] : ""; - const NickAlias *na = findnick(mask); + const NickAlias *na = NickAlias::Find(mask); NickCore *nc = NULL; const AutoKick *akick; @@ -178,34 +178,34 @@ class CommandCSAKick : public Command CommandSource &source; ChannelInfo *ci; Command *c; - unsigned Deleted; + unsigned deleted; public: - AkickDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &list) : NumberList(list, true), source(_source), ci(_ci), c(_c), Deleted(0) + AkickDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, const Anope::string &list) : NumberList(list, true), source(_source), ci(_ci), c(_c), deleted(0) { } ~AkickDelCallback() { bool override = !source.AccessFor(ci).HasPriv("AKICK"); - Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "to delete " << Deleted << (Deleted == 1 ? " entry" : " entries"); + Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "to delete " << deleted << (deleted == 1 ? " entry" : " entries"); - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on %s autokick list."), ci->name.c_str()); - else if (Deleted == 1) + else if (deleted == 1) source.Reply(_("Deleted 1 entry from %s autokick list."), ci->name.c_str()); else - source.Reply(_("Deleted %d entries from %s autokick list."), Deleted, ci->name.c_str()); + source.Reply(_("Deleted %d entries from %s autokick list."), deleted, ci->name.c_str()); } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number || Number > ci->GetAkickCount()) + if (!number || number > ci->GetAkickCount()) return; - FOREACH_MOD(I_OnAkickDel, OnAkickDel(source, ci, ci->GetAkick(Number - 1))); + FOREACH_MOD(I_OnAkickDel, OnAkickDel(source, ci, ci->GetAkick(number - 1))); - ++Deleted; - ci->EraseAkick(Number - 1); + ++deleted; + ci->EraseAkick(number - 1); } } delcallback(source, ci, this, mask); @@ -213,7 +213,7 @@ class CommandCSAKick : public Command } else { - const NickAlias *na = findnick(mask); + const NickAlias *na = NickAlias::Find(mask); const NickCore *nc = na ? *na->nc : NULL; for (i = 0, end = ci->GetAkickCount(); i < end; ++i) @@ -266,11 +266,11 @@ class CommandCSAKick : public Command Anope::string timebuf, lastused; if (akick->addtime) - timebuf = do_strftime(akick->addtime, NULL, false); + timebuf = Anope::strftime(akick->addtime, NULL, false); else timebuf = UNKNOWN; if (akick->last_used) - lastused = do_strftime(akick->last_used, NULL, false); + lastused = Anope::strftime(akick->last_used, NULL, false); else lastused = UNKNOWN; @@ -281,7 +281,7 @@ class CommandCSAKick : public Command entry["Created"] = timebuf; entry["Last used"] = lastused; entry["Reason"] = akick->reason; - this->list.addEntry(entry); + this->list.AddEntry(entry); } } nl_list(list, ci, mask); @@ -303,11 +303,11 @@ class CommandCSAKick : public Command Anope::string timebuf, lastused; if (akick->addtime) - timebuf = do_strftime(akick->addtime); + timebuf = Anope::strftime(akick->addtime); else timebuf = UNKNOWN; if (akick->last_used) - lastused = do_strftime(akick->last_used); + lastused = Anope::strftime(akick->last_used); else lastused = UNKNOWN; @@ -318,11 +318,11 @@ class CommandCSAKick : public Command entry["Created"] = timebuf; entry["Last used"] = lastused; entry["Reason"] = akick->reason; - list.addEntry(entry); + list.AddEntry(entry); } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on %s autokick list."), ci->name.c_str()); else { @@ -347,7 +347,7 @@ class CommandCSAKick : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Reason"); this->ProcessList(source, ci, params, list); } @@ -360,7 +360,7 @@ class CommandCSAKick : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Creator").addColumn("Created").addColumn("Last used").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Creator").AddColumn("Created").AddColumn("Last used").AddColumn("Reason"); this->ProcessList(source, ci, params, list); } @@ -416,7 +416,7 @@ class CommandCSAKick : public Command Anope::string cmd = params[1]; Anope::string mask = params.size() > 2 ? params[2] : ""; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -427,7 +427,7 @@ class CommandCSAKick : public Command this->OnSyntaxError(source, cmd); else if (!source.AccessFor(ci).HasPriv("AKICK") && !source.HasPriv("chanserv/access/modify")) source.Reply(ACCESS_DENIED); - else if (!cmd.equals_ci("LIST") && !cmd.equals_ci("VIEW") && !cmd.equals_ci("ENFORCE") && readonly) + else if (!cmd.equals_ci("LIST") && !cmd.equals_ci("VIEW") && !cmd.equals_ci("ENFORCE") && Anope::ReadOnly) source.Reply(_("Sorry, channel autokick list modification is temporarily disabled.")); else if (cmd.equals_ci("ADD")) this->DoAdd(source, ci, params); diff --git a/modules/commands/cs_appendtopic.cpp b/modules/commands/cs_appendtopic.cpp index 70cde7b7b..2d7c0f278 100644 --- a/modules/commands/cs_appendtopic.cpp +++ b/modules/commands/cs_appendtopic.cpp @@ -52,7 +52,7 @@ class CommandCSAppendTopic : public Command { const Anope::string &newtopic = params[1]; - Channel *c = findchan(params[0]);; + Channel *c = Channel::Find(params[0]);; if (!c) source.Reply(CHAN_X_NOT_IN_USE, params[0].c_str()); diff --git a/modules/commands/cs_ban.cpp b/modules/commands/cs_ban.cpp index 063d98ab5..e857243f9 100644 --- a/modules/commands/cs_ban.cpp +++ b/modules/commands/cs_ban.cpp @@ -29,7 +29,7 @@ class CommandCSBan : public Command const Anope::string &target = params[1]; const Anope::string &reason = params.size() > 2 ? params[2] : "Requested"; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -38,7 +38,7 @@ class CommandCSBan : public Command Channel *c = ci->c; User *u = source.GetUser(); - User *u2 = finduser(target); + User *u2 = User::Find(target, true); AccessGroup u_access = source.AccessFor(ci); @@ -56,14 +56,13 @@ class CommandCSBan : public Command if (u != u2 && ci->HasFlag(CI_PEACE) && u2_access >= u_access) source.Reply(ACCESS_DENIED); - else if (matches_list(ci->c, u2, CMODE_EXCEPT)) + else if (ci->c->MatchesList(u2, CMODE_EXCEPT)) source.Reply(CHAN_EXCEPTED, u2->nick.c_str(), ci->name.c_str()); else if (u2->IsProtected()) source.Reply(ACCESS_DENIED); else { - Anope::string mask; - get_idealban(ci, u2, mask); + Anope::string mask = ci->GetIdealBan(u2); // XXX need a way to detect if someone is overriding Log(LOG_COMMAND, source, this, ci) << "for " << mask; @@ -99,7 +98,7 @@ class CommandCSBan : public Command if (u != uc->user && ci->HasFlag(CI_PEACE) && u2_access >= u_access) continue; - else if (matches_list(ci->c, uc->user, CMODE_EXCEPT)) + else if (ci->c->MatchesList(uc->user, CMODE_EXCEPT)) continue; else if (uc->user->IsProtected()) continue; diff --git a/modules/commands/cs_clearusers.cpp b/modules/commands/cs_clearusers.cpp index d6eed6e4d..3a424e4ce 100644 --- a/modules/commands/cs_clearusers.cpp +++ b/modules/commands/cs_clearusers.cpp @@ -26,7 +26,7 @@ class CommandCSClearUsers : public Command { const Anope::string &chan = params[0]; - Channel *c = findchan(chan); + Channel *c = Channel::Find(chan); Anope::string modebuf; if (!c) diff --git a/modules/commands/cs_clone.cpp b/modules/commands/cs_clone.cpp index aef48ea4c..19a8ad436 100644 --- a/modules/commands/cs_clone.cpp +++ b/modules/commands/cs_clone.cpp @@ -29,7 +29,7 @@ public: Anope::string what = params.size() > 2 ? params[2] : ""; User *u = source.GetUser(); - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -42,7 +42,7 @@ public: return; } - ChannelInfo *target_ci = cs_findchan(target); + ChannelInfo *target_ci = ChannelInfo::Find(target); if (!target_ci) { source.Reply(CHAN_X_NOT_REGISTERED, target.c_str()); @@ -59,11 +59,11 @@ public: if (what.empty()) { - target_ci->destroy(); + target_ci->Destroy(); target_ci = new ChannelInfo(*ci); target_ci->name = target; (*RegisteredChannelList)[target_ci->name] = target_ci; - target_ci->c = findchan(target_ci->name); + target_ci->c = Channel::Find(target_ci->name); if (target_ci->c) { target_ci->c->ci = target_ci; @@ -88,7 +88,7 @@ public: target_ci->c->SetMode(NULL, CMODE_PERM); if (target_ci->bi && target_ci->c->FindUser(target_ci->bi) == NULL) - target_ci->bi->Join(target_ci->c, &Config->BotModeList); + target_ci->bi->Join(target_ci->c, &ModeManager::DefaultBotModes); } if (target_ci->c && !target_ci->c->topic.empty()) @@ -117,7 +117,7 @@ public: newaccess->creator = taccess->creator; newaccess->last_seen = taccess->last_seen; newaccess->created = taccess->created; - newaccess->Unserialize(taccess->Serialize()); + newaccess->AccessUnserialize(taccess->AccessSerialize()); target_ci->AddAccess(newaccess); } diff --git a/modules/commands/cs_drop.cpp b/modules/commands/cs_drop.cpp index cf8c5040e..829f44026 100644 --- a/modules/commands/cs_drop.cpp +++ b/modules/commands/cs_drop.cpp @@ -26,13 +26,13 @@ class CommandCSDrop : public Command { const Anope::string &chan = params[0]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, channel de-registration is temporarily disabled.")); // XXX: READ_ONLY_MODE? return; } - ChannelInfo *ci = cs_findchan(chan); + ChannelInfo *ci = ChannelInfo::Find(chan); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -57,7 +57,7 @@ class CommandCSDrop : public Command FOREACH_MOD(I_OnChanDrop, OnChanDrop(ci)); Channel *c = ci->c; - ci->destroy(); + ci->Destroy(); source.Reply(_("Channel \002%s\002 has been dropped."), chan.c_str()); diff --git a/modules/commands/cs_enforce.cpp b/modules/commands/cs_enforce.cpp index 755cd55b4..4622af04b 100644 --- a/modules/commands/cs_enforce.cpp +++ b/modules/commands/cs_enforce.cpp @@ -50,7 +50,7 @@ class CommandCSEnforce : public Command Log(LOG_COMMAND, source, this) << "to enforce secureops"; - /* Dirty hack to allow chan_set_correct_modes to work ok. + /* Dirty hack to allow Channel::SetCorrectModes to work ok. * We pretend like SECUREOPS is on so it doesn't ignore that * part of the code. This way we can enforce SECUREOPS even * if it's off. @@ -66,7 +66,7 @@ class CommandCSEnforce : public Command { UserContainer *uc = *it; - chan_set_correct_modes(uc->user, c, 0, false); + c->SetCorrectModes(uc->user, false, false); } if (hadsecureops) @@ -95,9 +95,8 @@ class CommandCSEnforce : public Command { User *user = users[i]; - Anope::string mask; - get_idealban(ci, user, mask); - Anope::string reason = translate(user, CHAN_NOT_ALLOWED_TO_JOIN); + Anope::string mask = ci->GetIdealBan(user); + Anope::string reason = Language::Translate(user, CHAN_NOT_ALLOWED_TO_JOIN); c->SetMode(NULL, CMODE_BAN, mask); c->Kick(NULL, user, "%s", reason.c_str()); } @@ -106,7 +105,6 @@ class CommandCSEnforce : public Command void DoCModeR(CommandSource &source, Channel *c) { ChannelInfo *ci = c->ci; - Anope::string mask; if (!ci) return; @@ -127,8 +125,8 @@ class CommandCSEnforce : public Command { User *user = users[i]; - get_idealban(ci, user, mask); - Anope::string reason = translate(user, CHAN_NOT_ALLOWED_TO_JOIN); + Anope::string mask = ci->GetIdealBan(user); + Anope::string reason = Language::Translate(user, CHAN_NOT_ALLOWED_TO_JOIN); if (!c->HasMode(CMODE_REGISTEREDONLY)) c->SetMode(NULL, CMODE_BAN, mask); c->Kick(NULL, user, "%s", reason.c_str()); @@ -145,7 +143,7 @@ class CommandCSEnforce : public Command { const Anope::string &what = params.size() > 1 ? params[1] : ""; - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (!c) source.Reply(CHAN_X_NOT_IN_USE, params[0].c_str()); diff --git a/modules/commands/cs_entrymsg.cpp b/modules/commands/cs_entrymsg.cpp index 1fce5fac0..85e428cc1 100644 --- a/modules/commands/cs_entrymsg.cpp +++ b/modules/commands/cs_entrymsg.cpp @@ -15,7 +15,7 @@ struct EntryMsg : Serializable { - serialize_obj<ChannelInfo> ci; + Serialize::Reference<ChannelInfo> ci; Anope::string creator; Anope::string message; time_t when; @@ -28,31 +28,31 @@ struct EntryMsg : Serializable this->when = ct; } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; data["ci"] << this->ci->name; data["creator"] << this->creator; data["message"] << this->message; - data["when"].setType(Serialize::DT_INT) << this->when; + data["when"].SetType(Serialize::DT_INT) << this->when; return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; static unsigned MaxEntries = 0; -struct EntryMessageList : serialize_checker<std::vector<EntryMsg *> >, ExtensibleItem +struct EntryMessageList : Serialize::Checker<std::vector<EntryMsg *> >, ExtensibleItem { - EntryMessageList() : serialize_checker<std::vector<EntryMsg *> >("EntryMsg") { } + EntryMessageList() : Serialize::Checker<std::vector<EntryMsg *> >("EntryMsg") { } }; -Serializable* EntryMsg::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* EntryMsg::Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (!ci) return NULL; @@ -99,7 +99,7 @@ class CommandEntryMessage : public Command source.Reply(_("Entry message list for \002%s\002:"), ci->name.c_str()); ListFormatter list; - list.addColumn("Number").addColumn("Creator").addColumn("Created").addColumn("Message"); + list.AddColumn("Number").AddColumn("Creator").AddColumn("Created").AddColumn("Message"); for (unsigned i = 0; i < (*messages)->size(); ++i) { EntryMsg *msg = (*messages)->at(i); @@ -107,9 +107,9 @@ class CommandEntryMessage : public Command ListFormatter::ListEntry entry; entry["Number"] = stringify(i + 1); entry["Creator"] = msg->creator; - entry["Created"] = do_strftime(msg->when); + entry["Created"] = Anope::strftime(msg->when); entry["Message"] = msg->message; - list.addEntry(entry); + list.AddEntry(entry); } std::vector<Anope::string> replies; @@ -159,7 +159,7 @@ class CommandEntryMessage : public Command unsigned i = convertTo<unsigned>(message); if (i > 0 && i <= (*messages)->size()) { - (*messages)->at(i - 1)->destroy(); + (*messages)->at(i - 1)->Destroy(); (*messages)->erase((*messages)->begin() + i - 1); if ((*messages)->empty()) ci->Shrink("cs_entrymsg"); @@ -182,7 +182,7 @@ class CommandEntryMessage : public Command if (messages != NULL) { for (unsigned i = 0; i < (*messages)->size(); ++i) - (*messages)->at(i)->destroy(); + (*messages)->at(i)->Destroy(); (*messages)->clear(); ci->Shrink("cs_entrymsg"); } @@ -203,7 +203,7 @@ class CommandEntryMessage : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -258,11 +258,11 @@ class CommandEntryMessage : public Command class CSEntryMessage : public Module { - SerializeType entrymsg_type; + Serialize::Type entrymsg_type; CommandEntryMessage commandentrymsg; public: - CSEntryMessage(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), entrymsg_type("EntryMsg", EntryMsg::unserialize), commandentrymsg(this) + CSEntryMessage(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), entrymsg_type("EntryMsg", EntryMsg::Unserialize), commandentrymsg(this) { this->SetAuthor("Anope"); diff --git a/modules/commands/cs_fantasy_stats.cpp b/modules/commands/cs_fantasy_stats.cpp index 7c79593a2..bbe135298 100644 --- a/modules/commands/cs_fantasy_stats.cpp +++ b/modules/commands/cs_fantasy_stats.cpp @@ -66,7 +66,7 @@ class CSStats : public Module { CommandCSStats commandcsstats; CommandCSGStats commandcsgstats; - service_reference<SQLProvider> sql; + ServiceReference<SQLProvider> sql; MySQLInterface sqlinterface; Anope::string prefix; public: @@ -86,7 +86,7 @@ class CSStats : public Module ConfigReader config; prefix = config.ReadValue("chanstats", "prefix", "anope_", 0); Anope::string engine = config.ReadValue("chanstats", "engine", "", 0); - this->sql = service_reference<SQLProvider>("SQLProvider", engine); + this->sql = ServiceReference<SQLProvider>("SQLProvider", engine); } SQLResult RunQuery(const SQLQuery &query) @@ -108,7 +108,7 @@ class CSStats : public Module Anope::string display; if (params.empty()) display = source.nc->display; - else if (const NickAlias *na = findnick(params[0])) + else if (const NickAlias *na = NickAlias::Find(params[0])) display = na->nc->display; else { diff --git a/modules/commands/cs_fantasy_top.cpp b/modules/commands/cs_fantasy_top.cpp index 587b4c525..86e25f122 100644 --- a/modules/commands/cs_fantasy_top.cpp +++ b/modules/commands/cs_fantasy_top.cpp @@ -93,7 +93,7 @@ class CSTop : public Module CommandCSGTop commandcsgtop; CommandCSTop10 commandcstop10; CommandCSGTop10 commandcsgtop10; - service_reference<SQLProvider> sql; + ServiceReference<SQLProvider> sql; MySQLInterface sqlinterface; Anope::string prefix; @@ -115,7 +115,7 @@ class CSTop : public Module ConfigReader config; prefix = config.ReadValue("chanstats", "prefix", "anope_", 0); Anope::string engine = config.ReadValue("chanstats", "engine", "", 0); - this->sql = service_reference<SQLProvider>("SQLProvider", engine); + this->sql = ServiceReference<SQLProvider>("SQLProvider", engine); } SQLResult RunQuery(const SQLQuery &query) diff --git a/modules/commands/cs_flags.cpp b/modules/commands/cs_flags.cpp index c137b55b1..65ae33f2f 100644 --- a/modules/commands/cs_flags.cpp +++ b/modules/commands/cs_flags.cpp @@ -32,12 +32,12 @@ class FlagsChanAccess : public ChanAccess return false; } - Anope::string Serialize() const + Anope::string AccessSerialize() const { return Anope::string(this->flags.begin(), this->flags.end()); } - void Unserialize(const Anope::string &data) anope_override + void AccessUnserialize(const Anope::string &data) anope_override { for (unsigned i = data.length(); i > 0; --i) this->flags.insert(data[i - 1]); @@ -46,7 +46,7 @@ class FlagsChanAccess : public ChanAccess static Anope::string DetermineFlags(const ChanAccess *access) { if (access->provider->name == "access/flags") - return access->Serialize(); + return access->AccessSerialize(); std::set<char> buffer; @@ -86,9 +86,9 @@ class CommandCSFlags : public Command AccessGroup u_access = source.AccessFor(ci); - if (mask.find_first_of("!*@") == Anope::string::npos && !findnick(mask)) + if (mask.find_first_of("!*@") == Anope::string::npos && !NickAlias::Find(mask)) { - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ != NULL) mask = "*!*@" + targ->GetDisplayedHost(); else @@ -191,7 +191,7 @@ class CommandCSFlags : public Command return; } - service_reference<AccessProvider> provider("AccessProvider", "access/flags"); + ServiceReference<AccessProvider> provider("AccessProvider", "access/flags"); if (!provider) return; FlagsChanAccess *access = anope_dynamic_static_cast<FlagsChanAccess *>(provider->Create()); @@ -209,8 +209,8 @@ class CommandCSFlags : public Command FOREACH_MOD(I_OnAccessAdd, OnAccessAdd(ci, source, access)); - Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to modify " << mask << "'s flags to " << access->Serialize(); - source.Reply(_("Access for \002%s\002 on %s set to +\002%s\002"), access->mask.c_str(), ci->name.c_str(), access->Serialize().c_str()); + Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to modify " << mask << "'s flags to " << access->AccessSerialize(); + source.Reply(_("Access for \002%s\002 on %s set to +\002%s\002"), access->mask.c_str(), ci->name.c_str(), access->AccessSerialize().c_str()); return; } @@ -227,7 +227,7 @@ class CommandCSFlags : public Command ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Flags").addColumn("Creator").addColumn("Created"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Flags").AddColumn("Creator").AddColumn("Created"); unsigned count = 0; for (unsigned i = 0, end = ci->GetAccessCount(); i < end; ++i) @@ -257,11 +257,11 @@ class CommandCSFlags : public Command entry["Mask"] = access->mask; entry["Flags"] = FlagsChanAccess::DetermineFlags(access); entry["Creator"] = access->creator; - entry["Created"] = do_strftime(access->created, source.nc, true); - list.addEntry(entry); + entry["Created"] = Anope::strftime(access->created, source.nc, true); + list.AddEntry(entry); } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on %s access list."), ci->name.c_str()); else { @@ -311,7 +311,7 @@ class CommandCSFlags : public Command const Anope::string &chan = params[0]; const Anope::string &cmd = params[1]; - ChannelInfo *ci = cs_findchan(chan); + ChannelInfo *ci = ChannelInfo::Find(chan); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); @@ -329,7 +329,7 @@ class CommandCSFlags : public Command if (!has_access) source.Reply(ACCESS_DENIED); - else if (readonly && !is_list) + else if (Anope::ReadOnly && !is_list) source.Reply(_("Sorry, channel access list modification is temporarily disabled.")); else if (cmd.equals_ci("MODIFY")) this->DoModify(source, ci, params); @@ -374,7 +374,7 @@ class CommandCSFlags : public Command Privilege *p = PrivilegeManager::FindPrivilege(it->second); if (p == NULL) continue; - source.Reply(" %c - %s", it->first, translate(source.nc, p->desc.c_str())); + source.Reply(" %c - %s", it->first, Language::Translate(source.nc, p->desc.c_str())); } return true; diff --git a/modules/commands/cs_getkey.cpp b/modules/commands/cs_getkey.cpp index e0205ad03..212388e3f 100644 --- a/modules/commands/cs_getkey.cpp +++ b/modules/commands/cs_getkey.cpp @@ -26,7 +26,7 @@ class CommandCSGetKey : public Command { const Anope::string &chan = params[0]; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_info.cpp b/modules/commands/cs_info.cpp index 310879135..c485c3cb4 100644 --- a/modules/commands/cs_info.cpp +++ b/modules/commands/cs_info.cpp @@ -22,7 +22,7 @@ class CommandCSInfo : public Command if (!buf.empty()) buf += ", "; - buf += translate(nc, str); + buf += Language::Translate(nc, str); } } @@ -39,7 +39,7 @@ class CommandCSInfo : public Command const Anope::string &chan = params[0]; NickCore *nc = source.nc; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -65,8 +65,8 @@ class CommandCSInfo : public Command if (!ci->desc.empty()) info["Description"] = ci->desc; - info["Registered"] = do_strftime(ci->time_registered); - info["Last used"] = do_strftime(ci->last_used); + info["Registered"] = Anope::strftime(ci->time_registered); + info["Last used"] = Anope::strftime(ci->last_used); const ModeLock *secret = ci->GetMLock(CMODE_SECRET); if (!ci->last_topic.empty() && (show_all || ((!secret || secret->set == false) && (!ci->c || !ci->c->HasMode(CMODE_SECRET))))) @@ -103,7 +103,7 @@ class CommandCSInfo : public Command info["Mode lock"] = ml; if (!ci->HasFlag(CI_NO_EXPIRE)) - info["Expires on"] = do_strftime(ci->last_used + Config->CSExpire); + info["Expires on"] = Anope::strftime(ci->last_used + Config->CSExpire); } if (ci->HasFlag(CI_SUSPENDED)) { diff --git a/modules/commands/cs_invite.cpp b/modules/commands/cs_invite.cpp index 32ef87e3e..1085947a2 100644 --- a/modules/commands/cs_invite.cpp +++ b/modules/commands/cs_invite.cpp @@ -27,7 +27,7 @@ class CommandCSInvite : public Command const Anope::string &chan = params[0]; User *u = source.GetUser(); - Channel *c = findchan(chan); + Channel *c = Channel::Find(chan); if (!c) { @@ -52,7 +52,7 @@ class CommandCSInvite : public Command if (params.size() == 1) u2 = u; else - u2 = finduser(params[1]); + u2 = User::Find(params[1], true); if (!u2) { @@ -71,7 +71,7 @@ class CommandCSInvite : public Command { bool override = !source.AccessFor(ci).HasPriv("INVITE"); - ircdproto->SendInvite(ci->WhoSends(), c, u2); + IRCD->SendInvite(ci->WhoSends(), c, u2); if (u2 != u) { source.Reply(_("\002%s\002 has been invited to \002%s\002."), u2->nick.c_str(), c->name.c_str()); diff --git a/modules/commands/cs_kick.cpp b/modules/commands/cs_kick.cpp index 97d879416..4073f3fe8 100644 --- a/modules/commands/cs_kick.cpp +++ b/modules/commands/cs_kick.cpp @@ -30,9 +30,9 @@ class CommandCSKick : public Command const Anope::string &reason = params.size() > 2 ? params[2] : "Requested"; User *u = source.GetUser(); - ChannelInfo *ci = cs_findchan(params[0]); - Channel *c = findchan(params[0]); - User *u2 = finduser(target); + ChannelInfo *ci = ChannelInfo::Find(params[0]); + Channel *c = Channel::Find(params[0]); + User *u2 = User::Find(target, true); if (!c) { diff --git a/modules/commands/cs_list.cpp b/modules/commands/cs_list.cpp index db5a5136a..9132d07a8 100644 --- a/modules/commands/cs_list.cpp +++ b/modules/commands/cs_list.cpp @@ -33,8 +33,9 @@ class CommandCSList : public Command if (pattern[0] == '#') { - Anope::string n1 = myStrGetToken(pattern.substr(1), '-', 0), /* Read FROM out */ - n2 = myStrGetTokenRemainder(pattern, '-', 1); + Anope::string n1, n2; + sepstream(pattern.substr(1), '-').GetToken(n1, 0); + sepstream(pattern, '-').GetToken(n2, 1); try { @@ -72,7 +73,7 @@ class CommandCSList : public Command source.Reply(_("List of entries matching \002%s\002:"), pattern.c_str()); ListFormatter list; - list.addColumn("Name").addColumn("Description"); + list.AddColumn("Name").AddColumn("Description"); for (registered_channel_map::const_iterator it = RegisteredChannelList->begin(), it_end = RegisteredChannelList->end(); it != it_end; ++it) { @@ -99,7 +100,7 @@ class CommandCSList : public Command entry["Description"] = "[Suspended]"; else entry["Description"] = ci->desc; - list.addEntry(entry); + list.AddEntry(entry); } ++count; } diff --git a/modules/commands/cs_log.cpp b/modules/commands/cs_log.cpp index bd630b4e2..4965ab561 100644 --- a/modules/commands/cs_log.cpp +++ b/modules/commands/cs_log.cpp @@ -28,7 +28,7 @@ public: { const Anope::string &channel = params[0]; - ChannelInfo *ci = cs_findchan(channel); + ChannelInfo *ci = ChannelInfo::Find(channel); if (ci == NULL) source.Reply(CHAN_X_NOT_REGISTERED, channel.c_str()); else if (!source.AccessFor(ci).HasPriv("SET") && !source.HasPriv("chanserv/set")) @@ -40,7 +40,7 @@ public: else { ListFormatter list; - list.addColumn("Number").addColumn("Service").addColumn("Command").addColumn("Method").addColumn(""); + list.AddColumn("Number").AddColumn("Service").AddColumn("Command").AddColumn("Method").AddColumn(""); for (unsigned i = 0; i < ci->log_settings->size(); ++i) { @@ -52,7 +52,7 @@ public: entry["Command"] = log->command_name; entry["Method"] = log->method; entry[""] = log->extra; - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("Log list for %s:"), ci->name.c_str()); @@ -79,7 +79,7 @@ public: Anope::string service = command.substr(0, sl), command_name = command.substr(sl + 1); - BotInfo *bi = findbot(service); + BotInfo *bi = BotInfo::Find(service, true); if (bi == NULL || bi->commands.count(command_name) == 0) { @@ -87,7 +87,7 @@ public: return; } - service_reference<Command> c_service("Command", bi->commands[command_name].name); + ServiceReference<Command> c_service("Command", bi->commands[command_name].name); if (!c_service) { source.Reply(_("%s is not a valid command."), command.c_str()); @@ -117,7 +117,7 @@ public: { if (log->extra == extra) { - log->destroy(); + log->Destroy(); ci->log_settings->erase(ci->log_settings->begin() + i - 1); Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to remove logging for " << command << " with method " << method << (extra == "" ? "" : " ") << extra; source.Reply(_("Logging for command %s on %s with log method %s%s%s has been removed."), command_name.c_str(), bi->nick.c_str(), method.c_str(), extra.empty() ? "" : " ", extra.empty() ? "" : extra.c_str()); @@ -194,7 +194,7 @@ class CSLog : public Module void OnLog(Log *l) anope_override { - if (l->Type != LOG_COMMAND || l->u == NULL || l->c == NULL || l->ci == NULL || !Me || !Me->IsSynced()) + if (l->type != LOG_COMMAND || l->u == NULL || l->c == NULL || l->ci == NULL || !Me || !Me->IsSynced()) return; for (unsigned i = l->ci->log_settings->size(); i > 0; --i) @@ -207,13 +207,13 @@ class CSLog : public Module if (log->method.equals_ci("MESSAGE") && l->ci->c && l->ci->bi && l->ci->c->FindUser(l->ci->bi) != NULL) { - ircdproto->SendPrivmsg(l->ci->bi, log->extra + l->ci->c->name, "%s", buffer.c_str()); + IRCD->SendPrivmsg(l->ci->bi, log->extra + l->ci->c->name, "%s", buffer.c_str()); l->ci->bi->lastmsg = Anope::CurTime; } else if (log->method.equals_ci("NOTICE") && l->ci->c && l->ci->bi && l->ci->c->FindUser(l->ci->bi) != NULL) - ircdproto->SendNotice(l->ci->bi, log->extra + l->ci->c->name, "%s", buffer.c_str()); - else if (log->method.equals_ci("MEMO") && memoserv && l->ci->WhoSends() != NULL) - memoserv->Send(l->ci->WhoSends()->nick, l->ci->name, buffer, true); + IRCD->SendNotice(l->ci->bi, log->extra + l->ci->c->name, "%s", buffer.c_str()); + else if (log->method.equals_ci("MEMO") && MemoServService && l->ci->WhoSends() != NULL) + MemoServService->Send(l->ci->WhoSends()->nick, l->ci->name, buffer, true); } } } diff --git a/modules/commands/cs_mode.cpp b/modules/commands/cs_mode.cpp index 840912aaf..c33b317a2 100644 --- a/modules/commands/cs_mode.cpp +++ b/modules/commands/cs_mode.cpp @@ -17,7 +17,7 @@ class CommandCSMode : public Command { bool CanSet(CommandSource &source, ChannelInfo *ci, ChannelMode *cm) { - if (!ci || !cm || cm->Type != MODE_STATUS) + if (!ci || !cm || cm->type != MODE_STATUS) return false; const Anope::string accesses[] = { "VOICE", "HALFOP", "OPDEOP", "PROTECT", "OWNER", "" }; @@ -30,7 +30,7 @@ class CommandCSMode : public Command if (access.HasPriv(accesses[i])) { ChannelMode *cm2 = ModeManager::FindChannelModeByName(modes[i]); - if (cm2 == NULL || cm2->Type != MODE_STATUS) + if (cm2 == NULL || cm2->type != MODE_STATUS) continue; ChannelModeStatus *cms2 = anope_dynamic_static_cast<ChannelModeStatus *>(cm2); if (cms2->Level > u_level) @@ -82,15 +82,15 @@ class CommandCSMode : public Command } Anope::string mode_param; - if (((cm->Type == MODE_STATUS || cm->Type == MODE_LIST) && !sep.GetToken(mode_param)) || (cm->Type == MODE_PARAM && adding && !sep.GetToken(mode_param))) - source.Reply(_("Missing parameter for mode %c."), cm->ModeChar); + if (((cm->type == MODE_STATUS || cm->type == MODE_LIST) && !sep.GetToken(mode_param)) || (cm->type == MODE_PARAM && adding && !sep.GetToken(mode_param))) + source.Reply(_("Missing parameter for mode %c."), cm->mchar); else { ci->SetMLock(cm, adding, mode_param, source.GetNick()); if (!mode_param.empty()) mode_param = " " + mode_param; - source.Reply(_("%c%c%s locked on %s"), adding ? '+' : '-', cm->ModeChar, mode_param.c_str(), ci->name.c_str()); - Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to lock " << (adding ? '+' : '-') << cm->ModeChar << mode_param; + source.Reply(_("%c%c%s locked on %s"), adding ? '+' : '-', cm->mchar, mode_param.c_str(), ci->name.c_str()); + Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to lock " << (adding ? '+' : '-') << cm->mchar << mode_param; } } } @@ -132,19 +132,19 @@ class CommandCSMode : public Command } Anope::string mode_param; - if (!cm->Type == MODE_REGULAR && !sep.GetToken(mode_param)) - source.Reply(_("Missing parameter for mode %c."), cm->ModeChar); + if (!cm->type == MODE_REGULAR && !sep.GetToken(mode_param)) + source.Reply(_("Missing parameter for mode %c."), cm->mchar); else { if (ci->RemoveMLock(cm, adding, mode_param)) { if (!mode_param.empty()) mode_param = " " + mode_param; - source.Reply(_("%c%c%s has been unlocked from %s."), adding == 1 ? '+' : '-', cm->ModeChar, mode_param.c_str(), ci->name.c_str()); - Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to unlock " << (adding ? '+' : '-') << cm->ModeChar << mode_param; + source.Reply(_("%c%c%s has been unlocked from %s."), adding == 1 ? '+' : '-', cm->mchar, mode_param.c_str(), ci->name.c_str()); + Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, this, ci) << "to unlock " << (adding ? '+' : '-') << cm->mchar << mode_param; } else - source.Reply(_("%c%c is not locked on %s."), adding == 1 ? '+' : '-', cm->ModeChar, ci->name.c_str()); + source.Reply(_("%c%c is not locked on %s."), adding == 1 ? '+' : '-', cm->mchar, ci->name.c_str()); } } } @@ -159,7 +159,7 @@ class CommandCSMode : public Command else { ListFormatter list; - list.addColumn("Mode").addColumn("Param").addColumn("Creator").addColumn("Created"); + list.AddColumn("Mode").AddColumn("Param").AddColumn("Creator").AddColumn("Created"); for (ChannelInfo::ModeList::const_iterator it = mlocks.begin(), it_end = mlocks.end(); it != it_end; ++it) { @@ -169,11 +169,11 @@ class CommandCSMode : public Command continue; ListFormatter::ListEntry entry; - entry["Mode"] = Anope::printf("%c%c", ml->set ? '+' : '-', cm->ModeChar); + entry["Mode"] = Anope::printf("%c%c", ml->set ? '+' : '-', cm->mchar); entry["Param"] = ml->param; entry["Creator"] = ml->setter; - entry["Created"] = do_strftime(ml->created, source.nc, false); - list.addEntry(entry); + entry["Created"] = Anope::strftime(ml->created, source.nc, false); + list.AddEntry(entry); } source.Reply(_("Mode locks for %s:"), ci->name.c_str()); @@ -218,7 +218,7 @@ class CommandCSMode : public Command ChannelMode *cm = ModeManager::ChannelModes[j]; if (!u || cm->CanSet(u)) { - if (cm->Type == MODE_REGULAR || (!adding && cm->Type == MODE_PARAM)) + if (cm->type == MODE_REGULAR || (!adding && cm->type == MODE_PARAM)) { if (adding) ci->c->SetMode(NULL, cm); @@ -234,7 +234,7 @@ class CommandCSMode : public Command ChannelMode *cm = ModeManager::FindChannelModeByChar(modes[i]); if (!cm || (u && !cm->CanSet(u))) continue; - switch (cm->Type) + switch (cm->type) { case MODE_REGULAR: if (adding) @@ -257,13 +257,13 @@ class CommandCSMode : public Command if (!this->CanSet(source, ci, cm)) { - source.Reply(_("You do not have access to set mode %c."), cm->ModeChar); + source.Reply(_("You do not have access to set mode %c."), cm->mchar); break; } AccessGroup u_access = source.AccessFor(ci); - if (str_is_wildcard(param)) + if (param.find_first_of("*?") != Anope::string::npos) { for (CUserList::const_iterator it = ci->c->users.begin(), it_end = ci->c->users.end(); it != it_end; ++it) { @@ -288,7 +288,7 @@ class CommandCSMode : public Command } else { - User *target = finduser(param); + User *target = User::Find(param, true); if (target == NULL) { source.Reply(NICK_X_NOT_IN_USE, param.c_str()); @@ -316,7 +316,7 @@ class CommandCSMode : public Command ci->c->SetMode(NULL, cm, param); else { - std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> its = ci->c->GetModeList(cm->Name); + std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> its = ci->c->GetModeList(cm->name); for (; its.first != its.second;) { const Anope::string &mask = its.first->second; @@ -343,7 +343,7 @@ class CommandCSMode : public Command { const Anope::string &subcommand = params[1]; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (!ci || !ci->c) source.Reply(CHAN_X_NOT_IN_USE, params[0].c_str()); diff --git a/modules/commands/cs_modes.cpp b/modules/commands/cs_modes.cpp index 2775e92bc..696c38dde 100644 --- a/modules/commands/cs_modes.cpp +++ b/modules/commands/cs_modes.cpp @@ -18,8 +18,8 @@ class CommandModeBase : public Command void do_mode(CommandSource &source, Command *com, ChannelMode *cm, const Anope::string &chan, const Anope::string &nick, bool set, const Anope::string &level, const Anope::string &levelself) { User *u = source.GetUser(); - User *u2 = finduser(nick); - Channel *c = findchan(chan); + User *u2 = User::Find(nick, true); + Channel *c = Channel::Find(chan); if (!c) { diff --git a/modules/commands/cs_register.cpp b/modules/commands/cs_register.cpp index 28fb931f5..e756482c7 100644 --- a/modules/commands/cs_register.cpp +++ b/modules/commands/cs_register.cpp @@ -29,10 +29,10 @@ class CommandCSRegister : public Command User *u = source.GetUser(); NickCore *nc = source.nc; - Channel *c = findchan(params[0]); - ChannelInfo *ci = cs_findchan(params[0]); + Channel *c = Channel::Find(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); - if (readonly) + if (Anope::ReadOnly) source.Reply(_("Sorry, channel registration is temporarily disabled.")); else if (nc->HasFlag(NI_UNCONFIRMED)) source.Reply(_("You must confirm your account before you can register a channel.")); @@ -40,7 +40,7 @@ class CommandCSRegister : public Command source.Reply(_("Local channels cannot be registered.")); else if (chan[0] != '#') source.Reply(CHAN_SYMBOL_REQUIRED); - else if (!ircdproto->IsChannelValid(chan)) + else if (!IRCD->IsChannelValid(chan)) source.Reply(CHAN_X_INVALID, chan.c_str()); else if (ci) source.Reply(_("Channel \002%s\002 is already registered!"), chan.c_str()); @@ -55,7 +55,7 @@ class CommandCSRegister : public Command if (!chdesc.empty()) ci->desc = chdesc; - for (ChannelInfo::ModeList::iterator it = def_mode_locks.begin(), it_end = def_mode_locks.end(); it != it_end; ++it) + for (ChannelInfo::ModeList::iterator it = ModeManager::DefaultModeLocks.begin(), it_end = ModeManager::DefaultModeLocks.end(); it != it_end; ++it) { ModeLock *ml = new ModeLock(*it->second); ml->setter = source.GetNick(); diff --git a/modules/commands/cs_saset.cpp b/modules/commands/cs_saset.cpp index a4a72ee76..211148e13 100644 --- a/modules/commands/cs_saset.cpp +++ b/modules/commands/cs_saset.cpp @@ -43,7 +43,7 @@ class CommandCSSASet : public Command const CommandInfo &info = it->second; if (c_name.find_ci(this_name + " ") == 0) { - service_reference<Command> command("Command", info.name); + ServiceReference<Command> command("Command", info.name); if (command) { source.command = it->first; diff --git a/modules/commands/cs_saset_noexpire.cpp b/modules/commands/cs_saset_noexpire.cpp index 78d8641d4..1c7b260ec 100644 --- a/modules/commands/cs_saset_noexpire.cpp +++ b/modules/commands/cs_saset_noexpire.cpp @@ -24,7 +24,7 @@ class CommandCSSASetNoexpire : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_seen.cpp b/modules/commands/cs_seen.cpp index d2686e013..18a21d35e 100644 --- a/modules/commands/cs_seen.cpp +++ b/modules/commands/cs_seen.cpp @@ -38,7 +38,7 @@ struct SeenInfo : Serializable { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; @@ -48,12 +48,12 @@ struct SeenInfo : Serializable data["nick2"] << nick2; data["channel"] << channel; data["message"] << message; - data["last"].setType(Serialize::DT_INT) << last; + data["last"].SetType(Serialize::DT_INT) << last; return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { SeenInfo *s; if (obj) @@ -95,8 +95,8 @@ static SeenInfo *FindInfo(const Anope::string &nick) static bool ShouldHide(const Anope::string &channel, User *u) { - Channel *targetchan = findchan(channel); - const ChannelInfo *targetchan_ci = targetchan ? *targetchan->ci : cs_findchan(channel); + Channel *targetchan = Channel::Find(channel); + const ChannelInfo *targetchan_ci = targetchan ? *targetchan->ci : ChannelInfo::Find(channel); if (targetchan && targetchan->HasMode(CMODE_SECRET)) return true; @@ -137,7 +137,7 @@ class CommandOSSeen : public Command else if (params[0].equals_ci("CLEAR")) { time_t time = 0; - if ((params.size() < 2) || (0 >= (time = dotime(params[1])))) + if ((params.size() < 2) || (0 >= (time = Anope::DoTime(params[1])))) { this->OnSyntaxError(source, params[0]); return; @@ -151,14 +151,14 @@ class CommandOSSeen : public Command ++it; if (time < buf->second->last) { - Log(LOG_DEBUG) << buf->first << " was last seen " << do_strftime(buf->second->last) << ", deleting entry"; - buf->second->destroy(); + Log(LOG_DEBUG) << buf->first << " was last seen " << Anope::strftime(buf->second->last) << ", deleting entry"; + buf->second->Destroy(); database.erase(buf); counter++; } } - Log(LOG_ADMIN, source, this) << "CLEAR and removed " << counter << " nicks that were added after " << do_strftime(time, NULL, true); - source.Reply(_("Database cleared, removed %lu nicks that were added after %s"), counter, do_strftime(time, source.nc, true).c_str()); + Log(LOG_ADMIN, source, this) << "CLEAR and removed " << counter << " nicks that were added after " << Anope::strftime(time, NULL, true); + source.Reply(_("Database cleared, removed %lu nicks that were added after %s"), counter, Anope::strftime(time, source.nc, true).c_str()); } else this->SendSyntax(source); @@ -199,7 +199,7 @@ class CommandSeen : public Command return; } - if (findbot(target) != NULL) + if (BotInfo::Find(target, true) != NULL) { source.Reply(_("%s is a client on services."), target.c_str()); return; @@ -218,15 +218,15 @@ class CommandSeen : public Command return; } - User *u2 = finduser(target); + User *u2 = User::Find(target, true); Anope::string onlinestatus; if (u2) onlinestatus = "."; else onlinestatus = Anope::printf(_(" but %s mysteriously dematerialized."), target.c_str()); - Anope::string timebuf = duration(Anope::CurTime - info->last, source.nc); - Anope::string timebuf2 = do_strftime(info->last, source.nc, true); + Anope::string timebuf = Anope::Duration(Anope::CurTime - info->last, source.nc); + Anope::string timebuf2 = Anope::strftime(info->last, source.nc, true); if (info->type == NEW) { @@ -235,7 +235,7 @@ class CommandSeen : public Command } else if (info->type == NICK_TO) { - u2 = finduser(info->nick2); + u2 = User::Find(info->nick2, true); if (u2) onlinestatus = Anope::printf( _(". %s is still online."), u2->nick.c_str()); else @@ -309,8 +309,8 @@ class DataBasePurger : public CallBack if ((Anope::CurTime - cur->second->last) > purgetime) { - Log(LOG_DEBUG) << cur->first << " was last seen " << do_strftime(cur->second->last) << ", purging entry"; - cur->second->destroy(); + Log(LOG_DEBUG) << cur->first << " was last seen " << Anope::strftime(cur->second->last) << ", purging entry"; + cur->second->Destroy(); database.erase(cur); } } @@ -320,12 +320,12 @@ class DataBasePurger : public CallBack class CSSeen : public Module { - SerializeType seeninfo_type; + Serialize::Type seeninfo_type; CommandSeen commandseen; CommandOSSeen commandosseen; DataBasePurger purger; public: - CSSeen(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), seeninfo_type("SeenInfo", SeenInfo::unserialize), commandseen(this), commandosseen(this), purger(this) + CSSeen(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), seeninfo_type("SeenInfo", SeenInfo::Unserialize), commandseen(this), commandosseen(this), purger(this) { this->SetAuthor("Anope"); @@ -344,14 +344,14 @@ class CSSeen : public Module void OnReload() anope_override { ConfigReader config; - purgetime = dotime(config.ReadValue("cs_seen", "purgetime", "30d", 0)); - expiretimeout = dotime(config.ReadValue("cs_seen", "expiretimeout", "1d", 0)); + purgetime = Anope::DoTime(config.ReadValue("cs_seen", "purgetime", "30d", 0)); + expiretimeout = Anope::DoTime(config.ReadValue("cs_seen", "expiretimeout", "1d", 0)); if (purger.GetSecs() != expiretimeout) purger.SetSecs(expiretimeout); } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { if (u) UpdateUser(u, NEW, u->nick, "", "", ""); diff --git a/modules/commands/cs_set.cpp b/modules/commands/cs_set.cpp index 9851a27a1..0ac07e2b2 100644 --- a/modules/commands/cs_set.cpp +++ b/modules/commands/cs_set.cpp @@ -43,7 +43,7 @@ class CommandCSSet : public Command const CommandInfo &info = it->second; if (c_name.find_ci(this_name + " ") == 0) { - service_reference<Command> command("Command", info.name); + ServiceReference<Command> command("Command", info.name); if (command) { source.command = it->first; diff --git a/modules/commands/cs_set_autoop.cpp b/modules/commands/cs_set_autoop.cpp index 8e576be3d..0b00b151b 100644 --- a/modules/commands/cs_set_autoop.cpp +++ b/modules/commands/cs_set_autoop.cpp @@ -24,7 +24,7 @@ class CommandCSSetAutoOp : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_bantype.cpp b/modules/commands/cs_set_bantype.cpp index a963720ff..e7dfc52ee 100644 --- a/modules/commands/cs_set_bantype.cpp +++ b/modules/commands/cs_set_bantype.cpp @@ -24,7 +24,7 @@ class CommandCSSetBanType : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_chanstats.cpp b/modules/commands/cs_set_chanstats.cpp index 904d7fb22..118387ee4 100644 --- a/modules/commands/cs_set_chanstats.cpp +++ b/modules/commands/cs_set_chanstats.cpp @@ -24,7 +24,7 @@ class CommandCSSetChanstats : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_description.cpp b/modules/commands/cs_set_description.cpp index b72c2cf8e..a5ad525ab 100644 --- a/modules/commands/cs_set_description.cpp +++ b/modules/commands/cs_set_description.cpp @@ -24,7 +24,7 @@ class CommandCSSetDescription : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_founder.cpp b/modules/commands/cs_set_founder.cpp index a1be1ba91..25b43d481 100644 --- a/modules/commands/cs_set_founder.cpp +++ b/modules/commands/cs_set_founder.cpp @@ -24,7 +24,7 @@ class CommandCSSetFounder : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -48,7 +48,7 @@ class CommandCSSetFounder : public Command return; } - const NickAlias *na = findnick(params[1]); + const NickAlias *na = NickAlias::Find(params[1]); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, params[1].c_str()); diff --git a/modules/commands/cs_set_keeptopic.cpp b/modules/commands/cs_set_keeptopic.cpp index d95d4ac2b..24b3d4f03 100644 --- a/modules/commands/cs_set_keeptopic.cpp +++ b/modules/commands/cs_set_keeptopic.cpp @@ -24,7 +24,7 @@ class CommandCSSetKeepTopic : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_misc.cpp b/modules/commands/cs_set_misc.cpp index b5a01174e..3bf0e9bbd 100644 --- a/modules/commands/cs_set_misc.cpp +++ b/modules/commands/cs_set_misc.cpp @@ -14,7 +14,7 @@ struct CSMiscData : ExtensibleItem, Serializable { - serialize_obj<ChannelInfo> ci; + Serialize::Reference<ChannelInfo> ci; Anope::string name; Anope::string data; @@ -22,7 +22,7 @@ struct CSMiscData : ExtensibleItem, Serializable { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data sdata; @@ -33,9 +33,9 @@ struct CSMiscData : ExtensibleItem, Serializable return sdata; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (ci == NULL) return NULL; @@ -75,7 +75,7 @@ class CommandCSSetMisc : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -108,12 +108,12 @@ class CommandCSSetMisc : public Command class CSSetMisc : public Module { - SerializeType csmiscdata_type; + Serialize::Type csmiscdata_type; CommandCSSetMisc commandcssetmisc; public: CSSetMisc(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - csmiscdata_type("CSMiscData", CSMiscData::unserialize), commandcssetmisc(this) + csmiscdata_type("CSMiscData", CSMiscData::Unserialize), commandcssetmisc(this) { this->SetAuthor("Anope"); diff --git a/modules/commands/cs_set_peace.cpp b/modules/commands/cs_set_peace.cpp index f7eb8af6b..35459b59b 100644 --- a/modules/commands/cs_set_peace.cpp +++ b/modules/commands/cs_set_peace.cpp @@ -24,7 +24,7 @@ class CommandCSSetPeace : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_persist.cpp b/modules/commands/cs_set_persist.cpp index bdd3b9004..03e5d3a84 100644 --- a/modules/commands/cs_set_persist.cpp +++ b/modules/commands/cs_set_persist.cpp @@ -24,7 +24,7 @@ class CommandCSSetPersist : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -60,21 +60,19 @@ class CommandCSSetPersist : public Command ci->bi->Join(c); } - /* No botserv bot, no channel mode */ - /* Give them ChanServ - * Yes, this works fine with no Config->s_BotServ + /* No botserv bot, no channel mode, give them ChanServ. + * Yes, this works fine with no Config->BotServ. */ if (!ci->bi && !cm) { - BotInfo *bi = findbot(Config->ChanServ); - if (!bi) + if (!ChanServ) { source.Reply(_("ChanServ is required to enable persist on this network.")); return; } - bi->Assign(NULL, ci); - if (!ci->c->FindUser(bi)) - bi->Join(ci->c); + ChanServ->Assign(NULL, ci); + if (!ci->c->FindUser(ChanServ)) + ChanServ->Join(ci->c); } /* Set the perm mode */ @@ -111,14 +109,13 @@ class CommandCSSetPersist : public Command */ if (!cm && Config->BotServ.empty() && ci->bi) { - BotInfo *bi = findbot(Config->ChanServ); - if (!bi) + if (!ChanServ) { source.Reply(_("ChanServ is required to enable persist on this network.")); return; } /* Unassign bot */ - bi->UnAssign(NULL, ci); + ChanServ->UnAssign(NULL, ci); } } diff --git a/modules/commands/cs_set_private.cpp b/modules/commands/cs_set_private.cpp index 45741eb20..a677aaf38 100644 --- a/modules/commands/cs_set_private.cpp +++ b/modules/commands/cs_set_private.cpp @@ -24,7 +24,7 @@ class CommandCSSetPrivate : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_restricted.cpp b/modules/commands/cs_set_restricted.cpp index 8b520006a..45a9b188e 100644 --- a/modules/commands/cs_set_restricted.cpp +++ b/modules/commands/cs_set_restricted.cpp @@ -23,7 +23,7 @@ class CommandCSSetRestricted : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_secure.cpp b/modules/commands/cs_set_secure.cpp index 84ea75121..7659c8674 100644 --- a/modules/commands/cs_set_secure.cpp +++ b/modules/commands/cs_set_secure.cpp @@ -24,7 +24,7 @@ class CommandCSSetSecure : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_securefounder.cpp b/modules/commands/cs_set_securefounder.cpp index b8d7ac14f..d3d22f294 100644 --- a/modules/commands/cs_set_securefounder.cpp +++ b/modules/commands/cs_set_securefounder.cpp @@ -24,7 +24,7 @@ class CommandCSSetSecureFounder : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_secureops.cpp b/modules/commands/cs_set_secureops.cpp index c92401e59..9a95735be 100644 --- a/modules/commands/cs_set_secureops.cpp +++ b/modules/commands/cs_set_secureops.cpp @@ -24,7 +24,7 @@ class CommandCSSetSecureOps : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_signkick.cpp b/modules/commands/cs_set_signkick.cpp index 52d3934af..f3b482a67 100644 --- a/modules/commands/cs_set_signkick.cpp +++ b/modules/commands/cs_set_signkick.cpp @@ -24,7 +24,7 @@ class CommandCSSetSignKick : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_set_successor.cpp b/modules/commands/cs_set_successor.cpp index 64f875dce..8b36d6853 100644 --- a/modules/commands/cs_set_successor.cpp +++ b/modules/commands/cs_set_successor.cpp @@ -24,7 +24,7 @@ class CommandCSSetSuccessor : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -55,7 +55,7 @@ class CommandCSSetSuccessor : public Command if (params.size() > 1) { - const NickAlias *na = findnick(params[1]); + const NickAlias *na = NickAlias::Find(params[1]); if (!na) { diff --git a/modules/commands/cs_set_topiclock.cpp b/modules/commands/cs_set_topiclock.cpp index eb0d75e2a..9212d291d 100644 --- a/modules/commands/cs_set_topiclock.cpp +++ b/modules/commands/cs_set_topiclock.cpp @@ -24,7 +24,7 @@ class CommandCSSetTopicLock : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_status.cpp b/modules/commands/cs_status.cpp index b8ac38f77..4d609eb8d 100644 --- a/modules/commands/cs_status.cpp +++ b/modules/commands/cs_status.cpp @@ -26,7 +26,7 @@ public: { const Anope::string &channel = params[0]; - ChannelInfo *ci = cs_findchan(channel); + ChannelInfo *ci = ChannelInfo::Find(channel); if (ci == NULL) source.Reply(CHAN_X_NOT_REGISTERED, channel.c_str()); else if (!source.AccessFor(ci).HasPriv("ACCESS_CHANGE") && !source.HasPriv("chanserv/access/modify")) @@ -38,20 +38,20 @@ public: nick = params[1]; AccessGroup ag; - User *u = finduser(nick); + User *u = User::Find(nick, true); NickAlias *na = NULL; if (u != NULL) ag = ci->AccessFor(u); else { - na = findnick(nick); + na = NickAlias::Find(nick); if (na != NULL) ag = ci->AccessFor(na->nc); } - if (ag.SuperAdmin) + if (ag.super_admin) source.Reply(_("\2%s\2 is a super administrator."), nick.c_str()); - else if (ag.Founder) + else if (ag.founder) source.Reply(_("\2%s\2 is the channel founder."), nick.c_str()); else if (ag.empty()) source.Reply(_("\2%s\2 has no access on \2%s\2."), nick.c_str(), ci->name.c_str()); @@ -63,7 +63,7 @@ public: { ChanAccess *acc = ag[i]; - source.Reply(_("\2%s\2 matches access entry %s, which has privilege %s."), nick.c_str(), acc->mask.c_str(), acc->Serialize().c_str()); + source.Reply(_("\2%s\2 matches access entry %s, which has privilege %s."), nick.c_str(), acc->mask.c_str(), acc->AccessSerialize().c_str()); } } diff --git a/modules/commands/cs_suspend.cpp b/modules/commands/cs_suspend.cpp index bce549e79..b380d4c97 100644 --- a/modules/commands/cs_suspend.cpp +++ b/modules/commands/cs_suspend.cpp @@ -22,7 +22,7 @@ struct ChanSuspend : ExtensibleItem, Serializable { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data sd; @@ -32,9 +32,9 @@ struct ChanSuspend : ExtensibleItem, Serializable return sd; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &sd) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &sd) { - ChannelInfo *ci = cs_findchan(sd["chan"].astr()); + ChannelInfo *ci = ChannelInfo::Find(sd["chan"].astr()); if (ci == NULL) return NULL; @@ -77,7 +77,7 @@ class CommandCSSuspend : public Command expiry.clear(); } else - expiry_secs = dotime(expiry); + expiry_secs = Anope::DoTime(expiry); if (Config->ForceForbidReason && reason.empty()) { @@ -85,10 +85,10 @@ class CommandCSSuspend : public Command return; } - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); - ChannelInfo *ci = cs_findchan(chan); + ChannelInfo *ci = ChannelInfo::Find(chan); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); @@ -113,7 +113,7 @@ class CommandCSSuspend : public Command } for (unsigned i = 0; i < users.size(); ++i) - ci->c->Kick(NULL, users[i], "%s", !reason.empty() ? reason.c_str() : translate(users[i], _("This channel has been suspended."))); + ci->c->Kick(NULL, users[i], "%s", !reason.empty() ? reason.c_str() : Language::Translate(users[i], _("This channel has been suspended."))); } if (expiry_secs > 0) @@ -125,7 +125,7 @@ class CommandCSSuspend : public Command ci->Extend("cs_suspend_expire", cs); } - Log(LOG_ADMIN, source, this, ci) << (!reason.empty() ? reason : "No reason") << ", expires in " << (expiry_secs ? do_strftime(Anope::CurTime + expiry_secs) : "never"); + Log(LOG_ADMIN, source, this, ci) << (!reason.empty() ? reason : "No reason") << ", expires in " << (expiry_secs ? Anope::strftime(Anope::CurTime + expiry_secs) : "never"); source.Reply(_("Channel \002%s\002 is now suspended."), ci->name.c_str()); FOREACH_MOD(I_OnChanSuspend, OnChanSuspend(ci)); @@ -161,10 +161,10 @@ class CommandCSUnSuspend : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -206,13 +206,13 @@ class CommandCSUnSuspend : public Command class CSSuspend : public Module { - SerializeType chansuspend_type; + Serialize::Type chansuspend_type; CommandCSSuspend commandcssuspend; CommandCSUnSuspend commandcsunsuspend; public: CSSuspend(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - chansuspend_type("ChanSuspend", ChanSuspend::unserialize), commandcssuspend(this), commandcsunsuspend(this) + chansuspend_type("ChanSuspend", ChanSuspend::Unserialize), commandcssuspend(this), commandcsunsuspend(this) { this->SetAuthor("Anope"); @@ -247,7 +247,7 @@ class CSSuspend : public Module ci->Shrink("suspend_by"); ci->Shrink("suspend_reason"); - Log(LOG_NORMAL, "expire", findbot(Config->ChanServ)) << "Expiring suspend for " << ci->name; + Log(LOG_NORMAL, "expire", ChanServ) << "Expiring suspend for " << ci->name; } } }; diff --git a/modules/commands/cs_sync.cpp b/modules/commands/cs_sync.cpp index e55864f1b..23d6928a1 100644 --- a/modules/commands/cs_sync.cpp +++ b/modules/commands/cs_sync.cpp @@ -22,7 +22,7 @@ class CommandCSSync : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -35,7 +35,7 @@ class CommandCSSync : public Command Log(LOG_COMMAND, source, this, ci); for (CUserList::iterator it = ci->c->users.begin(), it_end = ci->c->users.end(); it != it_end; ++it) - chan_set_correct_modes((*it)->user, ci->c, 1, false); + ci->c->SetCorrectModes((*it)->user, true, false); source.Reply(_("All user modes on \002%s\002 have been synced."), ci->name.c_str()); } diff --git a/modules/commands/cs_tban.cpp b/modules/commands/cs_tban.cpp index 1120d05d4..40fdfedb9 100644 --- a/modules/commands/cs_tban.cpp +++ b/modules/commands/cs_tban.cpp @@ -22,7 +22,7 @@ static Module *me; class TempBan : public CallBack { private: - dynamic_reference<Channel> chan; + Reference<Channel> chan; Anope::string mask; public: @@ -46,7 +46,7 @@ class CommandCSTBan : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); const Anope::string &nick = params[1]; const Anope::string &time = params[2]; @@ -58,23 +58,22 @@ class CommandCSTBan : public Command source.Reply(CHAN_X_NOT_REGISTERED, c->name.c_str()); else if (!source.AccessFor(c->ci).HasPriv("BAN")) source.Reply(ACCESS_DENIED); - else if (!(u2 = finduser(nick))) + else if (!(u2 = User::Find(nick, true))) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); - else if (matches_list(c, u2, CMODE_EXCEPT)) + else if (c->MatchesList(u2, CMODE_EXCEPT)) source.Reply(CHAN_EXCEPTED, u2->nick.c_str(), c->ci->name.c_str()); else if (u2->IsProtected()) source.Reply(ACCESS_DENIED); else { - time_t t = dotime(time); - Anope::string mask; - get_idealban(c->ci, u2, mask); + time_t t = Anope::DoTime(time); + Anope::string mask = c->ci->GetIdealBan(u2); c->SetMode(NULL, CMODE_BAN, mask); new TempBan(t, c, mask); - Log(LOG_COMMAND, source, this, c->ci) << "for " << mask << " to expire in " << duration(t); + Log(LOG_COMMAND, source, this, c->ci) << "for " << mask << " to expire in " << Anope::Duration(t); - source.Reply(_("%s banned from %s, will auto-expire in %s."), mask.c_str(), c->name.c_str(), duration(t).c_str()); + source.Reply(_("%s banned from %s, will auto-expire in %s."), mask.c_str(), c->name.c_str(), Anope::Duration(t).c_str()); } return; diff --git a/modules/commands/cs_topic.cpp b/modules/commands/cs_topic.cpp index 3474874d6..eccb8b2f6 100644 --- a/modules/commands/cs_topic.cpp +++ b/modules/commands/cs_topic.cpp @@ -27,7 +27,7 @@ class CommandCSTopic : public Command const Anope::string &topic = params.size() > 1 ? params[1] : ""; - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/cs_unban.cpp b/modules/commands/cs_unban.cpp index b60dfebcf..affe8eae9 100644 --- a/modules/commands/cs_unban.cpp +++ b/modules/commands/cs_unban.cpp @@ -24,7 +24,7 @@ class CommandCSUnban : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); @@ -45,7 +45,7 @@ class CommandCSUnban : public Command User *u2 = source.GetUser(); if (params.size() > 1) - u2 = finduser(params[1]); + u2 = User::Find(params[1], true); if (!u2) { @@ -55,7 +55,7 @@ class CommandCSUnban : public Command Log(LOG_COMMAND, source, this, ci) << "to unban " << u2->nick; - common_unban(ci, u2, source.GetUser() == u2); + ci->c->Unban(u2, source.GetUser() == u2); if (u2 == source.GetUser()) source.Reply(_("You have been unbanned from \002%s\002."), ci->c->name.c_str()); else diff --git a/modules/commands/cs_updown.cpp b/modules/commands/cs_updown.cpp index 4d84ff5f5..6d46c873e 100644 --- a/modules/commands/cs_updown.cpp +++ b/modules/commands/cs_updown.cpp @@ -32,19 +32,19 @@ class CommandCSUp : public Command for (UChannelList::iterator it = u->chans.begin(); it != u->chans.end(); ++it) { Channel *c = (*it)->chan; - chan_set_correct_modes(u, c, 1, false); + c->SetCorrectModes(u, true, false); } else { const Anope::string &channel = params[0]; - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c == NULL) source.Reply(CHAN_X_NOT_IN_USE, channel.c_str()); else if (!c->ci) source.Reply(CHAN_X_NOT_REGISTERED, channel.c_str()); else - chan_set_correct_modes(u, c, 1, false); + c->SetCorrectModes(u, true, false); } } @@ -67,7 +67,7 @@ class CommandCSDown : public Command { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm != NULL && cm->Type == MODE_STATUS) + if (cm != NULL && cm->type == MODE_STATUS) c->RemoveMode(NULL, cm, u->nick); } } @@ -94,7 +94,7 @@ class CommandCSDown : public Command else { const Anope::string &channel = params[0]; - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c == NULL) source.Reply(CHAN_X_NOT_IN_USE, channel.c_str()); diff --git a/modules/commands/cs_xop.cpp b/modules/commands/cs_xop.cpp index 1fc3cbdf0..77f6cb5a0 100644 --- a/modules/commands/cs_xop.cpp +++ b/modules/commands/cs_xop.cpp @@ -118,7 +118,7 @@ class XOPChanAccess : public ChanAccess return false; } - Anope::string Serialize() const + Anope::string AccessSerialize() const { for (int i = 0; xopAccess[i].type != XOP_UNKNOWN; ++i) { @@ -131,7 +131,7 @@ class XOPChanAccess : public ChanAccess return ""; } - void Unserialize(const Anope::string &data) anope_override + void AccessUnserialize(const Anope::string &data) anope_override { for (int i = 0; xopAccess[i].type != XOP_UNKNOWN; ++i) { @@ -210,7 +210,7 @@ class XOPBase : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, channel %s list modification is temporarily disabled."), source.command.c_str()); return; @@ -224,7 +224,7 @@ class XOPBase : public Command const ChanAccess *highest = access.Highest(); bool override = false; - if ((!access.Founder && !access.HasPriv("ACCESS_CHANGE")) || ((!highest || *highest <= tmp_access) && !access.Founder)) + if ((!access.founder && !access.HasPriv("ACCESS_CHANGE")) || ((!highest || *highest <= tmp_access) && !access.founder)) { if (source.HasPriv("chanserv/access/modify")) override = true; @@ -235,9 +235,9 @@ class XOPBase : public Command } } - if (mask.find_first_of("!*@") == Anope::string::npos && !findnick(mask)) + if (mask.find_first_of("!*@") == Anope::string::npos && !NickAlias::Find(mask)) { - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ != NULL) mask = "*!*@" + targ->GetDisplayedHost(); else @@ -253,7 +253,7 @@ class XOPBase : public Command if (a->mask.equals_ci(mask)) { - if ((!highest || *a >= *highest) && !access.Founder && !source.HasPriv("chanserv/access/modify")) + if ((!highest || *a >= *highest) && !access.founder && !source.HasPriv("chanserv/access/modify")) { source.Reply(ACCESS_DENIED); return; @@ -270,7 +270,7 @@ class XOPBase : public Command return; } - service_reference<AccessProvider> provider("AccessProvider", "access/xop"); + ServiceReference<AccessProvider> provider("AccessProvider", "access/xop"); if (!provider) return; XOPChanAccess *acc = anope_dynamic_static_cast<XOPChanAccess *>(provider->Create()); @@ -299,7 +299,7 @@ class XOPBase : public Command return; } - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, channel %s list modification is temporarily disabled."), source.command.c_str()); return; @@ -319,9 +319,9 @@ class XOPBase : public Command const ChanAccess *highest = access.Highest(); bool override = false; - if (mask.find_first_of("!*@") == Anope::string::npos && !findnick(mask)) + if (mask.find_first_of("!*@") == Anope::string::npos && !NickAlias::Find(mask)) { - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ != NULL) mask = "*!*@" + targ->GetDisplayedHost(); else @@ -331,7 +331,7 @@ class XOPBase : public Command } } - if ((!mask.equals_ci(nc->display) && !access.HasPriv("ACCESS_CHANGE") && !access.Founder) || ((!highest || tmp_access >= *highest) && !access.Founder)) + if ((!mask.equals_ci(nc->display) && !access.HasPriv("ACCESS_CHANGE") && !access.founder) || ((!highest || tmp_access >= *highest) && !access.founder)) { if (source.HasPriv("chanserv/access/modify")) override = true; @@ -350,49 +350,49 @@ class XOPBase : public Command CommandSource &source; ChannelInfo *ci; Command *c; - unsigned Deleted; - Anope::string Nicks; + unsigned deleted; + Anope::string nicks; bool override; XOPType type; public: - XOPDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, bool _override, XOPType _type, const Anope::string &numlist) : NumberList(numlist, true), source(_source), ci(_ci), c(_c), Deleted(0), override(_override), type(_type) + XOPDelCallback(CommandSource &_source, ChannelInfo *_ci, Command *_c, bool _override, XOPType _type, const Anope::string &numlist) : NumberList(numlist, true), source(_source), ci(_ci), c(_c), deleted(0), override(_override), type(_type) { } ~XOPDelCallback() { - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on %s %s list."), ci->name.c_str(), source.command.c_str()); else { - Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "to delete " << Nicks; + Log(override ? LOG_OVERRIDE : LOG_COMMAND, source, c, ci) << "to delete " << nicks; - if (Deleted == 1) + if (deleted == 1) source.Reply(_("Deleted one entry from %s %s list."), ci->name.c_str(), source.command.c_str()); else - source.Reply(_("Deleted %d entries from %s %s list."), Deleted, ci->name.c_str(), source.command.c_str()); + source.Reply(_("Deleted %d entries from %s %s list."), deleted, ci->name.c_str(), source.command.c_str()); } } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number || Number > ci->GetAccessCount()) + if (!number || number > ci->GetAccessCount()) return; - ChanAccess *caccess = ci->GetAccess(Number - 1); + ChanAccess *caccess = ci->GetAccess(number - 1); if (this->type != XOPChanAccess::DetermineLevel(caccess)) return; - ++Deleted; - if (!Nicks.empty()) - Nicks += ", " + caccess->mask; + ++deleted; + if (!nicks.empty()) + nicks += ", " + caccess->mask; else - Nicks = caccess->mask; + nicks = caccess->mask; FOREACH_MOD(I_OnAccessDel, OnAccessDel(ci, source, caccess)); - ci->EraseAccess(Number - 1); + ci->EraseAccess(number - 1); } } delcallback(source, ci, this, override, level, mask); @@ -441,7 +441,7 @@ class XOPBase : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Mask"); + list.AddColumn("Number").AddColumn("Mask"); if (!nick.empty() && nick.find_first_not_of("1234567890,-") == Anope::string::npos) { @@ -468,7 +468,7 @@ class XOPBase : public Command ListFormatter::ListEntry entry; entry["Number"] = stringify(Number); entry["Mask"] = a->mask; - this->list.addEntry(entry); + this->list.AddEntry(entry); } } nl_list(list, ci, nick, level); nl_list.Process(); @@ -487,11 +487,11 @@ class XOPBase : public Command ListFormatter::ListEntry entry; entry["Number"] = stringify(i + 1); entry["Mask"] = a->mask; - list.addEntry(entry); + list.AddEntry(entry); } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on %s access list."), ci->name.c_str()); else { @@ -507,7 +507,7 @@ class XOPBase : public Command void DoClear(CommandSource &source, ChannelInfo *ci, XOPType level) { - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, channel %s list modification is temporarily disabled."), source.command.c_str()); return; @@ -545,7 +545,7 @@ class XOPBase : public Command protected: void DoXop(CommandSource &source, const std::vector<Anope::string> ¶ms, XOPType level) { - ChannelInfo *ci = cs_findchan(params[0]); + ChannelInfo *ci = ChannelInfo::Find(params[0]); if (ci == NULL) { source.Reply(CHAN_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/gl_global.cpp b/modules/commands/gl_global.cpp index 09d44f9a0..2be0164e3 100644 --- a/modules/commands/gl_global.cpp +++ b/modules/commands/gl_global.cpp @@ -27,12 +27,12 @@ class CommandGLGlobal : public Command { const Anope::string &msg = params[0]; - if (!global) + if (!GlobalService) source.Reply("No global reference, is gl_main loaded?"); else { Log(LOG_ADMIN, source, this); - global->SendGlobal(findbot(Config->Global), source.GetNick(), msg); + GlobalService->SendGlobal(Global, source.GetNick(), msg); } } diff --git a/modules/commands/help.cpp b/modules/commands/help.cpp index de80a6ec1..252406590 100644 --- a/modules/commands/help.cpp +++ b/modules/commands/help.cpp @@ -41,11 +41,12 @@ class CommandHelp : public Command const CommandInfo &info = it->second; // Smaller command exists - Anope::string cmd = myStrGetToken(c_name, ' ', 0); + Anope::string cmd; + spacesepstream(c_name).GetToken(cmd, 0); if (cmd != it->first && map.count(cmd)) continue; - service_reference<Command> c("Command", info.name); + ServiceReference<Command> c("Command", info.name); if (!c) continue; else if (!Config->HidePrivilegedCommands) @@ -76,7 +77,7 @@ class CommandHelp : public Command const CommandInfo &info = it->second; - service_reference<Command> c("Command", info.name); + ServiceReference<Command> c("Command", info.name); if (!c) continue; else if (!Config->HidePrivilegedCommands) diff --git a/modules/commands/hs_del.cpp b/modules/commands/hs_del.cpp index 9ad39a95d..4e2cdc8b7 100644 --- a/modules/commands/hs_del.cpp +++ b/modules/commands/hs_del.cpp @@ -25,7 +25,7 @@ class CommandHSDel : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { const Anope::string &nick = params[0]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na) { Log(LOG_ADMIN, source, this) << "for user " << na->nick; @@ -59,12 +59,12 @@ class CommandHSDelAll : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { const Anope::string &nick = params[0]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na) { FOREACH_MOD(I_OnDeleteVhost, OnDeleteVhost(na)); const NickCore *nc = na->nc; - for (std::list<serialize_obj<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end; ++it) + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end; ++it) { na = *it; na->RemoveVhost(); diff --git a/modules/commands/hs_group.cpp b/modules/commands/hs_group.cpp index 22538ed1a..5d8bc069e 100644 --- a/modules/commands/hs_group.cpp +++ b/modules/commands/hs_group.cpp @@ -20,7 +20,7 @@ class CommandHSGroup : public Command if (!na || !na->HasVhost()) return; - for (std::list<serialize_obj<NickAlias> >::const_iterator it = na->nc->aliases.begin(), it_end = na->nc->aliases.end(); it != it_end;) + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = na->nc->aliases.begin(), it_end = na->nc->aliases.end(); it != it_end;) { NickAlias *nick = *it++; if (nick) @@ -37,7 +37,7 @@ class CommandHSGroup : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - NickAlias *na = findnick(source.GetNick()); + NickAlias *na = NickAlias::Find(source.GetNick()); if (na && source.GetAccount() == na->nc && na->HasVhost()) { this->Sync(na); diff --git a/modules/commands/hs_list.cpp b/modules/commands/hs_list.cpp index 9e708f0b4..29fa145b3 100644 --- a/modules/commands/hs_list.cpp +++ b/modules/commands/hs_list.cpp @@ -57,7 +57,7 @@ class CommandHSList : public Command unsigned display_counter = 0; ListFormatter list; - list.addColumn("Number").addColumn("Nick").addColumn("Vhost").addColumn("Creator").addColumn("Created"); + list.AddColumn("Number").AddColumn("Nick").AddColumn("Vhost").AddColumn("Creator").AddColumn("Created"); for (nickalias_map::const_iterator it = NickAliasList->begin(), it_end = NickAliasList->end(); it != it_end; ++it) { @@ -80,8 +80,8 @@ class CommandHSList : public Command else entry["Vhost"] = na->GetVhostHost(); entry["Creator"] = na->GetVhostCreator(); - entry["Created"] = do_strftime(na->GetVhostCreated()); - list.addEntry(entry); + entry["Created"] = Anope::strftime(na->GetVhostCreated()); + list.AddEntry(entry); } } else @@ -101,8 +101,8 @@ class CommandHSList : public Command else entry["Vhost"] = na->GetVhostHost(); entry["Creator"] = na->GetVhostCreator(); - entry["Created"] = do_strftime(na->GetVhostCreated()); - list.addEntry(entry); + entry["Created"] = Anope::strftime(na->GetVhostCreated()); + list.AddEntry(entry); } } ++counter; diff --git a/modules/commands/hs_off.cpp b/modules/commands/hs_off.cpp index 39b701fed..27c6c0756 100644 --- a/modules/commands/hs_off.cpp +++ b/modules/commands/hs_off.cpp @@ -28,13 +28,13 @@ class CommandHSOff : public Command if (!u) return; - const NickAlias *na = findnick(u->nick); + const NickAlias *na = NickAlias::Find(u->nick); if (!na || !na->HasVhost()) source.Reply(HOST_NOT_ASSIGNED); else { - ircdproto->SendVhostDel(u); + IRCD->SendVhostDel(u); Log(LOG_COMMAND, source, this) << "to disable their vhost"; source.Reply(_("Your vhost was removed and the normal cloaking restored.")); } diff --git a/modules/commands/hs_on.cpp b/modules/commands/hs_on.cpp index d02dd7dfe..c4cf2fee8 100644 --- a/modules/commands/hs_on.cpp +++ b/modules/commands/hs_on.cpp @@ -27,10 +27,10 @@ class CommandHSOn : public Command User *u = source.GetUser(); if (!u) return; - else if (!ircdproto->CanSetVHost) + else if (!IRCD->CanSetVHost) return; // HostServ wouldn't even be loaded at this point - const NickAlias *na = findnick(u->nick); + const NickAlias *na = NickAlias::Find(u->nick); if (na && u->Account() == na->nc && na->HasVhost()) { if (!na->GetVhostIdent().empty()) @@ -38,9 +38,9 @@ class CommandHSOn : public Command else source.Reply(_("Your vhost of \002%s\002 is now activated."), na->GetVhostHost().c_str()); Log(LOG_COMMAND, source, this) << "to enable their vhost of " << (!na->GetVhostIdent().empty() ? na->GetVhostIdent() + "@" : "") << na->GetVhostHost(); - ircdproto->SendVhost(u, na->GetVhostIdent(), na->GetVhostHost()); + IRCD->SendVhost(u, na->GetVhostIdent(), na->GetVhostHost()); u->vhost = na->GetVhostHost(); - if (ircdproto->CanSetVIdent && !na->GetVhostIdent().empty()) + if (IRCD->CanSetVIdent && !na->GetVhostIdent().empty()) u->SetVIdent(na->GetVhostIdent()); u->UpdateHost(); } diff --git a/modules/commands/hs_request.cpp b/modules/commands/hs_request.cpp index 8a9de386b..b11059f90 100644 --- a/modules/commands/hs_request.cpp +++ b/modules/commands/hs_request.cpp @@ -32,21 +32,21 @@ struct HostRequest : ExtensibleItem, Serializable HostRequest() : Serializable("HostRequest") { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; data["nick"] << this->nick; data["ident"] << this->ident; data["host"] << this->host; - data["time"].setType(Serialize::DT_INT) << this->time; + data["time"].SetType(Serialize::DT_INT) << this->time; return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { - NickAlias *na = findnick(data["nick"].astr()); + NickAlias *na = NickAlias::Find(data["nick"].astr()); if (na == NULL) return NULL; @@ -85,7 +85,7 @@ class CommandHSRequest : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { User *u = source.GetUser(); - NickAlias *na = findnick(source.GetNick()); + NickAlias *na = NickAlias::Find(source.GetNick()); if (!na || na->nc != source.GetAccount()) { source.Reply(ACCESS_DENIED); @@ -118,7 +118,7 @@ class CommandHSRequest : public Command source.Reply(HOST_SET_IDENTTOOLONG, Config->UserLen); return; } - else if (!ircdproto->CanSetVIdent) + else if (!IRCD->CanSetVIdent) { source.Reply(HOST_NO_VIDENT); return; @@ -137,7 +137,7 @@ class CommandHSRequest : public Command return; } - if (!IsValidHost(host)) + if (!IRCD->IsHostValid(host)) { source.Reply(HOST_SET_ERROR); return; @@ -190,15 +190,15 @@ class CommandHSActivate : public Command const Anope::string &nick = params[0]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); HostRequest *req = na ? na->GetExt<HostRequest *>("hs_request") : NULL; if (req) { na->SetVhost(req->ident, req->host, source.GetNick(), req->time); FOREACH_MOD(I_OnSetVhost, OnSetVhost(na)); - if (HSRequestMemoUser && memoserv) - memoserv->Send(Config->HostServ, na->nick, _("[auto memo] Your requested vHost has been approved."), true); + if (HSRequestMemoUser && MemoServService) + MemoServService->Send(Config->HostServ, na->nick, _("[auto memo] Your requested vHost has been approved."), true); source.Reply(_("vHost for %s has been activated"), na->nick.c_str()); Log(LOG_COMMAND, source, this) << "for " << na->nick << " for vhost " << (!req->ident.empty() ? req->ident + "@" : "") << req->host; @@ -234,13 +234,13 @@ class CommandHSReject : public Command const Anope::string &nick = params[0]; const Anope::string &reason = params.size() > 1 ? params[1] : ""; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); HostRequest *req = na ? na->GetExt<HostRequest *>("hs_request") : NULL; if (req) { na->Shrink("hs_request"); - if (HSRequestMemoUser && memoserv) + if (HSRequestMemoUser && MemoServService) { Anope::string message; if (!reason.empty()) @@ -248,7 +248,7 @@ class CommandHSReject : public Command else message = _("[auto memo] Your requested vHost has been rejected."); - memoserv->Send(Config->HostServ, nick, message, true); + MemoServService->Send(Config->HostServ, nick, message, true); } source.Reply(_("vHost for %s has been rejected"), nick.c_str()); @@ -281,7 +281,7 @@ class CommandHSWaiting : public Command unsigned display_counter = 0; ListFormatter list; - list.addColumn("Number").addColumn("Nick").addColumn("Vhost").addColumn("Created"); + list.AddColumn("Number").AddColumn("Nick").AddColumn("Vhost").AddColumn("Created"); for (nickalias_map::const_iterator it = NickAliasList->begin(), it_end = NickAliasList->end(); it != it_end; ++it) { @@ -301,8 +301,8 @@ class CommandHSWaiting : public Command entry["Vhost"] = hr->ident + "@" + hr->host; else entry["Vhost"] = hr->host; - entry["Created"] = do_strftime(hr->time); - list.addEntry(entry); + entry["Created"] = Anope::strftime(hr->time); + list.AddEntry(entry); } ++counter; } @@ -339,7 +339,7 @@ class CommandHSWaiting : public Command class HSRequest : public Module { - SerializeType request_type; + Serialize::Type request_type; CommandHSRequest commandhsrequest; CommandHSActivate commandhsactive; CommandHSReject commandhsreject; @@ -347,11 +347,11 @@ class HSRequest : public Module public: HSRequest(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - request_type("HostRequest", HostRequest::unserialize), commandhsrequest(this), commandhsactive(this), commandhsreject(this), commandhswaiting(this) + request_type("HostRequest", HostRequest::Unserialize), commandhsrequest(this), commandhsactive(this), commandhsreject(this), commandhswaiting(this) { this->SetAuthor("Anope"); - if (!ircdproto || !ircdproto->CanSetVHost) + if (!IRCD || !IRCD->CanSetVHost) throw ModuleException("Your IRCd does not support vhosts"); Implementation i[] = { I_OnReload }; @@ -389,18 +389,18 @@ void req_send_memos(CommandSource &source, const Anope::string &vIdent, const An else host = vHost; - if (HSRequestMemoOper == 1 && memoserv) + if (HSRequestMemoOper == 1 && MemoServService) for (unsigned i = 0; i < Config->Opers.size(); ++i) { Oper *o = Config->Opers[i]; - const NickAlias *na = findnick(o->name); + const NickAlias *na = NickAlias::Find(o->name); if (!na) continue; Anope::string message = Anope::printf(_("[auto memo] vHost \002%s\002 has been requested by %s."), host.c_str(), source.GetNick().c_str()); - memoserv->Send(Config->HostServ, na->nick, message, true); + MemoServService->Send(Config->HostServ, na->nick, message, true); } } diff --git a/modules/commands/hs_set.cpp b/modules/commands/hs_set.cpp index 2189f2483..bb4091da4 100644 --- a/modules/commands/hs_set.cpp +++ b/modules/commands/hs_set.cpp @@ -27,7 +27,7 @@ class CommandHSSet : public Command const Anope::string &nick = params[0]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -55,12 +55,12 @@ class CommandHSSet : public Command if (!user.empty()) { - if (!ircdproto->CanSetVIdent) + if (!IRCD->CanSetVIdent) { source.Reply(HOST_NO_VIDENT); return; } - else if (!IsValidIdent(user)) + else if (!IRCD->IsIdentValid(user)) { source.Reply(HOST_SET_IDENT_ERROR); return; @@ -73,7 +73,7 @@ class CommandHSSet : public Command return; } - if (!IsValidHost(host)) + if (!IRCD->IsHostValid(host)) { source.Reply(HOST_SET_ERROR); return; @@ -108,7 +108,7 @@ class CommandHSSetAll : public Command if (!na || !na->HasVhost()) return; - for (std::list<serialize_obj<NickAlias> >::const_iterator it = na->nc->aliases.begin(), it_end = na->nc->aliases.end(); it != it_end;) + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = na->nc->aliases.begin(), it_end = na->nc->aliases.end(); it != it_end;) { NickAlias *nick = *it++; if (nick) @@ -128,7 +128,7 @@ class CommandHSSetAll : public Command Anope::string nick = params[0]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -156,12 +156,12 @@ class CommandHSSetAll : public Command if (!user.empty()) { - if (!ircdproto->CanSetVIdent) + if (!IRCD->CanSetVIdent) { source.Reply(HOST_NO_VIDENT); return; } - else if (!IsValidIdent(user)) + else if (!IRCD->IsIdentValid(user)) { source.Reply(HOST_SET_IDENT_ERROR); return; @@ -174,7 +174,7 @@ class CommandHSSetAll : public Command return; } - if (!IsValidHost(host)) + if (!IRCD->IsHostValid(host)) { source.Reply(HOST_SET_ERROR); return; diff --git a/modules/commands/ms_cancel.cpp b/modules/commands/ms_cancel.cpp index e4ee9375e..8949baf17 100644 --- a/modules/commands/ms_cancel.cpp +++ b/modules/commands/ms_cancel.cpp @@ -25,14 +25,14 @@ class CommandMSCancel : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; const Anope::string &nname = params[0]; bool ischan; - MemoInfo *mi = memoserv->GetMemoInfo(nname, ischan); + MemoInfo *mi = MemoServService->GetMemoInfo(nname, ischan); if (mi == NULL) source.Reply(ischan ? CHAN_X_NOT_REGISTERED : _(NICK_X_NOT_REGISTERED), nname.c_str()); @@ -41,9 +41,9 @@ class CommandMSCancel : public Command ChannelInfo *ci = NULL; NickAlias *na = NULL; if (ischan) - ci = cs_findchan(nname); + ci = ChannelInfo::Find(nname); else - na = findnick(nname); + na = NickAlias::Find(nname); for (int i = mi->memos->size() - 1; i >= 0; --i) if (mi->GetMemo(i)->HasFlag(MF_UNREAD) && source.nc->display.equals_ci(mi->GetMemo(i)->sender)) { @@ -81,7 +81,7 @@ class MSCancel : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); } }; diff --git a/modules/commands/ms_check.cpp b/modules/commands/ms_check.cpp index 59340b6d7..8f34e7b9a 100644 --- a/modules/commands/ms_check.cpp +++ b/modules/commands/ms_check.cpp @@ -29,7 +29,7 @@ class CommandMSCheck : public Command bool found = false; - const NickAlias *na = findnick(recipient); + const NickAlias *na = NickAlias::Find(recipient); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, recipient.c_str()); @@ -48,9 +48,9 @@ class CommandMSCheck : public Command found = true; /* Yes, we've found the memo */ if (mi->GetMemo(i)->HasFlag(MF_UNREAD)) - source.Reply(_("The last memo you sent to %s (sent on %s) has not yet been read."), na->nick.c_str(), do_strftime(mi->GetMemo(i)->time).c_str()); + source.Reply(_("The last memo you sent to %s (sent on %s) has not yet been read."), na->nick.c_str(), Anope::strftime(mi->GetMemo(i)->time).c_str()); else - source.Reply(_("The last memo you sent to %s (sent on %s) has been read."), na->nick.c_str(), do_strftime(mi->GetMemo(i)->time).c_str()); + source.Reply(_("The last memo you sent to %s (sent on %s) has been read."), na->nick.c_str(), Anope::strftime(mi->GetMemo(i)->time).c_str()); break; } } diff --git a/modules/commands/ms_del.cpp b/modules/commands/ms_del.cpp index 330f45e87..99b388e52 100644 --- a/modules/commands/ms_del.cpp +++ b/modules/commands/ms_del.cpp @@ -23,18 +23,18 @@ class MemoDelCallback : public NumberList { } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number || Number > mi->memos->size()) + if (!number || number > mi->memos->size()) return; if (ci) - FOREACH_MOD(I_OnMemoDel, OnMemoDel(ci, mi, mi->GetMemo(Number - 1))); + FOREACH_MOD(I_OnMemoDel, OnMemoDel(ci, mi, mi->GetMemo(number - 1))); else - FOREACH_MOD(I_OnMemoDel, OnMemoDel(source.nc, mi, mi->GetMemo(Number - 1))); + FOREACH_MOD(I_OnMemoDel, OnMemoDel(source.nc, mi, mi->GetMemo(number - 1))); - mi->Del(Number - 1); - source.Reply(_("Memo %d has been deleted."), Number); + mi->Del(number - 1); + source.Reply(_("Memo %d has been deleted."), number); } }; @@ -59,13 +59,13 @@ class CommandMSDel : public Command chan = numstr; numstr = params.size() > 1 ? params[1] : ""; - ci = cs_findchan(chan); + ci = ChannelInfo::Find(chan); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); return; } - else if (readonly) + else if (Anope::ReadOnly) { source.Reply(READ_ONLY_MODE); return; @@ -114,7 +114,7 @@ class CommandMSDel : public Command FOREACH_MOD(I_OnMemoDel, OnMemoDel(ci, mi, mi->GetMemo(i))); else FOREACH_MOD(I_OnMemoDel, OnMemoDel(source.nc, mi, mi->GetMemo(i))); - mi->GetMemo(i)->destroy(); + mi->GetMemo(i)->Destroy(); } mi->memos->clear(); if (!chan.empty()) diff --git a/modules/commands/ms_ignore.cpp b/modules/commands/ms_ignore.cpp index 84ce540a8..465714852 100644 --- a/modules/commands/ms_ignore.cpp +++ b/modules/commands/ms_ignore.cpp @@ -26,7 +26,7 @@ class CommandMSIgnore : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; @@ -42,8 +42,8 @@ class CommandMSIgnore : public Command } bool ischan; - MemoInfo *mi = memoserv->GetMemoInfo(channel, ischan); - ChannelInfo *ci = cs_findchan(channel); + MemoInfo *mi = MemoServService->GetMemoInfo(channel, ischan); + ChannelInfo *ci = ChannelInfo::Find(channel); if (!mi) source.Reply(ischan ? CHAN_X_NOT_REGISTERED : _(NICK_X_NOT_REGISTERED), channel.c_str()); else if (ischan && !source.AccessFor(ci).HasPriv("MEMO")) @@ -77,12 +77,12 @@ class CommandMSIgnore : public Command else { ListFormatter list; - list.addColumn("Mask"); + list.AddColumn("Mask"); for (unsigned i = 0; i < mi->ignores.size(); ++i) { ListFormatter::ListEntry entry; entry["Mask"] = mi->ignores[i]; - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("Ignore list:")); @@ -120,7 +120,7 @@ class MSIgnore : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); } }; diff --git a/modules/commands/ms_info.cpp b/modules/commands/ms_info.cpp index d2c7eea3b..b209d0bf4 100644 --- a/modules/commands/ms_info.cpp +++ b/modules/commands/ms_info.cpp @@ -33,7 +33,7 @@ class CommandMSInfo : public Command if (!nname.empty() && nname[0] != '#' && source.HasPriv("memoserv/info")) { - na = findnick(nname); + na = NickAlias::Find(nname); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, nname.c_str()); @@ -44,7 +44,7 @@ class CommandMSInfo : public Command } else if (!nname.empty() && nname[0] == '#') { - ci = cs_findchan(nname); + ci = ChannelInfo::Find(nname); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, nname.c_str()); diff --git a/modules/commands/ms_list.cpp b/modules/commands/ms_list.cpp index f6a92e9df..91196cfee 100644 --- a/modules/commands/ms_list.cpp +++ b/modules/commands/ms_list.cpp @@ -34,7 +34,7 @@ class CommandMSList : public Command chan = param; param = params.size() > 1 ? params[1] : ""; - ci = cs_findchan(chan); + ci = ChannelInfo::Find(chan); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); @@ -63,7 +63,7 @@ class CommandMSList : public Command { ListFormatter list; - list.addColumn("Number").addColumn("Sender").addColumn("Date/Time"); + list.AddColumn("Number").AddColumn("Sender").AddColumn("Date/Time"); if (!param.empty() && isdigit(param[0])) { @@ -77,18 +77,18 @@ class CommandMSList : public Command { } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number || Number > mi->memos->size()) + if (!number || number > mi->memos->size()) return; - const Memo *m = mi->GetMemo(Number); + const Memo *m = mi->GetMemo(number); ListFormatter::ListEntry entry; - entry["Number"] = (m->HasFlag(MF_UNREAD) ? "* " : " ") + stringify(Number + 1); + entry["Number"] = (m->HasFlag(MF_UNREAD) ? "* " : " ") + stringify(number + 1); entry["Sender"] = m->sender; - entry["Date/Time"] = do_strftime(m->time); - this->list.addEntry(entry); + entry["Date/Time"] = Anope::strftime(m->time); + this->list.AddEntry(entry); } } mlc(list, source, mi, param); @@ -122,8 +122,8 @@ class CommandMSList : public Command ListFormatter::ListEntry entry; entry["Number"] = (m->HasFlag(MF_UNREAD) ? "* " : " ") + stringify(i + 1); entry["Sender"] = m->sender; - entry["Date/Time"] = do_strftime(m->time); - list.addEntry(entry); + entry["Date/Time"] = Anope::strftime(m->time); + list.AddEntry(entry); } } diff --git a/modules/commands/ms_read.cpp b/modules/commands/ms_read.cpp index 5b46ef0dd..6d5adfb05 100644 --- a/modules/commands/ms_read.cpp +++ b/modules/commands/ms_read.cpp @@ -17,10 +17,10 @@ static void rsend_notify(CommandSource &source, MemoInfo *mi, Memo *m, const Anope::string &targ) { /* Only send receipt if memos are allowed */ - if (memoserv && !readonly) + if (MemoServService && !Anope::ReadOnly) { /* Get nick alias for sender */ - const NickAlias *na = findnick(m->sender); + const NickAlias *na = NickAlias::Find(m->sender); if (!na) return; @@ -33,10 +33,10 @@ static void rsend_notify(CommandSource &source, MemoInfo *mi, Memo *m, const Ano /* Text of the memo varies if the recepient was a nick or channel */ - Anope::string text = Anope::printf(translate(na->nc, _("\002[auto-memo]\002 The memo you sent to %s has been viewed.")), targ.c_str()); + Anope::string text = Anope::printf(Language::Translate(na->nc, _("\002[auto-memo]\002 The memo you sent to %s has been viewed.")), targ.c_str()); /* Send notification */ - memoserv->Send(source.GetNick(), m->sender, text, true); + MemoServService->Send(source.GetNick(), m->sender, text, true); /* Notify recepient of the memo that a notification has been sent to the sender */ @@ -58,21 +58,21 @@ class MemoListCallback : public NumberList { } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number || Number > mi->memos->size()) + if (!number || number > mi->memos->size()) return; - MemoListCallback::DoRead(source, mi, ci, Number - 1); + MemoListCallback::DoRead(source, mi, ci, number - 1); } static void DoRead(CommandSource &source, MemoInfo *mi, const ChannelInfo *ci, unsigned index) { Memo *m = mi->GetMemo(index); if (ci) - source.Reply(_("Memo %d from %s (%s). To delete, type: \002%s%s DEL %s %d\002"), index + 1, m->sender.c_str(), do_strftime(m->time).c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), ci->name.c_str(), index + 1); + source.Reply(_("Memo %d from %s (%s). To delete, type: \002%s%s DEL %s %d\002"), index + 1, m->sender.c_str(), Anope::strftime(m->time).c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), ci->name.c_str(), index + 1); else - source.Reply(_("Memo %d from %s (%s). To delete, type: \002%s%s DEL %d\002"), index + 1, m->sender.c_str(), do_strftime(m->time).c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), index + 1); + source.Reply(_("Memo %d from %s (%s). To delete, type: \002%s%s DEL %d\002"), index + 1, m->sender.c_str(), Anope::strftime(m->time).c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), index + 1); source.Reply("%s", m->text.c_str()); m->UnsetFlag(MF_UNREAD); @@ -103,7 +103,7 @@ class CommandMSRead : public Command chan = numstr; numstr = params.size() > 1 ? params[1] : ""; - ci = cs_findchan(chan); + ci = ChannelInfo::Find(chan); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); diff --git a/modules/commands/ms_rsend.cpp b/modules/commands/ms_rsend.cpp index 9c47b9f53..b08b9be85 100644 --- a/modules/commands/ms_rsend.cpp +++ b/modules/commands/ms_rsend.cpp @@ -25,7 +25,7 @@ class CommandMSRSend : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; @@ -34,7 +34,7 @@ class CommandMSRSend : public Command const NickAlias *na = NULL; /* prevent user from rsend to themselves */ - if ((na = findnick(nick)) && na->nc == source.GetAccount()) + if ((na = NickAlias::Find(nick)) && na->nc == source.GetAccount()) { source.Reply(_("You can not request a receipt when sending a memo to yourself.")); return; @@ -49,7 +49,7 @@ class CommandMSRSend : public Command } else { - MemoServService::MemoResult result = memoserv->Send(source.GetNick(), nick, text); + MemoServService::MemoResult result = MemoServService->Send(source.GetNick(), nick, text); if (result == MemoServService::MEMO_INVALID_TARGET) source.Reply(_("\002%s\002 is not a registered unforbidden nick or channel."), nick.c_str()); else if (result == MemoServService::MEMO_TOO_FAST) @@ -61,7 +61,7 @@ class CommandMSRSend : public Command source.Reply(_("Memo sent to \002%s\002."), name.c_str()); bool ischan; - MemoInfo *mi = memoserv->GetMemoInfo(nick, ischan); + MemoInfo *mi = MemoServService->GetMemoInfo(nick, ischan); if (mi == NULL) throw CoreException("NULL mi in ms_rsend"); Memo *m = (mi->memos->size() ? mi->GetMemo(mi->memos->size() - 1) : NULL); @@ -98,7 +98,7 @@ class MSRSend : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); else if (!Config->MSMemoReceipt) throw ModuleException("Invalid value for memoreceipt"); diff --git a/modules/commands/ms_send.cpp b/modules/commands/ms_send.cpp index a2ba53a9e..42024227e 100644 --- a/modules/commands/ms_send.cpp +++ b/modules/commands/ms_send.cpp @@ -25,13 +25,13 @@ class CommandMSSend : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; const Anope::string &nick = params[0]; const Anope::string &text = params[1]; - MemoServService::MemoResult result = memoserv->Send(source.GetNick(), nick, text); + MemoServService::MemoResult result = MemoServService->Send(source.GetNick(), nick, text); if (result == MemoServService::MEMO_SUCCESS) source.Reply(_("Memo sent to \002%s\002."), nick.c_str()); else if (result == MemoServService::MEMO_INVALID_TARGET) @@ -66,7 +66,7 @@ class MSSend : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); } }; diff --git a/modules/commands/ms_sendall.cpp b/modules/commands/ms_sendall.cpp index 2fba2ecb3..5ade6722b 100644 --- a/modules/commands/ms_sendall.cpp +++ b/modules/commands/ms_sendall.cpp @@ -25,12 +25,12 @@ class CommandMSSendAll : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; const Anope::string &text = params[0]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(MEMO_SEND_DISABLED); return; @@ -41,7 +41,7 @@ class CommandMSSendAll : public Command const NickCore *nc = it->second; if (nc != source.nc) - memoserv->Send(source.GetNick(), nc->display, text); + MemoServService->Send(source.GetNick(), nc->display, text); } source.Reply(_("A massmemo has been sent to all registered users.")); @@ -67,7 +67,7 @@ class MSSendAll : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); } }; diff --git a/modules/commands/ms_set.cpp b/modules/commands/ms_set.cpp index 02ce8d32c..497dffd4c 100644 --- a/modules/commands/ms_set.cpp +++ b/modules/commands/ms_set.cpp @@ -86,7 +86,7 @@ class CommandMSSet : public Command p2 = p3; p3 = params.size() > 4 ? params[4] : ""; - ci = cs_findchan(chan); + ci = ChannelInfo::Find(chan); if (!ci) { source.Reply(CHAN_X_NOT_REGISTERED, chan.c_str()); @@ -104,7 +104,7 @@ class CommandMSSet : public Command if (!p2.empty() && !p2.equals_ci("HARD") && chan.empty()) { const NickAlias *na; - if (!(na = findnick(p1))) + if (!(na = NickAlias::Find(p1))) { source.Reply(NICK_X_NOT_REGISTERED, p1.c_str()); return; @@ -211,7 +211,7 @@ class CommandMSSet : public Command const Anope::string &cmd = params[0]; MemoInfo *mi = const_cast<MemoInfo *>(&source.nc->memos); - if (readonly) + if (Anope::ReadOnly) source.Reply(_("Sorry, memo option setting is temporarily disabled.")); else if (cmd.equals_ci("NOTIFY")) return this->DoNotify(source, params, mi); diff --git a/modules/commands/ms_staff.cpp b/modules/commands/ms_staff.cpp index 9896d5971..a1fbdf65d 100644 --- a/modules/commands/ms_staff.cpp +++ b/modules/commands/ms_staff.cpp @@ -25,12 +25,12 @@ class CommandMSStaff : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!memoserv) + if (!MemoServService) return; const Anope::string &text = params[0]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(MEMO_SEND_DISABLED); return; @@ -41,7 +41,7 @@ class CommandMSStaff : public Command const NickCore *nc = it->second; if (source.nc != nc && nc->IsServicesOper()) - memoserv->Send(source.GetNick(), nc->display, text, true); + MemoServService->Send(source.GetNick(), nc->display, text, true); } return; @@ -67,7 +67,7 @@ class MSStaff : public Module { this->SetAuthor("Anope"); - if (!memoserv) + if (!MemoServService) throw ModuleException("No MemoServ!"); } }; diff --git a/modules/commands/ns_access.cpp b/modules/commands/ns_access.cpp index 915b70cb3..f77836909 100644 --- a/modules/commands/ns_access.cpp +++ b/modules/commands/ns_access.cpp @@ -108,7 +108,7 @@ class CommandNSAccess : public Command NickCore *nc; if (!nick.empty()) { - const NickAlias *na = findnick(nick); + const NickAlias *na = NickAlias::Find(nick); if (na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); diff --git a/modules/commands/ns_ajoin.cpp b/modules/commands/ns_ajoin.cpp index 46f012c46..54e37ad36 100644 --- a/modules/commands/ns_ajoin.cpp +++ b/modules/commands/ns_ajoin.cpp @@ -15,20 +15,20 @@ struct AJoinEntry; -struct AJoinList : serialize_checker<std::vector<AJoinEntry *> >, ExtensibleItem +struct AJoinList : Serialize::Checker<std::vector<AJoinEntry *> >, ExtensibleItem { - AJoinList() : serialize_checker<std::vector<AJoinEntry *> >("AJoinEntry") { } + AJoinList() : Serialize::Checker<std::vector<AJoinEntry *> >("AJoinEntry") { } }; struct AJoinEntry : Serializable { - serialize_obj<NickCore> owner; + Serialize::Reference<NickCore> owner; Anope::string channel; Anope::string key; AJoinEntry() : Serializable("AJoinEntry") { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data sd; @@ -42,9 +42,9 @@ struct AJoinEntry : Serializable return sd; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &sd) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &sd) { - NickCore *nc = findcore(sd["owner"].astr()); + NickCore *nc = NickCore::Find(sd["owner"].astr()); if (nc == NULL) return NULL; @@ -91,7 +91,7 @@ class CommandNSAJoin : public Command else { ListFormatter list; - list.addColumn("Number").addColumn("Channel").addColumn("Key"); + list.AddColumn("Number").AddColumn("Channel").AddColumn("Key"); for (unsigned i = 0; i < (*channels)->size(); ++i) { AJoinEntry *aj = (*channels)->at(i); @@ -99,7 +99,7 @@ class CommandNSAJoin : public Command entry["Number"] = stringify(i + 1); entry["Channel"] = aj->channel; entry["Key"] = aj->key; - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("%s's auto join list:"), nc->display.c_str()); @@ -130,7 +130,7 @@ class CommandNSAJoin : public Command source.Reply(_("Your auto join list is full.")); else if (i != (*channels)->size()) source.Reply(_("%s is already on %s's auto join list."), chan.c_str(), nc->display.c_str()); - else if (ircdproto->IsChannelValid(chan) == false) + else if (IRCD->IsChannelValid(chan) == false) source.Reply(CHAN_X_INVALID, chan.c_str()); else { @@ -161,7 +161,7 @@ class CommandNSAJoin : public Command source.Reply(_("%s was not found on %s's auto join list."), chan.c_str(), nc->display.c_str()); else { - (*channels)->at(i)->destroy(); + (*channels)->at(i)->Destroy(); (*channels)->erase((*channels)->begin() + i); source.Reply(_("%s was removed from %s's auto join list."), chan.c_str(), nc->display.c_str()); } @@ -179,9 +179,9 @@ class CommandNSAJoin : public Command NickCore *nc = source.GetAccount(); Anope::string param, param2; - if (params.size() > 1 && source.IsServicesOper() && ircdproto->IsNickValid(params[1])) + if (params.size() > 1 && source.IsServicesOper() && IRCD->IsNickValid(params[1])) { - NickAlias *na = findnick(params[1]); + NickAlias *na = NickAlias::Find(params[1]); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, params[1].c_str()); @@ -224,12 +224,12 @@ class CommandNSAJoin : public Command class NSAJoin : public Module { - SerializeType ajoinentry_type; + Serialize::Type ajoinentry_type; CommandNSAJoin commandnsajoin; public: NSAJoin(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - ajoinentry_type("AJoinEntry", AJoinEntry::unserialize), commandnsajoin(this) + ajoinentry_type("AJoinEntry", AJoinEntry::Unserialize), commandnsajoin(this) { this->SetAuthor("Anope"); @@ -239,6 +239,9 @@ class NSAJoin : public Module void OnNickIdentify(User *u) anope_override { + if (!NickServ) + return; + AJoinList *channels = u->Account()->GetExt<AJoinList *>("ns_ajoin_channels"); if (channels == NULL) { @@ -246,20 +249,16 @@ class NSAJoin : public Module u->Account()->Extend("ns_ajoin_channels", channels); } - const BotInfo *bi = findbot(Config->NickServ); - if (bi == NULL) - return; - for (unsigned i = 0; i < (*channels)->size(); ++i) { AJoinEntry *entry = (*channels)->at(i); - Channel *c = findchan(entry->channel); + Channel *c = Channel::Find(entry->channel); ChannelInfo *ci; if (c) ci = c->ci; else - ci = cs_findchan(entry->channel); + ci = ChannelInfo::Find(entry->channel); bool need_invite = false; Anope::string key = entry->key; @@ -279,9 +278,9 @@ class NSAJoin : public Module continue; else if (c->HasMode(CMODE_SSL) && !u->HasMode(UMODE_SSL)) continue; - else if (matches_list(c, u, CMODE_BAN) == true && matches_list(c, u, CMODE_EXCEPT) == false) + else if (c->MatchesList(u, CMODE_BAN) == true && c->MatchesList(u, CMODE_EXCEPT) == false) need_invite = true; - else if (c->HasMode(CMODE_INVITE) && matches_list(c, u, CMODE_INVITEOVERRIDE) == false) + else if (c->HasMode(CMODE_INVITE) && c->MatchesList(u, CMODE_INVITEOVERRIDE) == false) need_invite = true; if (c->HasMode(CMODE_KEY)) @@ -315,10 +314,10 @@ class NSAJoin : public Module { if (!ci->AccessFor(u).HasPriv("INVITE")) continue; - ircdproto->SendInvite(bi, c, u); + IRCD->SendInvite(NickServ, c, u); } - ircdproto->SendSVSJoin(bi, u->nick, entry->channel, key); + IRCD->SendSVSJoin(NickServ, u->nick, entry->channel, key); } } }; diff --git a/modules/commands/ns_alist.cpp b/modules/commands/ns_alist.cpp index ef018ea8b..8da1b8346 100644 --- a/modules/commands/ns_alist.cpp +++ b/modules/commands/ns_alist.cpp @@ -30,7 +30,7 @@ class CommandNSAList : public Command if (params.size() && source.IsServicesOper()) { nick = params[0]; - const NickAlias *na = findnick(nick); + const NickAlias *na = NickAlias::Find(nick); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -42,7 +42,7 @@ class CommandNSAList : public Command ListFormatter list; int chan_count = 0; - list.addColumn("Number").addColumn("Channel").addColumn("Access"); + list.AddColumn("Number").AddColumn("Channel").AddColumn("Access"); source.Reply(_("Channels that \002%s\002 has access on:"), nc->display.c_str()); @@ -57,7 +57,7 @@ class CommandNSAList : public Command entry["Number"] = stringify(chan_count); entry["Channel"] = (ci->HasFlag(CI_NO_EXPIRE) ? "!" : "") + ci->name; entry["Access"] = "Founder"; - list.addEntry(entry); + list.AddEntry(entry); continue; } @@ -70,9 +70,9 @@ class CommandNSAList : public Command entry["Number"] = stringify(chan_count); entry["Channel"] = (ci->HasFlag(CI_NO_EXPIRE) ? "!" : "") + ci->name; for (unsigned i = 0; i < access.size(); ++i) - entry["Access"] = entry["Access"] + ", " + access[i]->Serialize(); + entry["Access"] = entry["Access"] + ", " + access[i]->AccessSerialize(); entry["Access"] = entry["Access"].substr(2); - list.addEntry(entry); + list.AddEntry(entry); } std::vector<Anope::string> replies; diff --git a/modules/commands/ns_cert.cpp b/modules/commands/ns_cert.cpp index a06dd1a3a..6c2100adf 100644 --- a/modules/commands/ns_cert.cpp +++ b/modules/commands/ns_cert.cpp @@ -31,14 +31,14 @@ class CommandNSCert : public Command } ListFormatter list; - list.addColumn("Certificate"); + list.AddColumn("Certificate"); for (unsigned i = 0, end = nc->cert.size(); i < end; ++i) { Anope::string fingerprint = nc->GetCert(i); ListFormatter::ListEntry entry; entry["Certificate"] = fingerprint; - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("Certificate list for \002%s\002:"), nc->display.c_str()); @@ -121,13 +121,13 @@ class CommandNSCert : public Command } ListFormatter list; - list.addColumn("Certificate"); + list.AddColumn("Certificate"); for (unsigned i = 0, end = nc->cert.size(); i < end; ++i) { ListFormatter::ListEntry entry; entry["Certificate"] = nc->GetCert(i); - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("Certificate list:")); @@ -152,7 +152,7 @@ class CommandNSCert : public Command const Anope::string &mask = params.size() > 1 ? params[1] : ""; const NickAlias *na; - if (cmd.equals_ci("LIST") && source.IsServicesOper() && !mask.empty() && (na = findnick(mask))) + if (cmd.equals_ci("LIST") && source.IsServicesOper() && !mask.empty() && (na = NickAlias::Find(mask))) return this->DoServAdminList(source, na->nc); NickCore *nc = source.nc; @@ -202,9 +202,8 @@ class NSCert : public Module void DoAutoIdentify(User *u) { - const BotInfo *bi = findbot(Config->NickServ); - NickAlias *na = findnick(u->nick); - if (!bi || !na) + NickAlias *na = NickAlias::Find(u->nick); + if (!NickServ || !na) return; if (u->IsIdentified() && u->Account() == na->nc) return; @@ -214,7 +213,7 @@ class NSCert : public Module return; u->Identify(na); - u->SendMessage(bi, _("SSL Fingerprint accepted. You are now identified.")); + u->SendMessage(NickServ, _("SSL Fingerprint accepted. You are now identified.")); Log(u) << "automatically identified for account " << na->nc->display << " using a valid SSL fingerprint"; return; } @@ -225,7 +224,7 @@ class NSCert : public Module { this->SetAuthor("Anope"); - if (!ircdproto || !ircdproto->CanCertFP) + if (!IRCD || !IRCD->CanCertFP) throw ModuleException("Your IRCd does not support ssl client certificates"); Implementation i[] = { I_OnFingerprint }; diff --git a/modules/commands/ns_drop.cpp b/modules/commands/ns_drop.cpp index d5ac7cef8..efd95cf1c 100644 --- a/modules/commands/ns_drop.cpp +++ b/modules/commands/ns_drop.cpp @@ -25,13 +25,13 @@ class CommandNSDrop : public Command { Anope::string nick = !params.empty() ? params[0] : ""; - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, nickname de-registration is temporarily disabled.")); return; } - NickAlias *na = findnick(!nick.empty() ? nick : source.GetNick()); + NickAlias *na = NickAlias::Find(!nick.empty() ? nick : source.GetNick()); if (!na) { source.Reply(NICK_NOT_REGISTERED); @@ -49,13 +49,13 @@ class CommandNSDrop : public Command source.Reply(_("You may not drop other services operators nicknames.")); else { - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); FOREACH_MOD(I_OnNickDrop, OnNickDrop(source, na)); Log(!is_mine ? LOG_OVERRIDE : LOG_COMMAND, source, this) << "to drop nickname " << na->nick << " (group: " << na->nc->display << ") (email: " << (!na->nc->email.empty() ? na->nc->email : "none") << ")"; - na->destroy(); + na->Destroy(); if (!is_mine) { diff --git a/modules/commands/ns_getpass.cpp b/modules/commands/ns_getpass.cpp index 2e5efdf4d..998316f5b 100644 --- a/modules/commands/ns_getpass.cpp +++ b/modules/commands/ns_getpass.cpp @@ -28,13 +28,13 @@ class CommandNSGetPass : public Command Anope::string tmp_pass; const NickAlias *na; - if (!(na = findnick(nick))) + if (!(na = NickAlias::Find(nick))) source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); else if (Config->NSSecureAdmins && na->nc->IsServicesOper()) source.Reply(_("You may not get the password of other services operators.")); else { - if (enc_decrypt(na->nc->pass, tmp_pass) == 1) + if (Anope::Decrypt(na->nc->pass, tmp_pass) == 1) { Log(LOG_ADMIN, source, this) << "for " << nick; source.Reply(_("Password for %s is \002%s\002."), nick.c_str(), tmp_pass.c_str()); @@ -68,7 +68,7 @@ class NSGetPass : public Module this->SetAuthor("Anope"); Anope::string tmp_pass = "plain:tmp"; - if (enc_decrypt(tmp_pass, tmp_pass) == -1) + if (Anope::Decrypt(tmp_pass, tmp_pass) == -1) throw ModuleException("Incompatible with the encryption module being used"); } diff --git a/modules/commands/ns_ghost.cpp b/modules/commands/ns_ghost.cpp index e7289f728..de85a941f 100644 --- a/modules/commands/ns_ghost.cpp +++ b/modules/commands/ns_ghost.cpp @@ -19,7 +19,7 @@ class NSGhostRequest : public IdentifyRequest { CommandSource source; Command *cmd; - dynamic_reference<User> u; + Reference<User> u; public: NSGhostRequest(Module *o, CommandSource &src, Command *c, User *user, const Anope::string &pass) : IdentifyRequest(o, user->nick, pass), source(src), cmd(c), u(user) { } @@ -38,7 +38,7 @@ class NSGhostRequest : public IdentifyRequest { NSGhostExtensibleInfo *ei = new NSGhostExtensibleInfo; for (UChannelList::iterator it = u->chans.begin(), it_end = u->chans.end(); it != it_end; ++it) - (*ei)[(*it)->chan->name] = *(*it)->Status; + (*ei)[(*it)->chan->name] = *(*it)->status; source.GetUser()->Extend("ns_ghost_info", ei); } @@ -50,14 +50,14 @@ class NSGhostRequest : public IdentifyRequest source.Reply(_("Ghost with your nick has been killed.")); if (Config->NSRestoreOnGhost) - ircdproto->SendForceNickChange(source.GetUser(), GetAccount(), Anope::CurTime); + IRCD->SendForceNickChange(source.GetUser(), GetAccount(), Anope::CurTime); } void OnFail() anope_override { if (!u) ; - else if (!findnick(GetAccount())) + else if (!NickAlias::Find(GetAccount())) source.Reply(NICK_X_NOT_REGISTERED, GetAccount().c_str()); else { @@ -66,7 +66,7 @@ class NSGhostRequest : public IdentifyRequest { Log(LOG_COMMAND, source, cmd) << "with an invalid password for " << GetAccount(); if (source.GetUser()) - bad_password(source.GetUser()); + source.GetUser()->BadPassword(); } } } @@ -87,8 +87,8 @@ class CommandNSGhost : public Command const Anope::string &nick = params[0]; const Anope::string &pass = params.size() > 1 ? params[1] : ""; - User *user = finduser(nick); - const NickAlias *na = findnick(nick); + User *user = User::Find(nick, true); + const NickAlias *na = NickAlias::Find(nick); if (!user) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); @@ -107,7 +107,7 @@ class CommandNSGhost : public Command bool ok = false; if (source.GetAccount() == na->nc) ok = true; - else if (!na->nc->HasFlag(NI_SECURE) && source.GetUser() && is_on_access(source.GetUser(), na->nc)) + else if (!na->nc->HasFlag(NI_SECURE) && source.GetUser() && na->nc->IsOnAccess(source.GetUser())) ok = true; else if (source.GetUser() && !source.GetUser()->fingerprint.empty() && na->nc->FindCert(source.GetUser()->fingerprint)) ok = true; @@ -183,7 +183,7 @@ class NSGhost : public Module if (ei != NULL) for (std::map<Anope::string, ChannelStatus>::iterator it = ei->begin(), it_end = ei->end(); it != it_end; ++it) - ircdproto->SendSVSJoin(findbot(Config->NickServ), u->GetUID(), it->first, ""); + IRCD->SendSVSJoin(NickServ, u->GetUID(), it->first, ""); } } diff --git a/modules/commands/ns_group.cpp b/modules/commands/ns_group.cpp index 58251d76d..f4a464d28 100644 --- a/modules/commands/ns_group.cpp +++ b/modules/commands/ns_group.cpp @@ -18,7 +18,7 @@ class NSGroupRequest : public IdentifyRequest CommandSource source; Command *cmd; Anope::string nick; - dynamic_reference<NickAlias> target; + Reference<NickAlias> target; public: NSGroupRequest(Module *o, CommandSource &src, Command *c, const Anope::string &n, NickAlias *targ, const Anope::string &pass) : IdentifyRequest(o, targ->nc->display, pass), source(src), cmd(c), nick(n), target(targ) { } @@ -29,12 +29,12 @@ class NSGroupRequest : public IdentifyRequest return; User *u = source.GetUser(); - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); /* If the nick is already registered, drop it. */ if (na) { FOREACH_MOD(I_OnChangeCoreDisplay, OnChangeCoreDisplay(na->nc, u->nick)); - na->destroy(); + na->Destroy(); } na = new NickAlias(nick, target->nc); @@ -45,9 +45,9 @@ class NSGroupRequest : public IdentifyRequest na->time_registered = na->last_seen = Anope::CurTime; u->Login(target->nc); - ircdproto->SendLogin(u); + IRCD->SendLogin(u); if (!Config->NoNicknameOwnership && na->nc == u->Account() && na->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + u->SetMode(NickServ, UMODE_REGISTERED); FOREACH_MOD(I_OnNickGroup, OnNickGroup(u, target)); Log(LOG_COMMAND, source, cmd) << "makes " << nick << " join group of " << target->nick << " (" << target->nc->display << ") (email: " << (!target->nc->email.empty() ? target->nc->email : "none") << ")"; @@ -64,7 +64,7 @@ class NSGroupRequest : public IdentifyRequest Log(LOG_COMMAND, source, cmd) << "failed group for " << target->nick; source.Reply(PASSWORD_INCORRECT); - bad_password(source.GetUser()); + source.GetUser()->BadPassword(); } }; @@ -88,13 +88,13 @@ class CommandNSGroup : public Command const Anope::string &nick = params[0]; const Anope::string &pass = params.size() > 1 ? params[1] : ""; - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, nickname grouping is temporarily disabled.")); return; } - if (!ircdproto->IsNickValid(u->nick)) + if (!IRCD->IsNickValid(u->nick)) { source.Reply(NICK_CANNOT_BE_REGISTERED, u->nick.c_str()); return; @@ -112,8 +112,8 @@ class CommandNSGroup : public Command } } - NickAlias *target, *na = findnick(u->nick); - if (!(target = findnick(nick))) + NickAlias *target, *na = NickAlias::Find(u->nick); + if (!(target = NickAlias::Find(nick))) source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); else if (Anope::CurTime < u->lastnickreg + Config->NSRegDelay) source.Reply(_("Please wait %d seconds before using the GROUP command again."), (Config->NSRegDelay + u->lastnickreg) - Anope::CurTime); @@ -212,7 +212,7 @@ class CommandNSUngroup : public Command return; Anope::string nick = !params.empty() ? params[0] : ""; - NickAlias *na = findnick(!nick.empty() ? nick : u->nick); + NickAlias *na = NickAlias::Find(!nick.empty() ? nick : u->nick); if (u->Account()->aliases.size() == 1) source.Reply(_("Your nick is not grouped to anything, you can't ungroup it.")); @@ -224,12 +224,12 @@ class CommandNSUngroup : public Command { NickCore *oldcore = na->nc; - std::list<serialize_obj<NickAlias> >::iterator it = std::find(oldcore->aliases.begin(), oldcore->aliases.end(), na); + std::list<Serialize::Reference<NickAlias> >::iterator it = std::find(oldcore->aliases.begin(), oldcore->aliases.end(), na); if (it != oldcore->aliases.end()) oldcore->aliases.erase(it); if (na->nick.equals_ci(oldcore->display)) - change_core_display(oldcore); + oldcore->SetDisplay(oldcore->aliases.front()); NickCore *nc = new NickCore(na->nick); na->nc = nc; @@ -244,10 +244,10 @@ class CommandNSUngroup : public Command source.Reply(_("Nick %s has been ungrouped from %s."), na->nick.c_str(), oldcore->display.c_str()); - User *user = finduser(na->nick); + User *user = User::Find(na->nick); if (user) /* The user on the nick who was ungrouped may be identified to the old group, set -r */ - user->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + user->RemoveMode(NickServ, UMODE_REGISTERED); } return; @@ -281,7 +281,7 @@ class CommandNSGList : public Command if (!nick.empty()) { - const NickAlias *na = findnick(nick); + const NickAlias *na = NickAlias::Find(nick); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -299,8 +299,8 @@ class CommandNSGList : public Command nc = source.GetAccount(); ListFormatter list; - list.addColumn("Nick").addColumn("Expires"); - for (std::list<serialize_obj<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) + list.AddColumn("Nick").AddColumn("Expires"); + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) { const NickAlias *na2 = *it++; if (!na2) @@ -308,8 +308,8 @@ class CommandNSGList : public Command ListFormatter::ListEntry entry; entry["Nick"] = na2->nick; - entry["Expires"] = (na2->HasFlag(NS_NO_EXPIRE) || !Config->NSExpire) ? "Does not expire" : ("expires in " + do_strftime(na2->last_seen + Config->NSExpire)); - list.addEntry(entry); + entry["Expires"] = (na2->HasFlag(NS_NO_EXPIRE) || !Config->NSExpire) ? "Does not expire" : ("expires in " + Anope::strftime(na2->last_seen + Config->NSExpire)); + list.AddEntry(entry); } source.Reply(!nick.empty() ? _("List of nicknames in the group of \002%s\002:") : _("List of nicknames in your group:"), nc->display.c_str()); diff --git a/modules/commands/ns_identify.cpp b/modules/commands/ns_identify.cpp index dde24d72d..4796e7bb6 100644 --- a/modules/commands/ns_identify.cpp +++ b/modules/commands/ns_identify.cpp @@ -27,7 +27,7 @@ class NSIdentifyRequest : public IdentifyRequest return; User *u = source.GetUser(); - NickAlias *na = findnick(GetAccount()); + NickAlias *na = NickAlias::Find(GetAccount()); if (!na) source.Reply(NICK_X_NOT_REGISTERED, GetAccount().c_str()); @@ -49,7 +49,7 @@ class NSIdentifyRequest : public IdentifyRequest { Log(LOG_COMMAND, source, cmd) << "and failed to identify"; source.Reply(PASSWORD_INCORRECT); - bad_password(source.GetUser()); + source.GetUser()->BadPassword(); } } }; @@ -74,7 +74,7 @@ class CommandNSIdentify : public Command const Anope::string &nick = params.size() == 2 ? params[0] : u->nick; Anope::string pass = params[params.size() - 1]; - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na && na->nc->HasFlag(NI_SUSPENDED)) source.Reply(NICK_X_SUSPENDED, na->nick.c_str()); else if (u->Account() && na && u->Account() == na->nc) diff --git a/modules/commands/ns_info.cpp b/modules/commands/ns_info.cpp index 5daf2357e..976589718 100644 --- a/modules/commands/ns_info.cpp +++ b/modules/commands/ns_info.cpp @@ -16,14 +16,14 @@ class CommandNSInfo : public Command { private: - template<typename T, unsigned END> void CheckOptStr(NickCore *core, Anope::string &buf, T opt, const char *str, const Flags<T, END> *nc, bool reverse_logic = false) + template<typename T> void CheckOptStr(NickCore *core, Anope::string &buf, T opt, const char *str, const Flags<T> *nc, bool reverse_logic = false) { if (reverse_logic ? !nc->HasFlag(opt) : nc->HasFlag(opt)) { if (!buf.empty()) buf += ", "; - buf += translate(core, str); + buf += Language::Translate(core, str); } } public: @@ -38,12 +38,12 @@ class CommandNSInfo : public Command { const Anope::string &nick = params.size() ? params[0] : (source.nc ? source.nc->display : source.GetNick()); - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); bool has_auspex = source.HasPriv("nickserv/auspex"); if (!na) { - if (nickIsServices(nick, true)) + if (BotInfo::Find(nick, true)) source.Reply(_("Nick \002%s\002 is part of this Network's Services."), nick.c_str()); else source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -53,7 +53,7 @@ class CommandNSInfo : public Command bool nick_online = false, show_hidden = false; /* Is the real owner of the nick we're looking up online? -TheShadow */ - User *u2 = finduser(na->nick); + User *u2 = User::Find(na->nick); if (u2 && u2->Account() == na->nc) nick_online = true; @@ -87,10 +87,10 @@ class CommandNSInfo : public Command info[_("Last seen address")] = na->last_realhost; } - info[_("Time registered")] = do_strftime(na->time_registered); + info[_("Time registered")] = Anope::strftime(na->time_registered); if (!nick_online) - info[_("Last seen")] = do_strftime(na->last_seen); + info[_("Last seen")] = Anope::strftime(na->last_seen); if (!na->last_quit.empty() && (show_hidden || !na->nc->HasFlag(NI_HIDE_QUIT))) info[_("Last quit message")] = na->last_quit; @@ -102,7 +102,7 @@ class CommandNSInfo : public Command { if (na->HasVhost()) { - if (ircdproto->CanSetVIdent && !na->GetVhostIdent().empty()) + if (IRCD->CanSetVIdent && !na->GetVhostIdent().empty()) info[_("VHost")] = na->GetVhostIdent() + "@" + na->GetVhostHost(); else info[_("VHost")] = na->GetVhostHost(); @@ -113,14 +113,14 @@ class CommandNSInfo : public Command Anope::string optbuf; - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_KILLPROTECT, _("Protection"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_SECURE, _("Security"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_PRIVATE, _("Private"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_MSG, _("Message mode"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_AUTOOP, _("Auto-op"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_SUSPENDED, _("Suspended"), na->nc); - CheckOptStr<NickCoreFlag, NI_END>(source.nc, optbuf, NI_STATS, _("Chanstats"), na->nc); - CheckOptStr<NickNameFlag, NS_END>(source.nc, optbuf, NS_NO_EXPIRE, _("No expire"), na); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_KILLPROTECT, _("Protection"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_SECURE, _("Security"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_PRIVATE, _("Private"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_MSG, _("Message mode"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_AUTOOP, _("Auto-op"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_SUSPENDED, _("Suspended"), na->nc); + CheckOptStr<NickCoreFlag>(source.nc, optbuf, NI_STATS, _("Chanstats"), na->nc); + CheckOptStr<NickNameFlag>(source.nc, optbuf, NS_NO_EXPIRE, _("No expire"), na); info[_("Options")] = optbuf.empty() ? _("None") : optbuf; @@ -129,10 +129,10 @@ class CommandNSInfo : public Command if (na->HasFlag(NS_NO_EXPIRE) || !Config->NSExpire) ; else - info[_("Expires")] = do_strftime(na->last_seen + Config->NSExpire); + info[_("Expires")] = Anope::strftime(na->last_seen + Config->NSExpire); } else - info[_("Expires")] = do_strftime(na->time_registered + Config->NSUnconfirmedExpire); + info[_("Expires")] = Anope::strftime(na->time_registered + Config->NSUnconfirmedExpire); } FOREACH_MOD(I_OnNickInfo, OnNickInfo(source, na, info, show_hidden)); diff --git a/modules/commands/ns_list.cpp b/modules/commands/ns_list.cpp index 89adfc6ea..9c3c164dd 100644 --- a/modules/commands/ns_list.cpp +++ b/modules/commands/ns_list.cpp @@ -36,8 +36,9 @@ class CommandNSList : public Command if (pattern[0] == '#') { - Anope::string n1 = myStrGetToken(pattern.substr(1), '-', 0), /* Read FROM out */ - n2 = myStrGetToken(pattern, '-', 1); + Anope::string n1, n2; + sepstream(pattern.substr(1), '-').GetToken(n1, 0); + sepstream(pattern, '-').GetToken(n2, 1); try { from = convertTo<int>(n1); @@ -72,7 +73,7 @@ class CommandNSList : public Command mync = source.nc; ListFormatter list; - list.addColumn("Nick").addColumn("Last usermask"); + list.AddColumn("Nick").AddColumn("Last usermask"); for (nickalias_map::const_iterator it = NickAliasList->begin(), it_end = NickAliasList->end(); it != it_end; ++it) { @@ -110,7 +111,7 @@ class CommandNSList : public Command entry["Last usermask"] = "[Unconfirmed]"; else entry["Last usermask"] = na->last_usermask; - list.addEntry(entry); + list.AddEntry(entry); } ++count; } diff --git a/modules/commands/ns_logout.cpp b/modules/commands/ns_logout.cpp index 4e0dc7131..5519e6ae8 100644 --- a/modules/commands/ns_logout.cpp +++ b/modules/commands/ns_logout.cpp @@ -32,16 +32,16 @@ class CommandNSLogout : public Command User *u2; if (!source.IsServicesOper() && !nick.empty()) this->OnSyntaxError(source, ""); - else if (!(u2 = (!nick.empty() ? finduser(nick) : source.GetUser()))) + else if (!(u2 = (!nick.empty() ? User::Find(nick, true) : source.GetUser()))) source.Reply(NICK_X_NOT_IN_USE, !nick.empty() ? nick.c_str() : source.GetNick().c_str()); else if (!nick.empty() && u2->IsServicesOper()) source.Reply(_("You can't logout %s because they are a Services Operator."), nick.c_str()); else { - if (!nick.empty() && !param.empty() && param.equals_ci("REVALIDATE") && nickserv) - nickserv->Validate(u2); + if (!nick.empty() && !param.empty() && param.equals_ci("REVALIDATE") && NickServService) + NickServService->Validate(u2); - u2->SuperAdmin = 0; /* Dont let people logout and remain a SuperAdmin */ + u2->super_admin = false; /* Dont let people logout and remain a SuperAdmin */ Log(LOG_COMMAND, source, this) << "to logout " << u2->nick; /* Remove founder status from this user in all channels */ @@ -50,8 +50,8 @@ class CommandNSLogout : public Command else source.Reply(_("Your nick has been logged out.")); - ircdproto->SendLogout(u2); - u2->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + IRCD->SendLogout(u2); + u2->RemoveMode(NickServ, UMODE_REGISTERED); u2->Logout(); /* Send out an event */ diff --git a/modules/commands/ns_recover.cpp b/modules/commands/ns_recover.cpp index 63d503553..54a10f3b4 100644 --- a/modules/commands/ns_recover.cpp +++ b/modules/commands/ns_recover.cpp @@ -18,8 +18,8 @@ class NSRecoverRequest : public IdentifyRequest { CommandSource source; Command *cmd; - dynamic_reference<NickAlias> na; - dynamic_reference<User> u; + Reference<NickAlias> na; + Reference<User> u; public: NSRecoverRequest(Module *m, CommandSource &src, Command *c, User *user, NickAlias *n, const Anope::string &pass) : IdentifyRequest(m, n->nc->display, pass), source(src), cmd(c), na(n), u(user) { } @@ -33,14 +33,14 @@ class NSRecoverRequest : public IdentifyRequest if (u->Account() == na->nc) { - ircdproto->SendLogout(u); - u->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + IRCD->SendLogout(u); + u->RemoveMode(NickServ, UMODE_REGISTERED); } u->Collide(na); /* Convert Config->NSReleaseTimeout seconds to string format */ - Anope::string relstr = duration(Config->NSReleaseTimeout); + Anope::string relstr = Anope::Duration(Config->NSReleaseTimeout); source.Reply(NICK_RECOVERED, Config->UseStrictPrivMsgString.c_str(), Config->NickServ.c_str(), na->nick.c_str(), relstr.c_str()); } @@ -53,7 +53,7 @@ class NSRecoverRequest : public IdentifyRequest if (!GetPassword().empty()) { Log(LOG_COMMAND, source, cmd) << "with invalid password for " << na->nick; - bad_password(u); + u->BadPassword(); } } }; @@ -76,11 +76,11 @@ class CommandNSRecover : public Command NickAlias *na; User *u2; - if (!(u2 = finduser(nick))) + if (!(u2 = User::Find(nick, true))) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); else if (u2->server == Me) source.Reply(_("\2%s\2 has already been recovered."), u2->nick.c_str()); - else if (!(na = findnick(u2->nick))) + else if (!(na = NickAlias::Find(u2->nick))) source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); else if (na->nc->HasFlag(NI_SUSPENDED)) source.Reply(NICK_X_SUSPENDED, na->nick.c_str()); @@ -91,7 +91,7 @@ class CommandNSRecover : public Command bool ok = false; if (source.GetAccount() == na->nc) ok = true; - else if (!na->nc->HasFlag(NI_SECURE) && source.GetUser() && is_on_access(source.GetUser(), na->nc)) + else if (!na->nc->HasFlag(NI_SECURE) && source.GetUser() && na->nc->IsOnAccess(source.GetUser())) ok = true; else if (source.GetUser() && !source.GetUser()->fingerprint.empty() && na->nc->FindCert(source.GetUser()->fingerprint)) ok = true; @@ -117,7 +117,7 @@ class CommandNSRecover : public Command bool OnHelp(CommandSource &source, const Anope::string &subcommand) anope_override { /* Convert Config->NSReleaseTimeout seconds to string format */ - Anope::string relstr = duration(Config->NSReleaseTimeout); + Anope::string relstr = Anope::Duration(Config->NSReleaseTimeout); this->SendSyntax(source); source.Reply(" "); diff --git a/modules/commands/ns_register.cpp b/modules/commands/ns_register.cpp index 0413f8cc8..d16144a18 100644 --- a/modules/commands/ns_register.cpp +++ b/modules/commands/ns_register.cpp @@ -31,7 +31,7 @@ class CommandNSConfirm : public Command if (source.nc && !source.nc->HasFlag(NI_UNCONFIRMED) && source.HasPriv("nickserv/confirm")) { - NickAlias *na = findnick(passcode); + NickAlias *na = NickAlias::Find(passcode); if (na == NULL) source.Reply(NICK_X_NOT_REGISTERED, passcode.c_str()); else if (na->nc->HasFlag(NI_UNCONFIRMED) == false) @@ -56,10 +56,10 @@ class CommandNSConfirm : public Command if (source.GetUser()) { - ircdproto->SendLogin(source.GetUser()); - const NickAlias *na = findnick(source.GetNick()); + IRCD->SendLogin(source.GetUser()); + const NickAlias *na = NickAlias::Find(source.GetNick()); if (!Config->NoNicknameOwnership && na != NULL && na->nc == source.GetAccount() && na->nc->HasFlag(NI_UNCONFIRMED) == false) - source.GetUser()->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + source.GetUser()->SetMode(NickServ, UMODE_REGISTERED); } } else @@ -118,7 +118,7 @@ class CommandNSRegister : public Command Anope::string pass = params[0]; Anope::string email = params.size() > 1 ? params[1] : ""; - if (readonly) + if (Anope::ReadOnly) { source.Reply(_("Sorry, nickname registration is temporarily disabled.")); return; @@ -147,7 +147,7 @@ class CommandNSRegister : public Command return; } - if (!ircdproto->IsNickValid(u_nick)) + if (!IRCD->IsNickValid(u_nick)) { source.Reply(NICK_CANNOT_BE_REGISTERED, u_nick.c_str()); return; @@ -169,19 +169,19 @@ class CommandNSRegister : public Command this->OnSyntaxError(source, ""); else if (u && Anope::CurTime < u->lastnickreg + Config->NSRegDelay) source.Reply(_("Please wait %d seconds before using the REGISTER command again."), (u->lastnickreg + Config->NSRegDelay) - Anope::CurTime); - else if ((na = findnick(u_nick))) + else if ((na = NickAlias::Find(u_nick))) source.Reply(NICK_ALREADY_REGISTERED, u_nick.c_str()); else if (pass.equals_ci(u_nick) || (Config->StrictPasswords && pass.length() < 5)) source.Reply(MORE_OBSCURE_PASSWORD); else if (pass.length() > Config->PassLen) source.Reply(PASSWORD_TOO_LONG); - else if (!email.empty() && !MailValidate(email)) + else if (!email.empty() && !Mail::Validate(email)) source.Reply(MAIL_X_INVALID, email.c_str()); else { NickCore *nc = new NickCore(u_nick); na = new NickAlias(u_nick, nc); - enc_encrypt(pass, nc->pass); + Anope::Encrypt(pass, nc->pass); if (!email.empty()) nc->email = email; @@ -193,7 +193,7 @@ class CommandNSRegister : public Command u->Login(nc); if (Config->NSAddAccessOnReg) - nc->AddAccess(create_mask(u)); + nc->AddAccess(u->Mask()); } Log(LOG_COMMAND, source, this) << "to register " << na->nick << " (email: " << (!na->nc->email.empty() ? na->nc->email : "none") << ")"; @@ -206,7 +206,7 @@ class CommandNSRegister : public Command source.Reply(_("Nickname \002%s\002 registered."), u_nick.c_str()); Anope::string tmp_pass; - if (enc_decrypt(na->nc->pass, tmp_pass) == 1) + if (Anope::Decrypt(na->nc->pass, tmp_pass) == 1) source.Reply(_("Your password is \002%s\002 - remember this for later use."), tmp_pass.c_str()); if (Config->NSRegistration.equals_ci("admin")) @@ -220,16 +220,16 @@ class CommandNSRegister : public Command if (SendRegmail(u, na, source.service)) { source.Reply(_("A passcode has been sent to %s, please type %s%s confirm <passcode> to confirm your email address."), email.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->NickServ.c_str()); - source.Reply(_("If you do not confirm your email address within %s your account will expire."), duration(Config->NSUnconfirmedExpire).c_str()); + source.Reply(_("If you do not confirm your email address within %s your account will expire."), Anope::Duration(Config->NSUnconfirmedExpire).c_str()); } } else if (Config->NSRegistration.equals_ci("none")) { if (u) { - ircdproto->SendLogin(u); + IRCD->SendLogin(u); if (!Config->NoNicknameOwnership && na->nc == u->Account() && na->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + u->SetMode(NickServ, UMODE_REGISTERED); } } @@ -290,7 +290,7 @@ class CommandNSResend : public Command if (Config->NSRegistration.equals_ci("mail")) return; - const NickAlias *na = findnick(source.GetNick()); + const NickAlias *na = NickAlias::Find(source.GetNick()); if (na == NULL) source.Reply(NICK_NOT_REGISTERED); @@ -372,8 +372,8 @@ static bool SendRegmail(User *u, const NickAlias *na, const BotInfo *bi) else codebuf = *code; - Anope::string subject = translate(na->nc, Config->MailRegistrationSubject.c_str()); - Anope::string message = translate(na->nc, Config->MailRegistrationMessage.c_str()); + Anope::string subject = Language::Translate(na->nc, Config->MailRegistrationSubject.c_str()); + Anope::string message = Language::Translate(na->nc, Config->MailRegistrationMessage.c_str()); subject = subject.replace_all_cs("%n", na->nick); subject = subject.replace_all_cs("%N", Config->NetworkName); @@ -383,7 +383,7 @@ static bool SendRegmail(User *u, const NickAlias *na, const BotInfo *bi) message = message.replace_all_cs("%N", Config->NetworkName); message = message.replace_all_cs("%c", codebuf); - return Mail(u, nc, bi, subject, message); + return Mail::Send(u, nc, bi, subject, message); } MODULE_INIT(NSRegister) diff --git a/modules/commands/ns_release.cpp b/modules/commands/ns_release.cpp index cd669e707..a3004f462 100644 --- a/modules/commands/ns_release.cpp +++ b/modules/commands/ns_release.cpp @@ -17,7 +17,7 @@ class NSReleaseRequest : public IdentifyRequest { CommandSource source; Command *cmd; - dynamic_reference<NickAlias> na; + Reference<NickAlias> na; public: NSReleaseRequest(Module *m, CommandSource &src, Command *c, NickAlias *n, const Anope::string &pass) : IdentifyRequest(m, n->nc->display, pass), source(src), cmd(c), na(n) { } @@ -40,7 +40,7 @@ class NSReleaseRequest : public IdentifyRequest { Log(LOG_COMMAND, source, cmd) << "with invalid password for " << na->nick; if (!source.GetUser()) - bad_password(source.GetUser()); + source.GetUser()->BadPassword(); } } }; @@ -61,7 +61,7 @@ class CommandNSRelease : public Command Anope::string pass = params.size() > 1 ? params[1] : ""; NickAlias *na; - if (!(na = findnick(nick))) + if (!(na = NickAlias::Find(nick))) source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); else if (na->nc->HasFlag(NI_SUSPENDED)) source.Reply(NICK_X_SUSPENDED, na->nick.c_str()); @@ -74,7 +74,7 @@ class CommandNSRelease : public Command bool ok = override; if (source.GetAccount() == na->nc) ok = true; - else if (source.GetUser() && !na->nc->HasFlag(NI_SECURE) && is_on_access(source.GetUser(), na->nc)) + else if (source.GetUser() && !na->nc->HasFlag(NI_SECURE) && na->nc->IsOnAccess(source.GetUser())) ok = true; else if (source.GetUser() && !source.GetUser()->fingerprint.empty() && na->nc->FindCert(source.GetUser()->fingerprint)) ok = true; @@ -101,7 +101,7 @@ class CommandNSRelease : public Command bool OnHelp(CommandSource &source, const Anope::string &subcommand) anope_override { /* Convert Config->NSReleaseTimeout seconds to string format */ - Anope::string relstr = duration(Config->NSReleaseTimeout); + Anope::string relstr = Anope::Duration(Config->NSReleaseTimeout); this->SendSyntax(source); source.Reply(" "); diff --git a/modules/commands/ns_resetpass.cpp b/modules/commands/ns_resetpass.cpp index 8965b6a3e..39eead56e 100644 --- a/modules/commands/ns_resetpass.cpp +++ b/modules/commands/ns_resetpass.cpp @@ -31,7 +31,7 @@ class CommandNSResetPass : public Command if (Config->RestrictMail && source.HasCommand("nickserv/resetpass")) source.Reply(ACCESS_DENIED); - else if (!(na = findnick(params[0]))) + else if (!(na = NickAlias::Find(params[0]))) source.Reply(NICK_X_NOT_REGISTERED, params[0].c_str()); else { @@ -82,7 +82,7 @@ class NSResetPass : public Module { if (command->name == "nickserv/confirm" && params.size() > 1) { - NickAlias *na = findnick(params[0]); + NickAlias *na = NickAlias::Find(params[0]); ResetInfo *ri = na ? na->nc->GetExt<ResetInfo *>("ns_resetpass") : NULL; if (na && ri) @@ -135,8 +135,8 @@ static bool SendResetEmail(User *u, const NickAlias *na, const BotInfo *bi) for (idx = 0; idx < 20; ++idx) passcode += chars[1 + static_cast<int>((static_cast<float>(max - min)) * static_cast<uint16_t>(rand()) / 65536.0) + min]; - Anope::string subject = translate(na->nc, Config->MailResetSubject.c_str()); - Anope::string message = translate(na->nc, Config->MailResetMessage.c_str()); + Anope::string subject = Language::Translate(na->nc, Config->MailResetSubject.c_str()); + Anope::string message = Language::Translate(na->nc, Config->MailResetMessage.c_str()); subject = subject.replace_all_cs("%n", na->nick); subject = subject.replace_all_cs("%N", Config->NetworkName); @@ -152,7 +152,7 @@ static bool SendResetEmail(User *u, const NickAlias *na, const BotInfo *bi) NickCore *nc = na->nc; nc->Extend("ns_resetpass", ri); - return Mail(u, nc, bi, subject, message); + return Mail::Send(u, nc, bi, subject, message); } MODULE_INIT(NSResetPass) diff --git a/modules/commands/ns_saset.cpp b/modules/commands/ns_saset.cpp index 8d2ba08d9..ac3cb1d8f 100644 --- a/modules/commands/ns_saset.cpp +++ b/modules/commands/ns_saset.cpp @@ -40,7 +40,7 @@ class CommandNSSASet : public Command if (c_name.find_ci(this_name + " ") == 0) { - service_reference<Command> command("Command", info.name); + ServiceReference<Command> command("Command", info.name); if (command) { source.command = c_name; @@ -66,7 +66,7 @@ class CommandNSSASetPassword : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - const NickAlias *setter_na = findnick(params[0]); + const NickAlias *setter_na = NickAlias::Find(params[0]); if (setter_na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, params[0].c_str()); @@ -92,9 +92,9 @@ class CommandNSSASetPassword : public Command return; } - enc_encrypt(params[1], nc->pass); + Anope::Encrypt(params[1], nc->pass); Anope::string tmp_pass; - if (enc_decrypt(nc->pass, tmp_pass) == 1) + if (Anope::Decrypt(nc->pass, tmp_pass) == 1) source.Reply(_("Password for \002%s\002 changed to \002%s\002."), nc->display.c_str(), tmp_pass.c_str()); else source.Reply(_("Password for \002%s\002 changed."), nc->display.c_str()); diff --git a/modules/commands/ns_saset_noexpire.cpp b/modules/commands/ns_saset_noexpire.cpp index 5ebfdce89..ea3e946ae 100644 --- a/modules/commands/ns_saset_noexpire.cpp +++ b/modules/commands/ns_saset_noexpire.cpp @@ -24,7 +24,7 @@ class CommandNSSASetNoexpire : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - NickAlias *na = findnick(params[0]); + NickAlias *na = NickAlias::Find(params[0]); if (na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, params[0].c_str()); diff --git a/modules/commands/ns_sendpass.cpp b/modules/commands/ns_sendpass.cpp index 5d88fd5a4..e85690e24 100644 --- a/modules/commands/ns_sendpass.cpp +++ b/modules/commands/ns_sendpass.cpp @@ -32,12 +32,12 @@ class CommandNSSendPass : public Command if (Config->RestrictMail && !source.HasCommand("nickserv/sendpass")) source.Reply(ACCESS_DENIED); - else if (!(na = findnick(nick))) + else if (!(na = NickAlias::Find(nick))) source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); else { Anope::string tmp_pass; - if (enc_decrypt(na->nc->pass, tmp_pass) == 1) + if (Anope::Decrypt(na->nc->pass, tmp_pass) == 1) { if (SendPassMail(source.GetUser(), na, source.service, tmp_pass)) { @@ -79,7 +79,7 @@ class NSSendPass : public Module throw ModuleException("Not using mail."); Anope::string tmp_pass = "plain:tmp"; - if (enc_decrypt(tmp_pass, tmp_pass) == -1) + if (Anope::Decrypt(tmp_pass, tmp_pass) == -1) throw ModuleException("Incompatible with the encryption module being used"); } @@ -87,8 +87,8 @@ class NSSendPass : public Module static bool SendPassMail(User *u, const NickAlias *na, const BotInfo *bi, const Anope::string &pass) { - Anope::string subject = translate(na->nc, Config->MailSendpassSubject.c_str()); - Anope::string message = translate(na->nc, Config->MailSendpassMessage.c_str()); + Anope::string subject = Language::Translate(na->nc, Config->MailSendpassSubject.c_str()); + Anope::string message = Language::Translate(na->nc, Config->MailSendpassMessage.c_str()); subject = subject.replace_all_cs("%n", na->nick); subject = subject.replace_all_cs("%N", Config->NetworkName); @@ -98,7 +98,7 @@ static bool SendPassMail(User *u, const NickAlias *na, const BotInfo *bi, const message = message.replace_all_cs("%N", Config->NetworkName); message = message.replace_all_cs("%p", pass); - return Mail(u, na->nc, bi, subject, message); + return Mail::Send(u, na->nc, bi, subject, message); } MODULE_INIT(NSSendPass) diff --git a/modules/commands/ns_set.cpp b/modules/commands/ns_set.cpp index 0917d45bd..bc6a67b35 100644 --- a/modules/commands/ns_set.cpp +++ b/modules/commands/ns_set.cpp @@ -41,7 +41,7 @@ class CommandNSSet : public Command if (c_name.find_ci(this_name + " ") == 0) { - service_reference<Command> command("Command", info.name); + ServiceReference<Command> command("Command", info.name); if (command) { source.command = c_name; @@ -81,9 +81,9 @@ class CommandNSSetPassword : public Command return; } - enc_encrypt(param, source.nc->pass); + Anope::Encrypt(param, source.nc->pass); Anope::string tmp_pass; - if (enc_decrypt(source.nc->pass, tmp_pass) == 1) + if (Anope::Decrypt(source.nc->pass, tmp_pass) == 1) source.Reply(_("Password for \002%s\002 changed to \002%s\002."), source.nc->display.c_str(), tmp_pass.c_str()); else source.Reply(_("Password for \002%s\002 changed."), source.nc->display.c_str()); diff --git a/modules/commands/ns_set_autoop.cpp b/modules/commands/ns_set_autoop.cpp index 7e3864420..e6533875b 100644 --- a/modules/commands/ns_set_autoop.cpp +++ b/modules/commands/ns_set_autoop.cpp @@ -24,7 +24,7 @@ class CommandNSSetAutoOp : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (na == NULL) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_chanstats.cpp b/modules/commands/ns_set_chanstats.cpp index 5bf23907b..7b8f371ff 100644 --- a/modules/commands/ns_set_chanstats.cpp +++ b/modules/commands/ns_set_chanstats.cpp @@ -23,7 +23,7 @@ class CommandNSSetChanstats : public Command } void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - NickAlias *na = findnick(user); + NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_display.cpp b/modules/commands/ns_set_display.cpp index 1980ba116..c532f4cf1 100644 --- a/modules/commands/ns_set_display.cpp +++ b/modules/commands/ns_set_display.cpp @@ -24,7 +24,7 @@ class CommandNSSetDisplay : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *user_na = findnick(user), *na = findnick(param); + const NickAlias *user_na = NickAlias::Find(user), *na = NickAlias::Find(param); if (user_na == NULL) { @@ -42,7 +42,7 @@ class CommandNSSetDisplay : public Command if (MOD_RESULT == EVENT_STOP) return; - change_core_display(user_na->nc, na->nick); + user_na->nc->SetDisplay(na); source.Reply(NICK_SET_DISPLAY_CHANGED, user_na->nc->display.c_str()); } diff --git a/modules/commands/ns_set_email.cpp b/modules/commands/ns_set_email.cpp index 6966c2a79..82b4a0cc8 100644 --- a/modules/commands/ns_set_email.cpp +++ b/modules/commands/ns_set_email.cpp @@ -40,7 +40,7 @@ static bool SendConfirmMail(User *u, const BotInfo *bi) message = message.replace_all_cs("%N", Config->NetworkName); message = message.replace_all_cs("%c", code); - return Mail(u, u->Account(), bi, subject, message); + return Mail::Send(u, u->Account(), bi, subject, message); } class CommandNSSetEmail : public Command @@ -54,7 +54,7 @@ class CommandNSSetEmail : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); @@ -72,7 +72,7 @@ class CommandNSSetEmail : public Command source.Reply(_("You may not change the email of other services operators.")); return; } - else if (!param.empty() && !MailValidate(param)) + else if (!param.empty() && !Mail::Validate(param)) { source.Reply(MAIL_X_INVALID, param.c_str()); return; diff --git a/modules/commands/ns_set_greet.cpp b/modules/commands/ns_set_greet.cpp index 87ac7d1ee..b28edc2bb 100644 --- a/modules/commands/ns_set_greet.cpp +++ b/modules/commands/ns_set_greet.cpp @@ -24,7 +24,7 @@ class CommandNSSetGreet : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_hide.cpp b/modules/commands/ns_set_hide.cpp index 4770653f2..d7fe886ea 100644 --- a/modules/commands/ns_set_hide.cpp +++ b/modules/commands/ns_set_hide.cpp @@ -24,7 +24,7 @@ class CommandNSSetHide : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m, const Anope::string &arg) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_kill.cpp b/modules/commands/ns_set_kill.cpp index ca0f804d3..0f62a4ba0 100644 --- a/modules/commands/ns_set_kill.cpp +++ b/modules/commands/ns_set_kill.cpp @@ -24,7 +24,7 @@ class CommandNSSetKill : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_language.cpp b/modules/commands/ns_set_language.cpp index 43162d6fd..d2830d4b8 100644 --- a/modules/commands/ns_set_language.cpp +++ b/modules/commands/ns_set_language.cpp @@ -24,7 +24,7 @@ class CommandNSSetLanguage : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); @@ -37,11 +37,11 @@ class CommandNSSetLanguage : public Command if (MOD_RESULT == EVENT_STOP) return; - for (unsigned j = 0; j < languages.size(); ++j) + for (unsigned j = 0; j < Language::Languages.size(); ++j) { - if (param == "en" || languages[j] == param) + if (param == "en" || Language::Languages[j] == param) break; - else if (j + 1 == languages.size()) + else if (j + 1 == Language::Languages.size()) { this->OnSyntaxError(source, ""); return; @@ -69,12 +69,12 @@ class CommandNSSetLanguage : public Command "supported languages:")); source.Reply(" en (English)"); - for (unsigned j = 0; j < languages.size(); ++j) + for (unsigned j = 0; j < Language::Languages.size(); ++j) { - const Anope::string &langname = anope_gettext(languages[j].c_str(), _("English")); + const Anope::string &langname = Language::Translate(Language::Languages[j].c_str(), _("English")); if (langname == "English") continue; - source.Reply(" %s (%s)", languages[j].c_str(), langname.c_str()); + source.Reply(" %s (%s)", Language::Languages[j].c_str(), langname.c_str()); } return true; @@ -104,12 +104,12 @@ class CommandNSSASetLanguage : public CommandNSSetLanguage "\037language\037 should be chosen from the following list of\n" "supported languages:")); source.Reply(" en (English)"); - for (unsigned j = 0; j < languages.size(); ++j) + for (unsigned j = 0; j < Language::Languages.size(); ++j) { - const Anope::string &langname = anope_gettext(languages[j].c_str(), _("English")); + const Anope::string &langname = Language::Translate(Language::Languages[j].c_str(), _("English")); if (langname == "English") continue; - source.Reply(" %s (%s)", languages[j].c_str(), langname.c_str()); + source.Reply(" %s (%s)", Language::Languages[j].c_str(), langname.c_str()); } return true; } diff --git a/modules/commands/ns_set_message.cpp b/modules/commands/ns_set_message.cpp index fa0ad7ec3..f515b22c1 100644 --- a/modules/commands/ns_set_message.cpp +++ b/modules/commands/ns_set_message.cpp @@ -24,7 +24,7 @@ class CommandNSSetMessage : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_misc.cpp b/modules/commands/ns_set_misc.cpp index 9c805b3ea..1e088a425 100644 --- a/modules/commands/ns_set_misc.cpp +++ b/modules/commands/ns_set_misc.cpp @@ -15,7 +15,7 @@ struct NSMiscData : ExtensibleItem, Serializable { - serialize_obj<NickCore> nc; + Serialize::Reference<NickCore> nc; Anope::string name; Anope::string data; @@ -23,7 +23,7 @@ struct NSMiscData : ExtensibleItem, Serializable { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data sdata; @@ -34,9 +34,9 @@ struct NSMiscData : ExtensibleItem, Serializable return sdata; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { - NickCore *nc = findcore(data["nc"].astr()); + NickCore *nc = NickCore::Find(data["nc"].astr()); if (nc == NULL) return NULL; @@ -76,7 +76,7 @@ class CommandNSSetMisc : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); @@ -126,13 +126,13 @@ class CommandNSSASetMisc : public CommandNSSetMisc class NSSetMisc : public Module { - SerializeType nsmiscdata_type; + Serialize::Type nsmiscdata_type; CommandNSSetMisc commandnssetmisc; CommandNSSASetMisc commandnssasetmisc; public: NSSetMisc(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - nsmiscdata_type("NSMiscData", NSMiscData::unserialize), commandnssetmisc(this), commandnssasetmisc(this) + nsmiscdata_type("NSMiscData", NSMiscData::Unserialize), commandnssetmisc(this), commandnssasetmisc(this) { this->SetAuthor("Anope"); diff --git a/modules/commands/ns_set_private.cpp b/modules/commands/ns_set_private.cpp index 358035567..8f953fcc0 100644 --- a/modules/commands/ns_set_private.cpp +++ b/modules/commands/ns_set_private.cpp @@ -24,7 +24,7 @@ class CommandNSSetPrivate : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_set_secure.cpp b/modules/commands/ns_set_secure.cpp index 52eea8e5b..b7dd79969 100644 --- a/modules/commands/ns_set_secure.cpp +++ b/modules/commands/ns_set_secure.cpp @@ -24,7 +24,7 @@ class CommandNSSetSecure : public Command void Run(CommandSource &source, const Anope::string &user, const Anope::string ¶m) { - const NickAlias *na = findnick(user); + const NickAlias *na = NickAlias::Find(user); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, user.c_str()); diff --git a/modules/commands/ns_status.cpp b/modules/commands/ns_status.cpp index 7a5a68a5a..495ae96a1 100644 --- a/modules/commands/ns_status.cpp +++ b/modules/commands/ns_status.cpp @@ -26,13 +26,13 @@ class CommandNSStatus : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { const Anope::string &nick = !params.empty() ? params[0] : source.GetNick(); - const NickAlias *na = findnick(nick); + const NickAlias *na = NickAlias::Find(nick); spacesepstream sep(nick); Anope::string nickbuf; while (sep.GetToken(nickbuf)) { - User *u2 = finduser(nickbuf); + User *u2 = User::Find(nickbuf, true); if (!u2) /* Nick is not online */ source.Reply(_("STATUS %s %d %s"), nickbuf.c_str(), 0, ""); else if (u2->IsIdentified() && na && na->nc == u2->Account()) /* Nick is identified */ diff --git a/modules/commands/ns_suspend.cpp b/modules/commands/ns_suspend.cpp index 6b316379e..6ff355437 100644 --- a/modules/commands/ns_suspend.cpp +++ b/modules/commands/ns_suspend.cpp @@ -22,7 +22,7 @@ struct NickSuspend : ExtensibleItem, Serializable { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data sd; @@ -32,9 +32,9 @@ struct NickSuspend : ExtensibleItem, Serializable return sd; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &sd) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &sd) { - const NickAlias *na = findnick(sd["nick"].astr()); + const NickAlias *na = NickAlias::Find(sd["nick"].astr()); if (na == NULL) return NULL; @@ -71,7 +71,7 @@ class CommandNSSuspend : public Command Anope::string reason = params.size() > 2 ? params[2] : ""; time_t expiry_secs = Config->NSSuspendExpire; - if (readonly) + if (Anope::ReadOnly) { source.Reply(READ_ONLY_MODE); return; @@ -84,9 +84,9 @@ class CommandNSSuspend : public Command expiry.clear(); } else - expiry_secs = dotime(expiry); + expiry_secs = Anope::DoTime(expiry); - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -107,7 +107,7 @@ class CommandNSSuspend : public Command nc->UnsetFlag(NI_KILL_QUICK); nc->UnsetFlag(NI_KILL_IMMED); - for (std::list<serialize_obj<NickAlias> >::iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) + for (std::list<Serialize::Reference<NickAlias> >::iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) { NickAlias *na2 = *it++; @@ -115,7 +115,7 @@ class CommandNSSuspend : public Command { na2->last_quit = reason; - User *u2 = finduser(na2->nick); + User *u2 = User::Find(na2->nick); if (u2) { u2->Logout(); @@ -133,7 +133,7 @@ class CommandNSSuspend : public Command nc->Extend("ns_suspend_expire", ns); } - Log(LOG_ADMIN, source, this) << "for " << nick << " (" << (!reason.empty() ? reason : "No reason") << "), expires in " << (expiry_secs ? do_strftime(Anope::CurTime + expiry_secs) : "never"); + Log(LOG_ADMIN, source, this) << "for " << nick << " (" << (!reason.empty() ? reason : "No reason") << "), expires in " << (expiry_secs ? Anope::strftime(Anope::CurTime + expiry_secs) : "never"); source.Reply(_("Nick %s is now suspended."), nick.c_str()); FOREACH_MOD(I_OnNickSuspended, OnNickSuspend(na)); @@ -166,13 +166,13 @@ class CommandNSUnSuspend : public Command { const Anope::string &nick = params[0]; - if (readonly) + if (Anope::ReadOnly) { source.Reply(READ_ONLY_MODE); return; } - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (!na) { source.Reply(NICK_X_NOT_REGISTERED, nick.c_str()); @@ -207,13 +207,13 @@ class CommandNSUnSuspend : public Command class NSSuspend : public Module { - SerializeType nicksuspend_type; + Serialize::Type nicksuspend_type; CommandNSSuspend commandnssuspend; CommandNSUnSuspend commandnsunsuspend; public: NSSuspend(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - nicksuspend_type("NickSuspend", NickSuspend::unserialize), commandnssuspend(this), commandnsunsuspend(this) + nicksuspend_type("NickSuspend", NickSuspend::Unserialize), commandnssuspend(this), commandnsunsuspend(this) { this->SetAuthor("Anope"); @@ -241,7 +241,7 @@ class NSSuspend : public Module na->nc->UnsetFlag(NI_SUSPENDED); na->nc->Shrink("ns_suspend_expire"); - Log(LOG_NORMAL, "expire", findbot(Config->NickServ)) << "Expiring suspend for " << na->nick; + Log(LOG_NORMAL, "expire", NickServ) << "Expiring suspend for " << na->nick; } } }; diff --git a/modules/commands/ns_update.cpp b/modules/commands/ns_update.cpp index 5ca8da26d..8f4812b9e 100644 --- a/modules/commands/ns_update.cpp +++ b/modules/commands/ns_update.cpp @@ -28,7 +28,7 @@ class CommandNSUpdate : public Command if (!u) return; - NickAlias *na = findnick(u->nick); + NickAlias *na = NickAlias::Find(u->nick); if (na && na->nc == source.GetAccount()) { diff --git a/modules/commands/os_akill.cpp b/modules/commands/os_akill.cpp index f09d1f87a..89b1d96ae 100644 --- a/modules/commands/os_akill.cpp +++ b/modules/commands/os_akill.cpp @@ -13,38 +13,38 @@ #include "module.h" -static service_reference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); +static ServiceReference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); class AkillDelCallback : public NumberList { CommandSource &source; - unsigned Deleted; + unsigned deleted; public: - AkillDelCallback(CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), source(_source), Deleted(0) + AkillDelCallback(CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), source(_source), deleted(0) { } ~AkillDelCallback() { - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on the AKILL list.")); - else if (Deleted == 1) + else if (deleted == 1) source.Reply(_("Deleted 1 entry from the AKILL list.")); else - source.Reply(_("Deleted %d entries from the AKILL list."), Deleted); + source.Reply(_("Deleted %d entries from the AKILL list."), deleted); } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number) + if (!number) return; - XLine *x = akills->GetEntry(Number - 1); + XLine *x = akills->GetEntry(number - 1); if (!x) return; - ++Deleted; + ++deleted; DoDel(source, x); } @@ -76,7 +76,7 @@ class CommandOSAKill : public Command sep.GetToken(mask); } - time_t expires = !expiry.empty() ? dotime(expiry) : Config->AutokillExpiry; + time_t expires = !expiry.empty() ? Anope::DoTime(expiry) : Config->AutokillExpiry; /* If the expiry given does not contain a final letter, it's in days, * said the doc. Ah well. */ @@ -127,7 +127,7 @@ class CommandOSAKill : public Command return; } - service_reference<RegexProvider> provider("Regex", Config->RegexEngine); + ServiceReference<RegexProvider> provider("Regex", Config->RegexEngine); if (!provider) { source.Reply(_("Unable to find regex engine %s"), Config->RegexEngine.c_str()); @@ -146,7 +146,7 @@ class CommandOSAKill : public Command } } - User *targ = finduser(mask); + User *targ = User::Find(mask, true); if (targ) mask = "*@" + targ->host; @@ -160,7 +160,7 @@ class CommandOSAKill : public Command XLine *x = new XLine(mask, source.GetNick(), expires, reason); if (Config->AkillIds) - x->UID = XLineManager::GenerateUID(); + x->id = XLineManager::GenerateUID(); unsigned int affected = 0; for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) @@ -172,7 +172,7 @@ class CommandOSAKill : public Command { source.Reply(USERHOST_MASK_TOO_WIDE, mask.c_str()); Log(LOG_ADMIN, source, this) << "tried to akill " << percent << "% of the network (" << affected << " users)"; - x->destroy(); + x->Destroy(); return; } @@ -180,7 +180,7 @@ class CommandOSAKill : public Command FOREACH_RESULT(I_OnAddXLine, OnAddXLine(source, x, akills)); if (MOD_RESULT == EVENT_STOP) { - x->destroy(); + x->Destroy(); return; } @@ -190,8 +190,8 @@ class CommandOSAKill : public Command source.Reply(_("\002%s\002 added to the AKILL list."), mask.c_str()); - Log(LOG_ADMIN, source, this) << "on " << mask << " (" << x->Reason << ") expires in " << (expires ? duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; - if (readonly) + Log(LOG_ADMIN, source, this) << "on " << mask << " (" << x->reason << ") expires in " << (expires ? Anope::Duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); } @@ -230,14 +230,14 @@ class CommandOSAKill : public Command { FOREACH_MOD(I_OnDelXLine, OnDelXLine(source, x, akills)); - source.Reply(_("\002%s\002 deleted from the AKILL list."), x->Mask.c_str()); + source.Reply(_("\002%s\002 deleted from the AKILL list."), x->mask.c_str()); AkillDelCallback::DoDel(source, x); } while ((x = akills->HasEntry(mask))); } - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); return; @@ -269,12 +269,12 @@ class CommandOSAKill : public Command ListFormatter::ListEntry entry; entry["Number"] = stringify(number); - entry["Mask"] = x->Mask; - entry["Creator"] = x->By; - entry["Created"] = do_strftime(x->Created, NULL, true); - entry["Expires"] = expire_left(NULL, x->Expires); - entry["Reason"] = x->Reason; - this->list.addEntry(entry); + entry["Mask"] = x->mask; + entry["Creator"] = x->by; + entry["Created"] = Anope::strftime(x->created, NULL, true); + entry["Expires"] = Anope::Expires(x->expires); + entry["Reason"] = x->reason; + this->list.AddEntry(entry); } } nl_list(list, mask); @@ -286,21 +286,21 @@ class CommandOSAKill : public Command { const XLine *x = akills->GetEntry(i); - if (mask.empty() || mask.equals_ci(x->Mask) || mask == x->UID || Anope::Match(x->Mask, mask, false, true)) + if (mask.empty() || mask.equals_ci(x->mask) || mask == x->id || Anope::Match(x->mask, mask, false, true)) { ListFormatter::ListEntry entry; entry["Number"] = stringify(i + 1); - entry["Mask"] = x->Mask; - entry["Creator"] = x->By; - entry["Created"] = do_strftime(x->Created, NULL, true); - entry["Expires"] = expire_left(source.nc, x->Expires); - entry["Reason"] = x->Reason; - list.addEntry(entry); + entry["Mask"] = x->mask; + entry["Creator"] = x->by; + entry["Created"] = Anope::strftime(x->created, NULL, true); + entry["Expires"] = Anope::Expires(x->expires, source.nc); + entry["Reason"] = x->reason; + list.AddEntry(entry); } } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on the AKILL list.")); else { @@ -325,7 +325,7 @@ class CommandOSAKill : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Reason"); this->ProcessList(source, params, list); } @@ -339,7 +339,7 @@ class CommandOSAKill : public Command } ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Creator").addColumn("Created").addColumn("Expires").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Creator").AddColumn("Created").AddColumn("Expires").AddColumn("Reason"); this->ProcessList(source, params, list); } diff --git a/modules/commands/os_chankill.cpp b/modules/commands/os_chankill.cpp index 456525a46..c1d71831b 100644 --- a/modules/commands/os_chankill.cpp +++ b/modules/commands/os_chankill.cpp @@ -13,7 +13,7 @@ #include "module.h" -static service_reference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); +static ServiceReference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); class CommandOSChanKill : public Command { @@ -42,7 +42,7 @@ class CommandOSChanKill : public Command last_param = 2; } - expires = !expiry.empty() ? dotime(expiry) : Config->ChankillExpiry; + expires = !expiry.empty() ? Anope::DoTime(expiry) : Config->ChankillExpiry; if (!expiry.empty() && isdigit(expiry[expiry.length() - 1])) expires *= 86400; if (expires && expires < 60) @@ -70,7 +70,7 @@ class CommandOSChanKill : public Command else realreason = reason; - if ((c = findchan(channel))) + if ((c = Channel::Find(channel))) { for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ) { diff --git a/modules/commands/os_config.cpp b/modules/commands/os_config.cpp index 11437a087..61cda44c0 100644 --- a/modules/commands/os_config.cpp +++ b/modules/commands/os_config.cpp @@ -117,7 +117,7 @@ class CommandOSConfig : public Command } case DT_TIME: { - time_t time = dotime(vi.GetValue()); + time_t time = Anope::DoTime(vi.GetValue()); ValueContainerTime *vci = anope_dynamic_static_cast<ValueContainerTime *>(v->val); vci->Set(&time, sizeof(time_t)); break; @@ -169,7 +169,7 @@ class CommandOSConfig : public Command continue; ListFormatter lflist; - lflist.addColumn("Name").addColumn("Value"); + lflist.AddColumn("Name").AddColumn("Value"); for (unsigned i = 0; i < list.size(); ++i) { const Anope::string &first = list[i].first, second = list[i].second; @@ -177,7 +177,7 @@ class CommandOSConfig : public Command ListFormatter::ListEntry entry; entry["Name"] = first; entry["Value"] = second; - lflist.addEntry(entry); + lflist.AddEntry(entry); } std::vector<Anope::string> replies; diff --git a/modules/commands/os_defcon.cpp b/modules/commands/os_defcon.cpp index ad08ba77c..1457a57dc 100644 --- a/modules/commands/os_defcon.cpp +++ b/modules/commands/os_defcon.cpp @@ -34,8 +34,8 @@ bool DefConModesSet = false; struct DefconConfig { std::vector<std::bitset<32> > DefCon; - Flags<ChannelModeName, CMODE_END * 2> DefConModesOn; - Flags<ChannelModeName, CMODE_END * 2> DefConModesOff; + Flags<ChannelModeName> DefConModesOn; + Flags<ChannelModeName> DefConModesOff; std::map<ChannelModeName, Anope::string> DefConModesOnParams; int defaultlevel, sessionlimit; @@ -117,17 +117,17 @@ class DefConTimeout : public CallBack { DConfig.defaultlevel = level; FOREACH_MOD(I_OnDefconLevel, OnDefconLevel(level)); - Log(findbot(Config->OperServ), "operserv/defcon") << "Defcon level timeout, returning to level " << level; + Log(OperServ, "operserv/defcon") << "Defcon level timeout, returning to level " << level; if (DConfig.globalondefcon) { if (!DConfig.offmessage.empty()) - global->SendGlobal(findbot(Config->Global), "", DConfig.offmessage); + GlobalService->SendGlobal(Global, "", DConfig.offmessage); else - global->SendGlobal(findbot(Config->Global), "", Anope::printf(translate(_("The Defcon Level is now at Level: \002%d\002")), DConfig.defaultlevel)); + GlobalService->SendGlobal(Global, "", Anope::printf(Language::Translate(_("The Defcon Level is now at Level: \002%d\002")), DConfig.defaultlevel)); if (!DConfig.message.empty()) - global->SendGlobal(findbot(Config->Global), "", DConfig.message); + GlobalService->SendGlobal(Global, "", DConfig.message); } runDefCon(); @@ -215,12 +215,12 @@ class CommandOSDefcon : public Command if (DConfig.globalondefcon) { if (DConfig.defaultlevel == 5 && !DConfig.offmessage.empty()) - global->SendGlobal(findbot(Config->Global), "", DConfig.offmessage); + GlobalService->SendGlobal(Global, "", DConfig.offmessage); else if (DConfig.defaultlevel != 5) { - global->SendGlobal(findbot(Config->Global), "", Anope::printf(_("The Defcon level is now at: \002%d\002"), DConfig.defaultlevel)); + GlobalService->SendGlobal(Global, "", Anope::printf(_("The Defcon level is now at: \002%d\002"), DConfig.defaultlevel)); if (!DConfig.message.empty()) - global->SendGlobal(findbot(Config->Global), "", DConfig.message); + GlobalService->SendGlobal(Global, "", DConfig.message); } } @@ -242,8 +242,8 @@ class CommandOSDefcon : public Command class OSDefcon : public Module { - service_reference<SessionService> session_service; - service_reference<XLineManager> akills; + ServiceReference<SessionService> session_service; + ServiceReference<XLineManager> akills; CommandOSDefcon commandosdefcon; void ParseModeString() @@ -280,17 +280,17 @@ class OSDefcon : public Module if ((cm = ModeManager::FindChannelModeByChar(mode))) { - if (cm->Type == MODE_STATUS || cm->Type == MODE_LIST || !cm->CanSet(NULL)) + if (cm->type == MODE_STATUS || cm->type == MODE_LIST || !cm->CanSet(NULL)) { Log(this) << "DefConChanModes mode character '" << mode << "' cannot be locked"; continue; } else if (add) { - DConfig.DefConModesOn.SetFlag(cm->Name); - DConfig.DefConModesOff.UnsetFlag(cm->Name); + DConfig.DefConModesOn.SetFlag(cm->name); + DConfig.DefConModesOff.UnsetFlag(cm->name); - if (cm->Type == MODE_PARAM) + if (cm->type == MODE_PARAM) { cmp = anope_dynamic_static_cast<ChannelModeParam *>(cm); @@ -303,21 +303,21 @@ class OSDefcon : public Module if (!cmp->IsValid(param)) continue; - DConfig.SetDefConParam(cmp->Name, param); + DConfig.SetDefConParam(cmp->name, param); } } - else if (DConfig.DefConModesOn.HasFlag(cm->Name)) + else if (DConfig.DefConModesOn.HasFlag(cm->name)) { - DConfig.DefConModesOn.UnsetFlag(cm->Name); + DConfig.DefConModesOn.UnsetFlag(cm->name); - if (cm->Type == MODE_PARAM) - DConfig.UnsetDefConParam(cm->Name); + if (cm->type == MODE_PARAM) + DConfig.UnsetDefConParam(cm->name); } } } /* We can't mlock +L if +l is not mlocked as well. */ - if ((cm = ModeManager::FindChannelModeByName(CMODE_REDIRECT)) && DConfig.DefConModesOn.HasFlag(cm->Name) && !DConfig.DefConModesOn.HasFlag(CMODE_LIMIT)) + if ((cm = ModeManager::FindChannelModeByName(CMODE_REDIRECT)) && DConfig.DefConModesOn.HasFlag(cm->name) && !DConfig.DefConModesOn.HasFlag(CMODE_LIMIT)) { DConfig.DefConModesOn.UnsetFlag(CMODE_REDIRECT); @@ -356,9 +356,9 @@ class OSDefcon : public Module dconfig.defcons[1] = config.ReadValue("defcon", "level1", 0); dconfig.sessionlimit = config.ReadInteger("defcon", "sessionlimit", 0, 0); dconfig.akillreason = config.ReadValue("defcon", "akillreason", 0); - dconfig.akillexpire = dotime(config.ReadValue("defcon", "akillexpire", 0)); + dconfig.akillexpire = Anope::DoTime(config.ReadValue("defcon", "akillexpire", 0)); dconfig.chanmodes = config.ReadValue("defcon", "chanmodes", 0); - dconfig.timeout = dotime(config.ReadValue("defcon", "timeout", 0)); + dconfig.timeout = Anope::DoTime(config.ReadValue("defcon", "timeout", 0)); dconfig.globalondefcon = config.ReadFlag("defcon", "globalondefcon", 0); dconfig.message = config.ReadValue("defcon", "message", 0); dconfig.offmessage = config.ReadValue("defcon", "offmessage", 0); @@ -414,9 +414,9 @@ class OSDefcon : public Module { if (DConfig.Check(DEFCON_AKILL_NEW_CLIENTS) && akills) { - Log(findbot(Config->OperServ), "operserv/defcon") << "DEFCON: adding akill for *@" << u->host; + Log(OperServ, "operserv/defcon") << "DEFCON: adding akill for *@" << u->host; XLine *x = new XLine("*@" + u->host, Config->OperServ, Anope::CurTime + DConfig.akillexpire, DConfig.akillreason, XLineManager::GenerateUID()); - x->By = Config->OperServ; + x->by = Config->OperServ; akills->AddXLine(x); } @@ -435,7 +435,7 @@ class OSDefcon : public Module if (DConfig.Check(DEFCON_FORCE_CHAN_MODES) && cm && DConfig.DefConModesOff.HasFlag(Name)) { - c->RemoveMode(findbot(Config->OperServ), Name, param); + c->RemoveMode(OperServ, Name, param); return EVENT_STOP; } @@ -452,9 +452,9 @@ class OSDefcon : public Module Anope::string param; if (DConfig.GetDefConParam(Name, param)) - c->SetMode(findbot(Config->OperServ), Name, param); + c->SetMode(OperServ, Name, param); else - c->SetMode(findbot(Config->OperServ), Name); + c->SetMode(OperServ, Name); return EVENT_STOP; @@ -501,16 +501,16 @@ class OSDefcon : public Module return EVENT_CONTINUE; } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { if (exempt || !u || !u->server->IsSynced() || u->server->IsULined()) return; if (DConfig.Check(DEFCON_AKILL_NEW_CLIENTS) && akills) { - Log(findbot(Config->OperServ), "operserv/defcon") << "DEFCON: adding akill for *@" << u->host; + Log(OperServ, "operserv/defcon") << "DEFCON: adding akill for *@" << u->host; XLine x("*@" + u->host, Config->OperServ, Anope::CurTime + DConfig.akillexpire, DConfig.akillreason, XLineManager::GenerateUID()); - x.By = Config->OperServ; + x.by = Config->OperServ; akills->Send(NULL, &x); } if (DConfig.Check(DEFCON_NO_NEW_CLIENTS) || DConfig.Check(DEFCON_AKILL_NEW_CLIENTS)) @@ -525,7 +525,7 @@ class OSDefcon : public Module return; } - if (!DConfig.sessionlimit || !session_service) + if (DConfig.sessionlimit <= 0 || !session_service) return; Session *session; @@ -541,19 +541,19 @@ class OSDefcon : public Module if (DConfig.Check(DEFCON_REDUCE_SESSION) && !exception) { - if (session && session->count > DConfig.sessionlimit) + if (session && session->count > static_cast<unsigned>(DConfig.sessionlimit)) { if (!Config->SessionLimitExceeded.empty()) - ircdproto->SendMessage(findbot(Config->OperServ), u->nick, Config->SessionLimitExceeded.c_str(), u->host.c_str()); + IRCD->SendMessage(OperServ, u->nick, Config->SessionLimitExceeded.c_str(), u->host.c_str()); if (!Config->SessionLimitDetailsLoc.empty()) - ircdproto->SendMessage(findbot(Config->OperServ), u->nick, "%s", Config->SessionLimitDetailsLoc.c_str()); + IRCD->SendMessage(OperServ, u->nick, "%s", Config->SessionLimitDetailsLoc.c_str()); ++session->hits; if (akills && Config->MaxSessionKill && session->hits >= Config->MaxSessionKill) { XLine x("*@" + u->host, Config->OperServ, Anope::CurTime + Config->SessionAutoKillExpiry, "Defcon session limit exceeded", XLineManager::GenerateUID()); akills->Send(NULL, &x); - Log(findbot(Config->OperServ), "akill/defcon") << "[DEFCON] Added a temporary AKILL for \2*@" << u->host << "\2 due to excessive connections"; + Log(OperServ, "akill/defcon") << "[DEFCON] Added a temporary AKILL for \2*@" << u->host << "\2 due to excessive connections"; } else { @@ -566,14 +566,14 @@ class OSDefcon : public Module void OnChannelModeAdd(ChannelMode *cm) anope_override { - if (DConfig.chanmodes.find(cm->ModeChar) != Anope::string::npos) + if (DConfig.chanmodes.find(cm->mchar) != Anope::string::npos) this->ParseModeString(); } void OnChannelCreate(Channel *c) anope_override { if (DConfig.Check(DEFCON_FORCE_CHAN_MODES)) - c->SetModes(findbot(Config->OperServ), false, "%s", DConfig.chanmodes.c_str()); + c->SetModes(OperServ, false, "%s", DConfig.chanmodes.c_str()); } }; @@ -612,10 +612,10 @@ void runDefCon() { if (DConfig.chanmodes[0] == '+' || DConfig.chanmodes[0] == '-') { - Log(findbot(Config->OperServ), "operserv/defcon") << "DEFCON: setting " << DConfig.chanmodes << " on all channels"; + Log(OperServ, "operserv/defcon") << "DEFCON: setting " << DConfig.chanmodes << " on all channels"; DefConModesSet = true; for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it) - it->second->SetModes(findbot(Config->OperServ), false, "%s", DConfig.chanmodes.c_str()); + it->second->SetModes(OperServ, false, "%s", DConfig.chanmodes.c_str()); } } } @@ -629,9 +629,9 @@ void runDefCon() Anope::string newmodes = defconReverseModes(DConfig.chanmodes); if (!newmodes.empty()) { - Log(findbot(Config->OperServ), "operserv/defcon") << "DEFCON: setting " << newmodes << " on all channels"; + Log(OperServ, "operserv/defcon") << "DEFCON: setting " << newmodes << " on all channels"; for (channel_map::const_iterator it = ChannelList.begin(), it_end = ChannelList.end(); it != it_end; ++it) - it->second->SetModes(findbot(Config->OperServ), false, "%s", newmodes.c_str()); + it->second->SetModes(OperServ, false, "%s", newmodes.c_str()); } } } diff --git a/modules/commands/os_dns.cpp b/modules/commands/os_dns.cpp index e304050b3..769a42f26 100644 --- a/modules/commands/os_dns.cpp +++ b/modules/commands/os_dns.cpp @@ -44,12 +44,12 @@ class DNSServer : public Serializable void Pool(bool p) { pooled = p; - if (DNSEngine) - DNSEngine->UpdateSerial(); + if (DNS::Engine) + DNS::Engine->UpdateSerial(); } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; @@ -62,7 +62,7 @@ class DNSServer : public Serializable return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { DNSServer *req; @@ -104,7 +104,7 @@ class CommandOSDNS : public Command } ListFormatter lf; - lf.addColumn("Server").addColumn("IP").addColumn("Limit").addColumn("State"); + lf.AddColumn("Server").AddColumn("IP").AddColumn("Limit").AddColumn("State"); for (unsigned i = 0; i < dns_servers.size(); ++i) { DNSServer *s = dns_servers[i]; @@ -129,7 +129,7 @@ class CommandOSDNS : public Command else entry["State"] = "Unpooled"; - lf.addEntry(entry); + lf.AddEntry(entry); } std::vector<Anope::string> replies; @@ -221,7 +221,7 @@ class CommandOSDNS : public Command Log(LOG_ADMIN, source, this) << "to add IP " << params[2] << " to " << s->GetName(); if (s->Pooled()) - DNSEngine->UpdateSerial(); + DNS::Engine->UpdateSerial(); } void DelIP(CommandSource &source, const std::vector<Anope::string> ¶ms) @@ -248,7 +248,7 @@ class CommandOSDNS : public Command } if (s->Pooled()) - DNSEngine->UpdateSerial(); + DNS::Engine->UpdateSerial(); return; } @@ -388,7 +388,7 @@ class CommandOSDNS : public Command class ModuleDNS : public Module { - SerializeType dns_type; + Serialize::Type dns_type; CommandOSDNS commandosdns; time_t ttl; @@ -400,7 +400,7 @@ class ModuleDNS : public Module public: ModuleDNS(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, SUPPORTED), - dns_type("DNSServer", DNSServer::unserialize), commandosdns(this) + dns_type("DNSServer", DNSServer::Unserialize), commandosdns(this) { this->SetAuthor("Anope"); @@ -414,10 +414,10 @@ class ModuleDNS : public Module { ConfigReader config; - this->ttl = dotime(config.ReadValue("os_dns", "ttl", 0)); + this->ttl = Anope::DoTime(config.ReadValue("os_dns", "ttl", 0)); this->user_drop_mark = config.ReadInteger("os_dns", "user_drop_mark", 0, false); - this->user_drop_time = dotime(config.ReadValue("os_dns", "user_drop_time", 0, false)); - this->user_drop_readd_time = dotime(config.ReadValue("os_dns", "user_drop_readd_time", 0, false)); + this->user_drop_time = Anope::DoTime(config.ReadValue("os_dns", "user_drop_time", 0, false)); + this->user_drop_readd_time = Anope::DoTime(config.ReadValue("os_dns", "user_drop_readd_time", 0, false)); this->remove_split_servers = config.ReadFlag("os_dns", "remove_split_servers", 0); this->readd_connected_servers = config.ReadFlag("os_dns", "readd_connected_servers", 0); } @@ -427,7 +427,7 @@ class ModuleDNS : public Module if (this->readd_connected_servers) { DNSServer *dns = DNSServer::Find(s->GetName()); - if (dns && !dns->Pooled() && !dns->GetIPs().empty() && dns->GetLimit() < s->Users) + if (dns && !dns->Pooled() && !dns->GetIPs().empty() && dns->GetLimit() < s->users) { dns->Pool(true); Log(this) << "Pooling server " << s->GetName(); @@ -446,15 +446,15 @@ class ModuleDNS : public Module } } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { if (u && u->server) { DNSServer *s = DNSServer::Find(u->server->GetName()); /* Check for user limit reached */ - if (s && s->GetLimit() && s->Pooled() && u->server->Users >= s->GetLimit()) + if (s && s->GetLimit() && s->Pooled() && u->server->users >= s->GetLimit()) { - Log(this) << "Depooling full server " << s->GetName() << ": " << u->server->Users << " users"; + Log(this) << "Depooling full server " << s->GetName() << ": " << u->server->users << " users"; s->Pool(false); } } @@ -469,7 +469,7 @@ class ModuleDNS : public Module return; /* Check for dropping under userlimit */ - if (s->GetLimit() && !s->Pooled() && s->GetLimit() > u->server->Users) + if (s->GetLimit() && !s->Pooled() && s->GetLimit() > u->server->users) { Log(this) << "Pooling server " << s->GetName(); s->Pool(true); @@ -505,13 +505,13 @@ class ModuleDNS : public Module } } - void OnDnsRequest(DNSPacket &req, DNSPacket *packet) anope_override + void OnDnsRequest(DNS::Packet &req, DNS::Packet *packet) anope_override { if (req.questions.empty()) return; /* Currently we reply to any QR for A/AAAA */ - const Question& q = req.questions[0]; - if (q.type != DNS_QUERY_A && q.type != DNS_QUERY_AAAA && q.type != DNS_QUERY_AXFR) + const DNS::Question& q = req.questions[0]; + if (q.type != DNS::QUERY_A && q.type != DNS::QUERY_AAAA && q.type != DNS::QUERY_AXFR) return; for (unsigned i = 0; i < dns_servers.size(); ++i) @@ -522,11 +522,11 @@ class ModuleDNS : public Module for (unsigned j = 0; j < s->GetIPs().size(); ++j) { - QueryType q_type = s->GetIPs()[j].find(':') != Anope::string::npos ? DNS_QUERY_AAAA : DNS_QUERY_A; + DNS::QueryType q_type = s->GetIPs()[j].find(':') != Anope::string::npos ? DNS::QUERY_AAAA : DNS::QUERY_A; - if (q.type == DNS_QUERY_AXFR || q_type == q.type) + if (q.type == DNS::QUERY_AXFR || q_type == q.type) { - ResourceRecord rr(q.name, q_type); + DNS::ResourceRecord rr(q.name, q_type); rr.ttl = this->ttl; rr.rdata = s->GetIPs()[j]; packet->answers.push_back(rr); @@ -550,11 +550,11 @@ class ModuleDNS : public Module for (unsigned j = 0; j < s->GetIPs().size(); ++j) { - QueryType q_type = s->GetIPs()[j].find(':') != Anope::string::npos ? DNS_QUERY_AAAA : DNS_QUERY_A; + DNS::QueryType q_type = s->GetIPs()[j].find(':') != Anope::string::npos ? DNS::QUERY_AAAA : DNS::QUERY_A; - if (q.type == DNS_QUERY_AXFR || q_type == q.type) + if (q.type == DNS::QUERY_AXFR || q_type == q.type) { - ResourceRecord rr(q.name, q_type); + DNS::ResourceRecord rr(q.name, q_type); rr.ttl = this->ttl; rr.rdata = s->GetIPs()[j]; packet->answers.push_back(rr); diff --git a/modules/commands/os_forbid.cpp b/modules/commands/os_forbid.cpp index 31ca94265..08710b223 100644 --- a/modules/commands/os_forbid.cpp +++ b/modules/commands/os_forbid.cpp @@ -31,7 +31,7 @@ class MyForbidService : public ForbidService std::vector<ForbidData *>::iterator it = std::find(this->forbidData.begin(), this->forbidData.end(), d); if (it != this->forbidData.end()) this->forbidData.erase(it); - d->destroy(); + d->Destroy(); } ForbidData *FindForbid(const Anope::string &mask, ForbidType ftype) anope_override @@ -65,7 +65,7 @@ class MyForbidService : public ForbidService Log(LOG_NORMAL, "expire/forbid") << "Expiring forbid for " << d->mask << " type " << ftype; this->forbidData.erase(this->forbidData.begin() + i - 1); - d->destroy(); + d->Destroy(); } } @@ -75,7 +75,7 @@ class MyForbidService : public ForbidService class CommandOSForbid : public Command { - service_reference<ForbidService> fs; + ServiceReference<ForbidService> fs; public: CommandOSForbid(Module *creator) : Command(creator, "operserv/forbid", 1, 5), fs("ForbidService", "forbid") { @@ -122,12 +122,12 @@ class CommandOSForbid : public Command if (!expiry.empty()) { - expiryt = dotime(expiry); + expiryt = Anope::DoTime(expiry); if (expiryt) expiryt += Anope::CurTime; } - NickAlias *target = findnick(entry); + NickAlias *target = NickAlias::Find(entry); if (target != NULL && Config->NSSecureAdmins && target->nc->IsServicesOper()) { source.Reply(ACCESS_DENIED); @@ -152,7 +152,7 @@ class CommandOSForbid : public Command this->fs->AddForbid(d); Log(LOG_ADMIN, source, this) << "to add a forbid on " << entry << " of type " << subcommand; - source.Reply(_("Added a%s forbid on %s to expire on %s"), ftype == FT_CHAN ? "n" : "", entry.c_str(), d->expires ? do_strftime(d->expires).c_str() : "never"); + source.Reply(_("Added a%s forbid on %s to expire on %s"), ftype == FT_CHAN ? "n" : "", entry.c_str(), d->expires ? Anope::strftime(d->expires).c_str() : "never"); } else if (command.equals_ci("DEL") && params.size() > 2 && ftype != FT_NONE) { @@ -176,7 +176,7 @@ class CommandOSForbid : public Command else { ListFormatter list; - list.addColumn("Mask").addColumn("Type").addColumn("Reason"); + list.AddColumn("Mask").AddColumn("Type").AddColumn("Reason"); for (unsigned i = 0; i < forbids.size(); ++i) { @@ -196,9 +196,9 @@ class CommandOSForbid : public Command entry["Mask"] = d->mask; entry["Type"] = stype; entry["Creator"] = d->creator; - entry["Expires"] = d->expires ? do_strftime(d->expires).c_str() : "never"; + entry["Expires"] = d->expires ? Anope::strftime(d->expires).c_str() : "never"; entry["Reason"] = d->reason; - list.addEntry(entry); + list.AddEntry(entry); } source.Reply(_("Forbid list:")); @@ -234,13 +234,13 @@ class CommandOSForbid : public Command class OSForbid : public Module { - SerializeType forbiddata_type; + Serialize::Type forbiddata_type; MyForbidService forbidService; CommandOSForbid commandosforbid; public: OSForbid(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - forbiddata_type("ForbidData", ForbidData::unserialize), forbidService(this), commandosforbid(this) + forbiddata_type("ForbidData", ForbidData::Unserialize), forbidService(this), commandosforbid(this) { this->SetAuthor("Anope"); @@ -248,7 +248,7 @@ class OSForbid : public Module ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { if (!u || exempt) return; @@ -264,13 +264,12 @@ class OSForbid : public Module ForbidData *d = this->forbidService.FindForbid(u->nick, FT_NICK); if (d != NULL) { - const BotInfo *bi = findbot(Config->OperServ); - if (bi) + if (OperServ) { if (d->reason.empty()) - u->SendMessage(bi, _("This nickname has been forbidden.")); + u->SendMessage(OperServ, _("This nickname has been forbidden.")); else - u->SendMessage(bi, _("This nickname has been forbidden: %s"), d->reason.c_str()); + u->SendMessage(OperServ, _("This nickname has been forbidden: %s"), d->reason.c_str()); } u->Collide(NULL); } @@ -278,17 +277,16 @@ class OSForbid : public Module void OnJoinChannel(User *u, Channel *c) anope_override { - if (u->HasMode(UMODE_OPER)) + if (u->HasMode(UMODE_OPER) || !OperServ) return; - BotInfo *bi = findbot(Config->OperServ); ForbidData *d = this->forbidService.FindForbid(c->name, FT_CHAN); - if (bi != NULL && d != NULL) + if (d != NULL) { - if (ircdproto->CanSQLineChannel) + if (IRCD->CanSQLineChannel) { - XLine x(c->name, bi->nick, Anope::CurTime + Config->CSInhabit, d->reason); - ircdproto->SendSQLine(NULL, &x); + XLine x(c->name, OperServ->nick, Anope::CurTime + Config->CSInhabit, d->reason); + IRCD->SendSQLine(NULL, &x); } else if (!c->HasFlag(CH_INHABIT)) { @@ -303,9 +301,9 @@ class OSForbid : public Module } if (d->reason.empty()) - c->Kick(bi, u, _("This channel has been forbidden.")); + c->Kick(OperServ, u, _("This channel has been forbidden.")); else - c->Kick(bi, u, _("This channel has been forbidden: %s"), d->reason.c_str()); + c->Kick(OperServ, u, _("This channel has been forbidden: %s"), d->reason.c_str()); } } diff --git a/modules/commands/os_forbid.h b/modules/commands/os_forbid.h index f79b63616..1fce928db 100644 --- a/modules/commands/os_forbid.h +++ b/modules/commands/os_forbid.h @@ -19,8 +19,8 @@ struct ForbidData : Serializable ForbidType type; ForbidData() : Serializable("ForbidData") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; class ForbidService : public Service @@ -37,9 +37,9 @@ class ForbidService : public Service virtual const std::vector<ForbidData *> &GetForbids() = 0; }; -static service_reference<ForbidService> forbid_service("ForbidService", "forbid"); +static ServiceReference<ForbidService> forbid_service("ForbidService", "forbid"); -Serialize::Data ForbidData::serialize() const +Serialize::Data ForbidData::Serialize() const { Serialize::Data data; @@ -53,7 +53,7 @@ Serialize::Data ForbidData::serialize() const return data; } -Serializable* ForbidData::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* ForbidData::Unserialize(Serializable *obj, Serialize::Data &data) { if (!forbid_service) return NULL; diff --git a/modules/commands/os_ignore.cpp b/modules/commands/os_ignore.cpp index 2377c28be..f959e7ebc 100644 --- a/modules/commands/os_ignore.cpp +++ b/modules/commands/os_ignore.cpp @@ -25,7 +25,7 @@ class OSIgnoreService : public IgnoreService Anope::string realmask = mask; size_t user, host; - User *u = finduser(mask); + User *u = User::Find(mask, true); if (u) realmask = "*!*@" + u->host; /* Determine whether we get a nick or a mask. */ @@ -86,7 +86,7 @@ class OSIgnoreService : public IgnoreService IgnoreData *Find(const Anope::string &mask) anope_override { - User *u = finduser(mask); + User *u = User::Find(mask, true); std::list<IgnoreData>::iterator ign = this->ignores.begin(), ign_end = this->ignores.end(); if (u) @@ -162,7 +162,7 @@ class CommandOSIgnore : public Command } else { - time_t t = dotime(time); + time_t t = Anope::DoTime(time); if (t <= -1) { @@ -205,7 +205,7 @@ class CommandOSIgnore : public Command else { ListFormatter list; - list.addColumn("Mask").addColumn("Creator").addColumn("Reason").addColumn("Expires"); + list.AddColumn("Mask").AddColumn("Creator").AddColumn("Reason").AddColumn("Expires"); for (std::list<IgnoreData>::const_iterator ign = ignores.begin(), ign_end = ignores.end(); ign != ign_end; ++ign) { const IgnoreData &ignore = *ign; @@ -214,8 +214,8 @@ class CommandOSIgnore : public Command entry["Mask"] = ignore.mask; entry["Creator"] = ignore.creator; entry["Reason"] = ignore.reason; - entry["Expires"] = do_strftime(ignore.time); - list.addEntry(entry); + entry["Expires"] = Anope::strftime(ignore.time); + list.AddEntry(entry); } source.Reply(_("Services ignore list:")); @@ -309,17 +309,16 @@ class CommandOSIgnore : public Command class OSIgnore : public Module { - SerializeType ignoredata_type; + Serialize::Type ignoredata_type; OSIgnoreService osignoreservice; CommandOSIgnore commandosignore; public: OSIgnore(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - ignoredata_type("IgnoreData", IgnoreData::unserialize), osignoreservice(this), commandosignore(this) + ignoredata_type("IgnoreData", IgnoreData::Unserialize), osignoreservice(this), commandosignore(this) { this->SetAuthor("Anope"); - Implementation i[] = { I_OnBotPrivmsg }; ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); } diff --git a/modules/commands/os_ignore.h b/modules/commands/os_ignore.h index 38042a72d..003d88b5b 100644 --- a/modules/commands/os_ignore.h +++ b/modules/commands/os_ignore.h @@ -18,8 +18,8 @@ struct IgnoreData : Serializable time_t time; /* When do we stop ignoring them? */ IgnoreData() : Serializable("IgnoreData") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; class IgnoreService : public Service @@ -41,9 +41,9 @@ class IgnoreService : public Service inline std::list<IgnoreData> &GetIgnores() { return this->ignores; } }; -static service_reference<IgnoreService> ignore_service("IgnoreService", "ignore"); +static ServiceReference<IgnoreService> ignore_service("IgnoreService", "ignore"); -Serialize::Data IgnoreData::serialize() const +Serialize::Data IgnoreData::Serialize() const { Serialize::Data data; @@ -55,7 +55,7 @@ Serialize::Data IgnoreData::serialize() const return data; } -Serializable* IgnoreData::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* IgnoreData::Unserialize(Serializable *obj, Serialize::Data &data) { if (!ignore_service) return NULL; diff --git a/modules/commands/os_jupe.cpp b/modules/commands/os_jupe.cpp index cfe917c13..49095129c 100644 --- a/modules/commands/os_jupe.cpp +++ b/modules/commands/os_jupe.cpp @@ -28,7 +28,7 @@ class CommandOSJupe : public Command const Anope::string &reason = params.size() > 1 ? params[1] : ""; Server *server = Server::Find(jserver); - if (!IsValidHost(jserver) || jserver.find('.') == Anope::string::npos) + if (!IRCD->IsHostValid(jserver) || jserver.find('.') == Anope::string::npos) source.Reply(_("Please use a valid server name when juping")); else if (server && (server == Me || server == Me->GetLinks().front())) source.Reply(_("You can not jupe your services server or your uplink server.")); @@ -36,9 +36,9 @@ class CommandOSJupe : public Command { Anope::string rbuf = "Juped by " + source.GetNick() + (!reason.empty() ? ": " + reason : ""); if (server) - ircdproto->SendSquit(server, rbuf); - Server *juped_server = new Server(Me, jserver, 1, rbuf, ts6_sid_retrieve(), SERVER_JUPED); - ircdproto->SendServer(juped_server); + IRCD->SendSquit(server, rbuf); + Server *juped_server = new Server(Me, jserver, 1, rbuf, Servers::TS6_SID_Retrieve(), SERVER_JUPED); + IRCD->SendServer(juped_server); Log(LOG_ADMIN, source, this) << "on " << jserver << " (" << rbuf << ")"; } diff --git a/modules/commands/os_kick.cpp b/modules/commands/os_kick.cpp index 0a5165621..5f33a4bbc 100644 --- a/modules/commands/os_kick.cpp +++ b/modules/commands/os_kick.cpp @@ -30,7 +30,7 @@ class CommandOSKick : public Command Channel *c; User *u2; - if (!(c = findchan(chan))) + if (!(c = Channel::Find(chan))) { source.Reply(CHAN_X_NOT_IN_USE, chan.c_str()); return; @@ -40,7 +40,7 @@ class CommandOSKick : public Command source.Reply(_("Services is unable to change modes. Are your servers' U:lines configured correctly?")); return; } - else if (!(u2 = finduser(nick))) + else if (!(u2 = User::Find(nick, true))) { source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); return; diff --git a/modules/commands/os_kill.cpp b/modules/commands/os_kill.cpp index e7f78b1b5..83cd81f58 100644 --- a/modules/commands/os_kill.cpp +++ b/modules/commands/os_kill.cpp @@ -27,7 +27,7 @@ class CommandOSKill : public Command const Anope::string &nick = params[0]; Anope::string reason = params.size() > 1 ? params[1] : ""; - User *u2 = finduser(nick); + User *u2 = User::Find(nick, true); if (u2 == NULL) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); else if (u2->IsProtected() || u2->server == Me) diff --git a/modules/commands/os_list.cpp b/modules/commands/os_list.cpp index 0272742c1..dfb0c00c8 100644 --- a/modules/commands/os_list.cpp +++ b/modules/commands/os_list.cpp @@ -36,9 +36,9 @@ class CommandOSChanList : public Command } ListFormatter list; - list.addColumn("Name").addColumn("Users").addColumn("Modes").addColumn("Topic"); + list.AddColumn("Name").AddColumn("Users").AddColumn("Modes").AddColumn("Topic"); - if (!pattern.empty() && (u2 = finduser(pattern))) + if (!pattern.empty() && (u2 = User::Find(pattern, true))) { source.Reply(_("\002%s\002 channel list:"), u2->nick.c_str()); @@ -56,7 +56,7 @@ class CommandOSChanList : public Command entry["Users"] = stringify(cc->chan->users.size()); entry["Modes"] = cc->chan->GetModes(true, true); entry["Topic"] = cc->chan->topic; - list.addEntry(entry); + list.AddEntry(entry); } } else @@ -79,7 +79,7 @@ class CommandOSChanList : public Command entry["Users"] = stringify(c->users.size()); entry["Modes"] = c->GetModes(true, true); entry["Topic"] = c->topic; - list.addEntry(entry); + list.AddEntry(entry); } } @@ -130,9 +130,9 @@ class CommandOSUserList : public Command Modes.push_back(UMODE_INVIS); ListFormatter list; - list.addColumn("Name").addColumn("Mask"); + list.AddColumn("Name").AddColumn("Mask"); - if (!pattern.empty() && (c = findchan(pattern))) + if (!pattern.empty() && (c = Channel::Find(pattern))) { source.Reply(_("\002%s\002 users list:"), pattern.c_str()); @@ -148,7 +148,7 @@ class CommandOSUserList : public Command ListFormatter::ListEntry entry; entry["Name"] = uc->user->nick; entry["Mask"] = uc->user->GetIdent() + "@" + uc->user->GetDisplayedHost(); - list.addEntry(entry); + list.AddEntry(entry); } } else @@ -178,7 +178,7 @@ class CommandOSUserList : public Command ListFormatter::ListEntry entry; entry["Name"] = u2->nick; entry["Mask"] = u2->GetIdent() + "@" + u2->GetDisplayedHost(); - list.addEntry(entry); + list.AddEntry(entry); } } diff --git a/modules/commands/os_login.cpp b/modules/commands/os_login.cpp index 7b223eb1f..735562819 100644 --- a/modules/commands/os_login.cpp +++ b/modules/commands/os_login.cpp @@ -41,7 +41,7 @@ class CommandOSLogin : public Command else if (o->password != password) { source.Reply(PASSWORD_INCORRECT); - bad_password(u); + u->BadPassword(); } else { diff --git a/modules/commands/os_logsearch.cpp b/modules/commands/os_logsearch.cpp index 12431798c..7ad806330 100644 --- a/modules/commands/os_logsearch.cpp +++ b/modules/commands/os_logsearch.cpp @@ -23,7 +23,7 @@ class CommandOSLogSearch : public Command strftime(timestamp, sizeof(timestamp), "%Y%m%d", tm); - return log_dir + "/" + file + "." + timestamp; + return Anope::LogDir + "/" + file + "." + timestamp; } public: diff --git a/modules/commands/os_mode.cpp b/modules/commands/os_mode.cpp index 419fc8442..676ef7ea5 100644 --- a/modules/commands/os_mode.cpp +++ b/modules/commands/os_mode.cpp @@ -27,7 +27,7 @@ class CommandOSMode : public Command const Anope::string &target = params[0]; const Anope::string &modes = params[1]; - Channel *c = findchan(target); + Channel *c = Channel::Find(target); if (!c) source.Reply(CHAN_X_NOT_IN_USE, target.c_str()); else if (c->bouncy_modes) @@ -62,23 +62,23 @@ class CommandOSMode : public Command continue; Anope::string param, param_log; - if (cm->Type != MODE_REGULAR) + if (cm->type != MODE_REGULAR) { if (!sep.GetToken(param)) continue; param_log = param; - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { - User *targ = finduser(param); + User *targ = User::Find(param, true); if (targ == NULL || c->FindUser(targ) == NULL) continue; param = targ->GetUID(); } } - log_modes += cm->ModeChar; + log_modes += cm->mchar; if (!param.empty()) log_params += " " + param_log; @@ -117,7 +117,7 @@ class CommandOSUMode : public Command const Anope::string &target = params[0]; const Anope::string &modes = params[1]; - User *u2 = finduser(target); + User *u2 = User::Find(target, true); if (!u2) source.Reply(NICK_X_NOT_IN_USE, target.c_str()); else diff --git a/modules/commands/os_modinfo.cpp b/modules/commands/os_modinfo.cpp index 88748a106..15e2d73a2 100644 --- a/modules/commands/os_modinfo.cpp +++ b/modules/commands/os_modinfo.cpp @@ -29,12 +29,12 @@ class CommandOSModInfo : public Command Module *m = ModuleManager::FindModule(file); if (m) { - source.Reply(_("Module: \002%s\002 Version: \002%s\002 Author: \002%s\002 loaded: \002%s\002"), m->name.c_str(), !m->version.empty() ? m->version.c_str() : "?", !m->author.empty() ? m->author.c_str() : "?", do_strftime(m->created).c_str()); + source.Reply(_("Module: \002%s\002 Version: \002%s\002 Author: \002%s\002 loaded: \002%s\002"), m->name.c_str(), !m->version.empty() ? m->version.c_str() : "?", !m->author.empty() ? m->author.c_str() : "?", Anope::strftime(m->created).c_str()); std::vector<Anope::string> servicekeys = Service::GetServiceKeys("Command"); for (unsigned i = 0; i < servicekeys.size(); ++i) { - service_reference<Command> c("Command", servicekeys[i]); + ServiceReference<Command> c("Command", servicekeys[i]); if (!c || c->owner != m) continue; @@ -156,9 +156,11 @@ class CommandOSModList : public Command } } + Module *protocol = ModuleManager::FindFirstOf(PROTOCOL); + source.Reply(_("Current Module list:")); - for (std::list<Module *>::iterator it = Modules.begin(), it_end = Modules.end(); it != it_end; ++it) + for (std::list<Module *>::iterator it = ModuleManager::Modules.begin(), it_end = ModuleManager::Modules.end(); it != it_end; ++it) { Module *m = *it; @@ -179,6 +181,8 @@ class CommandOSModList : public Command } break; case PROTOCOL: + if (m != protocol) + break; if (showProto) { source.Reply(_("Module: \002%s\002 [%s] [%s]"), m->name.c_str(), m->version.c_str(), proto); diff --git a/modules/commands/os_module.cpp b/modules/commands/os_module.cpp index e7e0e2c16..75bc82af6 100644 --- a/modules/commands/os_module.cpp +++ b/modules/commands/os_module.cpp @@ -76,6 +76,13 @@ class CommandOSModReLoad : public Command return; } + Module *protocol = ModuleManager::FindFirstOf(PROTOCOL); + if (m->type == PROTOCOL && m != protocol) + { + source.Reply(_("You may not reload this module directly, instead reload %s."), protocol ? protocol->name.c_str() : "(unknown)"); + return; + } + /* Unrecoverable */ bool fatal = m->type == PROTOCOL; ModuleReturn status = ModuleManager::UnloadModule(m, source.GetUser()); @@ -96,8 +103,8 @@ class CommandOSModReLoad : public Command { if (fatal) { - quitmsg = "Unable to reload module " + mname; - quitting = true; + Anope::QuitReason = "Unable to reload module " + mname; + Anope::Quitting = true; } else source.Reply(_("Unable to load module \002%s\002"), mname.c_str()); diff --git a/modules/commands/os_news.cpp b/modules/commands/os_news.cpp index ba23c431d..eea480d13 100644 --- a/modules/commands/os_news.cpp +++ b/modules/commands/os_news.cpp @@ -72,7 +72,7 @@ class MyNewsService : public NewsService { for (unsigned i = 0; i < 3; ++i) for (unsigned j = 0; j < newsItems[i].size(); ++j) - newsItems[i][j]->destroy(); + newsItems[i][j]->Destroy(); } void AddNewsItem(NewsItem *n) @@ -86,7 +86,7 @@ class MyNewsService : public NewsService std::vector<NewsItem *>::iterator it = std::find(list.begin(), list.end(), n); if (it != list.end()) list.erase(it); - n->destroy(); + n->Destroy(); } std::vector<NewsItem *> &GetNewsList(NewsType t) @@ -106,7 +106,7 @@ static const char **findmsgs(NewsType type) class NewsBase : public Command { - service_reference<NewsService> ns; + ServiceReference<NewsService> ns; protected: void DoList(CommandSource &source, NewsType ntype, const char **msgs) @@ -117,16 +117,16 @@ class NewsBase : public Command else { ListFormatter lflist; - lflist.addColumn("Number").addColumn("Creator").addColumn("Created").addColumn("Text"); + lflist.AddColumn("Number").AddColumn("Creator").AddColumn("Created").AddColumn("Text"); for (unsigned i = 0, end = list.size(); i < end; ++i) { ListFormatter::ListEntry entry; entry["Number"] = stringify(i + 1); entry["Creator"] = list[i]->who; - entry["Created"] = do_strftime(list[i]->time); + entry["Created"] = Anope::strftime(list[i]->time); entry["Text"] = list[i]->text; - lflist.addEntry(entry); + lflist.AddEntry(entry); } source.Reply(msgs[MSG_LIST_HEADER]); @@ -151,7 +151,7 @@ class NewsBase : public Command this->OnSyntaxError(source, "ADD"); else { - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); NewsItem *news = new NewsItem(); @@ -181,7 +181,7 @@ class NewsBase : public Command source.Reply(msgs[MSG_LIST_NONE]); else { - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); if (!text.equals_ci("ALL")) { @@ -336,7 +336,7 @@ class CommandOSRandomNews : public NewsBase class OSNews : public Module { - SerializeType newsitem_type; + Serialize::Type newsitem_type; MyNewsService newsservice; CommandOSLogonNews commandoslogonnews; @@ -364,14 +364,14 @@ class OSNews : public Module if (Type == NEWS_RANDOM && i != cur_rand_news) continue; - const BotInfo *gl = findbot(Config->Global); + const BotInfo *gl = Global; if (!gl && !BotListByNick->empty()) gl = BotListByNick->begin()->second; - const BotInfo *os = findbot(Config->OperServ); + const BotInfo *os = OperServ; if (!os) os = gl; if (gl) - u->SendMessage(Type != NEWS_OPER ? gl : os, msg.c_str(), do_strftime(newsList[i]->time).c_str(), newsList[i]->text.c_str()); + u->SendMessage(Type != NEWS_OPER ? gl : os, msg.c_str(), Anope::strftime(newsList[i]->time).c_str(), newsList[i]->text.c_str()); ++displayed; @@ -391,7 +391,7 @@ class OSNews : public Module public: OSNews(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - newsitem_type("NewsItem", NewsItem::unserialize), newsservice(this), commandoslogonnews(this), commandosopernews(this), commandosrandomnews(this) + newsitem_type("NewsItem", NewsItem::Unserialize), newsservice(this), commandoslogonnews(this), commandosopernews(this), commandosrandomnews(this) { this->SetAuthor("Anope"); @@ -405,7 +405,7 @@ class OSNews : public Module DisplayNews(u, NEWS_OPER); } - void OnUserConnect(dynamic_reference<User> &user, bool &) anope_override + void OnUserConnect(Reference<User> &user, bool &) anope_override { if (!user || !user->server->IsSynced()) return; diff --git a/modules/commands/os_news.h b/modules/commands/os_news.h index 426121fb7..44525b963 100644 --- a/modules/commands/os_news.h +++ b/modules/commands/os_news.h @@ -23,8 +23,8 @@ struct NewsItem : Serializable time_t time; NewsItem() : Serializable("NewsItem") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; class NewsService : public Service @@ -39,9 +39,9 @@ class NewsService : public Service virtual std::vector<NewsItem *> &GetNewsList(NewsType t) = 0; }; -static service_reference<NewsService> news_service("NewsService", "news"); +static ServiceReference<NewsService> news_service("NewsService", "news"); -Serialize::Data NewsItem::serialize() const +Serialize::Data NewsItem::Serialize() const { Serialize::Data data; @@ -53,7 +53,7 @@ Serialize::Data NewsItem::serialize() const return data; } -Serializable* NewsItem::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* NewsItem::Unserialize(Serializable *obj, Serialize::Data &data) { if (!news_service) return NULL; diff --git a/modules/commands/os_noop.cpp b/modules/commands/os_noop.cpp index 826f1313a..fa9361f7b 100644 --- a/modules/commands/os_noop.cpp +++ b/modules/commands/os_noop.cpp @@ -36,7 +36,7 @@ class CommandOSNOOP : public Command else if (cmd.equals_ci("SET")) { /* Remove the O:lines */ - ircdproto->SendSVSNOOP(s, true); + IRCD->SendSVSNOOP(s, true); s->Extend("noop", new ExtensibleItemClass<Anope::string>(source.GetNick())); Log(LOG_ADMIN, source, this) << "SET on " << s->GetName(); @@ -56,7 +56,7 @@ class CommandOSNOOP : public Command else if (cmd.equals_ci("REVOKE")) { s->Shrink("noop"); - ircdproto->SendSVSNOOP(s, false); + IRCD->SendSVSNOOP(s, false); Log(LOG_ADMIN, source, this) << "REVOKE on " << s->GetName(); source.Reply(_("All O:lines of \002%s\002 have been reset."), s->GetName().c_str()); } diff --git a/modules/commands/os_oline.cpp b/modules/commands/os_oline.cpp index 3fe622c1c..7b8be5768 100644 --- a/modules/commands/os_oline.cpp +++ b/modules/commands/os_oline.cpp @@ -29,11 +29,11 @@ class CommandOSOLine : public Command User *u2 = NULL; /* let's check whether the user is online */ - if (!(u2 = finduser(nick))) + if (!(u2 = User::Find(nick, true))) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); else if (u2 && flag[0] == '+') { - ircdproto->SendSVSO(source.service, nick, flag); + IRCD->SendSVSO(source.service, nick, flag); u2->SetMode(source.service, UMODE_OPER); u2->SendMessage(source.service, _("You are now an IRC Operator.")); source.Reply(_("Operflags \002%s\002 have been added for \002%s\002."), flag.c_str(), nick.c_str()); @@ -41,7 +41,7 @@ class CommandOSOLine : public Command } else if (u2 && flag[0] == '-') { - ircdproto->SendSVSO(source.service, nick, flag); + IRCD->SendSVSO(source.service, nick, flag); source.Reply(_("Operflags \002%s\002 have been added for \002%s\002."), flag.c_str(), nick.c_str()); Log(LOG_ADMIN, source, this) << "for " << nick; } @@ -72,7 +72,7 @@ class OSOLine : public Module { this->SetAuthor("Anope"); - if (!ircdproto || !ircdproto->CanSVSO) + if (!IRCD || !IRCD->CanSVSO) throw ModuleException("Your IRCd does not support OMODE."); } diff --git a/modules/commands/os_oper.cpp b/modules/commands/os_oper.cpp index e2e7b4ab3..882455898 100644 --- a/modules/commands/os_oper.cpp +++ b/modules/commands/os_oper.cpp @@ -17,7 +17,7 @@ struct MyOper : Oper, Serializable { MyOper(const Anope::string &n, OperType *o) : Oper(n, o), Serializable("Oper") { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; @@ -27,12 +27,12 @@ struct MyOper : Oper, Serializable return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { OperType *ot = OperType::Find(data["type"].astr()); if (ot == NULL) return NULL; - NickCore *nc = findcore(data["name"].astr()); + NickCore *nc = NickCore::Find(data["name"].astr()); if (nc == NULL) return NULL; @@ -68,7 +68,7 @@ class CommandOSOper : public Command const Anope::string &oper = params[1]; const Anope::string &otype = params[2]; - const NickAlias *na = findnick(oper); + const NickAlias *na = NickAlias::Find(oper); if (na == NULL) source.Reply(NICK_X_NOT_REGISTERED, oper.c_str()); else if (na->nc->o) @@ -91,7 +91,7 @@ class CommandOSOper : public Command { const Anope::string &oper = params[1]; - const NickAlias *na = findnick(oper); + const NickAlias *na = NickAlias::Find(oper); if (na == NULL) source.Reply(NICK_X_NOT_REGISTERED, oper.c_str()); else if (!na->nc || !na->nc->o) @@ -118,7 +118,7 @@ class CommandOSOper : public Command source.Reply(_("%-8s %s"), nc->o->name.c_str(), nc->o->ot->GetName().c_str()); if (nc->o->config) source.Reply(_(" This oper is configured in the configuration file.")); - for (std::list<User *>::const_iterator uit = nc->Users.begin(); uit != nc->Users.end(); ++uit) + for (std::list<User *>::const_iterator uit = nc->users.begin(); uit != nc->users.end(); ++uit) { User *u = *uit; source.Reply(_(" %s is online using this oper block."), u->nick.c_str()); @@ -202,12 +202,12 @@ class CommandOSOper : public Command class OSOper : public Module { - SerializeType myoper_type; + Serialize::Type myoper_type; CommandOSOper commandosoper; public: OSOper(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - myoper_type("Oper", MyOper::unserialize), commandosoper(this) + myoper_type("Oper", MyOper::Unserialize), commandosoper(this) { this->SetAuthor("Anope"); } diff --git a/modules/commands/os_session.cpp b/modules/commands/os_session.cpp index 2311b2ed2..27157d511 100644 --- a/modules/commands/os_session.cpp +++ b/modules/commands/os_session.cpp @@ -101,9 +101,9 @@ class ExpireTimer : public Timer if (!e->expires || e->expires > Anope::CurTime) continue; - Log(findbot(Config->OperServ), "expire/exception") << "Session exception for " << e->mask << "has expired."; + Log(OperServ, "expire/exception") << "Session exception for " << e->mask << "has expired."; session_service->DelException(e); - e->destroy(); + e->Destroy(); } } }; @@ -112,30 +112,30 @@ class ExceptionDelCallback : public NumberList { protected: CommandSource &source; - unsigned Deleted; + unsigned deleted; public: - ExceptionDelCallback(CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), source(_source), Deleted(0) + ExceptionDelCallback(CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), source(_source), deleted(0) { } ~ExceptionDelCallback() { - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on session-limit exception list.")); - else if (Deleted == 1) + else if (deleted == 1) source.Reply(_("Deleted 1 entry from session-limit exception list.")); else - source.Reply(_("Deleted %d entries from session-limit exception list."), Deleted); + source.Reply(_("Deleted %d entries from session-limit exception list."), deleted); } - virtual void HandleNumber(unsigned Number) anope_override + virtual void HandleNumber(unsigned number) anope_override { - if (!Number || Number > session_service->GetExceptions().size()) + if (!number || number > session_service->GetExceptions().size()) return; - ++Deleted; + ++deleted; - DoDel(source, Number - 1); + DoDel(source, number - 1); } static void DoDel(CommandSource &source, unsigned index) @@ -144,7 +144,7 @@ class ExceptionDelCallback : public NumberList FOREACH_MOD(I_OnExceptionDel, OnExceptionDel(source, e)); session_service->DelException(e); - e->destroy(); + e->Destroy(); } }; @@ -167,7 +167,7 @@ class CommandOSSession : public Command else { ListFormatter list; - list.addColumn("Session").addColumn("Host"); + list.AddColumn("Session").AddColumn("Host"); for (SessionService::SessionMap::iterator it = session_service->GetSessions().begin(), it_end = session_service->GetSessions().end(); it != it_end; ++it) { @@ -178,7 +178,7 @@ class CommandOSSession : public Command ListFormatter::ListEntry entry; entry["Session"] = stringify(session->count); entry["Host"] = session->addr.mask(); - list.addEntry(entry); + list.AddEntry(entry); } } @@ -296,7 +296,7 @@ class CommandOSException : public Command return; } - time_t expires = !expiry.empty() ? dotime(expiry) : Config->ExceptionExpiry; + time_t expires = !expiry.empty() ? Anope::DoTime(expiry) : Config->ExceptionExpiry; if (expires < 0) { source.Reply(BAD_EXPIRY_TIME); @@ -352,12 +352,12 @@ class CommandOSException : public Command EventReturn MOD_RESULT; FOREACH_RESULT(I_OnExceptionAdd, OnExceptionAdd(exception)); if (MOD_RESULT == EVENT_STOP) - exception->destroy(); + exception->Destroy(); else { session_service->AddException(exception); source.Reply(_("Session limit for \002%s\002 set to \002%d\002."), mask.c_str(), limit); - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); } } @@ -394,7 +394,7 @@ class CommandOSException : public Command source.Reply(_("\002%s\002 not found on session-limit exception list."), mask.c_str()); } - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); return; @@ -428,7 +428,7 @@ class CommandOSException : public Command source.Reply(_("Exception for \002%s\002 (#%d) moved to position \002%d\002."), session_service->GetExceptions()[n1]->mask.c_str(), n1 + 1, n2 + 1); - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); } else @@ -468,10 +468,10 @@ class CommandOSException : public Command entry["Number"] = stringify(Number); entry["Mask"] = e->mask; entry["By"] = e->who; - entry["Created"] = do_strftime(e->time); + entry["Created"] = Anope::strftime(e->time); entry["Limit"] = stringify(e->limit); entry["Reason"] = e->reason; - this->list.addEntry(entry); + this->list.AddEntry(entry); } } nl_list(list, mask); @@ -488,15 +488,15 @@ class CommandOSException : public Command entry["Number"] = stringify(i + 1); entry["Mask"] = e->mask; entry["By"] = e->who; - entry["Created"] = do_strftime(e->time); + entry["Created"] = Anope::strftime(e->time); entry["Limit"] = stringify(e->limit); entry["Reason"] = e->reason; - list.addEntry(entry); + list.AddEntry(entry); } } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on session-limit exception list.")); else { @@ -513,7 +513,7 @@ class CommandOSException : public Command void DoList(CommandSource &source, const std::vector<Anope::string> ¶ms) { ListFormatter list; - list.addColumn("Number").addColumn("Limit").addColumn("Mask"); + list.AddColumn("Number").AddColumn("Limit").AddColumn("Mask"); this->ProcessList(source, params, list); } @@ -521,7 +521,7 @@ class CommandOSException : public Command void DoView(CommandSource &source, const std::vector<Anope::string> ¶ms) { ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("By").addColumn("Created").addColumn("Limit").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("By").AddColumn("Created").AddColumn("Limit").AddColumn("Reason"); this->ProcessList(source, params, list); } @@ -604,12 +604,12 @@ class CommandOSException : public Command class OSSession : public Module { - SerializeType exception_type; + Serialize::Type exception_type; MySessionService ss; ExpireTimer expiretimer; CommandOSSession commandossession; CommandOSException commandosexception; - service_reference<XLineManager> akills; + ServiceReference<XLineManager> akills; void AddSession(User *u, bool exempt) { @@ -649,13 +649,12 @@ class OSSession : public Module if (kill && !exempt) { - const BotInfo *bi = findbot(Config->OperServ); - if (bi) + if (OperServ) { if (!Config->SessionLimitExceeded.empty()) - u->SendMessage(bi, Config->SessionLimitExceeded.c_str(), u->host.c_str()); + u->SendMessage(OperServ, Config->SessionLimitExceeded.c_str(), u->host.c_str()); if (!Config->SessionLimitDetailsLoc.empty()) - u->SendMessage(bi, "%s", Config->SessionLimitDetailsLoc.c_str()); + u->SendMessage(OperServ, "%s", Config->SessionLimitDetailsLoc.c_str()); } ++session->hits; @@ -665,7 +664,7 @@ class OSSession : public Module XLine *x = new XLine(akillmask, Config->OperServ, Anope::CurTime + Config->SessionAutoKillExpiry, "Session limit exceeded", XLineManager::GenerateUID()); akills->AddXLine(x); akills->Send(NULL, x); - Log(bi, "akill/session") << "Added a temporary AKILL for \2" << akillmask << "\2 due to excessive connections"; + Log(OperServ, "akill/session") << "Added a temporary AKILL for \2" << akillmask << "\2 due to excessive connections"; } else { @@ -694,8 +693,7 @@ class OSSession : public Module } if (!session) { - if (debug) - Log(this) << "Tried to delete non-existant session: " << u->host; + Log(LOG_DEBUG) << "Tried to delete non-existant session: " << u->host; return; } @@ -711,7 +709,7 @@ class OSSession : public Module public: OSSession(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - exception_type("Exception", Exception::unserialize), ss(this), commandossession(this), commandosexception(this), akills("XLineManager", "xlinemanager/sgline") + exception_type("Exception", Exception::Unserialize), ss(this), commandossession(this), commandosexception(this), akills("XLineManager", "xlinemanager/sgline") { this->SetAuthor("Anope"); @@ -720,7 +718,7 @@ class OSSession : public Module ModuleManager::SetPriority(this, PRIORITY_FIRST); } - void OnUserConnect(dynamic_reference<User> &user, bool &exempt) anope_override + void OnUserConnect(Reference<User> &user, bool &exempt) anope_override { if (user && Config->LimitSessions) this->AddSession(user, exempt); diff --git a/modules/commands/os_session.h b/modules/commands/os_session.h index 070975fd2..7304b21ae 100644 --- a/modules/commands/os_session.h +++ b/modules/commands/os_session.h @@ -20,8 +20,8 @@ struct Exception : Serializable time_t expires; /* Time when it expires. 0 == no expiry */ Exception() : Serializable("Exception") { } - Serialize::Data serialize() const anope_override; - static Serializable* unserialize(Serializable *obj, Serialize::Data &data); + Serialize::Data Serialize() const anope_override; + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data); }; class SessionService : public Service @@ -51,9 +51,9 @@ class SessionService : public Service virtual SessionMap &GetSessions() = 0; }; -static service_reference<SessionService> session_service("SessionService", "session"); +static ServiceReference<SessionService> session_service("SessionService", "session"); -Serialize::Data Exception::serialize() const +Serialize::Data Exception::Serialize() const { Serialize::Data data; @@ -67,7 +67,7 @@ Serialize::Data Exception::serialize() const return data; } -Serializable* Exception::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* Exception::Unserialize(Serializable *obj, Serialize::Data &data) { if (!session_service) return NULL; diff --git a/modules/commands/os_set.cpp b/modules/commands/os_set.cpp index a8a7e2e62..1592e7936 100644 --- a/modules/commands/os_set.cpp +++ b/modules/commands/os_set.cpp @@ -22,11 +22,11 @@ class CommandOSSet : public Command Anope::string index; - index = readonly ? _("%s is enabled") : _("%s is disabled"); + index = Anope::ReadOnly ? _("%s is enabled") : _("%s is disabled"); source.Reply(index.c_str(), "READONLY"); - index = debug ? _("%s is enabled") : _("%s is disabled"); + index = Anope::Debug ? _("%s is enabled") : _("%s is disabled"); source.Reply(index.c_str(), "DEBUG"); - index = noexpire ? _("%s is enabled") : _("%s is disabled"); + index = Anope::NoExpire ? _("%s is enabled") : _("%s is disabled"); source.Reply(index.c_str(), "NOEXPIRE"); return; @@ -44,13 +44,13 @@ class CommandOSSet : public Command if (setting.equals_ci("ON")) { - readonly = true; + Anope::ReadOnly = true; Log(LOG_ADMIN, source, this) << "READONLY ON"; source.Reply(_("Services are now in \002read-only\002 mode.")); } else if (setting.equals_ci("OFF")) { - readonly = false; + Anope::ReadOnly = false; Log(LOG_ADMIN, source, this) << "READONLY OFF"; source.Reply(_("Services are now in \002read-write\002 mode.")); } @@ -79,21 +79,21 @@ class CommandOSSet : public Command * Rob **/ if (!Config->SuperAdmin) - source.Reply(_("SuperAdmin setting not enabled in services.conf")); + source.Reply(_("Superadmin can not be set because it is not enabled in the configuration")); else if (setting.equals_ci("ON")) { - source.GetUser()->SuperAdmin = true; + source.GetUser()->super_admin = true; source.Reply(_("You are now a SuperAdmin")); Log(LOG_ADMIN, source, this) << "SUPERADMIN ON"; } else if (setting.equals_ci("OFF")) { - source.GetUser()->SuperAdmin = false; + source.GetUser()->super_admin = false; source.Reply(_("You are no longer a SuperAdmin")); Log(LOG_ADMIN, source, this) << "SUPERADMIN OFF"; } else - source.Reply(_("Setting for SuperAdmin must be \002on\002 or \002off\002 (must be enabled in services.conf)")); + source.Reply(_("Setting for SuperAdmin must be \002on\002 or \002off\002.")); return; } @@ -110,23 +110,23 @@ class CommandOSSet : public Command if (setting.equals_ci("ON")) { - debug = 1; + Anope::Debug = 1; Log(LOG_ADMIN, source, this) << "DEBUG ON"; source.Reply(_("Services are now in debug mode.")); } else if (setting.equals_ci("OFF") || setting == "0") { Log(LOG_ADMIN, source, this) << "DEBUG OFF"; - debug = 0; + Anope::Debug = 0; source.Reply(_("Services are now in non-debug mode.")); } else { try { - debug = convertTo<int>(setting); - Log(LOG_ADMIN, source, this) << "DEBUG " << debug; - source.Reply(_("Services are now in debug mode (level %d)."), debug); + Anope::Debug = convertTo<int>(setting); + Log(LOG_ADMIN, source, this) << "DEBUG " << Anope::Debug; + source.Reply(_("Services are now in debug mode (level %d)."), Anope::Debug); return; } catch (const ConvertException &) { } @@ -149,13 +149,13 @@ class CommandOSSet : public Command if (setting.equals_ci("ON")) { - noexpire = true; + Anope::NoExpire = true; Log(LOG_ADMIN, source, this) << "NOEXPIRE ON"; source.Reply(_("Services are now in \002no expire\002 mode.")); } else if (setting.equals_ci("OFF")) { - noexpire = false; + Anope::NoExpire = false; Log(LOG_ADMIN, source, this) << "NOEXPIRE OFF"; source.Reply(_("Services are now in \002expire\002 mode.")); } diff --git a/modules/commands/os_shutdown.cpp b/modules/commands/os_shutdown.cpp index 6edb3a64d..2f7827be3 100644 --- a/modules/commands/os_shutdown.cpp +++ b/modules/commands/os_shutdown.cpp @@ -24,8 +24,8 @@ class CommandOSQuit : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - quitmsg = source.command + " command received from " + source.GetNick(); - quitting = true; + Anope::QuitReason = source.command + " command received from " + source.GetNick(); + Anope::Quitting = true; return; } @@ -52,9 +52,9 @@ class CommandOSRestart : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - quitmsg = source.command + " command received from " + source.GetNick(); - quitting = restarting = true; - save_databases(); + Anope::QuitReason = source.command + " command received from " + source.GetNick(); + Anope::Quitting = Anope::Restarting = true; + Anope::SaveDatabases(); return; } @@ -78,9 +78,9 @@ class CommandOSShutdown : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - quitmsg = source.command + " command received from " + source.GetNick(); - quitting = true; - save_databases(); + Anope::QuitReason = source.command + " command received from " + source.GetNick(); + Anope::Quitting = true; + Anope::SaveDatabases(); return; } diff --git a/modules/commands/os_stats.cpp b/modules/commands/os_stats.cpp index 83f13a90a..bb029eed9 100644 --- a/modules/commands/os_stats.cpp +++ b/modules/commands/os_stats.cpp @@ -18,20 +18,20 @@ struct Stats : Serializable { Stats() : Serializable("Stats") { } - Serialize::Data serialize() const anope_override + Serialize::Data Serialize() const anope_override { Serialize::Data data; - data["maxusercnt"] << maxusercnt; - data["maxusertime"] << maxusertime; + data["maxusercnt"] << MaxUserCount; + data["maxusertime"] << MaxUserTime; return data; } - static Serializable* unserialize(Serializable *obj, Serialize::Data &data) + static Serializable* Unserialize(Serializable *obj, Serialize::Data &data) { - data["maxusercnt"] >> maxusercnt; - data["maxusertime"] >> maxusertime; + data["maxusercnt"] >> MaxUserCount; + data["maxusertime"] >> MaxUserTime; return NULL; } }; @@ -57,7 +57,7 @@ static int stats_count_servers(Server *s) class CommandOSStats : public Command { - service_reference<XLineManager> akills, snlines, sqlines; + ServiceReference<XLineManager> akills, snlines, sqlines; private: void DoStatsAkill(CommandSource &source) { @@ -82,7 +82,7 @@ class CommandOSStats : public Command else source.Reply(_("Default AKILL expiry time: \002No expiration\002")); } - if (ircdproto->CanSNLine && snlines) + if (IRCD->CanSNLine && snlines) { /* SNLINEs */ source.Reply(_("Current number of SNLINEs: \002%d\002"), snlines->GetCount()); @@ -102,7 +102,7 @@ class CommandOSStats : public Command else source.Reply(_("Default SNLINE expiry time: \002No expiration\002")); } - if (ircdproto->CanSQLine && sqlines) + if (IRCD->CanSQLine && sqlines) { /* SQLINEs */ source.Reply(_("Current number of SQLINEs: \002%d\002"), sqlines->GetCount()); @@ -127,17 +127,17 @@ class CommandOSStats : public Command void DoStatsReset(CommandSource &source) { - maxusercnt = usercnt; + MaxUserCount = UserListByNick.size(); source.Reply(_("Statistics reset.")); return; } void DoStatsUptime(CommandSource &source) { - time_t uptime = Anope::CurTime - start_time; - source.Reply(_("Current users: \002%d\002 (\002%d\002 ops)"), usercnt, opcnt); - source.Reply(_("Maximum users: \002%d\002 (%s)"), maxusercnt, do_strftime(maxusertime).c_str()); - source.Reply(_("Services up %s"), duration(uptime).c_str()); + time_t uptime = Anope::CurTime - Anope::StartTime; + source.Reply(_("Current users: \002%d\002 (\002%d\002 ops)"), UserListByNick.size(), OperCount); + source.Reply(_("Maximum users: \002%d\002 (%s)"), MaxUserCount, Anope::strftime(MaxUserTime).c_str()); + source.Reply(_("Services up %s"), Anope::Duration(uptime).c_str()); return; } @@ -145,7 +145,7 @@ class CommandOSStats : public Command void DoStatsUplink(CommandSource &source) { Anope::string buf; - for (std::set<Anope::string>::iterator it = Capab.begin(); it != Capab.end(); ++it) + for (std::set<Anope::string>::iterator it = Servers::Capab.begin(); it != Servers::Capab.end(); ++it) buf += " " + *it; if (!buf.empty()) buf.erase(buf.begin()); @@ -255,12 +255,12 @@ class CommandOSStats : public Command class OSStats : public Module { CommandOSStats commandosstats; - SerializeType stats_type; + Serialize::Type stats_type; Stats stats_saver; public: OSStats(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, CORE), - commandosstats(this), stats_type("Stats", Stats::unserialize) + commandosstats(this), stats_type("Stats", Stats::Unserialize) { this->SetAuthor("Anope"); diff --git a/modules/commands/os_svsnick.cpp b/modules/commands/os_svsnick.cpp index 4c6329acb..e08d5d3aa 100644 --- a/modules/commands/os_svsnick.cpp +++ b/modules/commands/os_svsnick.cpp @@ -36,28 +36,22 @@ class CommandOSSVSNick : public Command } /* Check for valid characters */ - if (newnick[0] == '-' || isdigit(newnick[0])) + if (!IRCD->IsNickValid(newnick)) { source.Reply(_("Nick \002%s\002 is an illegal nickname and cannot be used."), newnick.c_str()); return; } - for (unsigned i = 0, end = newnick.length(); i < end; ++i) - if (!isvalidnick(newnick[i])) - { - source.Reply(_("Nick \002%s\002 is an illegal nickname and cannot be used."), newnick.c_str()); - return; - } /* Check for a nick in use or a forbidden/suspended nick */ - if (!(u2 = finduser(nick))) + if (!(u2 = User::Find(nick, true))) source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); - else if (!nick.equals_ci(newnick) && finduser(newnick)) + else if (!nick.equals_ci(newnick) && User::Find(newnick)) source.Reply(_("Nick \002%s\002 is currently in use."), newnick.c_str()); else { source.Reply(_("The nick \002%s\002 is now being changed to \002%s\002."), nick.c_str(), newnick.c_str()); Log(LOG_ADMIN, source, this) << "to change " << nick << " to " << newnick; - ircdproto->SendForceNickChange(u2, newnick, Anope::CurTime); + IRCD->SendForceNickChange(u2, newnick, Anope::CurTime); } return; } @@ -81,7 +75,7 @@ class OSSVSNick : public Module { this->SetAuthor("Anope"); - if (!ircdproto || !ircdproto->CanSVSNick) + if (!IRCD || !IRCD->CanSVSNick) throw ModuleException("Your IRCd does not support SVSNICK"); } diff --git a/modules/commands/os_sxline.cpp b/modules/commands/os_sxline.cpp index 9261bcddd..7f48a2645 100644 --- a/modules/commands/os_sxline.cpp +++ b/modules/commands/os_sxline.cpp @@ -18,33 +18,33 @@ class SXLineDelCallback : public NumberList XLineManager *xlm; Command *command; CommandSource &source; - unsigned Deleted; + unsigned deleted; public: - SXLineDelCallback(XLineManager *x, Command *c, CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), xlm(x), command(c), source(_source), Deleted(0) + SXLineDelCallback(XLineManager *x, Command *c, CommandSource &_source, const Anope::string &numlist) : NumberList(numlist, true), xlm(x), command(c), source(_source), deleted(0) { } ~SXLineDelCallback() { - if (!Deleted) + if (!deleted) source.Reply(_("No matching entries on the %s list."), this->command->name.c_str()); - else if (Deleted == 1) + else if (deleted == 1) source.Reply(_("Deleted 1 entry from the %s list."), this->command->name.c_str()); else - source.Reply(_("Deleted %d entries from the %s list."), Deleted, this->command->name.c_str()); + source.Reply(_("Deleted %d entries from the %s list."), deleted, this->command->name.c_str()); } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number) + if (!number) return; - XLine *x = this->xlm->GetEntry(Number - 1); + XLine *x = this->xlm->GetEntry(number - 1); if (!x) return; - ++Deleted; + ++deleted; DoDel(this->xlm, source, x); } @@ -99,7 +99,7 @@ class CommandOSSXLineBase : public Command source.Reply(_("\002%s\002 deleted from the %s list."), mask.c_str(), source.command.c_str()); } - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); return; @@ -126,24 +126,24 @@ class CommandOSSXLineBase : public Command { } - void HandleNumber(unsigned Number) anope_override + void HandleNumber(unsigned number) anope_override { - if (!Number) + if (!number) return; - const XLine *x = this->xlm->GetEntry(Number - 1); + const XLine *x = this->xlm->GetEntry(number - 1); if (!x) return; ListFormatter::ListEntry entry; - entry["Number"] = stringify(Number); - entry["Mask"] = x->Mask; - entry["By"] = x->By; - entry["Created"] = do_strftime(x->Created, NULL, true); - entry["Expires"] = expire_left(NULL, x->Expires); - entry["Reason"] = x->Reason; - list.addEntry(entry); + entry["Number"] = stringify(number); + entry["Mask"] = x->mask; + entry["By"] = x->by; + entry["Created"] = Anope::strftime(x->created, NULL, true); + entry["Expires"] = Anope::Expires(x->expires); + entry["Reason"] = x->reason; + list.AddEntry(entry); } } sl_list(this->xlm(), list, mask); @@ -155,21 +155,21 @@ class CommandOSSXLineBase : public Command { const XLine *x = this->xlm()->GetEntry(i); - if (mask.empty() || mask.equals_ci(x->Mask) || mask == x->UID || Anope::Match(x->Mask, mask, false, true)) + if (mask.empty() || mask.equals_ci(x->mask) || mask == x->id || Anope::Match(x->mask, mask, false, true)) { ListFormatter::ListEntry entry; entry["Number"] = stringify(i + 1); - entry["Mask"] = x->Mask; - entry["By"] = x->By; - entry["Created"] = do_strftime(x->Created, NULL, true); - entry["Expires"] = expire_left(source.nc, x->Expires); - entry["Reason"] = x->Reason; - list.addEntry(entry); + entry["Mask"] = x->mask; + entry["By"] = x->by; + entry["Created"] = Anope::strftime(x->created, NULL, true); + entry["Expires"] = Anope::Expires(x->expires, source.nc); + entry["Reason"] = x->reason; + list.AddEntry(entry); } } } - if (list.isEmpty()) + if (list.IsEmpty()) source.Reply(_("No matching entries on the %s list."), source.command.c_str()); else { @@ -186,7 +186,7 @@ class CommandOSSXLineBase : public Command void OnList(CommandSource &source, const std::vector<Anope::string> ¶ms) { ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("Reason"); this->ProcessList(source, params, list); } @@ -194,7 +194,7 @@ class CommandOSSXLineBase : public Command void OnView(CommandSource &source, const std::vector<Anope::string> ¶ms) { ListFormatter list; - list.addColumn("Number").addColumn("Mask").addColumn("By").addColumn("Created").addColumn("Expires").addColumn("Reason"); + list.AddColumn("Number").AddColumn("Mask").AddColumn("By").AddColumn("Created").AddColumn("Expires").AddColumn("Reason"); this->ProcessList(source, params, list); } @@ -250,7 +250,7 @@ class CommandOSSNLine : public CommandOSSXLineBase void OnAdd(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!this->xlm() || !ircdproto->CanSNLine) + if (!this->xlm() || !IRCD->CanSNLine) { source.Reply(_("Your IRCd does not support SNLINE")); return; @@ -268,7 +268,7 @@ class CommandOSSNLine : public CommandOSSXLineBase last_param = 3; } - expires = !expiry.empty() ? dotime(expiry) : Config->SNLineExpiry; + expires = !expiry.empty() ? Anope::DoTime(expiry) : Config->SNLineExpiry; /* If the expiry given does not contain a final letter, it's in days, * said the doc. Ah well. */ @@ -318,7 +318,7 @@ class CommandOSSNLine : public CommandOSSXLineBase return; } - service_reference<RegexProvider> provider("Regex", Config->RegexEngine); + ServiceReference<RegexProvider> provider("Regex", Config->RegexEngine); if (!provider) { source.Reply(_("Unable to find regex engine %s"), Config->RegexEngine.c_str()); @@ -354,7 +354,7 @@ class CommandOSSNLine : public CommandOSSXLineBase XLine *x = new XLine(mask, source.GetNick(), expires, reason); if (Config->AkillIds) - x->UID = XLineManager::GenerateUID(); + x->id = XLineManager::GenerateUID(); unsigned int affected = 0; for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) @@ -366,7 +366,7 @@ class CommandOSSNLine : public CommandOSSXLineBase { source.Reply(USERHOST_MASK_TOO_WIDE, mask.c_str()); Log(LOG_ADMIN, source, this) << "tried to " << source.command << " " << percent << "% of the network (" << affected << " users)"; - x->destroy(); + x->Destroy(); return; } @@ -374,7 +374,7 @@ class CommandOSSNLine : public CommandOSSXLineBase FOREACH_RESULT(I_OnAddXLine, OnAddXLine(source, x, this->xlm())); if (MOD_RESULT == EVENT_STOP) { - x->destroy(); + x->Destroy(); return; } @@ -391,18 +391,18 @@ class CommandOSSNLine : public CommandOSSXLineBase User *user = it->second; ++it; - if (!user->HasMode(UMODE_OPER) && user->server != Me && Anope::Match(user->realname, x->Mask, false, true)) + if (!user->HasMode(UMODE_OPER) && user->server != Me && Anope::Match(user->realname, x->mask, false, true)) user->Kill(Config->ServerName, rreason); } } source.Reply(_("\002%s\002 added to the %s list."), mask.c_str(), source.command.c_str()); - Log(LOG_ADMIN, source, this) << "on " << mask << " (" << reason << ") expires in " << (expires ? duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; - if (readonly) + Log(LOG_ADMIN, source, this) << "on " << mask << " (" << reason << ") expires in " << (expires ? Anope::Duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); } - service_reference<XLineManager> snlines; + ServiceReference<XLineManager> snlines; public: CommandOSSNLine(Module *creator) : CommandOSSXLineBase(creator, "operserv/snline"), snlines("XLineManager", "xlinemanager/snline") { @@ -471,7 +471,7 @@ class CommandOSSQLine : public CommandOSSXLineBase void OnAdd(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (!this->xlm() || !ircdproto->CanSQLine) + if (!this->xlm() || !IRCD->CanSQLine) { source.Reply(_("Your IRCd does not support SQLINE")); return; @@ -489,7 +489,7 @@ class CommandOSSQLine : public CommandOSSXLineBase last_param = 3; } - expires = !expiry.empty() ? dotime(expiry) : Config->SQLineExpiry; + expires = !expiry.empty() ? Anope::DoTime(expiry) : Config->SQLineExpiry; /* If the expiry given does not contain a final letter, it's in days, * said the doc. Ah well. */ @@ -528,7 +528,7 @@ class CommandOSSQLine : public CommandOSSXLineBase return; } - service_reference<RegexProvider> provider("Regex", Config->RegexEngine); + ServiceReference<RegexProvider> provider("Regex", Config->RegexEngine); if (!provider) { source.Reply(_("Unable to find regex engine %s"), Config->RegexEngine.c_str()); @@ -557,7 +557,7 @@ class CommandOSSQLine : public CommandOSSXLineBase XLine *x = new XLine(mask, source.GetNick(), expires, reason); if (Config->AkillIds) - x->UID = XLineManager::GenerateUID(); + x->id = XLineManager::GenerateUID(); unsigned int affected = 0; for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) @@ -569,7 +569,7 @@ class CommandOSSQLine : public CommandOSSXLineBase { source.Reply(USERHOST_MASK_TOO_WIDE, mask.c_str()); Log(LOG_ADMIN, source, this) << "tried to SQLine " << percent << "% of the network (" << affected << " users)"; - x->destroy(); + x->Destroy(); return; } @@ -577,7 +577,7 @@ class CommandOSSQLine : public CommandOSSXLineBase FOREACH_RESULT(I_OnAddXLine, OnAddXLine(source, x, this->xlm())); if (MOD_RESULT == EVENT_STOP) { - x->destroy(); + x->Destroy(); return; } @@ -616,7 +616,7 @@ class CommandOSSQLine : public CommandOSSXLineBase User *user = it->second; ++it; - if (!user->HasMode(UMODE_OPER) && user->server != Me && Anope::Match(user->nick, x->Mask, false, true)) + if (!user->HasMode(UMODE_OPER) && user->server != Me && Anope::Match(user->nick, x->mask, false, true)) user->Kill(Config->ServerName, rreason); } } @@ -625,13 +625,13 @@ class CommandOSSQLine : public CommandOSSXLineBase } source.Reply(_("\002%s\002 added to the SQLINE list."), mask.c_str()); - Log(LOG_ADMIN, source, this) << "on " << mask << " (" << reason << ") expires in " << (expires ? duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; + Log(LOG_ADMIN, source, this) << "on " << mask << " (" << reason << ") expires in " << (expires ? Anope::Duration(expires - Anope::CurTime) : "never") << " [affects " << affected << " user(s) (" << percent << "%)]"; - if (readonly) + if (Anope::ReadOnly) source.Reply(READ_ONLY_MODE); } - service_reference<XLineManager> sqlines; + ServiceReference<XLineManager> sqlines; public: CommandOSSQLine(Module *creator) : CommandOSSXLineBase(creator, "operserv/sqline"), sqlines("XLineManager", "xlinemanager/sqline") { diff --git a/modules/commands/os_update.cpp b/modules/commands/os_update.cpp index b9b43230f..7bea34aaf 100644 --- a/modules/commands/os_update.cpp +++ b/modules/commands/os_update.cpp @@ -25,7 +25,7 @@ class CommandOSUpdate : public Command void Execute(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override { source.Reply(_("Updating databases.")); - save_databases(); + Anope::SaveDatabases(); return; } diff --git a/modules/database/db_flatfile.cpp b/modules/database/db_flatfile.cpp index 2b31c8a81..acb287cee 100644 --- a/modules/database/db_flatfile.cpp +++ b/modules/database/db_flatfile.cpp @@ -37,7 +37,7 @@ class DBFlatFile : public Module void BackupDatabase() { /* Do not backup a database that doesn't exist */ - if (!IsFile(DatabaseFile)) + if (!Anope::IsFile(DatabaseFile)) return; time_t now = Anope::CurTime; @@ -58,7 +58,7 @@ class DBFlatFile : public Module Log(this) << "Unable to back up database!"; if (!Config->NoBackupOkay) - quitting = true; + Anope::Quitting = true; return; } @@ -76,8 +76,8 @@ class DBFlatFile : public Module void OnReload() anope_override { ConfigReader config; - DatabaseFile = db_dir + "/" + config.ReadValue("db_flatfile", "database", "anope.db", 0); - BackupFile = db_dir + "/backups/" + config.ReadValue("db_flatfile", "database", "anope.db", 0); + DatabaseFile = Anope::DataDir + "/" + config.ReadValue("db_flatfile", "database", "anope.db", 0); + BackupFile = Anope::DataDir + "/backups/" + config.ReadValue("db_flatfile", "database", "anope.db", 0); } EventReturn OnLoadDatabase() anope_override @@ -92,23 +92,23 @@ class DBFlatFile : public Module return EVENT_CONTINUE; } - const std::vector<Anope::string> type_order = SerializeType::GetTypeOrder(); + const std::vector<Anope::string> type_order = Serialize::Type::GetTypeOrder(); for (unsigned i = 0; i < type_order.size(); ++i) { - SerializeType *stype = SerializeType::Find(type_order[i]); + Serialize::Type *stype = Serialize::Type::Find(type_order[i]); if (stype && !databases.count(stype->GetOwner())) { - Anope::string db_name = db_dir + "/module_" + stype->GetOwner()->name + ".db"; + Anope::string db_name = Anope::DataDir + "/module_" + stype->GetOwner()->name + ".db"; databases[stype->GetOwner()] = new std::fstream(db_name.c_str(), std::ios_base::in); } } - std::multimap<SerializeType *, Serialize::Data> objects; + std::multimap<Serialize::Type *, Serialize::Data> objects; for (std::map<Module *, std::fstream *>::iterator it = databases.begin(), it_end = databases.end(); it != it_end; ++it) { std::fstream *db = it->second; - SerializeType *st = NULL; + Serialize::Type *st = NULL; Serialize::Data data; for (Anope::string buf, token; std::getline(*db, buf.str());) { @@ -119,7 +119,7 @@ class DBFlatFile : public Module if (token == "OBJECT" && sep.GetToken(token)) { - st = SerializeType::Find(token); + st = Serialize::Type::Find(token); data.clear(); } else if (token == "DATA" && st != NULL && sep.GetToken(token)) @@ -136,9 +136,9 @@ class DBFlatFile : public Module for (unsigned i = 0; i < type_order.size(); ++i) { - SerializeType *stype = SerializeType::Find(type_order[i]); + Serialize::Type *stype = Serialize::Type::Find(type_order[i]); - std::multimap<SerializeType *, Serialize::Data>::iterator it = objects.find(stype), it_end = objects.upper_bound(stype); + std::multimap<Serialize::Type *, Serialize::Data>::iterator it = objects.find(stype), it_end = objects.upper_bound(stype); if (it == objects.end()) continue; for (; it != it_end; ++it) @@ -178,16 +178,16 @@ class DBFlatFile : public Module for (std::list<Serializable *>::const_iterator it = items.begin(), it_end = items.end(); it != it_end; ++it) { Serializable *base = *it; - SerializeType *s_type = base->GetSerializableType(); + Serialize::Type *s_type = base->GetSerializableType(); if (!s_type) continue; - Serialize::Data data = base->serialize(); + Serialize::Data data = base->Serialize(); if (!databases.count(s_type->GetOwner())) { - Anope::string db_name = db_dir + "/module_" + s_type->GetOwner()->name + ".db"; + Anope::string db_name = Anope::DataDir + "/module_" + s_type->GetOwner()->name + ".db"; databases[s_type->GetOwner()] = new std::fstream(db_name.c_str(), std::ios_base::out | std::ios_base::trunc); } std::fstream *fd = databases[s_type->GetOwner()]; @@ -203,7 +203,7 @@ class DBFlatFile : public Module Log(this) << "Unable to write database"; databases[NULL]->close(); if (!Config->NoBackupOkay) - quitting = true; + Anope::Quitting = true; if (IsFile(tmp_db)) rename(tmp_db.c_str(), DatabaseFile.c_str()); } diff --git a/modules/database/db_old.cpp b/modules/database/db_old.cpp index f09fb2aab..ea899edd6 100644 --- a/modules/database/db_old.cpp +++ b/modules/database/db_old.cpp @@ -309,7 +309,7 @@ static dbFILE *open_db_read(const char *service, const char *filename, int versi int myversion; f = new dbFILE; - strscpy(f->filename, (db_dir + "/" + filename).c_str(), sizeof(f->filename)); + strscpy(f->filename, (Anope::DataDir + "/" + filename).c_str(), sizeof(f->filename)); f->mode = 'r'; fp = fopen(f->filename, "rb"); if (!fp) @@ -595,7 +595,7 @@ static void LoadNicks() Anope::string core; READ(read_string(core, f)); - NickCore *nc = findcore(core); + NickCore *nc = NickCore::Find(core); if (nc == NULL) { Log() << "Skipping coreless nick " << nick << " with core " << core; @@ -634,7 +634,7 @@ static void LoadVHosts() READ(read_string(creator, f)); READ(read_int32(&vtime, f)); - NickAlias *na = findnick(nick); + NickAlias *na = NickAlias::Find(nick); if (na == NULL) { Log() << "Removing vhost for nonexistant nick " << nick; @@ -669,7 +669,7 @@ static void LoadBots() READ(read_int32(&created, f)); READ(read_int16(&chancount, f)); - BotInfo *bi = findbot(nick); + BotInfo *bi = BotInfo::Find(nick); if (!bi) bi = new BotInfo(nick, user, host, real); bi->created = created; @@ -698,10 +698,10 @@ static void LoadChannels() ChannelInfo *ci = new ChannelInfo(namebuf); READ(read_string(buffer, f)); - ci->SetFounder(findcore(buffer)); + ci->SetFounder(NickCore::Find(buffer)); READ(read_string(buffer, f)); - ci->successor = findcore(buffer); + ci->successor = NickCore::Find(buffer); char pwbuf[32]; READ(read_buffer(pwbuf, f)); @@ -777,7 +777,7 @@ static void LoadChannels() ci->SetLevel(GetLevelName(j), level); } - service_reference<AccessProvider> provider("AccessProvider", "access/access"); + ServiceReference<AccessProvider> provider("AccessProvider", "access/access"); uint16_t tmpu16; READ(read_uint16(&tmpu16, f)); for (uint16_t j = 0; j < tmpu16; ++j) @@ -793,7 +793,7 @@ static void LoadChannels() int16_t level; READ(read_int16(&level, f)); if (access) - access->Unserialize(stringify(level)); + access->AccessUnserialize(stringify(level)); Anope::string mask; READ(read_string(mask, f)); @@ -858,7 +858,7 @@ static void LoadChannels() READ(read_string(buffer, f)); READ(read_string(buffer, f)); - ci->bi = findbot(buffer); + ci->bi = BotInfo::Find(buffer); READ(read_int32(&tmp32, f)); if (tmp32 & OLD_BS_DONTKICKOPS) @@ -981,7 +981,7 @@ static void LoadOper() continue; XLine *x = new XLine(user + "@" + host, by, expires, reason, XLineManager::GenerateUID()); - x->Created = seton; + x->created = seton; akill->AddXLine(x); } @@ -1001,7 +1001,7 @@ static void LoadOper() continue; XLine *x = new XLine(mask, by, expires, reason, XLineManager::GenerateUID()); - x->Created = seton; + x->created = seton; snline->AddXLine(x); } @@ -1021,7 +1021,7 @@ static void LoadOper() continue; XLine *x = new XLine(mask, by, expires, reason, XLineManager::GenerateUID()); - x->Created = seton; + x->created = seton; sqline->AddXLine(x); } @@ -1041,7 +1041,7 @@ static void LoadOper() continue; XLine *x = new XLine(mask, by, expires, reason, XLineManager::GenerateUID()); - x->Created = seton; + x->created = seton; szline->AddXLine(x); } diff --git a/modules/database/db_plain.cpp b/modules/database/db_plain.cpp index e6d430556..f23cf4e4a 100644 --- a/modules/database/db_plain.cpp +++ b/modules/database/db_plain.cpp @@ -139,9 +139,9 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co else if (key.equals_ci("MEMOMAX")) ci->memos.memomax = params[0].is_pos_number_only() ? convertTo<int16_t>(params[0]) : -1; else if (key.equals_ci("FOUNDER")) - ci->SetFounder(findcore(params[0])); + ci->SetFounder(NickCore::Find(params[0])); else if (key.equals_ci("SUCCESSOR")) - ci->successor = findcore(params[0]); + ci->successor = NickCore::Find(params[0]); else if (key.equals_ci("LEVELS")) { for (unsigned j = 0, end = params.size(); j < end; j += 2) @@ -169,14 +169,14 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co } else if (key.equals_ci("ACCESS")) // Older access system, from Anope 1.9.4. { - service_reference<AccessProvider> provider("AccessProvider", "access/access"); + ServiceReference<AccessProvider> provider("AccessProvider", "access/access"); if (!provider) throw DatabaseException("Old access entry for nonexistant provider"); ChanAccess *access = const_cast<ChanAccess *>(provider->Create()); access->ci = ci; access->mask = params[0]; - access->Unserialize(params[1]); + access->AccessUnserialize(params[1]); access->last_seen = params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0; access->creator = params[3]; access->created = Anope::CurTime; @@ -185,14 +185,14 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co } else if (key.equals_ci("ACCESS2")) { - service_reference<AccessProvider> provider("AccessProvider", params[0]); + ServiceReference<AccessProvider> provider("AccessProvider", params[0]); if (!provider) throw DatabaseException("Access entry for nonexistant provider " + params[0]); ChanAccess *access = const_cast<ChanAccess *>(provider->Create()); access->ci = ci; access->mask = params[1]; - access->Unserialize(params[2]); + access->AccessUnserialize(params[2]); access->last_seen = params[3].is_pos_number_only() ? convertTo<time_t>(params[3]) : 0; access->creator = params[4]; access->created = params.size() > 5 && params[5].is_pos_number_only() ? convertTo<time_t>(params[5]) : Anope::CurTime; @@ -206,7 +206,7 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co NickCore *nc = NULL; if (Nick) { - nc = findcore(params[2]); + nc = NickCore::Find(params[2]); if (!nc) throw DatabaseException("Akick for nonexistant core " + params[2] + " on " + ci->name); } @@ -242,6 +242,7 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co Anope::string setter = params[2]; time_t mcreated = params[3].is_pos_number_only() ? convertTo<time_t>(params[3]) : Anope::CurTime; Anope::string param = params.size() > 4 ? params[4] : ""; + const Anope::string* ChannelModeNameStrings = Flags<ChannelModeName>::GetFlagStrings(); for (size_t i = CMODE_BEGIN + 1; i < CMODE_END; ++i) if (ChannelModeNameStrings[i] == mode_name) { @@ -270,7 +271,7 @@ EventReturn OnDatabaseReadMetadata(ChannelInfo *ci, const Anope::string &key, co else if (key.equals_ci("BI")) { if (params[0].equals_ci("NAME")) - ci->bi = findbot(params[1]); + ci->bi = BotInfo::Find(params[1]); else if (params[0].equals_ci("FLAGS")) ci->botflags.FromVector(params); else if (params[0].equals_ci("TTB")) @@ -396,22 +397,22 @@ static void ReadDatabase(Module *m = NULL) { if (params[0].equals_ci("NC")) { - nc = findcore(params[1]); + nc = NickCore::Find(params[1]); Type = MD_NC; } else if (params[0].equals_ci("NA")) { - na = findnick(params[2]); + na = NickAlias::Find(params[2]); Type = MD_NA; } else if (params[0].equals_ci("BI")) { - bi = findbot(params[1]); + bi = BotInfo::Find(params[1]); Type = MD_BI; } else if (params[0].equals_ci("CH")) { - ci = cs_findchan(params[1]); + ci = ChannelInfo::Find(params[1]); Type = MD_CH; } else if (params[0].equals_ci("MD")) @@ -484,7 +485,7 @@ static void LoadNickCore(const std::vector<Anope::string> ¶ms) static void LoadNickAlias(const std::vector<Anope::string> ¶ms) { - NickCore *nc = findcore(params[0]); + NickCore *nc = NickCore::Find(params[0]); if (!nc) { Log() << "[db_plain]: Unable to find core " << params[0]; @@ -502,7 +503,7 @@ static void LoadNickAlias(const std::vector<Anope::string> ¶ms) static void LoadBotInfo(const std::vector<Anope::string> ¶ms) { - BotInfo *bi = findbot(params[0]); + BotInfo *bi = BotInfo::Find(params[0]); if (!bi) bi = new BotInfo(params[0], params[1], params[2]); @@ -533,8 +534,8 @@ static void LoadOperInfo(const std::vector<Anope::string> ¶ms) { if (params[0].equals_ci("STATS")) { - maxusercnt = params[1].is_pos_number_only() ? convertTo<uint32_t>(params[1]) : 0; - maxusertime = params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0; + MaxUserCount = params[1].is_pos_number_only() ? convertTo<uint32_t>(params[1]) : 0; + MaxUserTime = params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0; } else if (params[0].equals_ci("SXLINE")) { @@ -551,7 +552,7 @@ static void LoadOperInfo(const std::vector<Anope::string> ¶ms) Anope::string reason = params[7]; XLine *x = new XLine(mask, by, expires, reason, XLineManager::GenerateUID()); - x->Created = seton; + x->created = seton; xl->AddXLine(x); break; } @@ -627,7 +628,7 @@ class DBPlain : public Module Log() << "Unable to back up database!"; if (!Config->NoBackupOkay) - quitting = true; + Anope::Quitting = true; return; } @@ -646,8 +647,8 @@ class DBPlain : public Module void OnReload() anope_override { ConfigReader config; - DatabaseFile = db_dir + "/" + config.ReadValue("db_plain", "database", "anope.db", 0); - BackupFile = db_dir + "/backups/" + config.ReadValue("db_plain", "database", "anope.db", 0); + DatabaseFile = Anope::DataDir + "/" + config.ReadValue("db_plain", "database", "anope.db", 0); + BackupFile = Anope::DataDir + "/backups/" + config.ReadValue("db_plain", "database", "anope.db", 0); } EventReturn OnLoadDatabase() anope_override @@ -777,7 +778,7 @@ class DBPlain : public Module for (unsigned k = 0, end = ci->GetAccessCount(); k < end; ++k) { const ChanAccess *access = ci->GetAccess(k); - db_buffer << "MD ACCESS2 " << access->provider->name << " " << access->mask << " " << access->Serialize() << " " << access->last_seen << " " << access->creator << " " << access->created << endl; + db_buffer << "MD ACCESS2 " << access->provider->name << " " << access->mask << " " << access->AccessSerialize() << " " << access->last_seen << " " << access->creator << " " << access->created << endl; } for (unsigned k = 0, end = ci->GetAkickCount(); k < end; ++k) { @@ -835,7 +836,7 @@ class DBPlain : public Module //FOREACH_MOD(I_OnDatabaseWriteMetadata, OnDatabaseWriteMetadata(WriteMetadata, ci)); } - db_buffer << "OS STATS " << maxusercnt << " " << maxusertime << endl; + db_buffer << "OS STATS " << MaxUserCount << " " << MaxUserTime << endl; for (std::list<XLineManager *>::iterator it = XLineManager::XLineManagers.begin(), it_end = XLineManager::XLineManagers.end(); it != it_end; ++it) { @@ -843,7 +844,7 @@ class DBPlain : public Module for (unsigned i = 0, end = xl->GetCount(); i < end; ++i) { const XLine *x = xl->GetEntry(i); - db_buffer << "OS SXLINE " << xl->Type() << " " << x->GetUser() << " " << x->GetHost() << " " << x->By << " " << x->Created << " " << x->Expires << " :" << x->Reason << endl; + db_buffer << "OS SXLINE " << xl->Type() << " " << x->GetUser() << " " << x->GetHost() << " " << x->by << " " << x->created << " " << x->expires << " :" << x->reason << endl; } } @@ -861,7 +862,7 @@ class DBPlain : public Module if (!db.is_open()) { - ircdproto->SendGlobops(NULL, "Unable to open %s for writing!", DatabaseFile.c_str()); + IRCD->SendGlobops(NULL, "Unable to open %s for writing!", DatabaseFile.c_str()); return EVENT_CONTINUE; } diff --git a/modules/database/db_sql.cpp b/modules/database/db_sql.cpp index 48c813a3c..60db11c0d 100644 --- a/modules/database/db_sql.cpp +++ b/modules/database/db_sql.cpp @@ -33,7 +33,7 @@ class SQLSQLInterface : public SQLInterface class ResultSQLSQLInterface : public SQLSQLInterface { - dynamic_reference<Serializable> obj; + Reference<Serializable> obj; public: ResultSQLSQLInterface(Module *o, Serializable *ob) : SQLSQLInterface(o), obj(ob) { } @@ -55,10 +55,10 @@ public: class DBSQL : public Module, public Pipe { - service_reference<SQLProvider> sql; + ServiceReference<SQLProvider> sql; SQLSQLInterface sqlinterface; Anope::string prefix; - std::set<dynamic_reference<Serializable> > updated_items; + std::set<Reference<Serializable> > updated_items; bool shutting_down; void RunBackground(const SQLQuery &q, SQLInterface *iface = NULL) @@ -72,7 +72,7 @@ class DBSQL : public Module, public Pipe Log(this) << "db_sql: Unable to execute query, is SQL configured correctly?"; } } - else if (!quitting) + else if (!Anope::Quitting) { if (iface == NULL) iface = &this->sqlinterface; @@ -95,9 +95,9 @@ class DBSQL : public Module, public Pipe void OnNotify() anope_override { - for (std::set<dynamic_reference<Serializable> >::iterator it = this->updated_items.begin(), it_end = this->updated_items.end(); it != it_end; ++it) + for (std::set<Reference<Serializable> >::iterator it = this->updated_items.begin(), it_end = this->updated_items.end(); it != it_end; ++it) { - dynamic_reference<Serializable> obj = *it; + Reference<Serializable> obj = *it; if (obj && this->sql) { @@ -105,11 +105,11 @@ class DBSQL : public Module, public Pipe continue; obj->UpdateCache(); - SerializeType *s_type = obj->GetSerializableType(); + Serialize::Type *s_type = obj->GetSerializableType(); if (!s_type) continue; - Serialize::Data data = obj->serialize(); + Serialize::Data data = obj->Serialize(); std::vector<SQLQuery> create = this->sql->CreateTable(this->prefix + s_type->GetName(), data); for (unsigned i = 0; i < create.size(); ++i) @@ -127,7 +127,7 @@ class DBSQL : public Module, public Pipe { ConfigReader config; Anope::string engine = config.ReadValue("db_sql", "engine", "", 0); - this->sql = service_reference<SQLProvider>("SQLProvider", engine); + this->sql = ServiceReference<SQLProvider>("SQLProvider", engine); this->prefix = config.ReadValue("db_sql", "prefix", "anope_db_", 0); } @@ -150,10 +150,10 @@ class DBSQL : public Module, public Pipe return EVENT_CONTINUE; } - const std::vector<Anope::string> type_order = SerializeType::GetTypeOrder(); + const std::vector<Anope::string> type_order = Serialize::Type::GetTypeOrder(); for (unsigned i = 0; i < type_order.size(); ++i) { - SerializeType *sb = SerializeType::Find(type_order[i]); + Serialize::Type *sb = Serialize::Type::Find(type_order[i]); SQLQuery query("SELECT * FROM `" + this->prefix + sb->GetName() + "`"); SQLResult res = this->sql->RunQuery(query); @@ -192,7 +192,7 @@ class DBSQL : public Module, public Pipe void OnSerializableDestruct(Serializable *obj) anope_override { - SerializeType *s_type = obj->GetSerializableType(); + Serialize::Type *s_type = obj->GetSerializableType(); if (s_type) this->RunBackground("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + stringify(obj->id)); } diff --git a/modules/database/db_sql_live.cpp b/modules/database/db_sql_live.cpp index 3473fc1a9..00561592f 100644 --- a/modules/database/db_sql_live.cpp +++ b/modules/database/db_sql_live.cpp @@ -7,22 +7,20 @@ class DBMySQL : public Module, public Pipe private: Anope::string engine; Anope::string prefix; - service_reference<SQLProvider> SQL; + ServiceReference<SQLProvider> SQL; time_t lastwarn; bool ro; bool init; - std::set<dynamic_reference<Serializable> > updated_items; + std::set<Reference<Serializable> > updated_items; bool CheckSQL() { if (SQL) { - if (readonly && this->ro) + if (Anope::ReadOnly && this->ro) { - readonly = this->ro = false; - const BotInfo *bi = findbot(Config->OperServ); - if (bi) - ircdproto->SendGlobops(bi, "Found SQL again, going out of readonly mode..."); + Anope::ReadOnly = this->ro = false; + Log() << "Found SQL again, going out of readonly mode..."; } return true; @@ -31,10 +29,8 @@ class DBMySQL : public Module, public Pipe { if (Anope::CurTime - Config->UpdateTimeout > lastwarn) { - const BotInfo *bi = findbot(Config->OperServ); - if (bi) - ircdproto->SendGlobops(bi, "Unable to locate SQL reference, going to readonly..."); - readonly = this->ro = true; + Log() << "Unable to locate SQL reference, going to readonly..."; + Anope::ReadOnly = this->ro = true; this->lastwarn = Anope::CurTime; } @@ -85,9 +81,9 @@ class DBMySQL : public Module, public Pipe if (!this->CheckInit()) return; - for (std::set<dynamic_reference<Serializable> >::iterator it = this->updated_items.begin(), it_end = this->updated_items.end(); it != it_end; ++it) + for (std::set<Reference<Serializable> >::iterator it = this->updated_items.begin(), it_end = this->updated_items.end(); it != it_end; ++it) { - dynamic_reference<Serializable> obj = *it; + Reference<Serializable> obj = *it; if (obj && this->SQL) { @@ -95,11 +91,11 @@ class DBMySQL : public Module, public Pipe continue; obj->UpdateCache(); - SerializeType *s_type = obj->GetSerializableType(); + Serialize::Type *s_type = obj->GetSerializableType(); if (!s_type) continue; - Serialize::Data data = obj->serialize(); + Serialize::Data data = obj->Serialize(); std::vector<SQLQuery> create = this->SQL->CreateTable(this->prefix + s_type->GetName(), data); for (unsigned i = 0; i < create.size(); ++i) @@ -133,7 +129,7 @@ class DBMySQL : public Module, public Pipe { ConfigReader config; this->engine = config.ReadValue("db_sql", "engine", "", 0); - this->SQL = service_reference<SQLProvider>("SQLProvider", this->engine); + this->SQL = ServiceReference<SQLProvider>("SQLProvider", this->engine); this->prefix = config.ReadValue("db_sql", "prefix", "anope_db_", 0); } @@ -149,14 +145,14 @@ class DBMySQL : public Module, public Pipe { if (!this->CheckInit()) return; - SerializeType *s_type = obj->GetSerializableType(); + Serialize::Type *s_type = obj->GetSerializableType(); if (!s_type) return; this->RunQuery("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + stringify(obj->id)); s_type->objects.erase(obj->id); } - void OnSerializeCheck(SerializeType *obj) anope_override + void OnSerializeCheck(Serialize::Type *obj) anope_override { if (!this->CheckInit() || obj->GetTimestamp() == Anope::CurTime) return; @@ -189,7 +185,7 @@ class DBMySQL : public Module, public Pipe std::map<unsigned int, Serializable *>::iterator it = obj->objects.find(id); if (it != obj->objects.end()) { - it->second->destroy(); + it->second->Destroy(); obj->objects.erase(it); } } @@ -217,7 +213,7 @@ class DBMySQL : public Module, public Pipe } } else - s->destroy(); + s->Destroy(); } } diff --git a/modules/encryption/enc_md5.cpp b/modules/encryption/enc_md5.cpp index bcbe4aeed..45c7f3df5 100644 --- a/modules/encryption/enc_md5.cpp +++ b/modules/encryption/enc_md5.cpp @@ -341,7 +341,7 @@ class EMD5 : public Module void OnCheckAuthentication(User *, IdentifyRequest *req) anope_override { - const NickAlias *na = findnick(req->GetAccount()); + const NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) return; NickCore *nc = na->nc; @@ -361,7 +361,7 @@ class EMD5 : public Module * we want to re-encrypt the pass with the new encryption */ if (ModuleManager::FindFirstOf(ENCRYPTION) != this) - enc_encrypt(req->GetPassword(), nc->pass); + Anope::Encrypt(req->GetPassword(), nc->pass); req->Success(this); } } diff --git a/modules/encryption/enc_none.cpp b/modules/encryption/enc_none.cpp index 9496939fd..4854e5eb0 100644 --- a/modules/encryption/enc_none.cpp +++ b/modules/encryption/enc_none.cpp @@ -43,7 +43,7 @@ class ENone : public Module void OnCheckAuthentication(User *, IdentifyRequest *req) anope_override { - const NickAlias *na = findnick(req->GetAccount()); + const NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) return; NickCore *nc = na->nc; @@ -63,7 +63,7 @@ class ENone : public Module * we want to re-encrypt the pass with the new encryption */ if (ModuleManager::FindFirstOf(ENCRYPTION) != this) - enc_encrypt(req->GetPassword(), nc->pass); + Anope::Encrypt(req->GetPassword(), nc->pass); req->Success(this); } } diff --git a/modules/encryption/enc_old.cpp b/modules/encryption/enc_old.cpp index b5ce86540..f7c83515d 100644 --- a/modules/encryption/enc_old.cpp +++ b/modules/encryption/enc_old.cpp @@ -351,7 +351,7 @@ class EOld : public Module void OnCheckAuthentication(User *, IdentifyRequest *req) anope_override { - const NickAlias *na = findnick(req->GetAccount()); + const NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) return; NickCore *nc = na->nc; @@ -371,7 +371,7 @@ class EOld : public Module * we want to re-encrypt the pass with the new encryption */ if (ModuleManager::FindFirstOf(ENCRYPTION) != this) - enc_encrypt(req->GetPassword(), nc->pass); + Anope::Encrypt(req->GetPassword(), nc->pass); req->Success(this); } } diff --git a/modules/encryption/enc_sha1.cpp b/modules/encryption/enc_sha1.cpp index 28d216972..88571d776 100644 --- a/modules/encryption/enc_sha1.cpp +++ b/modules/encryption/enc_sha1.cpp @@ -194,7 +194,7 @@ class ESHA1 : public Module void OnCheckAuthentication(User *, IdentifyRequest *req) anope_override { - const NickAlias *na = findnick(req->GetAccount()); + const NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) return; NickCore *nc = na->nc; @@ -211,7 +211,7 @@ class ESHA1 : public Module if (nc->pass.equals_cs(buf)) { if (ModuleManager::FindFirstOf(ENCRYPTION) != this) - enc_encrypt(req->GetPassword(), nc->pass); + Anope::Encrypt(req->GetPassword(), nc->pass); req->Success(this); } } diff --git a/modules/encryption/enc_sha256.cpp b/modules/encryption/enc_sha256.cpp index 36eaa98fc..396f975ed 100644 --- a/modules/encryption/enc_sha256.cpp +++ b/modules/encryption/enc_sha256.cpp @@ -280,7 +280,7 @@ class ESHA256 : public Module void OnCheckAuthentication(User *, IdentifyRequest *req) anope_override { - const NickAlias *na = findnick(req->GetAccount()); + const NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) return; NickCore *nc = na->nc; @@ -303,7 +303,7 @@ class ESHA256 : public Module * we want to re-encrypt the pass with the new encryption */ if (ModuleManager::FindFirstOf(ENCRYPTION) != this) - enc_encrypt(req->GetPassword(), nc->pass); + Anope::Encrypt(req->GetPassword(), nc->pass); req->Success(this); } } diff --git a/modules/extra/bs_autoassign.cpp b/modules/extra/bs_autoassign.cpp index f290a3856..c84e18964 100644 --- a/modules/extra/bs_autoassign.cpp +++ b/modules/extra/bs_autoassign.cpp @@ -31,7 +31,7 @@ class BSAutoAssign : public Module if (this->bot.empty()) return; - BotInfo *bi = findbot(this->bot); + BotInfo *bi = BotInfo::Find(this->bot); if (bi == NULL) { Log(this) << "bs_autoassign is configured to assign bot " << this->bot << ", but it does not exist?"; diff --git a/modules/extra/httpd.h b/modules/extra/httpd.h index 490bf72bb..bf6a9838d 100644 --- a/modules/extra/httpd.h +++ b/modules/extra/httpd.h @@ -130,7 +130,7 @@ class HTTPClient : public ClientSocket, public BufferedSocket, public BinarySock bool ProcessWrite() anope_override { - return !BinarySocket::ProcessWrite() || BinarySocket::WriteBuffer.empty() ? false : true; + return !BinarySocket::ProcessWrite() || BinarySocket::write_buffer.empty() ? false : true; } void Write(const char *buffer, size_t l) anope_override diff --git a/modules/extra/m_chanstats.cpp b/modules/extra/m_chanstats.cpp index 1c37aa8ec..b50592b0f 100644 --- a/modules/extra/m_chanstats.cpp +++ b/modules/extra/m_chanstats.cpp @@ -21,7 +21,7 @@ class MySQLInterface : public SQLInterface class MChanstats : public Module { - service_reference<SQLProvider> sql; + ServiceReference<SQLProvider> sql; MySQLInterface sqlinterface; SQLQuery query; Anope::string SmileysHappy, SmileysSad, SmileysOther, prefix; @@ -359,7 +359,7 @@ class MChanstats : public Module SmileysOther = config.ReadValue("chanstats", "SmileysOther", ":/", 0); Anope::string engine = config.ReadValue("chanstats", "engine", "", 0); - this->sql = service_reference<SQLProvider>("SQLProvider", engine); + this->sql = ServiceReference<SQLProvider>("SQLProvider", engine); if (sql) this->CheckTables(); else @@ -367,7 +367,7 @@ class MChanstats : public Module } void OnTopicUpdated(Channel *c, const Anope::string &user, const Anope::string &topic) anope_override { - User *u = finduser(user); + User *u = User::Find(user); if (!u || !u->Account() || !c->ci || !c->ci->HasFlag(CI_STATS)) return; query = "CALL " + prefix + "chanstats_proc_update(@channel@, @nick@, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);"; diff --git a/modules/extra/m_dnsbl.cpp b/modules/extra/m_dnsbl.cpp index b860bd64c..54c802cd4 100644 --- a/modules/extra/m_dnsbl.cpp +++ b/modules/extra/m_dnsbl.cpp @@ -7,7 +7,7 @@ #include "module.h" -static service_reference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); +static ServiceReference<XLineManager> akills("XLineManager", "xlinemanager/sgline"); struct Blacklist { @@ -19,21 +19,21 @@ struct Blacklist Blacklist(const Anope::string &n, time_t b, const Anope::string &r, const std::map<int, Anope::string> &re) : name(n), bantime(b), reason(r), replies(re) { } }; -class DNSBLResolver : public DNSRequest +class DNSBLResolver : public DNS::Request { - dynamic_reference<User> user; + Reference<User> user; Blacklist blacklist; bool add_to_akill; public: - DNSBLResolver(Module *c, User *u, const Blacklist &b, const Anope::string &host, bool add_akill) : DNSRequest(host, DNS_QUERY_A, true, c), user(u), blacklist(b), add_to_akill(add_akill) { } + DNSBLResolver(Module *c, User *u, const Blacklist &b, const Anope::string &host, bool add_akill) : DNS::Request(host, DNS::QUERY_A, true, c), user(u), blacklist(b), add_to_akill(add_akill) { } - void OnLookupComplete(const DNSQuery *record) anope_override + void OnLookupComplete(const DNS::Query *record) anope_override { if (!user || user->HasExt("m_dnsbl_akilled")) return; - const ResourceRecord &ans_record = record->answers[0]; + const DNS::ResourceRecord &ans_record = record->answers[0]; // Replies should be in 127.0.0.0/24 if (ans_record.rdata.find("127.0.0.") != 0) return; @@ -61,8 +61,7 @@ class DNSBLResolver : public DNSRequest reason = reason.replace_all_cs("%r", record_reason); reason = reason.replace_all_cs("%N", Config->NetworkName); - const BotInfo *operserv = findbot(Config->OperServ); - Log(operserv) << "DNSBL: " << user->GetMask() << " (" << user->ip << ") appears in " << this->blacklist.name; + Log(OperServ) << "DNSBL: " << user->GetMask() << " (" << user->ip << ") appears in " << this->blacklist.name; XLine *x = new XLine("*@" + user->ip, Config->OperServ, Anope::CurTime + this->blacklist.bantime, reason, XLineManager::GenerateUID()); if (this->add_to_akill && akills) { @@ -71,8 +70,8 @@ class DNSBLResolver : public DNSRequest } else { - ircdproto->SendAkill(NULL, x); - x->destroy(); + IRCD->SendAkill(NULL, x); + x->Destroy(); } } }; @@ -110,7 +109,7 @@ class ModuleDNSBL : public Module if (bname.empty()) continue; Anope::string sbantime = config.ReadValue("blacklist", "time", "4h", i); - time_t bantime = dotime(sbantime); + time_t bantime = Anope::DoTime(sbantime); if (bantime < 0) bantime = 9000; Anope::string reason = config.ReadValue("blacklist", "reason", "", i); @@ -126,7 +125,7 @@ class ModuleDNSBL : public Module } } - void OnUserConnect(dynamic_reference<User> &user, bool &exempt) anope_override + void OnUserConnect(Reference<User> &user, bool &exempt) anope_override { if (exempt || !user || (!this->check_on_connect && !Me->IsSynced())) return; diff --git a/modules/extra/m_helpchan.cpp b/modules/extra/m_helpchan.cpp index 08f90b644..6b450e581 100644 --- a/modules/extra/m_helpchan.cpp +++ b/modules/extra/m_helpchan.cpp @@ -26,10 +26,10 @@ class HelpChannel : public Module { if (Name == CMODE_OP && c && c->ci && c->name.equals_ci(this->HelpChan)) { - User *u = finduser(param); + User *u = User::Find(param); if (u && c->ci->AccessFor(u).HasPriv("OPDEOPME")) - u->SetMode(findbot(Config->OperServ), UMODE_HELPOP); + u->SetMode(OperServ, UMODE_HELPOP); } return EVENT_CONTINUE; diff --git a/modules/extra/m_httpd.cpp b/modules/extra/m_httpd.cpp index f2704d77c..0176b955a 100644 --- a/modules/extra/m_httpd.cpp +++ b/modules/extra/m_httpd.cpp @@ -42,7 +42,7 @@ class MyHTTPClient : public HTTPClient HTTPMessage header; bool header_done, served; Anope::string page_name; - dynamic_reference<HTTPPage> page; + Reference<HTTPPage> page; Anope::string ip; enum @@ -114,7 +114,8 @@ class MyHTTPClient : public HTTPClient { if (this->action == ACTION_NONE) { - std::vector<Anope::string> params = BuildStringVector(buf); + std::vector<Anope::string> params; + spacesepstream(buf).GetTokens(params); if (params.empty() || (params[0] != "GET" && params[0] != "POST")) { @@ -189,11 +190,11 @@ class MyHTTPClient : public HTTPClient } catch (const ConvertException &) { } - if (this->extrabuf.length() == content_length) + if (this->extra_buf.length() == content_length) { - Log(LOG_DEBUG_2) << "HTTP POST from " << this->clientaddr.addr() << ": " << this->extrabuf; + Log(LOG_DEBUG_2) << "HTTP POST from " << this->clientaddr.addr() << ": " << this->extra_buf; - sepstream sep(this->extrabuf, '&'); + sepstream sep(this->extra_buf, '&'); Anope::string token; while (sep.GetToken(token)) @@ -204,7 +205,7 @@ class MyHTTPClient : public HTTPClient this->header.post_data[token.substr(0, sz)] = HTTPUtils::URLDecode(token.substr(sz + 1)); } - this->header.content = this->extrabuf; + this->header.content = this->extra_buf; this->Serve(); } } @@ -281,7 +282,7 @@ class MyHTTPProvider : public HTTPProvider, public CallBack { int timeout; std::map<Anope::string, HTTPPage *> pages; - std::list<dynamic_reference<MyHTTPClient> > clients; + std::list<Reference<MyHTTPClient> > clients; public: MyHTTPProvider(Module *c, const Anope::string &n, const Anope::string &i, const unsigned short p, const int t) : Socket(-1, i.find(':') != Anope::string::npos), HTTPProvider(c, n, i, p), CallBack(c, 10, Anope::CurTime, true), timeout(t) { } @@ -290,7 +291,7 @@ class MyHTTPProvider : public HTTPProvider, public CallBack { while (!this->clients.empty()) { - dynamic_reference<MyHTTPClient>& c = this->clients.front(); + Reference<MyHTTPClient>& c = this->clients.front(); if (c && c->created + this->timeout >= Anope::CurTime) break; @@ -326,7 +327,7 @@ class MyHTTPProvider : public HTTPProvider, public CallBack class HTTPD : public Module { - service_reference<SSLService> sslref; + ServiceReference<SSLService> sslref; std::map<Anope::string, HTTPProvider *> providers; public: HTTPD(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, SUPPORTED), sslref("SSLService", "ssl") @@ -432,7 +433,7 @@ class HTTPD : public Module p->ext_ip = ext_ip; - p->ext_headers = BuildStringVector(ext_header); + spacesepstream(ext_header).GetTokens(p->ext_headers); } for (std::map<Anope::string, HTTPProvider *>::iterator it = this->providers.begin(), it_end = this->providers.end(); it != it_end;) diff --git a/modules/extra/m_ldap_authentication.cpp b/modules/extra/m_ldap_authentication.cpp index f2140eb71..233a43dde 100644 --- a/modules/extra/m_ldap_authentication.cpp +++ b/modules/extra/m_ldap_authentication.cpp @@ -12,13 +12,13 @@ static Anope::string username_attribute; struct IdentifyInfo { - dynamic_reference<User> user; + Reference<User> user; IdentifyRequest *req; - service_reference<LDAPProvider> lprov; + ServiceReference<LDAPProvider> lprov; bool admin_bind; Anope::string dn; - IdentifyInfo(User *u, IdentifyRequest *r, service_reference<LDAPProvider> &lp) : user(u), req(r), lprov(lp), admin_bind(true) + IdentifyInfo(User *u, IdentifyRequest *r, ServiceReference<LDAPProvider> &lp) : user(u), req(r), lprov(lp), admin_bind(true) { req->Hold(me); } @@ -100,18 +100,17 @@ class IdentifyInterface : public LDAPInterface } else { - NickAlias *na = findnick(ii->req->GetAccount()); + NickAlias *na = NickAlias::Find(ii->req->GetAccount()); if (na == NULL) { na = new NickAlias(ii->req->GetAccount(), new NickCore(ii->req->GetAccount())); if (ii->user) { if (Config->NSAddAccessOnReg) - na->nc->AddAccess(create_mask(ii->user)); + na->nc->AddAccess(ii->user->Mask()); - const BotInfo *bi = findbot(Config->NickServ); - if (bi) - ii->user->SendMessage(bi, _("Your account \002%s\002 has been successfully created."), na->nick.c_str()); + if (NickServ) + ii->user->SendMessage(NickServ, _("Your account \002%s\002 has been successfully created."), na->nick.c_str()); } } na->nc->Extend("m_ldap_authentication_dn", new ExtensibleItemClass<Anope::string>(ii->dn)); @@ -155,7 +154,7 @@ class OnIdentifyInterface : public LDAPInterface std::map<LDAPQuery, Anope::string>::iterator it = this->requests.find(r.id); if (it == this->requests.end()) return; - User *u = finduser(it->second); + User *u = User::Find(it->second); this->requests.erase(it); if (!u || !u->Account() || r.empty()) @@ -169,9 +168,8 @@ class OnIdentifyInterface : public LDAPInterface if (!email.equals_ci(u->Account()->email)) { u->Account()->email = email; - BotInfo *bi = findbot(Config->NickServ); - if (bi) - u->SendMessage(bi, _("Your email has been updated to \002%s\002"), email.c_str()); + if (NickServ) + u->SendMessage(NickServ, _("Your email has been updated to \002%s\002"), email.c_str()); Log(this->owner) << "m_ldap_authentication: Updated email address for " << u->nick << " (" << u->Account()->display << ") to " << email; } } @@ -206,7 +204,7 @@ class OnRegisterInterface : public LDAPInterface class NSIdentifyLDAP : public Module { - service_reference<LDAPProvider> ldap; + ServiceReference<LDAPProvider> ldap; IdentifyInterface iinterface; OnIdentifyInterface oninterface; OnRegisterInterface orinterface; diff --git a/modules/extra/m_ldap_oper.cpp b/modules/extra/m_ldap_oper.cpp index 53b3d4d43..ed2f5900a 100644 --- a/modules/extra/m_ldap_oper.cpp +++ b/modules/extra/m_ldap_oper.cpp @@ -23,7 +23,7 @@ class IdentifyInterface : public LDAPInterface std::map<LDAPQuery, Anope::string>::iterator it = this->requests.find(r.id); if (it == this->requests.end()) return; - User *u = finduser(it->second); + User *u = User::Find(it->second); this->requests.erase(it); @@ -77,7 +77,7 @@ class IdentifyInterface : public LDAPInterface class LDAPOper : public Module { - service_reference<LDAPProvider> ldap; + ServiceReference<LDAPProvider> ldap; IdentifyInterface iinterface; Anope::string binddn; diff --git a/modules/extra/m_mysql.cpp b/modules/extra/m_mysql.cpp index 7f1f965cd..47f6f41de 100644 --- a/modules/extra/m_mysql.cpp +++ b/modules/extra/m_mysql.cpp @@ -376,10 +376,10 @@ std::vector<SQLQuery> MySQLService::CreateTable(const Anope::string &table, cons known_cols.insert(it->first); query_text += ", `" + it->first + "` "; - if (it->second.getType() == Serialize::DT_INT) + if (it->second.GetType() == Serialize::DT_INT) query_text += "int(11)"; - else if (it->second.getMax() > 0) - query_text += "varchar(" + stringify(it->second.getMax()) + ")"; + else if (it->second.GetMax() > 0) + query_text += "varchar(" + stringify(it->second.GetMax()) + ")"; else query_text += "text"; } @@ -395,10 +395,10 @@ std::vector<SQLQuery> MySQLService::CreateTable(const Anope::string &table, cons known_cols.insert(it->first); Anope::string query_text = "ALTER TABLE `" + table + "` ADD `" + it->first + "` "; - if (it->second.getType() == Serialize::DT_INT) + if (it->second.GetType() == Serialize::DT_INT) query_text += "int(11)"; - else if (it->second.getMax() > 0) - query_text += "varchar(" + stringify(it->second.getMax()) + ")"; + else if (it->second.GetMax() > 0) + query_text += "varchar(" + stringify(it->second.GetMax()) + ")"; else query_text += "text"; diff --git a/modules/extra/m_proxyscan.cpp b/modules/extra/m_proxyscan.cpp index 00519c57f..6d2a6b7b0 100644 --- a/modules/extra/m_proxyscan.cpp +++ b/modules/extra/m_proxyscan.cpp @@ -36,7 +36,7 @@ class ProxyCallbackListener : public ListenSocket bool ProcessWrite() anope_override { - return !BufferedSocket::ProcessWrite() || this->WriteBuffer.empty() ? false : true; + return !BufferedSocket::ProcessWrite() || this->write_buffer.empty() ? false : true; } }; @@ -53,7 +53,7 @@ class ProxyCallbackListener : public ListenSocket class ProxyConnect : public ConnectionSocket { - static service_reference<XLineManager> akills; + static ServiceReference<XLineManager> akills; public: static std::set<ProxyConnect *> proxies; @@ -85,7 +85,7 @@ class ProxyConnect : public ConnectionSocket reason = reason.replace_all_cs("%i", this->conaddr.addr()); reason = reason.replace_all_cs("%p", stringify(this->conaddr.port())); - Log(findbot(Config->OperServ)) << "PROXYSCAN: Open " << this->GetType() << " proxy found on " << this->conaddr.addr() << ":" << this->conaddr.port() << " (" << reason << ")"; + Log(OperServ) << "PROXYSCAN: Open " << this->GetType() << " proxy found on " << this->conaddr.addr() << ":" << this->conaddr.port() << " (" << reason << ")"; XLine *x = new XLine("*@" + this->conaddr.addr(), Config->OperServ, Anope::CurTime + this->proxy.duration, reason, XLineManager::GenerateUID()); if (add_to_akill && akills) { @@ -94,15 +94,15 @@ class ProxyConnect : public ConnectionSocket } else { - if (ircdproto->CanSZLine) - ircdproto->SendSZLine(NULL, x); + if (IRCD->CanSZLine) + IRCD->SendSZLine(NULL, x); else - ircdproto->SendAkill(NULL, x); - x->destroy(); + IRCD->SendAkill(NULL, x); + x->Destroy(); } } }; -service_reference<XLineManager> ProxyConnect::akills("XLineManager", "xlinemanager/sgline"); +ServiceReference<XLineManager> ProxyConnect::akills("XLineManager", "xlinemanager/sgline"); std::set<ProxyConnect *> ProxyConnect::proxies; class HTTPProxyConnect : public ProxyConnect, public BufferedSocket @@ -255,7 +255,7 @@ class ModuleProxyScan : public Module ++it; ClientSocket *cs = dynamic_cast<ClientSocket *>(s); - if (cs != NULL && cs->LS == this->listener) + if (cs != NULL && cs->ls == this->listener) delete s; } @@ -332,7 +332,7 @@ class ModuleProxyScan : public Module if (p.ports.empty()) continue; - p.duration = dotime(config.ReadValue("proxyscan", "time", "4h", i)); + p.duration = Anope::DoTime(config.ReadValue("proxyscan", "time", "4h", i)); p.reason = config.ReadValue("proxyscan", "reason", "", i); if (p.reason.empty()) continue; @@ -341,7 +341,7 @@ class ModuleProxyScan : public Module } } - void OnUserConnect(dynamic_reference<User> &user, bool &exempt) anope_override + void OnUserConnect(Reference<User> &user, bool &exempt) anope_override { if (exempt || !user || !Me->IsSynced() || !user->server->IsSynced()) return; @@ -360,7 +360,7 @@ class ModuleProxyScan : public Module if (!this->con_notice.empty() && !this->con_source.empty()) { - const BotInfo *bi = findbot(this->con_source); + const BotInfo *bi = BotInfo::Find(this->con_source); if (bi) user->SendMessage(bi, this->con_notice); } diff --git a/modules/extra/m_rewrite.cpp b/modules/extra/m_rewrite.cpp index 6d8690960..70710bd8a 100644 --- a/modules/extra/m_rewrite.cpp +++ b/modules/extra/m_rewrite.cpp @@ -13,7 +13,8 @@ struct Rewrite bool Matches(const std::vector<Anope::string> &message) { - std::vector<Anope::string> sm = BuildStringVector(this->source_message); + std::vector<Anope::string> sm; + spacesepstream(this->source_message).GetTokens(sm); for (unsigned i = 0; i < sm.size(); ++i) if (sm[i] != "$" && !sm[i].equals_ci(message[i])) @@ -106,7 +107,8 @@ class ModuleRewrite : public Module EventReturn OnBotPrivmsg(User *u, BotInfo *bi, Anope::string &message) anope_override { - std::vector<Anope::string> tokens = BuildStringVector(message); + std::vector<Anope::string> tokens; + spacesepstream(message).GetTokens(tokens); for (unsigned i = 0; i < this->rewrites.size(); ++i) { Rewrite &rw = this->rewrites[i]; diff --git a/modules/extra/m_sql_authentication.cpp b/modules/extra/m_sql_authentication.cpp index 9412edc50..ce7a275b3 100644 --- a/modules/extra/m_sql_authentication.cpp +++ b/modules/extra/m_sql_authentication.cpp @@ -5,7 +5,7 @@ static Module *me; class SQLAuthenticationResult : public SQLInterface { - dynamic_reference<User> user; + Reference<User> user; IdentifyRequest *req; public: @@ -37,26 +37,25 @@ class SQLAuthenticationResult : public SQLInterface } catch (const SQLException &) { } - const BotInfo *bi = findbot(Config->NickServ); - NickAlias *na = findnick(req->GetAccount()); + NickAlias *na = NickAlias::Find(req->GetAccount()); if (na == NULL) { na = new NickAlias(req->GetAccount(), new NickCore(req->GetAccount())); if (user) { if (Config->NSAddAccessOnReg) - na->nc->AddAccess(create_mask(user)); + na->nc->AddAccess(user->Mask()); - if (bi) - user->SendMessage(bi, _("Your account \002%s\002 has been successfully created."), na->nick.c_str()); + if (NickServ) + user->SendMessage(NickServ, _("Your account \002%s\002 has been successfully created."), na->nick.c_str()); } } if (!email.empty() && email != na->nc->email) { na->nc->email = email; - if (user && bi) - user->SendMessage(bi, _("Your email has been updated to \002%s\002."), email.c_str()); + if (user && NickServ) + user->SendMessage(NickServ, _("Your email has been updated to \002%s\002."), email.c_str()); } req->Success(me); @@ -77,7 +76,7 @@ class ModuleSQLAuthentication : public Module bool disable_register; Anope::string disable_reason; - service_reference<SQLProvider> SQL; + ServiceReference<SQLProvider> SQL; public: ModuleSQLAuthentication(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, SUPPORTED) @@ -101,7 +100,7 @@ class ModuleSQLAuthentication : public Module this->disable_register = config.ReadFlag("m_sql_authentication", "disable_ns_register", "false", 0); this->disable_reason = config.ReadValue("m_sql_authentication", "disable_reason", "", 0); - this->SQL = service_reference<SQLProvider>("SQLProvider", this->engine); + this->SQL = ServiceReference<SQLProvider>("SQLProvider", this->engine); } EventReturn OnPreCommand(CommandSource &source, Command *command, std::vector<Anope::string> ¶ms) anope_override diff --git a/modules/extra/m_sql_oper.cpp b/modules/extra/m_sql_oper.cpp index 22218a646..523272a49 100644 --- a/modules/extra/m_sql_oper.cpp +++ b/modules/extra/m_sql_oper.cpp @@ -3,7 +3,7 @@ class SQLOperResult : public SQLInterface { - dynamic_reference<User> user; + Reference<User> user; struct SQLOperResultDeleter { @@ -51,7 +51,7 @@ class SQLOperResult : public SQLInterface delete user->Account()->o; user->Account()->o = NULL; Log(this->owner) << "m_sql_oper: Removed services operator from " << user->nick << " (" << user->Account()->display << ")"; - user->RemoveMode(findbot(Config->OperServ), UMODE_OPER); // Probably not set, just incase + user->RemoveMode(OperServ, UMODE_OPER); // Probably not set, just incase } return; } @@ -72,10 +72,10 @@ class SQLOperResult : public SQLInterface if (!user->HasMode(UMODE_OPER)) { - ircdproto->SendOper(user); + IRCD->SendOper(user); if (!modes.empty()) - user->SetModes(findbot(Config->OperServ), "%s", modes.c_str()); + user->SetModes(OperServ, "%s", modes.c_str()); } } @@ -91,7 +91,7 @@ class ModuleSQLOper : public Module Anope::string engine; Anope::string query; - service_reference<SQLProvider> SQL; + ServiceReference<SQLProvider> SQL; public: ModuleSQLOper(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, SUPPORTED) @@ -111,7 +111,7 @@ class ModuleSQLOper : public Module this->engine = config.ReadValue("m_sql_oper", "engine", "", 0); this->query = config.ReadValue("m_sql_oper", "query", "", 0); - this->SQL = service_reference<SQLProvider>("SQLProvider", this->engine); + this->SQL = ServiceReference<SQLProvider>("SQLProvider", this->engine); } void OnNickIdentify(User *u) anope_override diff --git a/modules/extra/m_sqlite.cpp b/modules/extra/m_sqlite.cpp index f0db04c66..971345475 100644 --- a/modules/extra/m_sqlite.cpp +++ b/modules/extra/m_sqlite.cpp @@ -107,7 +107,7 @@ class ModuleSQLite : public Module if (this->SQLiteServices.find(connname) == this->SQLiteServices.end()) { - Anope::string database = db_dir + "/" + config.ReadValue("sqlite", "database", "anope", i); + Anope::string database = Anope::DataDir + "/" + config.ReadValue("sqlite", "database", "anope", i); try { @@ -214,7 +214,7 @@ std::vector<SQLQuery> SQLiteService::CreateTable(const Anope::string &table, con known_cols.insert(it->first); query_text += ", `" + it->first + "` "; - if (it->second.getType() == Serialize::DT_INT) + if (it->second.GetType() == Serialize::DT_INT) query_text += "int(11)"; else query_text += "text"; @@ -242,7 +242,7 @@ std::vector<SQLQuery> SQLiteService::CreateTable(const Anope::string &table, con known_cols.insert(it->first); Anope::string query_text = "ALTER TABLE `" + table + "` ADD `" + it->first + "` "; - if (it->second.getType() == Serialize::DT_INT) + if (it->second.GetType() == Serialize::DT_INT) query_text += "int(11)"; else query_text += "text"; diff --git a/modules/extra/m_ssl.cpp b/modules/extra/m_ssl.cpp index 2f72744c7..fdde28919 100644 --- a/modules/extra/m_ssl.cpp +++ b/modules/extra/m_ssl.cpp @@ -110,7 +110,7 @@ class SSLModule : public Module this->OnReload(); - if (IsFile(this->certfile.c_str())) + if (Anope::IsFile(this->certfile.c_str())) { if (!SSL_CTX_use_certificate_file(client_ctx, this->certfile.c_str(), SSL_FILETYPE_PEM) || !SSL_CTX_use_certificate_file(server_ctx, this->certfile.c_str(), SSL_FILETYPE_PEM)) { @@ -124,7 +124,7 @@ class SSLModule : public Module else Log() << "Unable to open certificate " << this->certfile; - if (IsFile(this->keyfile.c_str())) + if (Anope::IsFile(this->keyfile.c_str())) { if (!SSL_CTX_use_PrivateKey_file(client_ctx, this->keyfile.c_str(), SSL_FILETYPE_PEM) || !SSL_CTX_use_PrivateKey_file(server_ctx, this->keyfile.c_str(), SSL_FILETYPE_PEM)) { @@ -137,7 +137,7 @@ class SSLModule : public Module } else { - if (IsFile(this->certfile.c_str())) + if (Anope::IsFile(this->certfile.c_str())) { SSL_CTX_free(client_ctx); SSL_CTX_free(server_ctx); @@ -168,7 +168,7 @@ class SSLModule : public Module Socket *s = it->second; ++it; - if (dynamic_cast<SSLSocketIO *>(s->IO)) + if (dynamic_cast<SSLSocketIO *>(s->io)) delete s; } @@ -188,7 +188,7 @@ class SSLModule : public Module { ConfigReader config; - if (config.ReadFlag("uplink", "ssl", "no", CurrentUplink)) + if (config.ReadFlag("uplink", "ssl", "no", Anope::CurrentUplink)) { this->service.Init(UplinkSock); } @@ -201,10 +201,10 @@ MySSLService::MySSLService(Module *o, const Anope::string &n) : SSLService(o, n) void MySSLService::Init(Socket *s) { - if (s->IO != &normalSocketIO) + if (s->io != &NormalSocketIO) throw CoreException("Socket initializing SSL twice"); - s->IO = new SSLSocketIO(); + s->io = new SSLSocketIO(); } SSLSocketIO::SSLSocketIO() @@ -228,7 +228,7 @@ int SSLSocketIO::Send(Socket *s, const char *buf, size_t sz) ClientSocket *SSLSocketIO::Accept(ListenSocket *s) { - if (s->IO == &normalSocketIO) + if (s->io == &NormalSocketIO) throw SocketException("Attempting to accept on uninitialized socket with SSL"); sockaddrs conaddr; @@ -245,15 +245,15 @@ ClientSocket *SSLSocketIO::Accept(ListenSocket *s) ClientSocket *newsocket = s->OnAccept(newsock, conaddr); me->service.Init(newsocket); - SSLSocketIO *IO = anope_dynamic_static_cast<SSLSocketIO *>(newsocket->IO); + SSLSocketIO *io = anope_dynamic_static_cast<SSLSocketIO *>(newsocket->io); - IO->sslsock = SSL_new(server_ctx); - if (!IO->sslsock) + io->sslsock = SSL_new(server_ctx); + if (!io->sslsock) throw SocketException("Unable to initialize SSL socket"); - SSL_set_accept_state(IO->sslsock); + SSL_set_accept_state(io->sslsock); - if (!SSL_set_fd(IO->sslsock, newsocket->GetFD())) + if (!SSL_set_fd(io->sslsock, newsocket->GetFD())) throw SocketException("Unable to set SSL fd"); newsocket->SetFlag(SF_ACCEPTING); @@ -264,19 +264,19 @@ ClientSocket *SSLSocketIO::Accept(ListenSocket *s) SocketFlag SSLSocketIO::FinishAccept(ClientSocket *cs) { - if (cs->IO == &normalSocketIO) + if (cs->io == &NormalSocketIO) throw SocketException("Attempting to finish connect uninitialized socket with SSL"); else if (cs->HasFlag(SF_ACCEPTED)) return SF_ACCEPTED; else if (!cs->HasFlag(SF_ACCEPTING)) throw SocketException("SSLSocketIO::FinishAccept called for a socket not accepted nor accepting?"); - SSLSocketIO *IO = anope_dynamic_static_cast<SSLSocketIO *>(cs->IO); + SSLSocketIO *io = anope_dynamic_static_cast<SSLSocketIO *>(cs->io); - int ret = SSL_accept(IO->sslsock); + int ret = SSL_accept(io->sslsock); if (ret <= 0) { - int error = SSL_get_error(IO->sslsock, ret); + int error = SSL_get_error(io->sslsock, ret); if (ret == -1 && (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)) { SocketEngine::Change(cs, error == SSL_ERROR_WANT_WRITE, SF_WRITABLE); @@ -304,7 +304,7 @@ SocketFlag SSLSocketIO::FinishAccept(ClientSocket *cs) void SSLSocketIO::Connect(ConnectionSocket *s, const Anope::string &target, int port) { - if (s->IO == &normalSocketIO) + if (s->io == &NormalSocketIO) throw SocketException("Attempting to connect uninitialized socket with SSL"); s->UnsetFlag(SF_CONNECTING); @@ -336,29 +336,29 @@ void SSLSocketIO::Connect(ConnectionSocket *s, const Anope::string &target, int SocketFlag SSLSocketIO::FinishConnect(ConnectionSocket *s) { - if (s->IO == &normalSocketIO) + if (s->io == &NormalSocketIO) throw SocketException("Attempting to finish connect uninitialized socket with SSL"); else if (s->HasFlag(SF_CONNECTED)) return SF_CONNECTED; else if (!s->HasFlag(SF_CONNECTING)) throw SocketException("SSLSocketIO::FinishConnect called for a socket not connected nor connecting?"); - SSLSocketIO *IO = anope_dynamic_static_cast<SSLSocketIO *>(s->IO); + SSLSocketIO *io = anope_dynamic_static_cast<SSLSocketIO *>(s->io); - if (IO->sslsock == NULL) + if (io->sslsock == NULL) { - IO->sslsock = SSL_new(client_ctx); - if (!IO->sslsock) + io->sslsock = SSL_new(client_ctx); + if (!io->sslsock) throw SocketException("Unable to initialize SSL socket"); - if (!SSL_set_fd(IO->sslsock, s->GetFD())) + if (!SSL_set_fd(io->sslsock, s->GetFD())) throw SocketException("Unable to set SSL fd"); } - int ret = SSL_connect(IO->sslsock); + int ret = SSL_connect(io->sslsock); if (ret <= 0) { - int error = SSL_get_error(IO->sslsock, ret); + int error = SSL_get_error(io->sslsock, ret); if (ret == -1 && (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)) { SocketEngine::Change(s, error == SSL_ERROR_WANT_WRITE, SF_WRITABLE); diff --git a/modules/extra/m_statusupdate.cpp b/modules/extra/m_statusupdate.cpp index 7cbd9c7be..41ea8833e 100644 --- a/modules/extra/m_statusupdate.cpp +++ b/modules/extra/m_statusupdate.cpp @@ -43,7 +43,7 @@ class StatusUpdate : public Module for (int i = 0; !modeInfo[i].priv.empty(); ++i) if (!access->HasPriv(modeInfo[i].priv)) ci->c->RemoveMode(NULL, modeInfo[i].name, user->nick); - chan_set_correct_modes(user, ci->c, 1, false); + ci->c->SetCorrectModes(user, true, false); } } } diff --git a/modules/extra/m_xmlrpc.cpp b/modules/extra/m_xmlrpc.cpp index 2ff648812..a3b999a5e 100644 --- a/modules/extra/m_xmlrpc.cpp +++ b/modules/extra/m_xmlrpc.cpp @@ -157,7 +157,7 @@ class MyXMLRPCServiceInterface : public XMLRPCServiceInterface, public HTTPPage class ModuleXMLRPC : public Module { - service_reference<HTTPProvider> httpref; + ServiceReference<HTTPProvider> httpref; public: MyXMLRPCServiceInterface xmlrpcinterface; @@ -183,7 +183,7 @@ class ModuleXMLRPC : public Module void OnReload() anope_override { ConfigReader config; - httpref = service_reference<HTTPProvider>("HTTPProvider", "httpd/main"); + httpref = ServiceReference<HTTPProvider>("HTTPProvider", "httpd/main"); } }; diff --git a/modules/extra/m_xmlrpc_main.cpp b/modules/extra/m_xmlrpc_main.cpp index 4bd9c0ec6..672ef5524 100644 --- a/modules/extra/m_xmlrpc_main.cpp +++ b/modules/extra/m_xmlrpc_main.cpp @@ -8,8 +8,8 @@ class XMLRPCIdentifyRequest : public IdentifyRequest XMLRPCRequest request; HTTPReply repl; /* Request holds a reference to the HTTPReply, because we might exist long enough to invalidate it we'll copy it here then reset the reference before we use it */ - dynamic_reference<HTTPClient> client; - dynamic_reference<XMLRPCServiceInterface> xinterface; + Reference<HTTPClient> client; + Reference<XMLRPCServiceInterface> xinterface; public: XMLRPCIdentifyRequest(Module *m, XMLRPCRequest& req, HTTPClient *c, XMLRPCServiceInterface* iface, const Anope::string &acc, const Anope::string &pass) : IdentifyRequest(m, acc, pass), request(req), repl(request.r), client(c), xinterface(iface) { } @@ -74,14 +74,14 @@ class MyXMLRPCEvent : public XMLRPCEvent request.reply("error", "Invalid parameters"); else { - BotInfo *bi = findbot(service); + BotInfo *bi = BotInfo::Find(service); if (!bi) request.reply("error", "Invalid service"); else { request.reply("result", "Success"); - NickAlias *na = findnick(user); + NickAlias *na = NickAlias::Find(user); Anope::string out; @@ -127,18 +127,18 @@ class MyXMLRPCEvent : public XMLRPCEvent void DoStats(XMLRPCServiceInterface *iface, HTTPClient *client, XMLRPCRequest &request) { - request.reply("uptime", stringify(Anope::CurTime - start_time)); + request.reply("uptime", stringify(Anope::CurTime - Anope::StartTime)); request.reply("uplinkname", Me->GetLinks().front()->GetName()); { Anope::string buf; - for (std::set<Anope::string>::iterator it = Capab.begin(); it != Capab.end(); ++it) + for (std::set<Anope::string>::iterator it = Servers::Capab.begin(); it != Servers::Capab.end(); ++it) buf += " " + *it; if (!buf.empty()) buf.erase(buf.begin()); request.reply("uplinkcapab", buf); } - request.reply("usercount", stringify(usercnt)); - request.reply("maxusercount", stringify(maxusercnt)); + request.reply("usercount", stringify(UserListByNick.size())); + request.reply("maxusercount", stringify(MaxUserCount)); request.reply("channelcount", stringify(ChannelList.size())); } @@ -147,7 +147,7 @@ class MyXMLRPCEvent : public XMLRPCEvent if (request.data.empty()) return; - Channel *c = findchan(request.data[0]); + Channel *c = Channel::Find(request.data[0]); request.reply("name", iface->Sanitize(c ? c->name : request.data[0])); @@ -175,7 +175,7 @@ class MyXMLRPCEvent : public XMLRPCEvent for (CUserList::const_iterator it = c->users.begin(); it != c->users.end(); ++it) { UserContainer *uc = *it; - users += uc->Status->BuildModePrefixList() + uc->user->nick + " "; + users += uc->status->BuildModePrefixList() + uc->user->nick + " "; } if (!users.empty()) { @@ -199,7 +199,7 @@ class MyXMLRPCEvent : public XMLRPCEvent if (request.data.empty()) return; - User *u = finduser(request.data[0]); + User *u = User::Find(request.data[0]); request.reply("nick", iface->Sanitize(u ? u->nick : request.data[0])); @@ -227,7 +227,7 @@ class MyXMLRPCEvent : public XMLRPCEvent for (UChannelList::const_iterator it = u->chans.begin(); it != u->chans.end(); ++it) { ChannelContainer *cc = *it; - channels += cc->Status->BuildModePrefixList() + cc->chan->name + " "; + channels += cc->status->BuildModePrefixList() + cc->chan->name + " "; } if (!channels.empty()) { @@ -253,7 +253,7 @@ class MyXMLRPCEvent : public XMLRPCEvent class ModuleXMLRPCMain : public Module { - service_reference<XMLRPCServiceInterface> xmlrpc; + ServiceReference<XMLRPCServiceInterface> xmlrpc; MyXMLRPCEvent stats; diff --git a/modules/extra/webcpanel/pages/chanserv/access.cpp b/modules/extra/webcpanel/pages/chanserv/access.cpp index a1b8be97f..d21546c3a 100644 --- a/modules/extra/webcpanel/pages/chanserv/access.cpp +++ b/modules/extra/webcpanel/pages/chanserv/access.cpp @@ -22,7 +22,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s return true; } - ChannelInfo *ci = cs_findchan(chname); + ChannelInfo *ci = ChannelInfo::Find(chname); if (!ci) return true; @@ -64,7 +64,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s if (acc->mask == message.post_data["mask"]) { - if ((!highest || *acc >= *highest) && !u_access.Founder && !has_priv) + if ((!highest || *acc >= *highest) && !u_access.founder && !has_priv) { replacements["MESSAGES"] = "Access denied"; denied = true; @@ -85,7 +85,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s new_acc->creator = na->nc->display; try { - new_acc->Unserialize(message.post_data["access"]); + new_acc->AccessUnserialize(message.post_data["access"]); } catch (...) { @@ -98,7 +98,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s new_acc->last_seen = 0; new_acc->created = Anope::CurTime; - if ((!highest || *highest <= *new_acc) && !u_access.Founder && !has_priv) + if ((!highest || *highest <= *new_acc) && !u_access.founder && !has_priv) delete new_acc; else if (new_acc->Serialize().empty()) { @@ -108,7 +108,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s else { ci->AddAccess(new_acc); - replacements["MESSAGES"] = "Access for " + new_acc->mask + " set to " + new_acc->Serialize(); + replacements["MESSAGES"] = "Access for " + new_acc->mask + " set to " + new_acc->AccessSerialize(); } } } @@ -123,7 +123,7 @@ bool WebCPanel::ChanServ::Access::OnRequest(HTTPProvider *server, const Anope::s ChanAccess *access = ci->GetAccess(i); replacements["MASKS"] = HTTPUtils::Escape(access->mask); - replacements["ACCESSES"] = HTTPUtils::Escape(access->Serialize()); + replacements["ACCESSES"] = HTTPUtils::Escape(access->AccessSerialize()); replacements["CREATORS"] = HTTPUtils::Escape(access->creator); replacements["ACCESS_CHANGES"] = ci->AccessFor(na->nc).HasPriv("ACCESS_CHANGE") ? "YES" : "NO"; } diff --git a/modules/extra/webcpanel/pages/chanserv/akick.cpp b/modules/extra/webcpanel/pages/chanserv/akick.cpp index d5351bfd9..bb678b715 100644 --- a/modules/extra/webcpanel/pages/chanserv/akick.cpp +++ b/modules/extra/webcpanel/pages/chanserv/akick.cpp @@ -22,7 +22,7 @@ bool WebCPanel::ChanServ::Akick::OnRequest(HTTPProvider *server, const Anope::st return true; } - ChannelInfo *ci = cs_findchan(chname); + ChannelInfo *ci = ChannelInfo::Find(chname); if (!ci) return true; diff --git a/modules/extra/webcpanel/pages/chanserv/set.cpp b/modules/extra/webcpanel/pages/chanserv/set.cpp index 4ad551e6a..4a61b37db 100644 --- a/modules/extra/webcpanel/pages/chanserv/set.cpp +++ b/modules/extra/webcpanel/pages/chanserv/set.cpp @@ -22,7 +22,7 @@ bool WebCPanel::ChanServ::Set::OnRequest(HTTPProvider *server, const Anope::stri return true; } - ChannelInfo *ci = cs_findchan(chname); + ChannelInfo *ci = ChannelInfo::Find(chname); if (!ci || !ci->AccessFor(na->nc).HasPriv("SET")) return true; @@ -93,8 +93,8 @@ bool WebCPanel::ChanServ::Set::OnRequest(HTTPProvider *server, const Anope::stri replacements["FOUNDER"] = ci->GetFounder()->display; if (ci->successor) replacements["SUCCESSOR"] = ci->successor->display; - replacements["TIME_REGISTERED"] = do_strftime(ci->time_registered, na->nc); - replacements["LAST_USED"] = do_strftime(ci->last_used, na->nc); + replacements["TIME_REGISTERED"] = Anope::strftime(ci->time_registered, na->nc); + replacements["LAST_USED"] = Anope::strftime(ci->last_used, na->nc); if (!ci->last_topic.empty()) { diff --git a/modules/extra/webcpanel/pages/index.cpp b/modules/extra/webcpanel/pages/index.cpp index c97737c21..6178dab29 100644 --- a/modules/extra/webcpanel/pages/index.cpp +++ b/modules/extra/webcpanel/pages/index.cpp @@ -11,9 +11,9 @@ class WebpanelRequest : public IdentifyRequest { HTTPReply reply; HTTPMessage message; - dynamic_reference<HTTPProvider> server; + Reference<HTTPProvider> server; Anope::string page_name; - dynamic_reference<HTTPClient> client; + Reference<HTTPClient> client; TemplateFileServer::Replacements replacements; public: @@ -23,7 +23,7 @@ class WebpanelRequest : public IdentifyRequest { if (!client) return; - NickAlias *na = findnick(this->GetAccount()); + NickAlias *na = NickAlias::Find(this->GetAccount()); if (!na) { this->OnFail(); diff --git a/modules/extra/webcpanel/pages/memoserv/memos.cpp b/modules/extra/webcpanel/pages/memoserv/memos.cpp index 00b913ef0..54c7a1227 100644 --- a/modules/extra/webcpanel/pages/memoserv/memos.cpp +++ b/modules/extra/webcpanel/pages/memoserv/memos.cpp @@ -36,7 +36,7 @@ bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::st } else { - ci = cs_findchan(chname); + ci = ChannelInfo::Find(chname); if (ci) { replacements["MESSAGES"] = "Displaying the memos for " + chname + "."; @@ -107,7 +107,7 @@ bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::st m = mi->GetMemo(i); replacements["NUMBER"] = stringify(i+1); replacements["SENDER"] = m->sender; - replacements["TIME"] = do_strftime(m->time); + replacements["TIME"] = Anope::strftime(m->time); replacements["TEXT"] = m->text; if (m->HasFlag(MF_UNREAD)) replacements["UNREAD"] = "YES"; diff --git a/modules/extra/webcpanel/pages/nickserv/alist.cpp b/modules/extra/webcpanel/pages/nickserv/alist.cpp index 2fd184dbb..3b5b8dab0 100644 --- a/modules/extra/webcpanel/pages/nickserv/alist.cpp +++ b/modules/extra/webcpanel/pages/nickserv/alist.cpp @@ -39,7 +39,7 @@ bool WebCPanel::NickServ::Alist::OnRequest(HTTPProvider *server, const Anope::st replacements["CHANNELS"] = (ci->HasFlag(CI_NO_EXPIRE) ? "!" : "") + ci->name; Anope::string access_str; for (unsigned i = 0; i < access.size(); ++i) - access_str += ", " + access[i]->Serialize(); + access_str += ", " + access[i]->AccessSerialize(); replacements["ACCESSES"] = access_str.substr(2); } diff --git a/modules/extra/webcpanel/pages/nickserv/info.cpp b/modules/extra/webcpanel/pages/nickserv/info.cpp index 3ec61b03f..cdd80b7cd 100644 --- a/modules/extra/webcpanel/pages/nickserv/info.cpp +++ b/modules/extra/webcpanel/pages/nickserv/info.cpp @@ -19,7 +19,7 @@ bool WebCPanel::NickServ::Info::OnRequest(HTTPProvider *server, const Anope::str { if (message.post_data["email"] != na->nc->email) { - if (!message.post_data["email"].empty() && !MailValidate(message.post_data["email"])) + if (!message.post_data["email"].empty() && !Mail::Validate(message.post_data["email"])) replacements["ERRORS"] = "Invalid email"; else { @@ -83,7 +83,7 @@ bool WebCPanel::NickServ::Info::OnRequest(HTTPProvider *server, const Anope::str replacements["DISPLAY"] = HTTPUtils::Escape(na->nc->display); if (na->nc->email.empty() == false) replacements["EMAIL"] = HTTPUtils::Escape(na->nc->email); - replacements["TIME_REGISTERED"] = do_strftime(na->time_registered, na->nc); + replacements["TIME_REGISTERED"] = Anope::strftime(na->time_registered, na->nc); if (na->HasVhost()) { if (na->GetVhostIdent().empty() == false) diff --git a/modules/extra/webcpanel/pages/operserv/akill.cpp b/modules/extra/webcpanel/pages/operserv/akill.cpp index 3d66b5c6a..112949d9e 100644 --- a/modules/extra/webcpanel/pages/operserv/akill.cpp +++ b/modules/extra/webcpanel/pages/operserv/akill.cpp @@ -14,7 +14,7 @@ WebCPanel::OperServ::Akill::Akill(const Anope::string &cat, const Anope::string bool WebCPanel::OperServ::Akill::OnRequest(HTTPProvider *server, const Anope::string &page_name, HTTPClient *client, HTTPMessage &message, HTTPReply &reply, NickAlias *na, TemplateFileServer::Replacements &replacements) { - static service_reference<XLineManager> akills("XLineManager","xlinemanager/sgline"); + static ServiceReference<XLineManager> akills("XLineManager","xlinemanager/sgline"); if (!na->nc->IsServicesOper() && !(na->nc->o && na->nc->o->ot && na->nc->o->ot->HasPriv("operserv/akill"))) { @@ -28,7 +28,7 @@ bool WebCPanel::OperServ::Akill::OnRequest(HTTPProvider *server, const Anope::st if (message.post_data.count("mask") > 0 && message.post_data.count("expiry") > 0 && message.post_data.count("reason") > 0) { std::vector<Anope::string> params; - stringstream cmdstr; + std::stringstream cmdstr; params.push_back("ADD"); cmdstr << "+" << HTTPUtils::URLDecode(message.post_data["expiry"]); cmdstr << " " << HTTPUtils::URLDecode(message.post_data["mask"]); @@ -49,11 +49,11 @@ bool WebCPanel::OperServ::Akill::OnRequest(HTTPProvider *server, const Anope::st { const XLine *x = akills->GetEntry(i); replacements["NUMBER"] = stringify(i + 1); - replacements["HOST"] = x->Mask; - replacements["SETTER"] = x->By; - replacements["TIME"] = do_strftime(x->Created, NULL, true); - replacements["EXPIRE"] = expire_left(na->nc, x->Expires); - replacements["REASON"] = x->Reason; + replacements["HOST"] = x->mask; + replacements["SETTER"] = x->by; + replacements["TIME"] = Anope::strftime(x->created, NULL, true); + replacements["EXPIRE"] = Anope::Expires(x->expires, na->nc); + replacements["REASON"] = x->reason; } } diff --git a/modules/extra/webcpanel/template_fileserver.cpp b/modules/extra/webcpanel/template_fileserver.cpp index b1881b811..cf7094e39 100644 --- a/modules/extra/webcpanel/template_fileserver.cpp +++ b/modules/extra/webcpanel/template_fileserver.cpp @@ -126,7 +126,8 @@ void TemplateFileServer::Serve(HTTPProvider *server, const Anope::string &page_n if (content.find("IF ") == 0) { - std::vector<Anope::string> tokens = BuildStringVector(content); + std::vector<Anope::string> tokens; + spacesepstream(content).GetTokens(tokens); if (tokens.size() == 4 && tokens[1] == "EQ") { @@ -163,13 +164,17 @@ void TemplateFileServer::Serve(HTTPProvider *server, const Anope::string &page_n } else if (content.find("FOR ") == 0) { - std::vector<Anope::string> tokens = BuildStringVector(content); + std::vector<Anope::string> tokens; + spacesepstream(content).GetTokens(tokens); + if (tokens.size() != 4 || tokens[2] != "IN") Log() << "Invalid FOR in web template " << this->file_name; else { - std::vector<Anope::string> temp_variables = BuildStringVector(tokens[1], ','), - real_variables = BuildStringVector(tokens[3], ','); + std::vector<Anope::string> temp_variables, real_variables; + commasepstream(tokens[1]).GetTokens(temp_variables); + commasepstream(tokens[3]).GetTokens(real_variables); + if (temp_variables.size() != real_variables.size()) Log() << "Invalid FOR in web template " << this->file_name << " variable mismatch"; else @@ -200,7 +205,9 @@ void TemplateFileServer::Serve(HTTPProvider *server, const Anope::string &page_n } else if (content.find("INCLUDE ") == 0) { - std::vector<Anope::string> tokens = BuildStringVector(content); + std::vector<Anope::string> tokens; + spacesepstream(content).GetTokens(tokens); + if (tokens.size() != 2) Log() << "Invalid INCLUDE in web template " << this->file_name; else diff --git a/modules/extra/webcpanel/webcpanel.cpp b/modules/extra/webcpanel/webcpanel.cpp index 77cf606aa..164c4b903 100644 --- a/modules/extra/webcpanel/webcpanel.cpp +++ b/modules/extra/webcpanel/webcpanel.cpp @@ -52,11 +52,11 @@ class ModuleWebCPanel : public Module ConfigReader reader; provider_name = reader.ReadValue("webcpanel", "server", "httpd/main", 0); template_name = reader.ReadValue("webcpanel", "template", "template", 0); - template_base = db_dir + "/modules/webcpanel/templates/" + template_name; + template_base = Anope::DataDir + "/modules/webcpanel/templates/" + template_name; page_title = reader.ReadValue("webcpanel", "title", "Anope IRC Services", 0); use_ssl = reader.ReadFlag("webcpanel", "ssl", "no", 0); // This is dumb, is there a better way to do this? - service_reference<HTTPProvider> provider("HTTPProvider", provider_name); + ServiceReference<HTTPProvider> provider("HTTPProvider", provider_name); if (!provider) throw ModuleException("Unable to find HTTPD provider. Is m_httpd loaded?"); @@ -80,7 +80,7 @@ class ModuleWebCPanel : public Module s.subsections.push_back(ss); provider->RegisterPage(&this->nickserv_info); - if (ircdproto && ircdproto->CanCertFP) + if (IRCD && IRCD->CanCertFP) { ss.name = "SSL Certificates"; ss.url = "/nickserv/cert"; @@ -160,7 +160,7 @@ class ModuleWebCPanel : public Module ~ModuleWebCPanel() { - service_reference<HTTPProvider> provider("HTTPProvider", provider_name); + ServiceReference<HTTPProvider> provider("HTTPProvider", provider_name); if (provider) { provider->UnregisterPage(&this->style_css); @@ -191,14 +191,14 @@ namespace WebPanel { void RunCommand(const Anope::string &user, NickCore *nc, const Anope::string &service, const Anope::string &c, const std::vector<Anope::string> ¶ms, TemplateFileServer::Replacements &r) { - service_reference<Command> cmd("Command", c); + ServiceReference<Command> cmd("Command", c); if (!cmd) { r["MESSAGES"] = "Unable to find command " + c; return; } - BotInfo *bi = findbot(service); + BotInfo *bi = BotInfo::Find(service); if (!bi) { if (BotListByNick->empty()) diff --git a/modules/extra/webcpanel/webcpanel.h b/modules/extra/webcpanel/webcpanel.h index 99cb2ec3a..27b8ce67a 100644 --- a/modules/extra/webcpanel/webcpanel.h +++ b/modules/extra/webcpanel/webcpanel.h @@ -46,7 +46,7 @@ class Panel : public Section, public Service if (acc.empty() || id.empty()) return NULL; - NickAlias *na = findnick(acc); + NickAlias *na = NickAlias::Find(acc); if (na == NULL) return NULL; @@ -83,7 +83,7 @@ class WebPanelProtectedPage : public WebPanelPage bool OnRequest(HTTPProvider *provider, const Anope::string &page_name, HTTPClient *client, HTTPMessage &message, HTTPReply &reply) anope_override anope_final { - service_reference<Panel> panel("Panel", "webcpanel"); + ServiceReference<Panel> panel("Panel", "webcpanel"); NickAlias *na; if (!panel || !(na = panel->GetNickFromSession(client, message))) diff --git a/modules/protocol/bahamut.cpp b/modules/protocol/bahamut.cpp index e39226dd8..839876d90 100644 --- a/modules/protocol/bahamut.cpp +++ b/modules/protocol/bahamut.cpp @@ -49,7 +49,7 @@ class BahamutIRCdProto : public IRCDProto void SendModeInternal(const BotInfo *source, const Channel *dest, const Anope::string &buf) anope_override { - if (Capab.count("TSMODE") > 0) + if (Servers::Capab.count("TSMODE") > 0) { if (source) UplinkSocket::Message(source) << "MODE " << dest->name << " " << dest->creation_time << " " << buf; @@ -93,13 +93,13 @@ class BahamutIRCdProto : public IRCDProto /* SQLINE */ void SendSQLine(User *, const XLine *x) anope_override { - UplinkSocket::Message() << "SQLINE " << x->Mask << " :" << x->GetReason(); + UplinkSocket::Message() << "SQLINE " << x->mask << " :" << x->GetReason(); } /* UNSLINE */ void SendSGLineDel(const XLine *x) anope_override { - UplinkSocket::Message() << "UNSGLINE 0 :" << x->Mask; + UplinkSocket::Message() << "UNSGLINE 0 :" << x->mask; } /* UNSZLINE */ @@ -115,13 +115,13 @@ class BahamutIRCdProto : public IRCDProto void SendSZLine(User *, const XLine *x) anope_override { // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; /* this will likely fail so its only here for legacy */ UplinkSocket::Message() << "SZLINE " << x->GetHost() << " :" << x->GetReason(); /* this is how we are supposed to deal with it */ - UplinkSocket::Message() << "AKILL " << x->GetHost() << " * " << timeleft << " " << x->By << " " << Anope::CurTime << " :" << x->GetReason(); + UplinkSocket::Message() << "AKILL " << x->GetHost() << " * " << timeleft << " " << x->by << " " << Anope::CurTime << " :" << x->GetReason(); } /* SVSNOOP */ @@ -133,7 +133,7 @@ class BahamutIRCdProto : public IRCDProto /* SGLINE */ void SendSGLine(User *, const XLine *x) anope_override { - UplinkSocket::Message() << "SGLINE " << x->Mask.length() << " :" << x->Mask << ":" << x->GetReason(); + UplinkSocket::Message() << "SGLINE " << x->mask.length() << " :" << x->mask << ":" << x->GetReason(); } /* RAKILL */ @@ -148,7 +148,7 @@ class BahamutIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLineDel(x); + IRCD->SendSZLineDel(x); return; } } @@ -166,7 +166,7 @@ class BahamutIRCdProto : public IRCDProto /* UNSQLINE */ void SendSQLineDel(const XLine *x) anope_override { - UplinkSocket::Message() << "UNSQLINE " << x->Mask; + UplinkSocket::Message() << "UNSQLINE " << x->mask; } /* JOIN - SJOIN */ @@ -182,11 +182,11 @@ class BahamutIRCdProto : public IRCDProto */ UserContainer *uc = c->FindUser(user); if (uc != NULL) - uc->Status->ClearFlags(); + uc->status->ClearFlags(); - BotInfo *setter = findbot(user->nick); + BotInfo *setter = BotInfo::Find(user->nick); for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); } } @@ -210,10 +210,10 @@ class BahamutIRCdProto : public IRCDProto return; /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - x = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); + x = new XLine("*@" + u->host, old->by, old->expires, old->reason, old->id); old->manager->AddXLine(x); - Log(findbot(Config->OperServ), "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; + Log(OperServ, "akill") << "AKILL: Added an akill for " << x->mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->mask; } /* ZLine if we can instead */ @@ -222,17 +222,17 @@ class BahamutIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLine(u, x); + IRCD->SendSZLine(u, x); return; } } catch (const SocketException &) { } // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; + time_t timeleft = x->expires - Anope::CurTime; if (timeleft > 172800) timeleft = 172800; - UplinkSocket::Message() << "AKILL " << x->GetHost() << " " << x->GetUser() << " " << timeleft << " " << x->By << " " << Anope::CurTime << " :" << x->GetReason(); + UplinkSocket::Message() << "AKILL " << x->GetHost() << " " << x->GetUser() << " " << timeleft << " " << x->by << " " << Anope::CurTime << " :" << x->GetReason(); } /* @@ -270,7 +270,7 @@ class BahamutIRCdProto : public IRCDProto void SendConnect() anope_override { - UplinkSocket::Message() << "PASS " << Config->Uplinks[CurrentUplink]->password << " :TS"; + UplinkSocket::Message() << "PASS " << Config->Uplinks[Anope::CurrentUplink]->password << " :TS"; UplinkSocket::Message() << "CAPAB SSJOIN NOQUIT BURST UNCONNECT NICKIP TSMODE TS3"; SendServer(Me); /* @@ -295,20 +295,18 @@ class BahamutIRCdProto : public IRCDProto void SendLogin(User *u) anope_override { - const BotInfo *ns = findbot(Config->NickServ); - ircdproto->SendMode(ns, u, "+d %d", u->timestamp); + IRCD->SendMode(NickServ, u, "+d %d", u->timestamp); } void SendLogout(User *u) anope_override { - const BotInfo *ns = findbot(Config->NickServ); - ircdproto->SendMode(ns, u, "+d 1"); + IRCD->SendMode(NickServ, u, "+d 1"); } }; struct IRCDMessageBurst : IRCDMessage { - IRCDMessageBurst() : IRCDMessage("BURST", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageBurst(Module *creator) : IRCDMessage(creator, "BURST", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -327,14 +325,15 @@ struct IRCDMessageBurst : IRCDMessage struct IRCDMessageMode : IRCDMessage { - IRCDMessageMode(const Anope::string &n) : IRCDMessage(n, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageMode(Module *creator, const Anope::string &sname) : IRCDMessage(creator, sname, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (params.size() > 2 && ircdproto->IsChannelValid(params[0])) + if (params.size() > 2 && IRCD->IsChannelValid(params[0])) { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); time_t ts = 0; + try { ts = convertTo<time_t>(params[1]); @@ -346,7 +345,7 @@ struct IRCDMessageMode : IRCDMessage } else { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetModesInternal("%s", params[1].c_str()); } @@ -375,7 +374,7 @@ struct IRCDMessageMode : IRCDMessage */ struct IRCDMessageNick : IRCDMessage { - IRCDMessageNick() : IRCDMessage("NICK", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -389,18 +388,18 @@ struct IRCDMessageNick : IRCDMessage } User *user = new User(params[0], params[4], params[5], "", params[8], s, params[9], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, params[3]); - if (user && nickserv) + if (user && NickServService) { const NickAlias *na; - if (user->timestamp == convertTo<time_t>(params[7]) && (na = findnick(user->nick))) + if (user->timestamp == convertTo<time_t>(params[7]) && (na = NickAlias::Find(user->nick))) { NickCore *nc = na->nc; user->Login(nc); if (!Config->NoNicknameOwnership && na->nc->HasFlag(NI_UNCONFIRMED) == false) - user->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + user->SetMode(NickServ, UMODE_REGISTERED); } else - nickserv->Validate(user); + NickServService->Validate(user); } } else @@ -412,7 +411,7 @@ struct IRCDMessageNick : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -424,77 +423,39 @@ struct IRCDMessageServer : IRCDMessage struct IRCDMessageSJoin : IRCDMessage { - IRCDMessageSJoin() : IRCDMessage("SJOIN", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageSJoin(Module *creator) : IRCDMessage(creator, "SJOIN", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[1]); - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[1], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this SJOIN string contains modes */ - if (keep_their_modes && params.size() >= 4) - { - /* Set the modes internally */ - Anope::string modes; + Anope::string modes; + if (params.size() >= 4) for (unsigned i = 2; i < params.size(); ++i) modes += " " + params[i]; - if (!modes.empty()) - modes.erase(modes.begin()); - c->SetModesInternal(source, modes); - } + if (!modes.empty()) + modes.erase(modes.begin()); + + std::list<Message::Join::SJoinUser> users; /* For some reason, bahamut will send a SJOIN from the user joining a channel * if the channel already existed */ - if (!c->HasFlag(CH_SYNCING) && params.size() == 2) + if (source.GetUser()) { - User *u = source.GetUser(); - - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT == EVENT_STOP && (!c->ci || !c->ci->CheckKick(u))) - { - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } + Message::Join::SJoinUser sju; + sju.second = source.GetUser(); + users.push_back(sju); } else { spacesepstream sep(params[params.size() - 1]); Anope::string buf; + while (sep.GetToken(buf)) { - std::list<ChannelMode *> Status; - char ch; + Message::Join::SJoinUser sju; /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) + for (char ch; (ch = ModeManager::GetStatusChar(buf[0]));) { buf.erase(buf.begin()); ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); @@ -504,50 +465,22 @@ struct IRCDMessageSJoin : IRCDMessage continue; } - if (keep_their_modes) - Status.push_back(cm); + sju.first.SetFlag(cm->name); } - User *u = finduser(buf); - if (!u) + sju.second = User::Find(buf); + if (!sju.second) { - Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << c->name; + Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << params[1]; continue; } - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); + users.push_back(sju); } } - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } + time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + Message::Join::SJoin(source, params[1], ts, modes, users); return true; } @@ -555,11 +488,11 @@ struct IRCDMessageSJoin : IRCDMessage struct IRCDMessageTopic : IRCDMessage { - IRCDMessageTopic() : IRCDMessage("TOPIC", 4) { } + IRCDMessageTopic(Module *creator) : IRCDMessage(creator, "TOPIC", 4) { } bool Run(MessageSource &, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c) c->ChangeTopicInternal(params[1], params[3], Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); return true; @@ -571,23 +504,22 @@ class ProtoBahamut : public Module BahamutIRCdProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageJoin core_message_join; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - CoreIRCDMessageWhois core_message_whois; + Message::Away message_away; + Message::Capab message_capab; + Message::Error message_error; + Message::Join message_join; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Version message_version; + Message::Whois message_whois; /* Our message handlers */ IRCDMessageBurst message_burst; @@ -636,7 +568,13 @@ class ProtoBahamut : public Module public: ProtoBahamut(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - message_mode("MODE"), message_svsmode("SVSMODE") + message_away(this), message_capab(this), message_error(this), message_join(this), + message_kick(this), message_kill(this), message_motd(this), message_part(this), + message_ping(this), message_privmsg(this), message_quit(this), message_squit(this), + message_stats(this), message_time(this), message_version(this), message_whois(this), + + message_burst(this), message_mode(this, "MODE"), message_svsmode(this, "SVSMODE"), + message_nick(this), message_server(this), message_sjoin(this), message_topic(this) { this->SetAuthor("Anope"); @@ -645,10 +583,15 @@ class ProtoBahamut : public Module ModuleManager::Attach(I_OnUserNickChange, this); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { u->RemoveModeInternal(ModeManager::FindUserModeByName(UMODE_REGISTERED)); - ircdproto->SendLogout(u); + IRCD->SendLogout(u); } }; diff --git a/modules/protocol/hybrid.cpp b/modules/protocol/hybrid.cpp index d3d67d84e..1161db3fa 100644 --- a/modules/protocol/hybrid.cpp +++ b/modules/protocol/hybrid.cpp @@ -37,44 +37,40 @@ class HybridProto : public IRCDProto UplinkSocket::Message(bi) << "PRIVMSG $$" << dest->GetName() << " :" << msg; } - void SendSQLine(User *, const XLine *x) anope_override + void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) anope_override { - const BotInfo *bi = findbot(Config->OperServ); + UplinkSocket::Message(source) << "OPERWALL :" << buf; + } - UplinkSocket::Message(bi) << "RESV * " << x->Mask << " :" << x->GetReason(); + void SendSQLine(User *, const XLine *x) anope_override + { + UplinkSocket::Message(OperServ) << "RESV * " << x->mask << " :" << x->GetReason(); } void SendSGLineDel(const XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); - - UplinkSocket::Message(bi) << "UNXLINE * " << x->Mask; + UplinkSocket::Message(OperServ) << "UNXLINE * " << x->mask; } void SendSGLine(User *, const XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); - - UplinkSocket::Message(bi) << "XLINE * " << x->Mask << " 0 :" << x->GetReason(); + UplinkSocket::Message(OperServ) << "XLINE * " << x->mask << " 0 :" << x->GetReason(); } void SendSZLineDel(const XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); - - UplinkSocket::Message(bi) << "UNDLINE * " << x->GetHost(); + UplinkSocket::Message(OperServ) << "UNDLINE * " << x->GetHost(); } void SendSZLine(User *, const XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); /* Calculate the time left before this would expire, capping it at 2 days */ - time_t timeleft = x->Expires - Anope::CurTime; + time_t timeleft = x->expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(bi) << "DLINE * " << timeleft << " " << x->GetHost() << " :" << x->GetReason(); + UplinkSocket::Message(OperServ) << "DLINE * " << timeleft << " " << x->GetHost() << " :" << x->GetReason(); } void SendAkillDel(const XLine *x) anope_override @@ -82,16 +78,12 @@ class HybridProto : public IRCDProto if (x->IsRegex() || x->HasNickOrReal()) return; - const BotInfo *bi = findbot(Config->OperServ); - - UplinkSocket::Message(bi) << "UNKLINE * " << x->GetUser() << " " << x->GetHost(); + UplinkSocket::Message(OperServ) << "UNKLINE * " << x->GetUser() << " " << x->GetHost(); } void SendSQLineDel(const XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); - - UplinkSocket::Message(bi) << "UNRESV * " << x->Mask; + UplinkSocket::Message(OperServ) << "UNRESV * " << x->mask; } void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override @@ -111,14 +103,12 @@ class HybridProto : public IRCDProto UserContainer *uc = c->FindUser(user); if (uc != NULL) - *uc->Status = *status; + *uc->status = *status; } } void SendAkill(User *u, XLine *x) anope_override { - const BotInfo *bi = findbot(Config->OperServ); - if (x->IsRegex() || x->HasNickOrReal()) { if (!u) @@ -140,32 +130,35 @@ class HybridProto : public IRCDProto return; /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - XLine *xline = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); + XLine *xline = new XLine("*@" + u->host, old->by, old->expires, old->reason, old->id); old->manager->AddXLine(xline); x = xline; - Log(bi, "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" - << u->realname << " matches " << old->Mask; + Log(OperServ, "akill") << "AKILL: Added an akill for " << x->mask << " because " << u->GetMask() << "#" + << u->realname << " matches " << old->mask; } /* Calculate the time left before this would expire, capping it at 2 days */ - time_t timeleft = x->Expires - Anope::CurTime; + time_t timeleft = x->expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(bi) << "KLINE * " << timeleft << " " << x->GetUser() << " " << x->GetHost() << " :" << x->GetReason(); + UplinkSocket::Message(OperServ) << "KLINE * " << timeleft << " " << x->GetUser() << " " << x->GetHost() << " :" << x->GetReason(); } void SendServer(const Server *server) anope_override { - UplinkSocket::Message() << "SERVER " << server->GetName() << " " << server->GetHops() << " :" << server->GetDescription(); + if (server == Me) + UplinkSocket::Message() << "SERVER " << server->GetName() << " " << server->GetHops() << " :" << server->GetDescription(); + else + UplinkSocket::Message(Me) << "SID " << server->GetName() << " " << server->GetHops() << " " << server->GetSID() << " :" << server->GetDescription(); } void SendConnect() anope_override { - UplinkSocket::Message() << "PASS " << Config->Uplinks[CurrentUplink]->password << " TS 6 :" << Me->GetSID(); + UplinkSocket::Message() << "PASS " << Config->Uplinks[Anope::CurrentUplink]->password << " TS 6 :" << Me->GetSID(); /* * As of October 13, 2012, ircd-hybrid-8 does support the following capabilities @@ -213,16 +206,12 @@ class HybridProto : public IRCDProto void SendLogin(User *u) anope_override { - const BotInfo *ns = findbot(Config->NickServ); - - ircdproto->SendMode(ns, u, "+d %s", u->Account()->display.c_str()); + IRCD->SendMode(NickServ, u, "+d %s", u->Account()->display.c_str()); } void SendLogout(User *u) anope_override { - const BotInfo *ns = findbot(Config->NickServ); - - ircdproto->SendMode(ns, u, "+d 0"); + IRCD->SendMode(NickServ, u, "+d 0"); } void SendChannel(Channel *c) anope_override @@ -256,13 +245,13 @@ class HybridProto : public IRCDProto struct IRCDMessageBMask : IRCDMessage { - IRCDMessageBMask() : IRCDMessage("BMASK", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageBMask(Module *creator) : IRCDMessage(creator, "BMASK", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* 0 1 2 3 */ /* :0MC BMASK 1350157102 #channel b :*!*@*.test.com */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[1]); + Channel *c = Channel::Find(params[1]); if (c) { @@ -270,20 +259,16 @@ struct IRCDMessageBMask : IRCDMessage *except = ModeManager::FindChannelModeByName(CMODE_EXCEPT), *invex = ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE); - Anope::string bans = params[3]; - - int count = myNumToken(bans, ' '), i; - - for (i = 0; i < count; ++i) + spacesepstream bans(params[3]); + Anope::string token; + while (bans.GetToken(token)) { - Anope::string b = myStrGetToken(bans, ' ', i); - if (ban && params[2].equals_cs("b")) - c->SetModeInternal(source, ban, b); + c->SetModeInternal(source, ban, token); else if (except && params[2].equals_cs("e")) - c->SetModeInternal(source, except, b); + c->SetModeInternal(source, except, token); else if (invex && params[2].equals_cs("I")) - c->SetModeInternal(source, invex, b); + c->SetModeInternal(source, invex, token); } } @@ -291,57 +276,36 @@ struct IRCDMessageBMask : IRCDMessage } }; -struct IRCDMessageJoin : CoreIRCDMessageJoin +struct IRCDMessageEOB : IRCDMessage { - IRCDMessageJoin() : CoreIRCDMessageJoin("JOIN") { } + IRCDMessageEOB(Module *craetor) : IRCDMessage(craetor, "EOB", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (params.size() < 2) - return true; - - std::vector<Anope::string> p = params; - p.erase(p.begin()); - - return CoreIRCDMessageJoin::Run(source, p); + source.GetServer()->Sync(true); + return true; } }; -struct IRCDMessageMode : IRCDMessage +struct IRCDMessageJoin : Message::Join { - IRCDMessageMode(const Anope::string &n) : IRCDMessage(n, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageJoin(Module *creator) : Message::Join(creator, "JOIN") { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (params.size() > 2 && ircdproto->IsChannelValid(params[0])) - { - Channel *c = findchan(params[0]); - time_t ts = 0; - - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) { } - - if (c) - c->SetModesInternal(source, params[2], ts); - } - else - { - User *u = finduser(params[0]); + if (params.size() < 2) + return true; - if (u) - u->SetModesInternal("%s", params[1].c_str()); - } + std::vector<Anope::string> p = params; + p.erase(p.begin()); - return true; + return Message::Join::Run(source, p); } }; struct IRCDMessageNick : IRCDMessage { - IRCDMessageNick() : IRCDMessage("NICK", 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } /* 0 1 */ /* :0MCAAAAAB NICK newnick 1350157102 */ @@ -354,7 +318,7 @@ struct IRCDMessageNick : IRCDMessage struct IRCDMessagePass : IRCDMessage { - IRCDMessagePass() : IRCDMessage("PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePass(Module *creator) : IRCDMessage(creator, "PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* 0 1 2 3 */ /* PASS password TS 6 0MC */ @@ -367,7 +331,7 @@ struct IRCDMessagePass : IRCDMessage struct IRCDMessagePong : IRCDMessage { - IRCDMessagePong() : IRCDMessage("PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePong(Module *creator) : IRCDMessage(creator, "PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -378,7 +342,7 @@ struct IRCDMessagePong : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* 0 1 2 */ /* SERVER hades.arpa 1 :ircd-hybrid test server */ @@ -390,14 +354,14 @@ struct IRCDMessageServer : IRCDMessage new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], 1, params[2], UplinkSID); - ircdproto->SendPing(Config->ServerName, params[0]); + IRCD->SendPing(Config->ServerName, params[0]); return true; } }; struct IRCDMessageSID : IRCDMessage { - IRCDMessageSID() : IRCDMessage("SID", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageSID(Module *creator) : IRCDMessage(creator, "SID", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* 0 1 2 3 */ /* :0MC SID hades.arpa 2 4XY :ircd-hybrid test server */ @@ -406,64 +370,37 @@ struct IRCDMessageSID : IRCDMessage unsigned int hops = params[1].is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[3], params[2]); - ircdproto->SendPing(Config->ServerName, params[0]); + IRCD->SendPing(Config->ServerName, params[0]); return true; } }; -struct IRCDMessageSjoin : IRCDMessage +struct IRCDMessageSJoin : IRCDMessage { - IRCDMessageSjoin() : IRCDMessage("SJOIN", 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageSJoin(Module *creator) : IRCDMessage(creator, "SJOIN", 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[1]); - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[1], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this SJOIN string contains modes */ - if (keep_their_modes && params.size() >= 3) - { - Anope::string modes; - + Anope::string modes; + if (params.size() >= 3) for (unsigned i = 2; i < params.size() - 1; ++i) modes += " " + params[i]; + if (!modes.empty()) + modes.erase(modes.begin()); - if (!modes.empty()) - modes.erase(modes.begin()); - - /* Set the modes internally */ - c->SetModesInternal(source, modes); - } + std::list<Message::Join::SJoinUser> users; spacesepstream sep(params[params.size() - 1]); Anope::string buf; while (sep.GetToken(buf)) { - std::list<ChannelMode *> Status; - char ch; + Message::Join::SJoinUser sju; /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) + for (char ch; (ch = ModeManager::GetStatusChar(buf[0]));) { buf.erase(buf.begin()); - ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); if (!cm) @@ -472,66 +409,60 @@ struct IRCDMessageSjoin : IRCDMessage continue; } - if (keep_their_modes) - Status.push_back(cm); + sju.first.SetFlag(cm->name); } - User *u = finduser(buf); - - if (!u) + sju.second = User::Find(buf); + if (!sju.second) { - Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << c->name; + Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << params[1]; continue; } - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* - * Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); + users.push_back(sju); + } - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); + time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + Message::Join::SJoin(source, params[1], ts, modes, users); - /* - * Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; + return true; + } +}; - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } +struct IRCDMessageSVSMode : IRCDMessage +{ + IRCDMessageSVSMode(Module *creator) : IRCDMessage(creator, "SVSMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + /* + * parv[0] = nickname + * parv[1] = TS + * parv[2] = mode + * parv[3] = optional argument (services id) + */ + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + User *u = User::Find(params[0]); + if (!u) + return true; - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } + if (!params[1].is_pos_number_only() || convertTo<time_t>(params[1]) != u->timestamp) + return true; + u->SetModesInternal("%s", params[2].c_str()); return true; } }; struct IRCDMessageTBurst : IRCDMessage { - IRCDMessageTBurst() : IRCDMessage("TBURST", 5) { } + IRCDMessageTBurst(Module *creator) : IRCDMessage(creator, "TBURST", 5) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Anope::string setter = myStrGetToken(params[3], '!', 0); + Anope::string setter; + sepstream(params[3], '!').GetToken(setter, 0); time_t topic_time = Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime; - Channel *c = findchan(params[1]); + Channel *c = Channel::Find(params[1]); if (c) c->ChangeTopicInternal(setter, params[4], topic_time); @@ -542,7 +473,7 @@ struct IRCDMessageTBurst : IRCDMessage struct IRCDMessageTMode : IRCDMessage { - IRCDMessageTMode() : IRCDMessage("TMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageTMode(Module *creator) : IRCDMessage(creator, "TMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -554,7 +485,7 @@ struct IRCDMessageTMode : IRCDMessage } catch (const ConvertException &) { } - Channel *c = findchan(params[1]); + Channel *c = Channel::Find(params[1]); Anope::string modes = params[2]; for (unsigned i = 3; i < params.size(); ++i) @@ -569,7 +500,7 @@ struct IRCDMessageTMode : IRCDMessage struct IRCDMessageUID : IRCDMessage { - IRCDMessageUID() : IRCDMessage("UID", 10) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageUID(Module *creator) : IRCDMessage(creator, "UID", 10) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* 0 1 2 3 4 5 6 7 8 9 */ /* :0MC UID Steve 1 1350157102 +oi ~steve resolved.host 10.0.0.1 0MCAAAAAB 1350157108 :Mining all the time */ @@ -586,22 +517,22 @@ struct IRCDMessageUID : IRCDMessage params[9], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, params[3], params[7]); - if (user && nickserv) + if (user && NickServService) { const NickAlias *na = NULL; if (params[8] != "0") - na = findnick(params[8]); + na = NickAlias::Find(params[8]); if (na) { user->Login(na->nc); if (!Config->NoNicknameOwnership && na->nc->HasFlag(NI_UNCONFIRMED) == false) - user->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + user->SetMode(NickServ, UMODE_REGISTERED); } else - nickserv->Validate(user); + NickServService->Validate(user); } return true; @@ -613,33 +544,35 @@ class ProtoHybrid : public Module HybridProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - CoreIRCDMessageWhois core_message_whois; + Message::Away message_away; + Message::Capab message_capab; + Message::Error message_error; + Message::Kick message_kick; + Message::Kill message_kill; + Message::Mode message_mode; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Topic message_topic; + Message::Version message_version; + Message::Whois message_whois; /* Our message handlers */ IRCDMessageBMask message_bmask; + IRCDMessageEOB message_eob; IRCDMessageJoin message_join; - IRCDMessageMode message_mode, message_svsmode; IRCDMessageNick message_nick; IRCDMessagePass message_pass; IRCDMessagePong message_pong; IRCDMessageServer message_server; IRCDMessageSID message_sid; - IRCDMessageSjoin message_sjoin; + IRCDMessageSJoin message_sjoin; + IRCDMessageSVSMode message_svsmode; IRCDMessageTBurst message_tburst; IRCDMessageTMode message_tmode; IRCDMessageUID message_uid; @@ -663,12 +596,15 @@ class ProtoHybrid : public Module /* v/h/o/a/q */ ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_VOICE, 'v', '+', 0)); - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_OP, 'o', '@', 1)); + ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_HALFOP, 'h', '%', 1)); + ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_OP, 'o', '@', 2)); + + /* l/k */ + ModeManager::AddChannelMode(new ChannelModeParam(CMODE_LIMIT, 'l')); + ModeManager::AddChannelMode(new ChannelModeKey('k')); /* Add channel modes */ ModeManager::AddChannelMode(new ChannelMode(CMODE_INVITE, 'i')); - ModeManager::AddChannelMode(new ChannelModeKey('k')); - ModeManager::AddChannelMode(new ChannelModeParam(CMODE_LIMIT, 'l')); ModeManager::AddChannelMode(new ChannelMode(CMODE_MODERATED, 'm')); ModeManager::AddChannelMode(new ChannelMode(CMODE_NOEXTERNAL, 'n')); ModeManager::AddChannelMode(new ChannelMode(CMODE_PRIVATE, 'p')); @@ -681,8 +617,15 @@ class ProtoHybrid : public Module } public: - ProtoHybrid(const Anope::string &modname, const Anope::string &creator) : - Module(modname, creator, PROTOCOL), message_mode("MODE"), message_svsmode("SVSMODE") + ProtoHybrid(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), + message_away(this), message_capab(this), message_error(this), message_kick(this), message_kill(this), + message_mode(this), message_motd(this), message_part(this), message_ping(this), message_privmsg(this), + message_quit(this), message_squit(this), message_stats(this), message_time(this), message_topic(this), + message_version(this), message_whois(this), + + message_bmask(this), message_eob(this), message_join(this), + message_nick(this), message_pass(this), message_pong(this), message_server(this), message_sid(this), + message_sjoin(this), message_svsmode(this), message_tburst(this), message_tmode(this), message_uid(this) { this->SetAuthor("Anope"); this->AddModes(); @@ -691,7 +634,7 @@ public: if (Config->Numeric.empty()) { - Anope::string numeric = ts6_sid_retrieve(); + Anope::string numeric = Servers::TS6_SID_Retrieve(); Me->SetSID(numeric); Config->Numeric = numeric; } @@ -700,10 +643,14 @@ public: it->second->GenerateUID(); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { u->RemoveModeInternal(ModeManager::FindUserModeByName(UMODE_REGISTERED)); - ircdproto->SendLogout(u); } }; diff --git a/modules/protocol/inspircd-ts6.h b/modules/protocol/inspircd-ts6.h deleted file mode 100644 index 7e0fe971d..000000000 --- a/modules/protocol/inspircd-ts6.h +++ /dev/null @@ -1,817 +0,0 @@ -/* Inspircd 1.2+ generic TS6 functions - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -class ChannelModeFlood : public ChannelModeParam -{ - public: - ChannelModeFlood(char modeChar, bool minusNoArg) : ChannelModeParam(CMODE_FLOOD, modeChar, minusNoArg) { } - - bool IsValid(const Anope::string &value) const anope_override - { - try - { - Anope::string rest; - if (!value.empty() && value[0] != ':' && convertTo<int>(value[0] == '*' ? value.substr(1) : value, rest, false) > 0 && rest[0] == ':' && rest.length() > 1 && convertTo<int>(rest.substr(1), rest, false) > 0 && rest.empty()) - return true; - } - catch (const ConvertException &) { } - - return false; - } -}; - -class InspIRCdTS6Proto : public IRCDProto -{ - private: - void SendChgIdentInternal(const Anope::string &nick, const Anope::string &vIdent) - { - if (!has_chgidentmod) - Log() << "CHGIDENT not loaded!"; - else - UplinkSocket::Message(findbot(Config->HostServ)) << "CHGIDENT " << nick << " " << vIdent; - } - - void SendChgHostInternal(const Anope::string &nick, const Anope::string &vhost) - { - if (!has_chghostmod) - Log() << "CHGHOST not loaded!"; - else - UplinkSocket::Message(Me) << "CHGHOST " << nick << " " << vhost; - } - - void SendAddLine(const Anope::string &type, const Anope::string &mask, time_t duration, const Anope::string &addedby, const Anope::string &reason) - { - UplinkSocket::Message(Me) << "ADDLINE " << type << " " << mask << " " << addedby << " " << Anope::CurTime << " " << duration << " :" << reason; - } - - void SendDelLine(const Anope::string &type, const Anope::string &mask) - { - UplinkSocket::Message(Me) << "DELLINE " << type << " " << mask; - } - - protected: - InspIRCdTS6Proto(const Anope::string &name) : IRCDProto(name) - { - DefaultPseudoclientModes = "+I"; - CanSVSNick = true; - CanSetVHost = true; - CanSetVIdent = true; - CanSQLine = true; - CanSZLine = true; - CanSVSHold = true; - CanCertFP = true; - RequiresID = true; - MaxModes = 20; - } - - void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "NOTICE $" << dest->GetName() << " :" << msg; - } - - void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "PRIVMSG $" << dest->GetName() << " :" << msg; - } - - void SendAkillDel(const XLine *x) anope_override - { - /* InspIRCd may support regex bans */ - if (x->IsRegex() && has_rlinemod) - { - Anope::string mask = x->Mask; - size_t h = x->Mask.find('#'); - if (h != Anope::string::npos) - mask = mask.replace(h, 1, ' '); - SendDelLine("R", mask); - return; - } - else if (x->IsRegex() || x->HasNickOrReal()) - return; - - SendDelLine("G", x->Mask); - } - - void SendTopic(BotInfo *whosets, Channel *c) anope_override - { - if (has_svstopic_topiclock) - { - UplinkSocket::Message(c->ci->WhoSends()) << "SVSTOPIC " << c->name << " " << c->topic_ts << " " << c->topic_setter << " :" << c->topic; - } - else - { - /* If the last time a topic was set is after the TS we want for this topic we must bump this topic's timestamp to now */ - time_t ts = c->topic_ts; - if (c->topic_time > ts) - ts = Anope::CurTime; - /* But don't modify c->topic_ts, it should remain set to the real TS we want as ci->last_topic_time pulls from it */ - UplinkSocket::Message(whosets) << "FTOPIC " << c->name << " " << ts << " " << c->topic_setter << " :" << c->topic; - } - } - - void SendVhostDel(User *u) anope_override - { - if (u->HasMode(UMODE_CLOAK)) - this->SendChgHostInternal(u->nick, u->chost); - else - this->SendChgHostInternal(u->nick, u->host); - - if (has_chgidentmod && u->GetIdent() != u->GetVIdent()) - this->SendChgIdentInternal(u->nick, u->GetIdent()); - } - - void SendAkill(User *u, XLine *x) anope_override - { - // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) - timeleft = 172800; - - const BotInfo *bi = findbot(Config->OperServ); - /* InspIRCd may support regex bans, if they do we can send this and forget about it */ - if (x->IsRegex() && has_rlinemod) - { - Anope::string mask = x->Mask; - size_t h = x->Mask.find('#'); - if (h != Anope::string::npos) - mask = mask.replace(h, 1, ' '); - SendAddLine("R", mask, timeleft, x->By, x->GetReason()); - return; - } - else if (x->IsRegex() || x->HasNickOrReal()) - { - if (!u) - { - /* No user (this akill was just added), and contains nick and/or realname. Find users that match and ban them */ - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) - if (x->manager->Check(it->second, x)) - this->SendAkill(it->second, x); - return; - } - - const XLine *old = x; - - if (old->manager->HasEntry("*@" + u->host)) - return; - - /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - x = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); - old->manager->AddXLine(x); - - Log(bi, "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; - } - - /* ZLine if we can instead */ - try - { - if (x->GetUser() == "*") - { - sockaddrs(x->GetHost()); - ircdproto->SendSZLine(u, x); - return; - } - } - catch (const SocketException &) { } - SendAddLine("G", x->GetUser() + "@" + x->GetHost(), timeleft, x->By, x->GetReason()); - } - - void SendNumericInternal(int numeric, const Anope::string &dest, const Anope::string &buf) anope_override - { - UplinkSocket::Message() << "PUSH " << dest << " ::" << Me->GetName() << " " << numeric << " " << dest << " " << buf; - } - - void SendModeInternal(const BotInfo *source, const Channel *dest, const Anope::string &buf) anope_override - { - UplinkSocket::Message(source) << "FMODE " << dest->name << " " << dest->creation_time << " " << buf; - } - - void SendModeInternal(const BotInfo *bi, const User *u, const Anope::string &buf) anope_override - { - UplinkSocket::Message(bi) << "MODE " << u->GetUID() << " " << buf; - } - - void SendClientIntroduction(const User *u) anope_override - { - Anope::string modes = "+" + u->GetModes(); - UplinkSocket::Message(Me) << "UID " << u->GetUID() << " " << u->timestamp << " " << u->nick << " " << u->host << " " << u->host << " " << u->GetIdent() << " 0.0.0.0 " << u->timestamp << " " << modes << " :" << u->realname; - } - - /* SERVER services-dev.chatspike.net password 0 :Description here */ - void SendServer(const Server *server) anope_override - { - UplinkSocket::Message() << "SERVER " << server->GetName() << " " << Config->Uplinks[CurrentUplink]->password << " " << server->GetHops() << " " << server->GetSID() << " :" << server->GetDescription(); - } - - /* JOIN */ - void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override - { - UplinkSocket::Message(Me) << "FJOIN " << c->name << " " << c->creation_time << " +" << c->GetModes(true, true) << " :," << user->GetUID(); - /* Note that we can send this with the FJOIN but choose not to - * because the mode stacker will handle this and probably will - * merge these modes with +nrt and other mlocked modes - */ - if (status) - { - /* First save the channel status incase uc->Status == status */ - ChannelStatus cs = *status; - /* If the user is internally on the channel with flags, kill them so that - * the stacker will allow this. - */ - UserContainer *uc = c->FindUser(user); - if (uc != NULL) - uc->Status->ClearFlags(); - - BotInfo *setter = findbot(user->nick); - for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) - c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); - } - } - - /* UNSQLINE */ - void SendSQLineDel(const XLine *x) anope_override - { - SendDelLine("Q", x->Mask); - } - - /* SQLINE */ - void SendSQLine(User *, const XLine *x) anope_override - { - // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) - timeleft = 172800; - SendAddLine("Q", x->Mask, timeleft, x->By, x->GetReason()); - } - - /* Functions that use serval cmd functions */ - - void SendVhost(User *u, const Anope::string &vIdent, const Anope::string &vhost) anope_override - { - if (!vIdent.empty()) - this->SendChgIdentInternal(u->nick, vIdent); - if (!vhost.empty()) - this->SendChgHostInternal(u->nick, vhost); - } - - void SendConnect() anope_override - { - SendServer(Me); - UplinkSocket::Message(Me) << "BURST"; - Module *enc = ModuleManager::FindFirstOf(ENCRYPTION); - UplinkSocket::Message(Me) << "VERSION :Anope-" << Anope::Version() << " " << Config->ServerName << " :" << ircdproto->GetProtocolName() << " - (" << (enc ? enc->name : "unknown") << ") -- " << Anope::VersionBuildString(); - } - - /* SVSHOLD - set */ - void SendSVSHold(const Anope::string &nick) anope_override - { - const BotInfo *bi = findbot(Config->NickServ); - if (bi) - UplinkSocket::Message(bi) << "SVSHOLD " << nick << " " << Config->NSReleaseTimeout << " :Being held for registered user"; - } - - /* SVSHOLD - release */ - void SendSVSHoldDel(const Anope::string &nick) anope_override - { - const BotInfo *bi = findbot(Config->NickServ); - if (bi) - UplinkSocket::Message(bi) << "SVSHOLD " << nick; - } - - /* UNSZLINE */ - void SendSZLineDel(const XLine *x) anope_override - { - SendDelLine("Z", x->GetHost()); - } - - /* SZLINE */ - void SendSZLine(User *, const XLine *x) anope_override - { - // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) - timeleft = 172800; - SendAddLine("Z", x->GetHost(), timeleft, x->By, x->GetReason()); - } - - void SendSVSJoin(const BotInfo *source, const Anope::string &nick, const Anope::string &chan, const Anope::string &) anope_override - { - User *u = finduser(nick); - UplinkSocket::Message(source) << "SVSJOIN " << u->GetUID() << " " << chan; - } - - void SendSWhois(const BotInfo *, const Anope::string &who, const Anope::string &mask) anope_override - { - User *u = finduser(who); - - UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " swhois :" << mask; - } - - void SendBOB() anope_override - { - UplinkSocket::Message(Me) << "BURST " << Anope::CurTime; - } - - void SendEOB() anope_override - { - UplinkSocket::Message(Me) << "ENDBURST"; - } - - void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) - { - if (has_globopsmod) - UplinkSocket::Message(source) << "SNONOTICE g :" << buf; - else - UplinkSocket::Message(source) << "SNONOTICE A :" << buf; - } - - void SendLogin(User *u) anope_override - { - if (!u->Account() || u->Account()->HasFlag(NI_UNCONFIRMED)) - return; - - UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " accountname :" << u->Account()->display; - } - - void SendLogout(User *u) anope_override - { - UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " accountname :"; - } - - void SendChannel(Channel *c) anope_override - { - UplinkSocket::Message(Me) << "FJOIN " << c->name << " " << c->creation_time << " +" << c->GetModes(true, true) << " :"; - } - - bool IsNickValid(const Anope::string &nick) anope_override - { - /* InspIRCd, like TS6, uses UIDs on collision, so... */ - if (isdigit(nick[0])) - return false; - - return true; - } - - void SendOper(User *u) anope_override - { - } -}; - -struct IRCDMessageEndburst : IRCDMessage -{ - IRCDMessageEndburst() : IRCDMessage("ENDBURST", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Server *s = source.GetServer(); - - Log(LOG_DEBUG) << "Processed ENDBURST for " << s->GetName(); - - s->Sync(true); - return true; - } -}; - -struct IRCDMessageFHost : IRCDMessage -{ - IRCDMessageFHost(const Anope::string &n) : IRCDMessage(n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetUser()->SetDisplayedHost(params[0]); - return true; - } -}; - -struct IRCDMessageFJoin : IRCDMessage -{ - IRCDMessageFJoin() : IRCDMessage("FJOIN", 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Channel *c = findchan(params[0]); - time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[0], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this FJOIN string contains modes */ - if (keep_their_modes && params.size() >= 3) - { - Anope::string modes; - for (unsigned i = 2; i < params.size() - 1; ++i) - modes += " " + params[i]; - if (!modes.empty()) - modes.erase(modes.begin()); - /* Set the modes internally */ - c->SetModesInternal(source, modes); - } - - spacesepstream sep(params[params.size() - 1]); - Anope::string buf; - while (sep.GetToken(buf)) - { - std::list<ChannelMode *> Status; - - /* Loop through prefixes and find modes for them */ - while (buf[0] != ',') - { - ChannelMode *cm = ModeManager::FindChannelModeByChar(buf[0]); - if (!cm) - { - Log() << "Received unknown mode prefix " << buf[0] << " in FJOIN string"; - buf.erase(buf.begin()); - continue; - } - - buf.erase(buf.begin()); - if (keep_their_modes) - Status.push_back(cm); - } - buf.erase(buf.begin()); - - User *u = finduser(buf); - if (!u) - { - Log(LOG_DEBUG) << "FJOIN for nonexistant user " << buf << " on " << c->name; - continue; - } - - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } - - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } - - return true; - } -}; - -struct IRCDMessageFMode : IRCDMessage -{ - IRCDMessageFMode() : IRCDMessage("FMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* :source FMODE #test 12345678 +nto foo */ - - Anope::string modes = params[2]; - for (unsigned n = 3; n < params.size(); ++n) - modes += " " + params[n]; - - Channel *c = findchan(params[0]); - time_t ts; - - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) - { - ts = 0; - } - - if (c) - c->SetModesInternal(source, modes, ts); - - return true; - } -}; - -struct IRCDMessageFTopic : IRCDMessage -{ - IRCDMessageFTopic() : IRCDMessage("FTOPIC", 4) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* :source FTOPIC channel topicts setby :topic */ - - Channel *c = findchan(params[0]); - if (c) - c->ChangeTopicInternal(params[2], params[3], Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime); - - return true; - } -}; - -struct IRCDMessageIdle : IRCDMessage -{ - IRCDMessageIdle() : IRCDMessage("IDLE", 1) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - const BotInfo *bi = findbot(params[0]); - if (bi) - UplinkSocket::Message(bi) << "IDLE " << source.GetSource() << " " << start_time << " " << (Anope::CurTime - bi->lastmsg); - return true; - } -}; - -/* - * source = numeric of the sending server - * params[0] = uuid - * params[1] = metadata name - * params[2] = data - */ -struct IRCDMessageMetadata : IRCDMessage -{ - IRCDMessageMetadata() : IRCDMessage("METADATA", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (isdigit(params[0][0])) - { - if (params[1].equals_cs("accountname")) - { - User *u = finduser(params[0]); - NickCore *nc = findcore(params[2]); - if (u && nc) - { - u->Login(nc); - - const BotInfo *bi = findbot(Config->NickServ); - const NickAlias *user_na = findnick(u->nick); - if (!Config->NoNicknameOwnership && nickserv && user_na && user_na->nc == nc && user_na->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(bi, UMODE_REGISTERED); - - /* Sometimes a user connects, we send them the usual "this nickname is registered" mess (if - * their server isn't syncing) and then we receive this.. so tell them about it. - */ - if (u->server->IsSynced() && bi) - u->SendMessage(bi, _("You have been logged in as \2%s\2."), nc->display.c_str()); - } - } - - /* - * possible incoming ssl_cert messages: - * Received: :409 METADATA 409AAAAAA ssl_cert :vTrSe c38070ce96e41cc144ed6590a68d45a6 <...> <...> - * Received: :409 METADATA 409AAAAAC ssl_cert :vTrSE Could not get peer certificate: error:00000000:lib(0):func(0):reason(0) - */ - else if (params[1].equals_cs("ssl_cert")) - { - User *u = finduser(params[0]); - if (!u) - return true; - std::string data = params[2].c_str(); - size_t pos1 = data.find(' ') + 1; - size_t pos2 = data.find(' ', pos1); - if ((pos2 - pos1) >= 32) // inspircd supports md5 and sha1 fingerprint hashes -> size 32 or 40 bytes. - { - u->fingerprint = data.substr(pos1, pos2 - pos1); - FOREACH_MOD(I_OnFingerprint, OnFingerprint(u)); - } - } - } - else if (params[0][0] == '#') - { - } - else if (params[0] == "*") - { - // Wed Oct 3 15:40:27 2012: S[14] O :20D METADATA * modules :-m_svstopic.so - - if (params[1].equals_cs("modules") && !params[2].empty()) - { - // only interested when it comes from our uplink - Server* server = source.GetServer(); - if (!server || server->GetUplink() != Me) - return true; - - bool plus = (params[2][0] == '+'); - if (!plus && params[2][0] != '-') - return true; - - bool required = false; - Anope::string module = params[2].substr(1); - - if (module.equals_cs("m_services_account.so")) - required = true; - else if (module.equals_cs("m_hidechans.so")) - required = true; - else if (module.equals_cs("m_chghost.so")) - has_chghostmod = plus; - else if (module.equals_cs("m_chgident.so")) - has_chgidentmod = plus; - else if (module.equals_cs("m_svshold.so")) - ircdproto->CanSVSHold = plus; - else if (module.equals_cs("m_rline.so")) - has_rlinemod = plus; - else if (module.equals_cs("m_topiclock.so")) - has_svstopic_topiclock = plus; - else - return true; - - if (required) - { - if (!plus) - Log() << "Warning: InspIRCd unloaded module " << module << ", Anope won't function correctly without it"; - } - else - { - Log() << "InspIRCd " << (plus ? "loaded" : "unloaded") << " module " << module << ", adjusted functionality"; - } - - } - } - - return true; - } -}; - -struct IRCDMessageMode : IRCDMessage -{ - IRCDMessageMode() : IRCDMessage("MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (ircdproto->IsChannelValid(params[0])) - { - Channel *c = findchan(params[0]); - - Anope::string modes = params[1]; - for (unsigned n = 2; n < params.size(); ++n) - modes += " " + params[n]; - - if (c) - c->SetModesInternal(source, modes); - } - else - { - /* InspIRCd lets opers change another - users modes, we have to kludge this - as it slightly breaks RFC1459 - */ - User *u = source.GetUser(); - // This can happen with server-origin modes. - if (!u) - u = finduser(params[0]); - // if it's still null, drop it like fire. - // most likely situation was that server introduced a nick which we subsequently akilled - if (u) - u->SetModesInternal("%s", params[1].c_str()); - } - - return true; - } -}; - -struct IRCDMessageNick : IRCDMessage -{ - IRCDMessageNick() : IRCDMessage("NICK", 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetUser()->ChangeNick(params[0]); - return true; - } -}; - -struct IRCDMessageOperType : IRCDMessage -{ - IRCDMessageOperType() : IRCDMessage("OPERTYPE", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* opertype is equivalent to mode +o because servers - dont do this directly */ - User *u = source.GetUser(); - if (!u->HasMode(UMODE_OPER)) - u->SetModesInternal("+o"); - - return true; - } -}; - -struct IRCDMessageRSQuit : IRCDMessage -{ - IRCDMessageRSQuit() : IRCDMessage("RSQUIT", 1) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Server *s = Server::Find(params[0]); - if (!s) - return true; - - /* On InspIRCd we must send a SQUIT when we recieve RSQUIT for a server we have juped */ - if (s->HasFlag(SERVER_JUPED)) - UplinkSocket::Message(Me) << "SQUIT " << s->GetSID() << " :" << (params.size() > 1 ? params[1].c_str() : ""); - - FOREACH_MOD(I_OnServerQuit, OnServerQuit(s)); - - s->Delete(s->GetName() + " " + s->GetUplink()->GetName()); - - return true; - } -}; - -struct IRCDMessageServer : IRCDMessage -{ - IRCDMessageServer() : IRCDMessage("SERVER", 5) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - /* - * [Nov 04 00:08:46.308435 2009] debug: Received: SERVER irc.inspircd.com pass 0 964 :Testnet Central! - * 0: name - * 1: pass - * 2: hops - * 3: numeric - * 4: desc - */ - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - unsigned int hops = Anope::string(params[2]).is_pos_number_only() ? convertTo<unsigned>(params[2]) : 0; - new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[4], params[3]); - return true; - } -}; - -struct IRCDMessageTime : IRCDMessage -{ - IRCDMessageTime() : IRCDMessage("TIME", 2) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - UplinkSocket::Message(Me) << "TIME " << source.GetSource() << " " << params[1] << " " << Anope::CurTime; - return true; - } -}; - -struct IRCDMessageUID : IRCDMessage -{ - IRCDMessageUID() : IRCDMessage("UID", 8) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - /* - * [Nov 03 22:09:58.176252 2009] debug: Received: :964 UID 964AAAAAC 1225746297 w00t2 localhost testnet.user w00t 127.0.0.1 1225746302 +iosw +ACGJKLNOQcdfgjklnoqtx :Robin Burchell <w00t@inspircd.org> - * 0: uid - * 1: ts - * 2: nick - * 3: host - * 4: dhost - * 5: ident - * 6: ip - * 7: signon - * 8+: modes and params -- IMPORTANT, some modes (e.g. +s) may have parameters. So don't assume a fixed position of realname! - * last: realname - */ - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - time_t ts = convertTo<time_t>(params[1]); - - Anope::string modes = params[8]; - for (unsigned i = 9; i < params.size() - 1; ++i) - modes += " " + params[i]; - - User *u = new User(params[2], params[5], params[3], params[4], params[6], source.GetServer(), params[params.size() - 1], ts, modes, params[0]); - if (u->server->IsSynced() && nickserv) - nickserv->Validate(u); - - return true; - } -}; - diff --git a/modules/protocol/inspircd11.cpp b/modules/protocol/inspircd11.cpp index 1ac97ddcc..aaaec9fef 100644 --- a/modules/protocol/inspircd11.cpp +++ b/modules/protocol/inspircd11.cpp @@ -45,7 +45,7 @@ class InspIRCdProto : public IRCDProto { if (nick.empty() || vIdent.empty()) return; - UplinkSocket::Message(findbot(Config->OperServ)) << "CHGIDENT " << nick << " " << vIdent; + UplinkSocket::Message(OperServ) << "CHGIDENT " << nick << " " << vIdent; } else Log() << "CHGIDENT not loaded!"; @@ -57,7 +57,7 @@ class InspIRCdProto : public IRCDProto { if (nick.empty() || vhost.empty()) return; - UplinkSocket::Message(findbot(Config->OperServ)) << "CHGHOST " << nick << " " << vhost; + UplinkSocket::Message(OperServ) << "CHGHOST " << nick << " " << vhost; } else Log() << "CHGHOST not loaded!"; @@ -84,13 +84,13 @@ class InspIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLineDel(x); + IRCD->SendSZLineDel(x); return; } } catch (const SocketException &) { } - UplinkSocket::Message(findbot(Config->OperServ)) << "GLINE " << x->Mask; + UplinkSocket::Message(OperServ) << "GLINE " << x->mask; } void SendTopic(BotInfo *whosets, Channel *c) anope_override @@ -128,10 +128,10 @@ class InspIRCdProto : public IRCDProto return; /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - x = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); + x = new XLine("*@" + u->host, old->by, old->expires, old->reason, old->id); old->manager->AddXLine(x); - Log(findbot(Config->OperServ), "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; + Log(OperServ, "akill") << "AKILL: Added an akill for " << x->mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->mask; } /* ZLine if we can instead */ @@ -140,17 +140,17 @@ class InspIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLine(u, x); + IRCD->SendSZLine(u, x); return; } } catch (const SocketException &) { } // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(Me) << "ADDLINE G " << x->Mask << " " << x->By << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); + UplinkSocket::Message(Me) << "ADDLINE G " << x->mask << " " << x->by << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); } void SendSVSKillInternal(const BotInfo *source, User *user, const Anope::string &buf) anope_override @@ -214,11 +214,11 @@ class InspIRCdProto : public IRCDProto */ UserContainer *uc = c->FindUser(user); if (uc != NULL) - uc->Status->ClearFlags(); + uc->status->ClearFlags(); - BotInfo *setter = findbot(user->nick); + BotInfo *setter = BotInfo::Find(user->nick); for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); } } @@ -226,17 +226,17 @@ class InspIRCdProto : public IRCDProto /* UNSQLINE */ void SendSQLineDel(const XLine *x) anope_override { - UplinkSocket::Message(findbot(Config->OperServ)) << "QLINE " << x->Mask; + UplinkSocket::Message(OperServ) << "QLINE " << x->mask; } /* SQLINE */ void SendSQLine(User *, const XLine *x) anope_override { // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(Me) << "ADDLINE Q " << x->Mask << " " << x->By << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); + UplinkSocket::Message(Me) << "ADDLINE Q " << x->mask << " " << x->by << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); } /* Functions that use serval cmd functions */ @@ -251,7 +251,7 @@ class InspIRCdProto : public IRCDProto void SendConnect() anope_override { - current_pass = Config->Uplinks[CurrentUplink]->password; + current_pass = Config->Uplinks[Anope::CurrentUplink]->password; SendServer(Me); UplinkSocket::Message() << "BURST"; Module *enc = ModuleManager::FindFirstOf(ENCRYPTION); @@ -261,29 +261,29 @@ class InspIRCdProto : public IRCDProto /* SVSHOLD - set */ void SendSVSHold(const Anope::string &nick) anope_override { - UplinkSocket::Message(findbot(Config->OperServ)) << "SVSHOLD " << nick << " " << Config->NSReleaseTimeout << "s :Being held for registered user"; + UplinkSocket::Message(OperServ) << "SVSHOLD " << nick << " " << Config->NSReleaseTimeout << "s :Being held for registered user"; } /* SVSHOLD - release */ void SendSVSHoldDel(const Anope::string &nick) anope_override { - UplinkSocket::Message(findbot(Config->OperServ)) << "SVSHOLD " << nick; + UplinkSocket::Message(OperServ) << "SVSHOLD " << nick; } /* UNSZLINE */ void SendSZLineDel(const XLine *x) anope_override { - UplinkSocket::Message(findbot(Config->OperServ)) << "ZLINE " << x->GetHost(); + UplinkSocket::Message(OperServ) << "ZLINE " << x->GetHost(); } /* SZLINE */ void SendSZLine(User *, const XLine *x) anope_override { // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(Me) << "ADDLINE Z " << x->GetHost() << " " << x->By << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); + UplinkSocket::Message(Me) << "ADDLINE Z " << x->GetHost() << " " << x->by << " " << Anope::CurTime << " " << timeleft << " :" << x->GetReason(); } void SendSVSJoin(const BotInfo *source, const Anope::string &nick, const Anope::string &chan, const Anope::string &) anope_override @@ -334,11 +334,11 @@ class ChannelModeFlood : public ChannelModeParam } }; -struct IRCDMessageCapab : IRCDMessage +struct IRCDMessageCapab : Message::Capab { - IRCDMessageCapab() : IRCDMessage("CAPAB", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageCapab(Module *creator) : Message::Capab(creator, "CAPAB") { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - bool Run(MessageSource &, const std::vector<Anope::string> ¶ms) anope_override + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { if (params[0].equals_cs("START")) { @@ -348,7 +348,7 @@ struct IRCDMessageCapab : IRCDMessage has_chghostmod = false; has_chgidentmod = false; has_hidechansmod = false; - ircdproto->CanSVSHold = false; + IRCD->CanSVSHold = false; } else if (params[0].equals_cs("MODULES") && params.size() > 1) { @@ -357,7 +357,7 @@ struct IRCDMessageCapab : IRCDMessage if (params[1].find("m_services.so") != Anope::string::npos) has_servicesmod = true; if (params[1].find("m_svshold.so") != Anope::string::npos) - ircdproto->CanSVSHold = true; + IRCD->CanSVSHold = true; if (params[1].find("m_chghost.so") != Anope::string::npos) has_chghostmod = true; if (params[1].find("m_chgident.so") != Anope::string::npos) @@ -531,7 +531,7 @@ struct IRCDMessageCapab : IRCDMessage else if (capab.find("MAXMODES=") != Anope::string::npos) { Anope::string maxmodes(capab.begin() + 9, capab.end()); - ircdproto->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; + IRCD->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; } } } @@ -540,25 +540,25 @@ struct IRCDMessageCapab : IRCDMessage if (!has_globopsmod) { UplinkSocket::Message() << "ERROR :m_globops is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_globops module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_globops module loaded, and this is required."; + Anope::Quitting = true; return false; } if (!has_servicesmod) { UplinkSocket::Message() << "ERROR :m_services is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_services module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_services module loaded, and this is required."; + Anope::Quitting = true; return false; } if (!has_hidechansmod) { UplinkSocket::Message() << "ERROR :m_hidechans.so is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server deos not have the m_hidechans module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server deos not have the m_hidechans module loaded, and this is required."; + Anope::Quitting = true; return false; } - if (!ircdproto->CanSVSHold) + if (!IRCD->CanSVSHold) Log() << "SVSHOLD missing, Usage disabled until module is loaded."; if (!has_chghostmod) Log() << "CHGHOST missing, Usage disabled until module is loaded."; @@ -566,17 +566,17 @@ struct IRCDMessageCapab : IRCDMessage Log() << "CHGIDENT missing, Usage disabled until module is loaded."; } - return true; + return Message::Capab::Run(source, params); } }; struct IRCDMessageChgIdent : IRCDMessage { - IRCDMessageChgIdent(const Anope::string &n) : IRCDMessage(n, 2) { } + IRCDMessageChgIdent(Module *creator, const Anope::string &n) : IRCDMessage(creator, n, 2) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (!u) { Log(LOG_DEBUG) << "CHGIDENT for nonexistent user " << params[0]; @@ -590,7 +590,7 @@ struct IRCDMessageChgIdent : IRCDMessage struct IRCDMessageChgName : IRCDMessage { - IRCDMessageChgName(const Anope::string &n) : IRCDMessage(n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageChgName(Module *creator, const Anope::string &n) : IRCDMessage(creator, n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -601,7 +601,7 @@ struct IRCDMessageChgName : IRCDMessage struct IRCDMessageEndBurst : IRCDMessage { - IRCDMessageEndBurst() : IRCDMessage("ENDBURST", 0) { } + IRCDMessageEndBurst(Module *creator) : IRCDMessage(creator, "ENDBURST", 0) { } bool Run(MessageSource &, const std::vector<Anope::string> ¶ms) anope_override { @@ -612,7 +612,7 @@ struct IRCDMessageEndBurst : IRCDMessage struct IRCDMessageFHost : IRCDMessage { - IRCDMessageFHost(const Anope::string &n) : IRCDMessage(n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageFHost(Module *creator, const Anope::string &n) : IRCDMessage(creator, n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -623,94 +623,47 @@ struct IRCDMessageFHost : IRCDMessage struct IRCDMessageFJoin : IRCDMessage { - IRCDMessageFJoin() : IRCDMessage("FJOIN", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageFJoin(Module *creator) : IRCDMessage(creator, "FJOIN", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); - time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[0], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; + std::list<Message::Join::SJoinUser> users; spacesepstream sep(params[params.size() - 1]); Anope::string buf; + while (sep.GetToken(buf)) { - std::list<ChannelMode *> Status; - char ch; + Message::Join::SJoinUser sju; /* Loop through prefixes */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) + for (char ch; (ch = ModeManager::GetStatusChar(buf[0]));) { ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); + buf.erase(buf.begin()); if (!cm) { - Log() << "Received unknown mode prefix " << buf[0] << " in FJOIN string"; - buf.erase(buf.begin()); + Log() << "Received unknown mode prefix " << ch << " in FJOIN string"; continue; } - buf.erase(buf.begin()); - if (keep_their_modes) - Status.push_back(cm); + sju.first.SetFlag(cm->name); } /* Erase the , */ buf.erase(buf.begin()); - User *u = finduser(buf); - if (!u) + sju.second = User::Find(buf); + if (!sju.second) { - Log(LOG_DEBUG) << "FJOIN for nonexistant user " << buf << " on " << c->name; + Log(LOG_DEBUG) << "FJOIN for nonexistant user " << buf << " on " << params[0]; continue; } - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); } - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } + time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime; + Message::Join::SJoin(source, params[0], ts, "", users); return true; } @@ -718,13 +671,13 @@ struct IRCDMessageFJoin : IRCDMessage struct IRCDMessageFMode : IRCDMessage { - IRCDMessageFMode() : IRCDMessage("FMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageFMode(Module *creator) : IRCDMessage(creator, "FMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { /* :source FMODE #test 12345678 +nto foo */ - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (!c) return true; time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : 0; @@ -742,11 +695,11 @@ struct IRCDMessageFMode : IRCDMessage struct IRCDMessageFTopic : IRCDMessage { - IRCDMessageFTopic() : IRCDMessage("FTOPIC", 4) { } + IRCDMessageFTopic(Module *creator) : IRCDMessage(creator, "FTOPIC", 4) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c) c->ChangeTopicInternal(params[2], params[3], Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime); @@ -756,25 +709,25 @@ struct IRCDMessageFTopic : IRCDMessage struct IRCDMessageIdle : IRCDMessage { - IRCDMessageIdle() : IRCDMessage("IDLE", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageIdle(Module *creator) : IRCDMessage(creator, "IDLE", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - const BotInfo *bi = findbot(params[0]); - UplinkSocket::Message(bi) << "IDLE " << source.GetSource() << " " << start_time << " " << (bi ? Anope::CurTime - bi->lastmsg : 0); + const BotInfo *bi = BotInfo::Find(params[0]); + UplinkSocket::Message(bi) << "IDLE " << source.GetSource() << " " << Anope::StartTime << " " << (bi ? Anope::CurTime - bi->lastmsg : 0); return true; } }; struct IRCDMessageMode : IRCDMessage { - IRCDMessageMode() : IRCDMessage("MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageMode(Module *creator) : IRCDMessage(creator, "MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (ircdproto->IsChannelValid(params[0])) + if (IRCD->IsChannelValid(params[0])) { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); time_t ts; try @@ -791,7 +744,7 @@ struct IRCDMessageMode : IRCDMessage } else { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetModesInternal("%s", params[1].c_str()); } @@ -802,7 +755,7 @@ struct IRCDMessageMode : IRCDMessage struct IRCDMessageNick : IRCDMessage { - IRCDMessageNick() : IRCDMessage("NICK", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -811,19 +764,19 @@ struct IRCDMessageNick : IRCDMessage time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; User *user = new User(params[1], params[4], params[2], params[3], params[6], source.GetServer(), params[7], ts, params[5]); - if (nickserv) + if (NickServService) { - NickAlias *na = findnick(user->nick); + NickAlias *na = NickAlias::Find(user->nick); Anope::string *svidbuf = na ? na->nc->GetExt<ExtensibleItemClass<Anope::string> *>("authenticationtoken") : NULL; if (na && svidbuf && *svidbuf == params[0]) { NickCore *nc = na->nc; user->Login(nc); if (!Config->NoNicknameOwnership && na->nc->HasFlag(NI_UNCONFIRMED) == false) - user->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + user->SetMode(NickServ, UMODE_REGISTERED); } - else if (nickserv) - nickserv->Validate(user); + else + NickServService->Validate(user); } } else if (params.size() == 1 && source.GetUser()) @@ -835,7 +788,7 @@ struct IRCDMessageNick : IRCDMessage struct IRCDMessageOperType : IRCDMessage { - IRCDMessageOperType() : IRCDMessage("OPERTYPE", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageOperType(Module *creator) : IRCDMessage(creator, "OPERTYPE", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -851,7 +804,7 @@ struct IRCDMessageOperType : IRCDMessage struct IRCDMessageRSQuit : IRCDMessage { - IRCDMessageRSQuit() : IRCDMessage("RSQUIT", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageRSQuit(Module *creator) : IRCDMessage(creator, "RSQUIT", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -873,7 +826,7 @@ struct IRCDMessageRSQuit : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -888,22 +841,21 @@ class ProtoInspIRCd : public Module InspIRCdProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageJoin core_message_join; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; + Message::Away message_away; + Message::Error message_error; + Message::Join message_join; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Topic message_topic; + Message::Version message_version; /* Our message handlers */ IRCDMessageCapab message_capab; @@ -934,19 +886,30 @@ class ProtoInspIRCd : public Module public: ProtoInspIRCd(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - message_chgident("CHGIDENT"), message_setident("SETIDENT"), - message_chgname("CHGNAME"), message_setname("SETNAME"), - message_fhost("FHOST"), message_sethost("SETHOST") + message_away(this), message_error(this), message_join(this), message_kick(this), message_kill(this), + message_motd(this), message_part(this), message_ping(this), message_privmsg(this), message_quit(this), + message_squit(this), message_stats(this), message_time(this), message_topic(this), message_version(this), + + message_capab(this), message_chgident(this, "CHGIDENT"), message_setident(this, "SETIDENT"), + message_chgname(this, "CHGNAME"), message_setname(this, "SETNAME"), message_endburst(this), + message_fhost(this, "FHOST"), message_sethost(this, "SETHOST"), message_fjoin(this), + message_fmode(this), message_ftopic(this), message_idle(this), message_mode(this), + message_nick(this), message_opertype(this), message_rsquit(this), message_server(this) { this->SetAuthor("Anope"); - Capab.insert("NOQUIT"); + Servers::Capab.insert("NOQUIT"); this->AddModes(); ModuleManager::Attach(I_OnUserNickChange, this); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { u->RemoveModeInternal(ModeManager::FindUserModeByName(UMODE_REGISTERED)); diff --git a/modules/protocol/inspircd12.cpp b/modules/protocol/inspircd12.cpp index 3d925bd4a..09ba57f00 100644 --- a/modules/protocol/inspircd12.cpp +++ b/modules/protocol/inspircd12.cpp @@ -13,22 +13,354 @@ #include "module.h" -/* inspircd-ts6.h uses these */ static bool has_globopsmod = false; static bool has_chghostmod = false; static bool has_chgidentmod = false; static bool has_rlinemod = false; static bool has_svstopic_topiclock = false; -//static unsigned int spanningtree_proto_ver = 1201; -#include "inspircd-ts6.h" - static bool has_servicesmod = false; static bool has_hidechansmod = false; -class InspIRCd12Proto : public InspIRCdTS6Proto +class ChannelModeFlood : public ChannelModeParam +{ + public: + ChannelModeFlood(char modeChar, bool minusNoArg) : ChannelModeParam(CMODE_FLOOD, modeChar, minusNoArg) { } + + bool IsValid(const Anope::string &value) const anope_override + { + try + { + Anope::string rest; + if (!value.empty() && value[0] != ':' && convertTo<int>(value[0] == '*' ? value.substr(1) : value, rest, false) > 0 && rest[0] == ':' && rest.length() > 1 && convertTo<int>(rest.substr(1), rest, false) > 0 && rest.empty()) + return true; + } + catch (const ConvertException &) { } + + return false; + } +}; + +class InspIRCd12Proto : public IRCDProto { + private: + void SendChgIdentInternal(const Anope::string &nick, const Anope::string &vIdent) + { + if (!has_chgidentmod) + Log() << "CHGIDENT not loaded!"; + else + UplinkSocket::Message(HostServ) << "CHGIDENT " << nick << " " << vIdent; + } + + void SendChgHostInternal(const Anope::string &nick, const Anope::string &vhost) + { + if (!has_chghostmod) + Log() << "CHGHOST not loaded!"; + else + UplinkSocket::Message(Me) << "CHGHOST " << nick << " " << vhost; + } + + void SendAddLine(const Anope::string &type, const Anope::string &mask, time_t duration, const Anope::string &addedby, const Anope::string &reason) + { + UplinkSocket::Message(Me) << "ADDLINE " << type << " " << mask << " " << addedby << " " << Anope::CurTime << " " << duration << " :" << reason; + } + + void SendDelLine(const Anope::string &type, const Anope::string &mask) + { + UplinkSocket::Message(Me) << "DELLINE " << type << " " << mask; + } + public: - InspIRCd12Proto() : InspIRCdTS6Proto("InspIRCd 1.2") { } + InspIRCd12Proto() : IRCDProto("InspIRCd 1.2") + { + DefaultPseudoclientModes = "+I"; + CanSVSNick = true; + CanSetVHost = true; + CanSetVIdent = true; + CanSQLine = true; + CanSZLine = true; + CanSVSHold = true; + CanCertFP = true; + RequiresID = true; + MaxModes = 20; + } + + void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override + { + UplinkSocket::Message(bi) << "NOTICE $" << dest->GetName() << " :" << msg; + } + + void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override + { + UplinkSocket::Message(bi) << "PRIVMSG $" << dest->GetName() << " :" << msg; + } + + void SendAkillDel(const XLine *x) anope_override + { + /* InspIRCd may support regex bans */ + if (x->IsRegex() && has_rlinemod) + { + Anope::string mask = x->mask; + size_t h = x->mask.find('#'); + if (h != Anope::string::npos) + mask = mask.replace(h, 1, ' '); + SendDelLine("R", mask); + return; + } + else if (x->IsRegex() || x->HasNickOrReal()) + return; + + SendDelLine("G", x->mask); + } + + void SendTopic(BotInfo *whosets, Channel *c) anope_override + { + if (has_svstopic_topiclock) + { + UplinkSocket::Message(c->ci->WhoSends()) << "SVSTOPIC " << c->name << " " << c->topic_ts << " " << c->topic_setter << " :" << c->topic; + } + else + { + /* If the last time a topic was set is after the TS we want for this topic we must bump this topic's timestamp to now */ + time_t ts = c->topic_ts; + if (c->topic_time > ts) + ts = Anope::CurTime; + /* But don't modify c->topic_ts, it should remain set to the real TS we want as ci->last_topic_time pulls from it */ + UplinkSocket::Message(whosets) << "FTOPIC " << c->name << " " << ts << " " << c->topic_setter << " :" << c->topic; + } + } + + void SendVhostDel(User *u) anope_override + { + if (u->HasMode(UMODE_CLOAK)) + this->SendChgHostInternal(u->nick, u->chost); + else + this->SendChgHostInternal(u->nick, u->host); + + if (has_chgidentmod && u->GetIdent() != u->GetVIdent()) + this->SendChgIdentInternal(u->nick, u->GetIdent()); + } + + void SendAkill(User *u, XLine *x) anope_override + { + // Calculate the time left before this would expire, capping it at 2 days + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) + timeleft = 172800; + + /* InspIRCd may support regex bans, if they do we can send this and forget about it */ + if (x->IsRegex() && has_rlinemod) + { + Anope::string mask = x->mask; + size_t h = x->mask.find('#'); + if (h != Anope::string::npos) + mask = mask.replace(h, 1, ' '); + SendAddLine("R", mask, timeleft, x->by, x->GetReason()); + return; + } + else if (x->IsRegex() || x->HasNickOrReal()) + { + if (!u) + { + /* No user (this akill was just added), and contains nick and/or realname. Find users that match and ban them */ + for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) + if (x->manager->Check(it->second, x)) + this->SendAkill(it->second, x); + return; + } + + const XLine *old = x; + + if (old->manager->HasEntry("*@" + u->host)) + return; + + /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ + x = new XLine("*@" + u->host, old->by, old->expires, old->reason, old->id); + old->manager->AddXLine(x); + + Log(OperServ, "akill") << "AKILL: Added an akill for " << x->mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->mask; + } + + /* ZLine if we can instead */ + try + { + if (x->GetUser() == "*") + { + sockaddrs(x->GetHost()); + IRCD->SendSZLine(u, x); + return; + } + } + catch (const SocketException &) { } + SendAddLine("G", x->GetUser() + "@" + x->GetHost(), timeleft, x->by, x->GetReason()); + } + + void SendNumericInternal(int numeric, const Anope::string &dest, const Anope::string &buf) anope_override + { + UplinkSocket::Message() << "PUSH " << dest << " ::" << Me->GetName() << " " << numeric << " " << dest << " " << buf; + } + + void SendModeInternal(const BotInfo *source, const Channel *dest, const Anope::string &buf) anope_override + { + UplinkSocket::Message(source) << "FMODE " << dest->name << " " << dest->creation_time << " " << buf; + } + + void SendModeInternal(const BotInfo *bi, const User *u, const Anope::string &buf) anope_override + { + UplinkSocket::Message(bi) << "MODE " << u->GetUID() << " " << buf; + } + + void SendClientIntroduction(const User *u) anope_override + { + Anope::string modes = "+" + u->GetModes(); + UplinkSocket::Message(Me) << "UID " << u->GetUID() << " " << u->timestamp << " " << u->nick << " " << u->host << " " << u->host << " " << u->GetIdent() << " 0.0.0.0 " << u->timestamp << " " << modes << " :" << u->realname; + } + + /* SERVER services-dev.chatspike.net password 0 :Description here */ + void SendServer(const Server *server) anope_override + { + UplinkSocket::Message() << "SERVER " << server->GetName() << " " << Config->Uplinks[Anope::CurrentUplink]->password << " " << server->GetHops() << " " << server->GetSID() << " :" << server->GetDescription(); + } + + /* JOIN */ + void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override + { + UplinkSocket::Message(Me) << "FJOIN " << c->name << " " << c->creation_time << " +" << c->GetModes(true, true) << " :," << user->GetUID(); + /* Note that we can send this with the FJOIN but choose not to + * because the mode stacker will handle this and probably will + * merge these modes with +nrt and other mlocked modes + */ + if (status) + { + /* First save the channel status incase uc->Status == status */ + ChannelStatus cs = *status; + /* If the user is internally on the channel with flags, kill them so that + * the stacker will allow this. + */ + UserContainer *uc = c->FindUser(user); + if (uc != NULL) + uc->status->ClearFlags(); + + BotInfo *setter = BotInfo::Find(user->nick); + for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) + c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); + } + } + + /* UNSQLINE */ + void SendSQLineDel(const XLine *x) anope_override + { + SendDelLine("Q", x->mask); + } + + /* SQLINE */ + void SendSQLine(User *, const XLine *x) anope_override + { + // Calculate the time left before this would expire, capping it at 2 days + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) + timeleft = 172800; + SendAddLine("Q", x->mask, timeleft, x->by, x->GetReason()); + } + + /* Functions that use serval cmd functions */ + + void SendVhost(User *u, const Anope::string &vIdent, const Anope::string &vhost) anope_override + { + if (!vIdent.empty()) + this->SendChgIdentInternal(u->nick, vIdent); + if (!vhost.empty()) + this->SendChgHostInternal(u->nick, vhost); + } + + void SendConnect() anope_override + { + SendServer(Me); + UplinkSocket::Message(Me) << "BURST"; + Module *enc = ModuleManager::FindFirstOf(ENCRYPTION); + UplinkSocket::Message(Me) << "VERSION :Anope-" << Anope::Version() << " " << Config->ServerName << " :" << IRCD->GetProtocolName() << " - (" << (enc ? enc->name : "unknown") << ") -- " << Anope::VersionBuildString(); + } + + /* SVSHOLD - set */ + void SendSVSHold(const Anope::string &nick) anope_override + { + UplinkSocket::Message(NickServ) << "SVSHOLD " << nick << " " << Config->NSReleaseTimeout << " :Being held for registered user"; + } + + /* SVSHOLD - release */ + void SendSVSHoldDel(const Anope::string &nick) anope_override + { + UplinkSocket::Message(NickServ) << "SVSHOLD " << nick; + } + + /* UNSZLINE */ + void SendSZLineDel(const XLine *x) anope_override + { + SendDelLine("Z", x->GetHost()); + } + + /* SZLINE */ + void SendSZLine(User *, const XLine *x) anope_override + { + // Calculate the time left before this would expire, capping it at 2 days + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) + timeleft = 172800; + SendAddLine("Z", x->GetHost(), timeleft, x->by, x->GetReason()); + } + + void SendSVSJoin(const BotInfo *source, const Anope::string &nick, const Anope::string &chan, const Anope::string &) anope_override + { + User *u = User::Find(nick); + UplinkSocket::Message(source) << "SVSJOIN " << u->GetUID() << " " << chan; + } + + void SendSWhois(const BotInfo *, const Anope::string &who, const Anope::string &mask) anope_override + { + User *u = User::Find(who); + + UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " swhois :" << mask; + } + + void SendBOB() anope_override + { + UplinkSocket::Message(Me) << "BURST " << Anope::CurTime; + } + + void SendEOB() anope_override + { + UplinkSocket::Message(Me) << "ENDBURST"; + } + + void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) + { + if (has_globopsmod) + UplinkSocket::Message(source) << "SNONOTICE g :" << buf; + else + UplinkSocket::Message(source) << "SNONOTICE A :" << buf; + } + + void SendLogin(User *u) anope_override + { + if (!u->Account() || u->Account()->HasFlag(NI_UNCONFIRMED)) + return; + + UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " accountname :" << u->Account()->display; + } + + void SendLogout(User *u) anope_override + { + UplinkSocket::Message(Me) << "METADATA " << u->GetUID() << " accountname :"; + } + + void SendChannel(Channel *c) anope_override + { + UplinkSocket::Message(Me) << "FJOIN " << c->name << " " << c->creation_time << " +" << c->GetModes(true, true) << " :"; + } + + void SendOper(User *u) anope_override + { + } }; class InspIRCdExtBan : public ChannelModeList @@ -44,7 +376,7 @@ class InspIRCdExtBan : public ChannelModeList { Anope::string real_mask = mask.substr(2); - Entry en(this->Name, real_mask); + Entry en(this->name, real_mask); if (en.Matches(u)) return true; } @@ -52,7 +384,7 @@ class InspIRCdExtBan : public ChannelModeList { Anope::string real_mask = mask.substr(2); - Channel *c = findchan(real_mask); + Channel *c = Channel::Find(real_mask); if (c != NULL && c->FindUser(u) != NULL) return true; } @@ -82,9 +414,9 @@ class InspIRCdExtBan : public ChannelModeList } }; -struct IRCDMessageCapab : IRCDMessage +struct IRCDMessageCapab : Message::Capab { - IRCDMessageCapab() : IRCDMessage("CAPAB", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageCapab(Module *creator) : Message::Capab(creator, "CAPAB") { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -96,7 +428,7 @@ struct IRCDMessageCapab : IRCDMessage has_chghostmod = false; has_chgidentmod = false; has_hidechansmod = false; - ircdproto->CanSVSHold = false; + IRCD->CanSVSHold = false; } else if (params[0].equals_cs("MODULES") && params.size() > 1) { @@ -105,7 +437,7 @@ struct IRCDMessageCapab : IRCDMessage if (params[1].find("m_services_account.so") != Anope::string::npos) has_servicesmod = true; if (params[1].find("m_svshold.so") != Anope::string::npos) - ircdproto->CanSVSHold = true; + IRCD->CanSVSHold = true; if (params[1].find("m_chghost.so") != Anope::string::npos) has_chghostmod = true; if (params[1].find("m_chgident.so") != Anope::string::npos) @@ -113,7 +445,7 @@ struct IRCDMessageCapab : IRCDMessage if (params[1].find("m_hidechans.so") != Anope::string::npos) has_hidechansmod = true; if (params[1].find("m_servprotect.so") != Anope::string::npos) - ircdproto->DefaultPseudoclientModes = "+Ik"; + IRCD->DefaultPseudoclientModes = "+Ik"; if (params[1].find("m_rline.so") != Anope::string::npos) has_rlinemod = true; } @@ -383,7 +715,7 @@ struct IRCDMessageCapab : IRCDMessage else if (capab.find("MAXMODES=") != Anope::string::npos) { Anope::string maxmodes(capab.begin() + 9, capab.end()); - ircdproto->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; + IRCD->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; } } } @@ -392,25 +724,25 @@ struct IRCDMessageCapab : IRCDMessage if (!has_globopsmod) { UplinkSocket::Message() << "ERROR :m_globops is not loaded. This is required by Anope"; - quitmsg = "Remote server does not have the m_globops module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "Remote server does not have the m_globops module loaded, and this is required."; + Anope::Quitting = true; return false; } if (!has_servicesmod) { UplinkSocket::Message() << "ERROR :m_services_account.so is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_services_account module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_services_account module loaded, and this is required."; + Anope::Quitting = true; return false; } if (!has_hidechansmod) { UplinkSocket::Message() << "ERROR :m_hidechans.so is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_hidechans module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_hidechans module loaded, and this is required."; + Anope::Quitting = true; return false; } - if (!ircdproto->CanSVSHold) + if (!IRCD->CanSVSHold) Log() << "SVSHOLD missing, Usage disabled until module is loaded."; if (!has_chghostmod) Log() << "CHGHOST missing, Usage disabled until module is loaded."; @@ -418,17 +750,19 @@ struct IRCDMessageCapab : IRCDMessage Log() << "CHGIDENT missing, Usage disabled until module is loaded."; } - return true; + Servers::Capab.insert("NOQUIT"); + + return Message::Capab::Run(source, params); } }; struct IRCDMessageChgIdent : IRCDMessage { - IRCDMessageChgIdent() : IRCDMessage("CHGIDENT", 2) { } + IRCDMessageChgIdent(Module *creator) : IRCDMessage(creator, "CHGIDENT", 2) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetIdent(params[1]); return true; @@ -437,7 +771,7 @@ struct IRCDMessageChgIdent : IRCDMessage struct IRCDMessageChgName : IRCDMessage { - IRCDMessageChgName(const Anope::string &n) : IRCDMessage(n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageChgName(Module *creator, const Anope::string &n) : IRCDMessage(creator, n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -446,9 +780,345 @@ struct IRCDMessageChgName : IRCDMessage } }; +struct IRCDMessageEndburst : IRCDMessage +{ + IRCDMessageEndburst(Module *creator) : IRCDMessage(creator, "ENDBURST", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + Server *s = source.GetServer(); + + Log(LOG_DEBUG) << "Processed ENDBURST for " << s->GetName(); + + s->Sync(true); + return true; + } +}; + +struct IRCDMessageFHost : IRCDMessage +{ + IRCDMessageFHost(Module *creator, const Anope::string &n) : IRCDMessage(creator, n, 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + source.GetUser()->SetDisplayedHost(params[0]); + return true; + } +}; + +struct IRCDMessageFJoin : IRCDMessage +{ + IRCDMessageFJoin(Module *creator) : IRCDMessage(creator, "FJOIN", 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + Anope::string modes; + if (params.size() >= 3) + { + for (unsigned i = 2; i < params.size() - 1; ++i) + modes += " " + params[i]; + if (!modes.empty()) + modes.erase(modes.begin()); + } + + std::list<Message::Join::SJoinUser> users; + + spacesepstream sep(params[params.size() - 1]); + Anope::string buf; + while (sep.GetToken(buf)) + { + Message::Join::SJoinUser sju; + + /* Loop through prefixes and find modes for them */ + for (char c; (c = buf[0]) != ',';) + { + ChannelMode *cm = ModeManager::FindChannelModeByChar(c); + if (!cm) + { + Log() << "Received unknown mode prefix " << c << " in FJOIN string"; + continue; + } + + sju.first.SetFlag(cm->name); + } + /* Erase the , */ + buf.erase(buf.begin()); + + sju.second = User::Find(buf); + if (!sju.second) + { + Log(LOG_DEBUG) << "FJOIN for nonexistant user " << buf << " on " << params[0]; + continue; + } + + users.push_back(sju); + } + + time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime; + Message::Join::SJoin(source, params[0], ts, "", users); + + return true; + } +}; + +struct IRCDMessageFMode : IRCDMessage +{ + IRCDMessageFMode(Module *creator) : IRCDMessage(creator, "FMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + /* :source FMODE #test 12345678 +nto foo */ + + Anope::string modes = params[2]; + for (unsigned n = 3; n < params.size(); ++n) + modes += " " + params[n]; + + Channel *c = Channel::Find(params[0]); + time_t ts; + + try + { + ts = convertTo<time_t>(params[1]); + } + catch (const ConvertException &) + { + ts = 0; + } + + if (c) + c->SetModesInternal(source, modes, ts); + + return true; + } +}; + +struct IRCDMessageFTopic : IRCDMessage +{ + IRCDMessageFTopic(Module *creator) : IRCDMessage(creator, "FTOPIC", 4) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + /* :source FTOPIC channel topicts setby :topic */ + + Channel *c = Channel::Find(params[0]); + if (c) + c->ChangeTopicInternal(params[2], params[3], Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime); + + return true; + } +}; + +struct IRCDMessageIdle : IRCDMessage +{ + IRCDMessageIdle(Module *creator) : IRCDMessage(creator, "IDLE", 1) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + const BotInfo *bi = BotInfo::Find(params[0]); + if (bi) + UplinkSocket::Message(bi) << "IDLE " << source.GetSource() << " " << Anope::StartTime << " " << (Anope::CurTime - bi->lastmsg); + return true; + } +}; + +/* + * source = numeric of the sending server + * params[0] = uuid + * params[1] = metadata name + * params[2] = data + */ +struct IRCDMessageMetadata : IRCDMessage +{ + IRCDMessageMetadata(Module *creator) : IRCDMessage(creator, "METADATA", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + if (isdigit(params[0][0])) + { + if (params[1].equals_cs("accountname")) + { + User *u = User::Find(params[0]); + NickCore *nc = NickCore::Find(params[2]); + if (u && nc) + { + u->Login(nc); + + const NickAlias *user_na = NickAlias::Find(u->nick); + if (!Config->NoNicknameOwnership && user_na && user_na->nc == nc && user_na->nc->HasFlag(NI_UNCONFIRMED) == false) + u->SetMode(NickServ, UMODE_REGISTERED); + + /* Sometimes a user connects, we send them the usual "this nickname is registered" mess (if + * their server isn't syncing) and then we receive this.. so tell them about it. + */ + if (u->server->IsSynced() && NickServ) + u->SendMessage(NickServ, _("You have been logged in as \2%s\2."), nc->display.c_str()); + } + } + + /* + * possible incoming ssl_cert messages: + * Received: :409 METADATA 409AAAAAA ssl_cert :vTrSe c38070ce96e41cc144ed6590a68d45a6 <...> <...> + * Received: :409 METADATA 409AAAAAC ssl_cert :vTrSE Could not get peer certificate: error:00000000:lib(0):func(0):reason(0) + */ + else if (params[1].equals_cs("ssl_cert")) + { + User *u = User::Find(params[0]); + if (!u) + return true; + std::string data = params[2].c_str(); + size_t pos1 = data.find(' ') + 1; + size_t pos2 = data.find(' ', pos1); + if ((pos2 - pos1) >= 32) // inspircd supports md5 and sha1 fingerprint hashes -> size 32 or 40 bytes. + { + u->fingerprint = data.substr(pos1, pos2 - pos1); + FOREACH_MOD(I_OnFingerprint, OnFingerprint(u)); + } + } + } + else if (params[0][0] == '#') + { + } + else if (params[0] == "*") + { + // Wed Oct 3 15:40:27 2012: S[14] O :20D METADATA * modules :-m_svstopic.so + + if (params[1].equals_cs("modules") && !params[2].empty()) + { + // only interested when it comes from our uplink + Server* server = source.GetServer(); + if (!server || server->GetUplink() != Me) + return true; + + bool plus = (params[2][0] == '+'); + if (!plus && params[2][0] != '-') + return true; + + bool required = false; + Anope::string module = params[2].substr(1); + + if (module.equals_cs("m_services_account.so")) + required = true; + else if (module.equals_cs("m_hidechans.so")) + required = true; + else if (module.equals_cs("m_chghost.so")) + has_chghostmod = plus; + else if (module.equals_cs("m_chgident.so")) + has_chgidentmod = plus; + else if (module.equals_cs("m_svshold.so")) + IRCD->CanSVSHold = plus; + else if (module.equals_cs("m_rline.so")) + has_rlinemod = plus; + else if (module.equals_cs("m_topiclock.so")) + has_svstopic_topiclock = plus; + else + return true; + + if (required) + { + if (!plus) + Log() << "Warning: InspIRCd unloaded module " << module << ", Anope won't function correctly without it"; + } + else + { + Log() << "InspIRCd " << (plus ? "loaded" : "unloaded") << " module " << module << ", adjusted functionality"; + } + + } + } + + return true; + } +}; + +struct IRCDMessageMode : IRCDMessage +{ + IRCDMessageMode(Module *creator) : IRCDMessage(creator, "MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + if (IRCD->IsChannelValid(params[0])) + { + Channel *c = Channel::Find(params[0]); + + Anope::string modes = params[1]; + for (unsigned n = 2; n < params.size(); ++n) + modes += " " + params[n]; + + if (c) + c->SetModesInternal(source, modes); + } + else + { + /* InspIRCd lets opers change another + users modes, we have to kludge this + as it slightly breaks RFC1459 + */ + User *u = source.GetUser(); + // This can happen with server-origin modes. + if (!u) + u = User::Find(params[0]); + // if it's still null, drop it like fire. + // most likely situation was that server introduced a nick which we subsequently akilled + if (u) + u->SetModesInternal("%s", params[1].c_str()); + } + + return true; + } +}; + +struct IRCDMessageNick : IRCDMessage +{ + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + source.GetUser()->ChangeNick(params[0]); + return true; + } +}; + +struct IRCDMessageOperType : IRCDMessage +{ + IRCDMessageOperType(Module *creator) : IRCDMessage(creator, "OPERTYPE", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_USER); } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + /* opertype is equivalent to mode +o because servers + dont do this directly */ + User *u = source.GetUser(); + if (!u->HasMode(UMODE_OPER)) + u->SetModesInternal("+o"); + + return true; + } +} +; +struct IRCDMessageRSQuit : IRCDMessage +{ + IRCDMessageRSQuit(Module *creator) : IRCDMessage(creator, "RSQUIT", 1) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + Server *s = Server::Find(params[0]); + if (!s) + return true; + + /* On InspIRCd we must send a SQUIT when we recieve RSQUIT for a server we have juped */ + if (s->HasFlag(SERVER_JUPED)) + UplinkSocket::Message(Me) << "SQUIT " << s->GetSID() << " :" << (params.size() > 1 ? params[1].c_str() : ""); + + FOREACH_MOD(I_OnServerQuit, OnServerQuit(s)); + + s->Delete(s->GetName() + " " + s->GetUplink()->GetName()); + + return true; + } +}; + struct IRCDMessageSetIdent : IRCDMessage { - IRCDMessageSetIdent() : IRCDMessage("SETIDENT", 0) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageSetIdent(Module *creator) : IRCDMessage(creator, "SETIDENT", 0) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -457,28 +1127,94 @@ struct IRCDMessageSetIdent : IRCDMessage } }; +struct IRCDMessageServer : IRCDMessage +{ + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 5) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + + /* + * [Nov 04 00:08:46.308435 2009] debug: Received: SERVER irc.inspircd.com pass 0 964 :Testnet Central! + * 0: name + * 1: pass + * 2: hops + * 3: numeric + * 4: desc + */ + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + unsigned int hops = Anope::string(params[2]).is_pos_number_only() ? convertTo<unsigned>(params[2]) : 0; + new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[4], params[3]); + return true; + } +}; + +struct IRCDMessageTime : IRCDMessage +{ + IRCDMessageTime(Module *creator) : IRCDMessage(creator, "TIME", 2) { } + + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + UplinkSocket::Message(Me) << "TIME " << source.GetSource() << " " << params[1] << " " << Anope::CurTime; + return true; + } +}; + +struct IRCDMessageUID : IRCDMessage +{ + IRCDMessageUID(Module *creator) : IRCDMessage(creator, "UID", 8) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + + /* + * [Nov 03 22:09:58.176252 2009] debug: Received: :964 UID 964AAAAAC 1225746297 w00t2 localhost testnet.user w00t 127.0.0.1 1225746302 +iosw +ACGJKLNOQcdfgjklnoqtx :Robin Burchell <w00t@inspircd.org> + * 0: uid + * 1: ts + * 2: nick + * 3: host + * 4: dhost + * 5: ident + * 6: ip + * 7: signon + * 8+: modes and params -- IMPORTANT, some modes (e.g. +s) may have parameters. So don't assume a fixed position of realname! + * last: realname + */ + bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override + { + time_t ts = convertTo<time_t>(params[1]); + + Anope::string modes = params[8]; + for (unsigned i = 9; i < params.size() - 1; ++i) + modes += " " + params[i]; + + User *u = new User(params[2], params[5], params[3], params[4], params[6], source.GetServer(), params[params.size() - 1], ts, modes, params[0]); + if (u->server->IsSynced() && NickServService) + NickServService->Validate(u); + + return true; + } +}; + class ProtoInspIRCd : public Module { InspIRCd12Proto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageJoin core_message_join; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - - /* inspircd-ts6.h message handlers */ + Message::Away message_away; + Message::Error message_error; + Message::Join message_join; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Topic message_topic; + Message::Version message_version; + + /* Our message handlers */ + IRCDMessageChgIdent message_chgident; + IRCDMessageChgName message_setname, message_chgname; + IRCDMessageCapab message_capab; IRCDMessageEndburst message_endburst; IRCDMessageFHost message_fhost, message_sethost; IRCDMessageFJoin message_sjoin; @@ -490,31 +1226,30 @@ class ProtoInspIRCd : public Module IRCDMessageNick message_nick; IRCDMessageOperType message_opertype; IRCDMessageRSQuit message_rsquit; + IRCDMessageSetIdent message_setident; IRCDMessageServer message_server; IRCDMessageTime message_time; IRCDMessageUID message_uid; - /* Our message handlers */ - IRCDMessageChgIdent message_chgident; - IRCDMessageChgName message_setname, message_chgname; - IRCDMessageCapab message_capab; - IRCDMessageSetIdent message_setident; - public: ProtoInspIRCd(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - message_fhost("FHOST"), message_sethost("SETHOST"), - message_setname("SETNAME"), message_chgname("FNAME") + message_away(this), message_error(this), message_join(this), message_kick(this), message_kill(this), + message_motd(this), message_part(this), message_ping(this), message_privmsg(this), message_quit(this), + message_squit(this), message_stats(this), message_topic(this), message_version(this), + + message_chgident(this), message_setname(this, "SETNAME"), message_chgname(this, "FNAME"), message_capab(this), message_endburst(this), + message_fhost(this, "FHOST"), message_sethost(this, "SETHOST"), message_sjoin(this), message_fmode(this), message_ftopic(this), + message_idle(this), message_metadata(this), message_mode(this), message_nick(this), message_opertype(this), message_rsquit(this), + message_setident(this), message_server(this), message_time(this), message_uid(this) { this->SetAuthor("Anope"); - Capab.insert("NOQUIT"); - Implementation i[] = { I_OnUserNickChange, I_OnServerSync }; ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); if (Config->Numeric.empty()) { - Anope::string numeric = ts6_sid_retrieve(); + Anope::string numeric = Servers::TS6_SID_Retrieve(); Me->SetSID(numeric); Config->Numeric = numeric; } @@ -523,22 +1258,27 @@ class ProtoInspIRCd : public Module it->second->GenerateUID(); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { /* InspIRCd 1.2 doesn't set -r on nick change, remove -r here. Note that if we have to set +r later * this will cancel out this -r, resulting in no mode changes. */ - u->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + u->RemoveMode(NickServ, UMODE_REGISTERED); } void OnServerSync(Server *s) anope_override { - if (nickserv) + if (NickServService) for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) { User *u = it->second; if (u->server == s && !u->IsIdentified()) - nickserv->Validate(u); + NickServService->Validate(u); } } }; diff --git a/modules/protocol/inspircd20.cpp b/modules/protocol/inspircd20.cpp index 9bb3d9e1a..85cfd9088 100644 --- a/modules/protocol/inspircd20.cpp +++ b/modules/protocol/inspircd20.cpp @@ -13,29 +13,67 @@ #include "module.h" -/* inspircd-ts6.h uses these */ static bool has_chghostmod = false; static bool has_chgidentmod = false; -static bool has_globopsmod = true; // Not a typo static bool has_rlinemod = false; static bool has_svstopic_topiclock = false; static unsigned int spanningtree_proto_ver = 0; -#include "inspircd-ts6.h" - static bool has_servicesmod = false; -class InspIRCd20Proto : public InspIRCdTS6Proto +static IRCDProto *insp12; + +class InspIRCd20Proto : public IRCDProto { public: - InspIRCd20Proto() : InspIRCdTS6Proto("InspIRCd 2.0") { } + InspIRCd20Proto() : IRCDProto("InspIRCd 2.0") + { + DefaultPseudoclientModes = "+I"; + CanSVSNick = true; + CanSetVHost = true; + CanSetVIdent = true; + CanSQLine = true; + CanSZLine = true; + CanSVSHold = true; + CanCertFP = true; + RequiresID = true; + MaxModes = 20; + } void SendConnect() anope_override { UplinkSocket::Message() << "CAPAB START 1202"; UplinkSocket::Message() << "CAPAB CAPABILITIES :PROTOCOL=1202"; UplinkSocket::Message() << "CAPAB END"; - InspIRCdTS6Proto::SendConnect(); + insp12->SendConnect(); } + + void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { insp12->SendGlobalNotice(bi, dest, msg); } + void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { insp12->SendGlobalPrivmsg(bi, dest, msg); } + void SendAkillDel(const XLine *x) anope_override { insp12->SendAkillDel(x); } + void SendTopic(BotInfo *whosets, Channel *c) anope_override { insp12->SendTopic(whosets, c); }; + void SendVhostDel(User *u) anope_override { insp12->SendVhostDel(u); } + void SendAkill(User *u, XLine *x) anope_override { insp12->SendAkill(u, x); } + void SendNumericInternal(int numeric, const Anope::string &dest, const Anope::string &buf) anope_override { insp12->SendNumericInternal(numeric, dest, buf); } + void SendModeInternal(const BotInfo *source, const Channel *dest, const Anope::string &buf) anope_override { insp12->SendModeInternal(source, dest, buf); } + void SendModeInternal(const BotInfo *bi, const User *u, const Anope::string &buf) anope_override { insp12->SendModeInternal(bi, u, buf); } + void SendClientIntroduction(const User *u) anope_override { insp12->SendClientIntroduction(u); } + void SendServer(const Server *server) anope_override { insp12->SendServer(server); } + void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override { insp12->SendJoin(user, c, status); } + void SendSQLineDel(const XLine *x) anope_override { insp12->SendSQLineDel(x); } + void SendSQLine(User *u, const XLine *x) anope_override { insp12->SendSQLine(u, x); } + void SendVhost(User *u, const Anope::string &vident, const Anope::string &vhost) anope_override { insp12->SendVhost(u, vident, vhost); } + void SendSVSHold(const Anope::string &nick) anope_override { insp12->SendSVSHold(nick); } + void SendSVSHoldDel(const Anope::string &nick) anope_override { insp12->SendSVSHoldDel(nick); } + void SendSZLineDel(const XLine *x) anope_override { insp12->SendSZLineDel(x); } + void SendSZLine(User *u, const XLine *x) anope_override { insp12->SendSZLine(u, x); } + void SendSVSJoin(const BotInfo *source, const Anope::string &nick, const Anope::string &chan, const Anope::string &other) anope_override { insp12->SendSVSJoin(source, nick, chan, other); } + void SendSWhois(const BotInfo *bi, const Anope::string &who, const Anope::string &mask) anope_override { insp12->SendSWhois(bi, who, mask); } + void SendBOB() anope_override { insp12->SendBOB(); } + void SendEOB() anope_override { insp12->SendEOB(); } + void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) { insp12->SendGlobopsInternal(source, buf); } + void SendLogin(User *u) anope_override { insp12->SendLogin(u); } + void SendLogout(User *u) anope_override { insp12->SendLogout(u); } + void SendChannel(Channel *c) anope_override { insp12->SendChannel(c); } }; class InspIRCdExtBan : public ChannelModeList @@ -51,7 +89,7 @@ class InspIRCdExtBan : public ChannelModeList { Anope::string real_mask = mask.substr(3); - Entry en(this->Name, real_mask); + Entry en(this->name, real_mask); if (en.Matches(u)) return true; } @@ -65,16 +103,16 @@ class InspIRCdExtBan : public ChannelModeList char modeChar = ModeManager::GetStatusChar(channel[0]); channel.erase(channel.begin()); cm = ModeManager::FindChannelModeByChar(modeChar); - if (cm != NULL && cm->Type != MODE_STATUS) + if (cm != NULL && cm->type != MODE_STATUS) cm = NULL; } - Channel *c = findchan(channel); + Channel *c = Channel::Find(channel); if (c != NULL) { UserContainer *uc = c->FindUser(u); if (uc != NULL) - if (cm == NULL || uc->Status->HasFlag(cm->Name)) + if (cm == NULL || uc->status->HasFlag(cm->name)) return true; } } @@ -111,9 +149,28 @@ class InspIRCdExtBan : public ChannelModeList } }; -struct IRCDMessageCapab : IRCDMessage +class ChannelModeFlood : public ChannelModeParam { - IRCDMessageCapab() : IRCDMessage("CAPAB", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + public: + ChannelModeFlood(char modeChar, bool minusNoArg) : ChannelModeParam(CMODE_FLOOD, modeChar, minusNoArg) { } + + bool IsValid(const Anope::string &value) const anope_override + { + try + { + Anope::string rest; + if (!value.empty() && value[0] != ':' && convertTo<int>(value[0] == '*' ? value.substr(1) : value, rest, false) > 0 && rest[0] == ':' && rest.length() > 1 && convertTo<int>(rest.substr(1), rest, false) > 0 && rest.empty()) + return true; + } + catch (const ConvertException &) { } + + return false; + } +}; + +struct IRCDMessageCapab : Message::Capab +{ + IRCDMessageCapab(Module *creator) : Message::Capab(creator, "CAPAB") { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -125,8 +182,8 @@ struct IRCDMessageCapab : IRCDMessage if (spanningtree_proto_ver < 1202) { UplinkSocket::Message() << "ERROR :Protocol mismatch, no or invalid protocol version given in CAPAB START"; - quitmsg = "Protocol mismatch, no or invalid protocol version given in CAPAB START"; - quitting = true; + Anope::QuitReason = "Protocol mismatch, no or invalid protocol version given in CAPAB START"; + Anope::Quitting = true; return false; } @@ -135,7 +192,7 @@ struct IRCDMessageCapab : IRCDMessage has_chghostmod = false; has_chgidentmod = false; has_svstopic_topiclock = false; - ircdproto->CanSVSHold = false; + IRCD->CanSVSHold = false; } else if (params[0].equals_cs("CHANMODES") && params.size() > 1) { @@ -275,7 +332,7 @@ struct IRCDMessageCapab : IRCDMessage else if (modename.equals_cs("servprotect")) { um = new UserMode(UMODE_PROTECTED, modechar[0]); - ircdproto->DefaultPseudoclientModes += "k"; + IRCD->DefaultPseudoclientModes += "k"; } else if (modename.equals_cs("showwhois")) um = new UserMode(UMODE_WHOIS, modechar[0]); @@ -302,7 +359,7 @@ struct IRCDMessageCapab : IRCDMessage while (ssep.GetToken(module)) { if (module.equals_cs("m_svshold.so")) - ircdproto->CanSVSHold = true; + IRCD->CanSVSHold = true; else if (module.find("m_rline.so") == 0) { has_rlinemod = true; @@ -392,7 +449,7 @@ struct IRCDMessageCapab : IRCDMessage else if (capab.find("MAXMODES=") != Anope::string::npos) { Anope::string maxmodes(capab.begin() + 9, capab.end()); - ircdproto->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; + IRCD->MaxModes = maxmodes.is_pos_number_only() ? convertTo<unsigned>(maxmodes) : 3; } else if (capab.find("PREFIX=") != Anope::string::npos) { @@ -403,7 +460,7 @@ struct IRCDMessageCapab : IRCDMessage for (size_t t = 0, end = modes.length(); t < end; ++t) { ChannelMode *cm = ModeManager::FindChannelModeByChar(modes[t]); - if (cm == NULL || cm->Type != MODE_STATUS) + if (cm == NULL || cm->type != MODE_STATUS) { Log() << "CAPAB PREFIX gave unknown channel status mode " << modes[t]; continue; @@ -420,18 +477,18 @@ struct IRCDMessageCapab : IRCDMessage if (!has_servicesmod) { UplinkSocket::Message() << "ERROR :m_services_account.so is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_services_account module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_services_account module loaded, and this is required."; + Anope::Quitting = true; return false; } if (!ModeManager::FindUserModeByName(UMODE_PRIV)) { UplinkSocket::Message() << "ERROR :m_hidechans.so is not loaded. This is required by Anope"; - quitmsg = "ERROR: Remote server does not have the m_hidechans module loaded, and this is required."; - quitting = true; + Anope::QuitReason = "ERROR: Remote server does not have the m_hidechans module loaded, and this is required."; + Anope::Quitting = true; return false; } - if (!ircdproto->CanSVSHold) + if (!IRCD->CanSVSHold) Log() << "SVSHOLD missing, Usage disabled until module is loaded."; if (!has_chghostmod) Log() << "CHGHOST missing, Usage disabled until module is loaded."; @@ -441,15 +498,15 @@ struct IRCDMessageCapab : IRCDMessage Log() << "m_topiclock missing, server side topic locking disabled until module is loaded."; } - return true; + Servers::Capab.insert("NOQUIT"); + + return Message::Capab::Run(source, params); } }; struct IRCDMessageEncap : IRCDMessage { - Module *me; - - IRCDMessageEncap(Module *m) : IRCDMessage("ENCAP", 4), me(m) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageEncap(Module *creator) : IRCDMessage(creator, "ENCAP", 4) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -458,7 +515,7 @@ struct IRCDMessageEncap : IRCDMessage if (params[1] == "CHGIDENT") { - User *u = finduser(params[2]); + User *u = User::Find(params[2]); if (!u || u->server != Me) return true; @@ -467,7 +524,7 @@ struct IRCDMessageEncap : IRCDMessage } else if (params[1] == "CHGHOST") { - User *u = finduser(params[2]); + User *u = User::Find(params[2]); if (!u || u->server != Me) return true; @@ -476,7 +533,7 @@ struct IRCDMessageEncap : IRCDMessage } else if (params[1] == "CHGNAME") { - User *u = finduser(params[2]); + User *u = User::Find(params[2]); if (!u || u->server != Me) return true; @@ -502,7 +559,7 @@ struct IRCDMessageEncap : IRCDMessage { UplinkSocket::Message(Me) << "ENCAP " << this->uid.substr(0, 3) << " SASL " << Me->GetSID() << " " << this->uid << " " << " D F"; - Log(findbot(Config->NickServ)) << "A user failed to identify for account " << this->GetAccount() << " using SASL"; + Log(NickServ) << "A user failed to identify for account " << this->GetAccount() << " using SASL"; } }; @@ -534,7 +591,7 @@ struct IRCDMessageEncap : IRCDMessage if (acc.empty() || pass.empty()) return true; - IdentifyRequest *req = new InspIRCDSASLIdentifyRequest(me, params[2], acc, pass); + IdentifyRequest *req = new InspIRCDSASLIdentifyRequest(this->owner, params[2], acc, pass); FOREACH_MOD(I_OnCheckAuthentication, OnCheckAuthentication(NULL, req)); req->Dispatch(); } @@ -546,7 +603,7 @@ struct IRCDMessageEncap : IRCDMessage struct IRCDMessageFIdent : IRCDMessage { - IRCDMessageFIdent() : IRCDMessage("FIDENT", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageFIdent(Module *creator) : IRCDMessage(creator, "FIDENT", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -557,40 +614,31 @@ struct IRCDMessageFIdent : IRCDMessage class ProtoInspIRCd : public Module { + Module *m_insp12; + InspIRCd20Proto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageJoin core_message_join; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - - /* inspircd-ts6.h message handlers */ - IRCDMessageEndburst message_endburst; - IRCDMessageFHost message_fhost; - IRCDMessageFJoin message_sjoin; - IRCDMessageFMode message_fmode; - IRCDMessageFTopic message_ftopic; - IRCDMessageIdle message_idle; - IRCDMessageMetadata message_metadata; - IRCDMessageMode message_mode; - IRCDMessageNick message_nick; - IRCDMessageOperType message_opertype; - IRCDMessageRSQuit message_rsquit; - IRCDMessageServer message_server; - IRCDMessageTime message_time; - IRCDMessageUID message_uid; + Message::Away message_away; + Message::Error message_error; + Message::Join message_join; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Topic message_topic; + Message::Version message_version; + + /* InspIRCd 1.2 message handlers */ + ServiceAlias message_endburst, message_fhost, message_sjoin, message_fmode, + message_ftopic, message_idle, message_metadata, message_mode, + message_nick, message_opertype, message_rsquit, message_server, + message_time, message_uid; /* Our message handlers */ IRCDMessageCapab message_capab; @@ -604,24 +652,51 @@ class ProtoInspIRCd : public Module public: ProtoInspIRCd(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - message_fhost("FHOST"), message_encap(this) + message_away(this), message_error(this), message_join(this), message_kick(this), message_kill(this), + message_motd(this), message_part(this), message_ping(this), message_privmsg(this), message_quit(this), + message_squit(this), message_stats(this), message_topic(this), message_version(this), + + message_endburst("IRCDMessage", "inspircd20/endburst", "inspircd12/endburst"), + message_fhost("IRCDMessage", "inspircd20/fhost", "inspircd12/fhost"), + message_sjoin("IRCDMessage", "inspircd20/sjoin", "inspircd12/sjoin"), + message_fmode("IRCDMessage", "inspircd20/mode", "inspircd12/fmode"), + message_ftopic("IRCDMessage", "inspircd20/ftopic", "inspircd12/ftopic"), + message_idle("IRCDMessage", "inspircd20/idle", "inspircd12/idle"), + message_metadata("IRCDMessage", "inspircd20/metadata", "inspircd12/metadata"), + message_mode("IRCDMessage", "inspircd20/mode", "inspircd12/mode"), + message_nick("IRCDMessage", "inspircd20/nick", "inspircd12/nick"), + message_opertype("IRCDMessage", "inspircd20/opertype", "inspircd12/opertype"), + message_rsquit("IRCDMessage", "inspircd20/rsquit", "inspircd12/rsquit"), + message_server("IRCDMessage", "inspircd20/server", "inspircd12/server"), + message_time("IRCDMessage", "inspircd20/time", "inspircd12/time"), + message_uid("IRCDMessage", "inspircd20/uid", "inspircd12/uid"), + + message_capab(this), message_encap(this), message_fident(this) { this->SetAuthor("Anope"); - Capab.insert("NOQUIT"); + if (ModuleManager::LoadModule("inspircd12", User::Find(creator)) != MOD_ERR_OK) + throw ModuleException("Unable to load inspircd12"); + m_insp12 = ModuleManager::FindModule("inspircd12"); + if (!m_insp12) + throw ModuleException("Unable to find inspircd12"); + insp12 = m_insp12->GetIRCDProto(); + if (!insp12) + throw ModuleException("No protocol interface for insp12"); + ModuleManager::DetachAll(m_insp12); Implementation i[] = { I_OnUserNickChange, I_OnServerSync, I_OnChannelCreate, I_OnChanRegistered, I_OnDelChan, I_OnMLock, I_OnUnMLock, I_OnSetChannelOption }; ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); + } - if (Config->Numeric.empty()) - { - Anope::string numeric = ts6_sid_retrieve(); - Me->SetSID(numeric); - Config->Numeric = numeric; - } + ~ProtoInspIRCd() + { + ModuleManager::UnloadModule(m_insp12, NULL); + } - for (botinfo_map::iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) - it->second->GenerateUID(); + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; } void OnUserNickChange(User *u, const Anope::string &) anope_override @@ -631,13 +706,7 @@ class ProtoInspIRCd : public Module void OnServerSync(Server *s) anope_override { - if (nickserv) - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) - { - User *u = it->second; - if (u->server == s && !u->IsIdentified()) - nickserv->Validate(u); - } + m_insp12->OnServerSync(s); } void OnChannelCreate(Channel *c) anope_override @@ -673,9 +742,9 @@ class ProtoInspIRCd : public Module EventReturn OnMLock(ChannelInfo *ci, ModeLock *lock) anope_override { ChannelMode *cm = ModeManager::FindChannelModeByName(lock->name); - if (cm && ci->c && (cm->Type == MODE_REGULAR || cm->Type == MODE_PARAM) && Config->UseServerSideMLock) + if (cm && ci->c && (cm->type == MODE_REGULAR || cm->type == MODE_PARAM) && Config->UseServerSideMLock) { - Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "") + cm->ModeChar; + Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "") + cm->mchar; SendChannelMetadata(ci->c, "mlock", modes); } @@ -685,9 +754,9 @@ class ProtoInspIRCd : public Module EventReturn OnUnMLock(ChannelInfo *ci, ModeLock *lock) anope_override { ChannelMode *cm = ModeManager::FindChannelModeByName(lock->name); - if (cm && ci->c && (cm->Type == MODE_REGULAR || cm->Type == MODE_PARAM) && Config->UseServerSideMLock) + if (cm && ci->c && (cm->type == MODE_REGULAR || cm->type == MODE_PARAM) && Config->UseServerSideMLock) { - Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "").replace_all_cs(cm->ModeChar, ""); + Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "").replace_all_cs(cm->mchar, ""); SendChannelMetadata(ci->c, "mlock", modes); } diff --git a/modules/protocol/ngircd.cpp b/modules/protocol/ngircd.cpp index f822922fa..28d534d2a 100644 --- a/modules/protocol/ngircd.cpp +++ b/modules/protocol/ngircd.cpp @@ -28,15 +28,15 @@ class ngIRCdProto : public IRCDProto void SendAkill(User *u, XLine *x) anope_override { // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message(Me) << "GLINE " << x->Mask << " " << timeleft << " :" << x->GetReason() << " (" << x->By << ")"; + UplinkSocket::Message(Me) << "GLINE " << x->mask << " " << timeleft << " :" << x->GetReason() << " (" << x->by << ")"; } void SendAkillDel(const XLine *x) anope_override { - UplinkSocket::Message(Me) << "GLINE " << x->Mask; + UplinkSocket::Message(Me) << "GLINE " << x->mask; } void SendChannel(Channel *c) anope_override @@ -53,7 +53,7 @@ class ngIRCdProto : public IRCDProto void SendConnect() anope_override { - UplinkSocket::Message() << "PASS " << Config->Uplinks[CurrentUplink]->password << " 0210-IRC+ Anope|" << Anope::VersionShort() << ":CLHMSo P"; + UplinkSocket::Message() << "PASS " << Config->Uplinks[Anope::CurrentUplink]->password << " 0210-IRC+ Anope|" << Anope::VersionShort() << ":CLHMSo P"; /* Make myself known to myself in the serverlist */ SendServer(Me); /* finish the enhanced server handshake and register the connection */ @@ -95,11 +95,11 @@ class ngIRCdProto : public IRCDProto */ UserContainer *uc = c->FindUser(user); if (uc != NULL) - uc->Status->ClearFlags(); + uc->status->ClearFlags(); - BotInfo *setter = findbot(user->nick); + BotInfo *setter = BotInfo::Find(user->nick); for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); } } @@ -176,7 +176,7 @@ class ngIRCdProto : public IRCDProto struct IRCDMessage005 : IRCDMessage { - IRCDMessage005() : IRCDMessage("005", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessage005(Module *creator) : IRCDMessage(creator, "005", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } // Please see <http://www.irc.org/tech_docs/005.html> for details. bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override @@ -193,7 +193,7 @@ struct IRCDMessage005 : IRCDMessage if (parameter == "MODES") { unsigned maxmodes = convertTo<unsigned>(data); - ircdproto->MaxModes = maxmodes; + IRCD->MaxModes = maxmodes; } else if (parameter == "NICKLEN") { @@ -212,7 +212,7 @@ struct IRCDMessage005 : IRCDMessage struct IRCDMessage376 : IRCDMessage { - IRCDMessage376() : IRCDMessage("376", 2) { } + IRCDMessage376(Module *creator) : IRCDMessage(creator, "376", 2) { } /* * :ngircd.dev.anope.de 376 services.anope.de :End of MOTD command @@ -230,7 +230,7 @@ struct IRCDMessage376 : IRCDMessage struct IRCDMessageChaninfo : IRCDMessage { - IRCDMessageChaninfo() : IRCDMessage("CHANINFO", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageChaninfo(Module *creator) : IRCDMessage(creator, "CHANINFO", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* * CHANINFO is used by servers to inform each other about a channel: its @@ -252,7 +252,7 @@ struct IRCDMessageChaninfo : IRCDMessage bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (!c) c = new Channel(params[0]); @@ -284,9 +284,9 @@ struct IRCDMessageChaninfo : IRCDMessage } }; -struct IRCDMessageJoin : IRCDMessage +struct IRCDMessageJoin : Message::Join { - IRCDMessageJoin() : IRCDMessage("JOIN", 1) { } + IRCDMessageJoin(Module *creator) : Message::Join(creator, "JOIN") { } /* * <@po||ux> DukeP: RFC 2813, 4.2.1: the JOIN command on server-server links @@ -296,7 +296,6 @@ struct IRCDMessageJoin : IRCDMessage */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *chan; User *user = source.GetUser(); size_t pos = params[0].find('\7'); Anope::string channel, modes; @@ -311,41 +310,16 @@ struct IRCDMessageJoin : IRCDMessage channel = params[0]; } - chan = findchan(channel); - /* Channel doesn't exist, create it */ - if (!chan) - { - chan = new Channel(channel, Anope::CurTime); - chan->SetFlag(CH_SYNCING); - } - - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(user, chan)); + std::vector<Anope::string> new_params; + new_params.push_back(channel); - /* Join the user to the channel */ - chan->JoinUser(user); + Message::Join::Run(source, new_params); if (!modes.empty()) - chan->SetModesInternal(source, modes); - - /* Set the proper modes on the user */ - chan_set_correct_modes(user, chan, 1, true); - - /* Modules may want to allow this user in the channel, check. - * If not, CheckKick will kick/ban them, don't call OnJoinChannel after this as the user will have - * been destroyed - */ - if (MOD_RESULT != EVENT_STOP && (!chan->ci || !chan->ci->CheckKick(user))) - { - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(user, chan)); - } - - /* Channel is done syncing */ - if (chan->HasFlag(CH_SYNCING)) { - /* Unset the syncing flag */ - chan->UnsetFlag(CH_SYNCING); - chan->Sync(); + Channel *c = Channel::Find(channel); + if (c) + c->SetModesInternal(source, modes); } return true; @@ -395,7 +369,7 @@ struct IRCDMessageMetadata : IRCDMessage struct IRCDMessageMode : IRCDMessage { - IRCDMessageMode() : IRCDMessage("MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageMode(Module *creator) : IRCDMessage(creator, "MODE", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } /* * Received: :DukeP MODE #anope +b *!*@*.aol.com @@ -412,16 +386,16 @@ struct IRCDMessageMode : IRCDMessage for (size_t i = 2; i < params.size(); ++i) modes += " " + params[i]; - if (ircdproto->IsChannelValid(params[0])) + if (IRCD->IsChannelValid(params[0])) { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c) c->SetModesInternal(source, modes); } else { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetModesInternal("%s", params[1].c_str()); @@ -432,7 +406,7 @@ struct IRCDMessageMode : IRCDMessage struct IRCDMessageNick : IRCDMessage { - IRCDMessageNick() : IRCDMessage("NICK", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 1) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } /* * NICK - NEW @@ -464,8 +438,8 @@ struct IRCDMessageNick : IRCDMessage { // a new user is connecting to the network User *user = new User(params[0], params[2], params[3], "", "", source.GetServer(), params[6], Anope::CurTime, params[5], ""); - if (user && nickserv) - nickserv->Validate(user); + if (user && NickServService) + NickServService->Validate(user); } else { @@ -477,7 +451,7 @@ struct IRCDMessageNick : IRCDMessage struct IRCDMessageNJoin : IRCDMessage { - IRCDMessageNJoin() : IRCDMessage("NJOIN",2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); }; + IRCDMessageNJoin(Module *creator) : IRCDMessage(creator, "NJOIN",2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); }; /* * RFC 2813, 4.2.2: Njoin Message: @@ -492,76 +466,46 @@ struct IRCDMessageNJoin : IRCDMessage */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + std::list<Message::Join::SJoinUser> users; + commasepstream sep(params[1]); Anope::string buf; - - if (!c) - { - c = new Channel(params[0], Anope::CurTime); - c->SetFlag(CH_SYNCING); - } - while (sep.GetToken(buf)) { - std::list<ChannelMode *> Status; - char ch; + + Message::Join::SJoinUser sju; /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) + for (char ch; (ch = ModeManager::GetStatusChar(buf[0]));) { - buf.erase(buf.begin()); ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); + buf.erase(buf.begin()); if (!cm) { Log(LOG_DEBUG) << "Received unknown mode prefix " << ch << " in NJOIN string."; continue; } - Status.push_back(cm); + + sju.first.SetFlag(cm->name); } - User *u = finduser(buf); - if (!u) + + sju.second = User::Find(buf); + if (!sju.second) { - Log(LOG_DEBUG) << "NJOIN for nonexistant user " << buf << " on " << c->name; + Log(LOG_DEBUG) << "NJOIN for nonexistant user " << buf << " on " << params[0]; continue; } + } - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); + Message::Join::SJoin(source, params[0], 0, "", users); - /* Add the user to the Channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } /* while */ - - if (c->HasFlag(CH_SYNCING)) - { - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } return true; } }; struct IRCDMessagePong : IRCDMessage { - IRCDMessagePong() : IRCDMessage("PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePong(Module *creator) : IRCDMessage(creator, "PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* * ngIRCd does not send an EOB, so we send a PING immediately @@ -578,7 +522,7 @@ struct IRCDMessagePong : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } /* * SERVER tolsun.oulu.fi 1 :Experimental server @@ -624,19 +568,19 @@ struct IRCDMessageServer : IRCDMessage * when receiving a new server and then finish sync once we * get a pong back from that server. */ - ircdproto->SendPing(Config->ServerName, params[0]); + IRCD->SendPing(Config->ServerName, params[0]); return true; } }; struct IRCDMessageTopic : IRCDMessage { - IRCDMessageTopic() : IRCDMessage("TOPIC", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageTopic(Module *creator) : IRCDMessage(creator, "TOPIC", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } // Received: :DukeP TOPIC #anope :test bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (!c) { Log(LOG_DEBUG) << "TOPIC for nonexistant channel " << params[0]; @@ -654,19 +598,19 @@ class ProtongIRCd : public Module ngIRCdProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg, core_message_squery; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageVersion core_message_version; + Message::Capab message_capab; + Message::Error message_error; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg, message_squery; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Version message_version; /* Our message handlers */ IRCDMessage005 message_005; @@ -728,11 +672,17 @@ class ProtongIRCd : public Module public: ProtongIRCd(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - core_message_squery("SQUERY") + message_capab(this), message_error(this), message_kick(this), message_kill(this), message_motd(this), + message_part(this), message_ping(this), message_privmsg(this), message_squery(this, "SQUERY"), + message_quit(this), message_squit(this), message_stats(this), message_time(this), message_version(this), + + message_005(this), message_376(this), message_chaninfo(this), message_join(this), message_mode(this), + message_nick(this), message_njoin(this), message_pong(this), message_server(this), message_topic(this) + { this->SetAuthor("Anope"); - Capab.insert("QS"); + Servers::Capab.insert("QS"); this->AddModes(); @@ -740,6 +690,11 @@ class ProtongIRCd : public Module ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { u->RemoveModeInternal(ModeManager::FindUserModeByName(UMODE_REGISTERED)); diff --git a/modules/protocol/plexus.cpp b/modules/protocol/plexus.cpp index 432cc3c02..53efdbd88 100644 --- a/modules/protocol/plexus.cpp +++ b/modules/protocol/plexus.cpp @@ -12,6 +12,7 @@ #include "module.h" static Anope::string UplinkSID; +static IRCDProto *hybrid; class PlexusProto : public IRCDProto { @@ -31,51 +32,17 @@ class PlexusProto : public IRCDProto MaxModes = 4; } - void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "NOTICE $$" << dest->GetName() << " :" << msg; - } - - void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "PRIVMSG $$" << dest->GetName() << " :" << msg; - } - - void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) anope_override - { - UplinkSocket::Message(source) << "OPERWALL :" << buf; - } - - void SendSQLine(User *, const XLine *x) anope_override - { - UplinkSocket::Message(Me) << "RESV * " << x->Mask << " :" << x->GetReason(); - } - - void SendSGLineDel(const XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "UNXLINE * " << x->Mask; - } - - void SendSGLine(User *, const XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "XLINE * " << x->Mask << " 0 :" << x->GetReason(); - } - - void SendAkillDel(const XLine *x) anope_override - { - if (x->IsRegex() || x->HasNickOrReal()) - return; - - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "UNKLINE * " << x->GetUser() << " " << x->GetHost(); - } - - void SendSQLineDel(const XLine *x) anope_override - { - UplinkSocket::Message(Me) << "UNRESV * " << x->Mask; - } + void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { hybrid->SendGlobalNotice(bi, dest, msg); } + void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { hybrid->SendGlobalPrivmsg(bi, dest, msg); } + void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) anope_override { hybrid->SendGlobopsInternal(source, buf); } + void SendSQLine(User *u, const XLine *x) anope_override { hybrid->SendSQLine(u, x); } + void SendSQLineDel(const XLine *x) anope_override { hybrid->SendSQLineDel(x); } + void SendSGLineDel(const XLine *x) anope_override { hybrid->SendSGLineDel(x); } + void SendSGLine(User *u, const XLine *x) anope_override { hybrid->SendSGLine(u, x); } + void SendAkillDel(const XLine *x) anope_override { hybrid->SendAkillDel(x); } + void SendAkill(User *u, XLine *x) anope_override { hybrid->SendAkill(u, x); } + void SendServer(const Server *server) anope_override { hybrid->SendServer(server); } + void SendChannel(Channel *c) anope_override { hybrid->SendChannel(c); } void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override { @@ -89,82 +56,38 @@ class PlexusProto : public IRCDProto */ UserContainer *uc = c->FindUser(user); if (uc != NULL) - uc->Status->ClearFlags(); + uc->status->ClearFlags(); - BotInfo *setter = findbot(user->nick); + BotInfo *setter = BotInfo::Find(user->nick); for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); } } - void SendAkill(User *u, XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - - if (x->IsRegex() || x->HasNickOrReal()) - { - if (!u) - { - /* No user (this akill was just added), and contains nick and/or realname. Find users that match and ban them */ - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) - if (x->manager->Check(it->second, x)) - this->SendAkill(it->second, x); - return; - } - - const XLine *old = x; - - if (old->manager->HasEntry("*@" + u->host)) - return; - - /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - XLine *xline = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); - old->manager->AddXLine(xline); - x = xline; - - Log(bi, "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; - } - - // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) - timeleft = 172800; - UplinkSocket::Message(bi) << "KLINE * " << timeleft << " " << x->GetUser() << " " << x->GetHost() << " :" << x->GetReason(); - } - - void SendServer(const Server *server) anope_override + void SendForceNickChange(const User *u, const Anope::string &newnick, time_t when) anope_override { - if (server == Me) - UplinkSocket::Message() << "SERVER " << server->GetName() << " " << server->GetHops() << " :" << server->GetDescription(); - else - UplinkSocket::Message(Me) << "SID " << server->GetName() << " " << server->GetHops() << " " << server->GetSID() << " :" << server->GetDescription(); + UplinkSocket::Message(Me) << "ENCAP " << u->server->GetName() << " SVSNICK " << u->GetUID() << " " << u->timestamp << " " << newnick << " " << when; } - void SendForceNickChange(const User *u, const Anope::string &newnick, time_t when) anope_override + void SendVhost(User *u, const Anope::string &ident, const Anope::string &host) anope_override { - UplinkSocket::Message(Me) << "ENCAP " << u->server->GetName() << " SVSNICK " << u->GetUID() << " " << u->timestamp << " " << newnick << " " << when; + if (!ident.empty()) + UplinkSocket::Message(Me) << "ENCAP * CHGIDENT " << u->GetUID() << " " << ident; + UplinkSocket::Message(Me) << "ENCAP * CHGHOST " << u->GetUID() << " " << host; } void SendVhostDel(User *u) anope_override { - const BotInfo *bi = findbot(Config->HostServ); if (u->HasMode(UMODE_CLOAK)) - u->RemoveMode(bi, UMODE_CLOAK); + u->RemoveMode(HostServ, UMODE_CLOAK); else this->SendVhost(u, u->GetIdent(), u->chost); } - void SendVhost(User *u, const Anope::string &ident, const Anope::string &host) anope_override - { - if (!ident.empty()) - UplinkSocket::Message(Me) << "ENCAP * CHGIDENT " << u->GetUID() << " " << ident; - UplinkSocket::Message(Me) << "ENCAP * CHGHOST " << u->GetUID() << " " << host; - } - void SendConnect() anope_override { - UplinkSocket::Message() << "PASS " << Config->Uplinks[CurrentUplink]->password << " TS 6 :" << Me->GetSID(); + UplinkSocket::Message() << "PASS " << Config->Uplinks[Anope::CurrentUplink]->password << " TS 6 :" << Me->GetSID(); /* CAPAB * QS - Can handle quit storm removal * EX - Can do channel +e exemptions @@ -227,53 +150,11 @@ class PlexusProto : public IRCDProto { UplinkSocket::Message(bi) << "ENCAP * TOPIC " << c->name << " " << c->topic_setter << " " << c->topic_ts << " :" << c->topic; } - - void SendChannel(Channel *c) anope_override - { - Anope::string modes = c->GetModes(true, true); - if (modes.empty()) - modes = "+"; - UplinkSocket::Message(Me) << "SJOIN " << c->creation_time << " " << c->name << " " << modes << " :"; - } -}; - -struct IRCDMessageBMask : IRCDMessage -{ - IRCDMessageBMask() : IRCDMessage("BMASK", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* :42X BMASK 1106409026 #ircops b :*!*@*.aol.com */ - /* 0 1 2 3 */ - Channel *c = findchan(params[1]); - - if (c) - { - ChannelMode *ban = ModeManager::FindChannelModeByName(CMODE_BAN), - *except = ModeManager::FindChannelModeByName(CMODE_EXCEPT), - *invex = ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE); - - Anope::string bans = params[3]; - int count = myNumToken(bans, ' '), i; - for (i = 0; i < count; ++i) - { - Anope::string b = myStrGetToken(bans, ' ', i); - if (ban && params[2].equals_cs("b")) - c->SetModeInternal(source, ban, b); - else if (except && params[2].equals_cs("e")) - c->SetModeInternal(source, except, b); - if (invex && params[2].equals_cs("I")) - c->SetModeInternal(source, invex, b); - } - } - - return true; - } }; struct IRCDMessageEncap : IRCDMessage { - IRCDMessageEncap() : IRCDMessage("ENCAP", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageEncap(Module *creator) : IRCDMessage(creator, "ENCAP", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -286,14 +167,14 @@ struct IRCDMessageEncap : IRCDMessage */ if (params[1].equals_cs("SU")) { - User *u = finduser(params[2]); - const NickAlias *user_na = findnick(params[2]); - NickCore *nc = findcore(params[3]); + User *u = User::Find(params[2]); + const NickAlias *user_na = NickAlias::Find(params[2]); + NickCore *nc = NickCore::Find(params[3]); if (u && nc) { u->Login(nc); if (!Config->NoNicknameOwnership && user_na && user_na->nc == nc && user_na->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + u->SetMode(NickServ, UMODE_REGISTERED); } } @@ -306,7 +187,7 @@ struct IRCDMessageEncap : IRCDMessage */ else if (params[1].equals_cs("CERTFP")) { - User *u = finduser(params[2]); + User *u = User::Find(params[2]); if (u) { u->fingerprint = params[3]; @@ -317,82 +198,9 @@ struct IRCDMessageEncap : IRCDMessage } }; -struct IRCDMessageEOB : IRCDMessage -{ - IRCDMessageEOB() : IRCDMessage("EOB", 0) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetServer()->Sync(true); - return true; - } -}; - -struct IRCDMessageJoin : CoreIRCDMessageJoin -{ - IRCDMessageJoin() : CoreIRCDMessageJoin("JOIN") { } - - /* - * params[0] = ts - * params[1] = channel - */ - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (params.size() < 2) - return true; - - std::vector<Anope::string> p = params; - p.erase(p.begin()); - - return CoreIRCDMessageJoin::Run(source, p); - } -}; - -struct IRCDMessageMode : IRCDMessage -{ - IRCDMessageMode() : IRCDMessage("MODE", 3) { } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (ircdproto->IsChannelValid(params[0])) - { - // 0 = channel, 1 = ts, 2 = modes - Channel *c = findchan(params[0]); - time_t ts = 0; - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) { } - - if (c) - c->SetModesInternal(source, params[2], ts); - } - else - { - User *u = finduser(params[0]); - if (u) - u->SetModesInternal("%s", params[1].c_str()); - } - - return true; - } -}; - -struct IRCDMessageNick : IRCDMessage -{ - IRCDMessageNick() : IRCDMessage("NICK", 2) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetUser()->ChangeNick(params[0]); - return true; - } -}; - struct IRCDMessagePass : IRCDMessage { - IRCDMessagePass() : IRCDMessage("PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePass(Module *creator) : IRCDMessage(creator, "PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -403,206 +211,25 @@ struct IRCDMessagePass : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + /* 0 1 2 */ + /* SERVER hades.arpa 1 :ircd-hybrid test server */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - // Servers other then our immediate uplink are introduced via SID + /* Servers other than our immediate uplink are introduced via SID */ if (params[1] != "1") return true; - new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], 1, params[2], UplinkSID); - return true; - } -}; - -struct IRCDMessageSID : IRCDMessage -{ - IRCDMessageSID() : IRCDMessage("SID", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - /* :42X SID trystan.nomadirc.net 2 43X :ircd-plexus test server */ - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - unsigned int hops = params[1].is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; - new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[3], params[2]); - return true; - } -}; - -struct IRCDMessageSJoin : IRCDMessage -{ - IRCDMessageSJoin() : IRCDMessage("SJOIN", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Channel *c = findchan(params[1]); - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[1], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this SJOIN string contains modes */ - if (keep_their_modes && params.size() >= 3) - { - Anope::string modes; - for (unsigned i = 2; i < params.size() - 1; ++i) - modes += " " + params[i]; - if (!modes.empty()) - modes.erase(modes.begin()); - /* Set the modes internally */ - c->SetModesInternal(source, modes); - } - - spacesepstream sep(params[params.size() - 1]); - Anope::string buf; - while (sep.GetToken(buf)) - { - std::list<ChannelMode *> Status; - char ch; - - /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) - { - buf.erase(buf.begin()); - ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); - if (!cm) - { - Log() << "Received unknown mode prefix " << ch << " in SJOIN string"; - continue; - } - - if (keep_their_modes) - Status.push_back(cm); - } - - User *u = finduser(buf); - if (!u) - { - Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << c->name; - continue; - } - - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } - - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } - return true; - } -}; - -struct IRCDMessageTBurst : IRCDMessage -{ - IRCDMessageTBurst() : IRCDMessage("TBURST", 5) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - // 0 1 2 3 4 - // :rizon.server TBURST 1298674830 #lol 1298674833 Adam!Adam@i.has.a.spoof :lol - // chan ts topic ts - - Channel *c = findchan(params[1]); - - try - { - if (!c || c->creation_time < convertTo<time_t>(params[0])) - return true; - } - catch (const ConvertException &) - { - return true; - } - - Anope::string setter = myStrGetToken(params[3], '!', 0); - time_t topic_time = Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime; - c->ChangeTopicInternal(setter, params.size() > 4 ? params[4] : "", topic_time); - - return true; - } -}; - -struct IRCDMessageTMode : IRCDMessage -{ - IRCDMessageTMode() : IRCDMessage("TMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - time_t ts = 0; - try - { - ts = convertTo<time_t>(params[0]); - } - catch (const ConvertException &) { } - Channel *c = findchan(params[1]); - Anope::string modes = params[2]; - for (unsigned i = 3; i < params.size(); ++i) - modes += " " + params[i]; - - if (c) - c->SetModesInternal(source, modes, ts); - - return true; - } -}; - -struct IRCDMessageTopic : IRCDMessage -{ - IRCDMessageTopic() : IRCDMessage("TOPIC", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Channel *c = findchan(params[0]); - if (!c) - return true; + new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], 1, params[2], UplinkSID); - c->ChangeTopicInternal(params[1], params[3], Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); return true; } }; struct IRCDMessageUID : IRCDMessage { - IRCDMessageUID() : IRCDMessage("UID", 11) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageUID(Module *creator) : IRCDMessage(creator, "UID", 11) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* params[0] = nick @@ -628,12 +255,12 @@ struct IRCDMessageUID : IRCDMessage User *user = new User(params[0], params[4], params[9], params[5], ip, source.GetServer(), params[10], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, params[3], params[7]); if (params[8] != "0" && params[8].is_pos_number_only() && convertTo<time_t>(params[8]) == user->timestamp) { - NickAlias *na = findnick(user->nick); + NickAlias *na = NickAlias::Find(user->nick); if (na) user->Login(na->nc); } - else if (user && user->server->IsSynced() && nickserv) - nickserv->Validate(user); + else if (user && user->server->IsSynced() && NickServService) + NickServService->Validate(user); return true; } @@ -641,127 +268,117 @@ struct IRCDMessageUID : IRCDMessage class ProtoPlexus : public Module { + Module *m_hybrid; + PlexusProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - CoreIRCDMessageWhois core_message_whois; + Message::Away message_away; + Message::Capab message_capab; + Message::Error message_error; + Message::Kick message_kick; + Message::Kill message_kill; + Message::Mode message_mode; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Topic message_topic; + Message::Version message_version; + Message::Whois message_whois; + + /* Hybrid message handlers */ + ServiceAlias message_bmask, message_eob, message_join, message_nick, message_sid, message_sjoin, + message_tburst, message_tmode; /* Our message handlers */ - IRCDMessageBMask message_bmask; IRCDMessageEncap message_encap; - IRCDMessageEOB message_eob; - IRCDMessageJoin message_join; - IRCDMessageMode message_mode; - IRCDMessageNick message_nick; IRCDMessagePass message_pass; IRCDMessageServer message_server; - IRCDMessageSID message_sid; - IRCDMessageSJoin message_sjoin; - IRCDMessageTBurst message_tburst; - IRCDMessageTMode message_tmode; - IRCDMessageTopic message_topic; IRCDMessageUID message_uid; void AddModes() { /* Add user modes */ - ModeManager::AddUserMode(new UserMode(UMODE_ADMIN, 'a')); - ModeManager::AddUserMode(new UserMode(UMODE_INVIS, 'i')); - ModeManager::AddUserMode(new UserMode(UMODE_OPER, 'o')); - ModeManager::AddUserMode(new UserMode(UMODE_SNOMASK, 's')); - ModeManager::AddUserMode(new UserMode(UMODE_WALLOPS, 'w')); + ModeManager::RemoveUserMode(ModeManager::FindUserModeByName(UMODE_HIDEOPER)); ModeManager::AddUserMode(new UserMode(UMODE_NOCTCP, 'C')); ModeManager::AddUserMode(new UserMode(UMODE_DEAF, 'D')); ModeManager::AddUserMode(new UserMode(UMODE_SOFTCALLERID, 'G')); ModeManager::AddUserMode(new UserMode(UMODE_NETADMIN, 'N')); - ModeManager::AddUserMode(new UserMode(UMODE_REGPRIV, 'R')); ModeManager::AddUserMode(new UserMode(UMODE_SSL, 'S')); ModeManager::AddUserMode(new UserMode(UMODE_WEBIRC, 'W')); ModeManager::AddUserMode(new UserMode(UMODE_CALLERID, 'g')); ModeManager::AddUserMode(new UserMode(UMODE_PRIV, 'p')); - ModeManager::AddUserMode(new UserMode(UMODE_REGISTERED, 'r')); ModeManager::AddUserMode(new UserMode(UMODE_CLOAK, 'x')); ModeManager::AddUserMode(new UserMode(UMODE_PROTECTED, 'U')); - /* b/e/I */ - ModeManager::AddChannelMode(new ChannelModeList(CMODE_BAN, 'b')); - ModeManager::AddChannelMode(new ChannelModeList(CMODE_EXCEPT, 'e')); - ModeManager::AddChannelMode(new ChannelModeList(CMODE_INVITEOVERRIDE, 'I')); - - /* l/k */ - ModeManager::AddChannelMode(new ChannelModeKey('k')); - ModeManager::AddChannelMode(new ChannelModeParam(CMODE_LIMIT, 'l')); - /* v/h/o/a/q */ - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_VOICE, 'v', '+', 0)); - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_HALFOP, 'h', '%', 1)); - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_OP, 'o', '@', 2)); ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_PROTECT, 'a', '&', 3)); ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_OWNER, 'q', '~', 4)); /* Add channel modes */ + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_REGISTERED)); ModeManager::AddChannelMode(new ChannelMode(CMODE_BANDWIDTH, 'B')); ModeManager::AddChannelMode(new ChannelMode(CMODE_NOCTCP, 'C')); ModeManager::AddChannelMode(new ChannelMode(CMODE_REGMODERATED, 'M')); ModeManager::AddChannelMode(new ChannelMode(CMODE_NONOTICE, 'N')); - ModeManager::AddChannelMode(new ChannelModeOper('O')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_REGISTEREDONLY, 'R')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_SSL, 'S')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_BLOCKCOLOR, 'c')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_INVITE, 'i')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_MODERATED, 'm')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_NOEXTERNAL, 'n')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_PRIVATE, 'p')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_SECRET, 's')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_TOPIC, 't')); ModeManager::AddChannelMode(new ChannelMode(CMODE_PERM, 'z')); } public: - ProtoPlexus(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL) + ProtoPlexus(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), + message_away(this), message_capab(this), message_error(this), message_kick(this), message_kill(this), + message_mode(this), message_motd(this), message_part(this), message_ping(this), message_privmsg(this), message_quit(this), + message_squit(this), message_stats(this), message_time(this), message_topic(this), message_version(this), message_whois(this), + + message_bmask("IRCDMessage", "plexus/bmask", "hybrid/bmask"), message_eob("IRCDMessage", "plexus/eob", "hybrid/eob"), + message_join("IRCDMessage", "plexus/join", "hybrid/join"), message_nick("IRCDMessage", "plexus/nick", "hybrid/nick"), + message_sid("IRCDMessage", "plexus/sid", "hybrid/sid"), + message_sjoin("IRCDMessage", "plexus/sjoin", "hybrid/sjoin"), message_tburst("IRCDMessage", "plexus/tburst", "hybrid/tburst"), + message_tmode("IRCDMessage", "plexus/tmode", "hybrid/tmode"), + + message_encap(this), message_pass(this), message_server(this), message_uid(this) { this->SetAuthor("Anope"); + if (ModuleManager::LoadModule("hybrid", User::Find(creator)) != MOD_ERR_OK) + throw ModuleException("Unable to load hybrid"); + m_hybrid = ModuleManager::FindModule("hybrid"); + if (!m_hybrid) + throw ModuleException("Unable to find hybrid"); + hybrid = m_hybrid->GetIRCDProto(); + if (!hybrid) + throw ModuleException("No protocol interface for hybrid"); + this->AddModes(); Implementation i[] = { I_OnServerSync }; ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); + } - if (Config->Numeric.empty()) - { - Anope::string numeric = ts6_sid_retrieve(); - Me->SetSID(numeric); - Config->Numeric = numeric; - } + ~ProtoPlexus() + { + ModuleManager::UnloadModule(m_hybrid, NULL); + } - for (botinfo_map::iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) - it->second->GenerateUID(); + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; } void OnServerSync(Server *s) anope_override { - if (nickserv) + if (NickServService) for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) { User *u = it->second; if (u->server == s && !u->IsIdentified()) - nickserv->Validate(u); + NickServService->Validate(u); } } }; diff --git a/modules/protocol/ratbox.cpp b/modules/protocol/ratbox.cpp index 3ae4b6e17..32226fae7 100644 --- a/modules/protocol/ratbox.cpp +++ b/modules/protocol/ratbox.cpp @@ -12,6 +12,7 @@ #include "module.h" static Anope::string UplinkSID; +static IRCDProto *hybrid; class RatboxProto : public IRCDProto { @@ -26,112 +27,24 @@ class RatboxProto : public IRCDProto MaxModes = 4; } - void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "NOTICE $$" << dest->GetName() << " :" << msg; - } - - void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override - { - UplinkSocket::Message(bi) << "PRIVMSG $$" << dest->GetName() << " :" << msg; - } - - void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) anope_override - { - UplinkSocket::Message(source) << "OPERWALL :" << buf; - } - - void SendSQLine(User *, const XLine *x) anope_override - { - UplinkSocket::Message(Me) << "RESV * " << x->Mask << " :" << x->GetReason(); - } - - void SendSGLineDel(const XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "UNXLINE * " << x->Mask; - } - - void SendSGLine(User *, const XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "XLINE * " << x->Mask << " 0 :" << x->GetReason(); - } - - void SendAkillDel(const XLine *x) anope_override - { - if (x->IsRegex() || x->HasNickOrReal()) - return; - - const BotInfo *bi = findbot(Config->OperServ); - UplinkSocket::Message(bi) << "UNKLINE * " << x->GetUser() << " " << x->GetHost(); - } - - void SendSQLineDel(const XLine *x) anope_override - { - UplinkSocket::Message(Me) << "UNRESV * " << x->Mask; - } - - void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override - { - /* Note that we must send our modes with the SJOIN and - * can not add them to the mode stacker because ratbox - * does not allow *any* client to op itself - */ - UplinkSocket::Message() << "SJOIN " << c->creation_time << " " << c->name << " +" << c->GetModes(true, true) << " :" << (status != NULL ? status->BuildModePrefixList() : "") << user->GetUID(); - /* And update our internal status for this user since this is not going through our mode handling system */ - if (status != NULL) - { - UserContainer *uc = c->FindUser(user); - if (uc != NULL) - *uc->Status = *status; - } - } - - void SendAkill(User *u, XLine *x) anope_override - { - const BotInfo *bi = findbot(Config->OperServ); - - if (x->IsRegex() || x->HasNickOrReal()) - { - if (!u) - { - /* No user (this akill was just added), and contains nick and/or realname. Find users that match and ban them */ - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) - if (x->manager->Check(it->second, x)) - this->SendAkill(it->second, x); - return; - } - - const XLine *old = x; - - if (old->manager->HasEntry("*@" + u->host)) - return; - - /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - XLine *xline = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); - old->manager->AddXLine(xline); - x = xline; - - Log(bi, "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; - } - - // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) - timeleft = 172800; - UplinkSocket::Message(bi) << "KLINE * " << timeleft << " " << x->GetUser() << " " << x->GetHost() << " :" << x->GetReason(); - } - - /* SERVER name hop descript */ - void SendServer(const Server *server) anope_override - { - UplinkSocket::Message() << "SERVER " << server->GetName() << " " << server->GetHops() << " :" << server->GetDescription(); - } + void SendGlobalNotice(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { hybrid->SendGlobalNotice(bi, dest, msg); } + void SendGlobalPrivmsg(const BotInfo *bi, const Server *dest, const Anope::string &msg) anope_override { hybrid->SendGlobalPrivmsg(bi, dest, msg); } + void SendGlobopsInternal(const BotInfo *source, const Anope::string &buf) anope_override { hybrid->SendGlobopsInternal(source, buf); } + void SendSQLine(User *u, const XLine *x) anope_override { hybrid->SendSQLine(u, x); } + void SendSGLine(User *u, const XLine *x) anope_override { hybrid->SendSGLine(u, x); } + void SendSGLineDel(const XLine *x) anope_override { hybrid->SendSGLineDel(x); } + void SendAkill(User *u, XLine *x) anope_override { hybrid->SendAkill(u, x); } + void SendAkillDel(const XLine *x) anope_override { hybrid->SendAkillDel(x); } + void SendSQLineDel(const XLine *x) anope_override { hybrid->SendSQLineDel(x); } + void SendJoin(const User *user, Channel *c, const ChannelStatus *status) anope_override { hybrid->SendJoin(user, c, status); } + void SendServer(const Server *server) anope_override { hybrid->SendServer(server); } + void SendModeInternal(const BotInfo *bi, const User *u, const Anope::string &buf) anope_override { hybrid->SendModeInternal(bi, u, buf); } + void SendChannel(Channel *c) anope_override { hybrid->SendChannel(c); } + void SendTopic(BotInfo *bi, Channel *c) anope_override { hybrid->SendTopic(bi, c); } void SendConnect() anope_override { - UplinkSocket::Message() << "PASS " << Config->Uplinks[CurrentUplink]->password << " TS 6 :" << Me->GetSID(); + UplinkSocket::Message() << "PASS " << Config->Uplinks[Anope::CurrentUplink]->password << " TS 6 :" << Me->GetSID(); /* QS - Can handle quit storm removal EX - Can do channel +e exemptions @@ -162,11 +75,6 @@ class RatboxProto : public IRCDProto UplinkSocket::Message(Me) << "UID " << u->nick << " 1 " << u->timestamp << " " << modes << " " << u->GetIdent() << " " << u->host << " 0 " << u->GetUID() << " :" << u->realname; } - void SendModeInternal(const BotInfo *bi, const User *u, const Anope::string &buf) anope_override - { - UplinkSocket::Message(bi) << "SVSMODE " << u->nick << " " << buf; - } - void SendLogin(User *u) anope_override { if (!u->Account()) @@ -179,157 +87,36 @@ class RatboxProto : public IRCDProto { UplinkSocket::Message(Me) << "ENCAP * SU " << u->GetUID(); } - - void SendChannel(Channel *c) anope_override - { - Anope::string modes = c->GetModes(true, true); - if (modes.empty()) - modes = "+"; - UplinkSocket::Message() << "SJOIN " << c->creation_time << " " << c->name << " " << modes << " :"; - } - - bool IsNickValid(const Anope::string &nick) anope_override - { - /* TS6 Save extension -Certus */ - if (isdigit(nick[0])) - return false; - - return true; - } - - void SendTopic(BotInfo *bi, Channel *c) anope_override - { - bool needjoin = c->FindUser(bi) == NULL; - if (needjoin) - { - ChannelStatus status; - status.SetFlag(CMODE_OP); - bi->Join(c, &status); - } - IRCDProto::SendTopic(bi, c); - if (needjoin) - bi->Part(c); - } -}; - -struct IRCDMessageBMask : IRCDMessage -{ - IRCDMessageBMask() : IRCDMessage("BMASK", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* :42X BMASK 1106409026 #ircops b :*!*@*.aol.com */ - /* 0 1 2 3 */ - Channel *c = findchan(params[1]); - - if (c) - { - ChannelMode *ban = ModeManager::FindChannelModeByName(CMODE_BAN), - *except = ModeManager::FindChannelModeByName(CMODE_EXCEPT), - *invex = ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE); - - Anope::string bans = params[3]; - int count = myNumToken(bans, ' '), i; - for (i = 0; i < count; ++i) - { - Anope::string b = myStrGetToken(bans, ' ', i); - if (ban && params[2].equals_cs("b")) - c->SetModeInternal(source, ban, b); - else if (except && params[2].equals_cs("e")) - c->SetModeInternal(source, except, b); - if (invex && params[2].equals_cs("I")) - c->SetModeInternal(source, invex, b); - } - } - - return true; - } }; struct IRCDMessageEncap : IRCDMessage { - IRCDMessageEncap() : IRCDMessage("ENCAP", 3) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageEncap(Module *creator) : IRCDMessage(creator, "ENCAP", 3) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } // Debug: Received: :00BAAAAAB ENCAP * LOGIN Adam bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - if (params[1] == "LOGIN") + if (params[1] == "LOGIN" || params[1] == "SU") { User *u = source.GetUser(); - NickCore *nc = findcore(params[2]); + NickCore *nc = NickCore::Find(params[2]); if (!nc) return true; u->Login(nc); - const NickAlias *user_na = findnick(u->nick); + const NickAlias *user_na = NickAlias::Find(u->nick); if (!Config->NoNicknameOwnership && user_na && user_na->nc == nc && user_na->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); - } - - return true; - } -}; - -struct IRCDMessageJoin : CoreIRCDMessageJoin -{ - IRCDMessageJoin() : CoreIRCDMessageJoin("JOIN") { } - - /* - * params[0] = ts - * params[1] = channel - * params[2] = modes - */ - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (params.size() < 2) - return true; - - std::vector<Anope::string> p = params; - p.erase(p.begin()); - - return CoreIRCDMessageJoin::Run(source, p); - } -}; - -struct IRCDMessageMode : IRCDMessage -{ - IRCDMessageMode() : IRCDMessage("MODE", 2) { } - - // Received: :42CAAAIHS MODE 42CAAAIHS :+ao - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - if (ircdproto->IsChannelValid(params[0])) - { - Channel *c = findchan(params[0]); - if (c) - c->SetModesInternal(source, params[1]); - } - else - { - User *u = finduser(params[0]); - if (u) - u->SetModesInternal("%s", params[1].c_str()); + u->SetMode(NickServ, UMODE_REGISTERED); } return true; } }; -struct IRCDMessageNick : IRCDMessage -{ - IRCDMessageNick() : IRCDMessage("NICK", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetUser()->ChangeNick(params[0]); - return true; - } -}; - struct IRCDMessagePass : IRCDMessage { - IRCDMessagePass() : IRCDMessage("PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePass(Module *creator) : IRCDMessage(creator, "PASS", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -338,20 +125,9 @@ struct IRCDMessagePass : IRCDMessage } }; -struct IRCDMessagePong : IRCDMessage -{ - IRCDMessagePong() : IRCDMessage("PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - source.GetServer()->Sync(false); - return true; - } -}; - struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } // SERVER hades.arpa 1 :ircd-ratbox test server bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override @@ -360,166 +136,33 @@ struct IRCDMessageServer : IRCDMessage if (params[1] != "1") return true; new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], 1, params[2], UplinkSID); - ircdproto->SendPing(Config->ServerName, params[0]); - return true; - } -}; - -struct IRCDMessageSID : IRCDMessage -{ - IRCDMessageSID() : IRCDMessage("SID", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - /* :42X SID trystan.nomadirc.net 2 43X :ircd-ratbox test server */ - unsigned int hops = params[1].is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; - new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[3], params[2]); - ircdproto->SendPing(Config->ServerName, params[0]); - return true; - } -}; - -struct IRCDMessageSjoin : IRCDMessage -{ - IRCDMessageSjoin() : IRCDMessage("SJOIN", 2) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - Channel *c = findchan(params[1]); - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[1], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this SJOIN string contains modes */ - if (keep_their_modes && params.size() >= 3) - { - Anope::string modes; - for (unsigned i = 2; i < params.size() - 1; ++i) - modes += " " + params[i]; - if (!modes.empty()) - modes.erase(modes.begin()); - /* Set the modes internally */ - c->SetModesInternal(source, modes); - } - - spacesepstream sep(params[params.size() - 1]); - Anope::string buf; - while (sep.GetToken(buf)) - { - std::list<ChannelMode *> Status; - char ch; - - /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) - { - buf.erase(buf.begin()); - ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); - if (!cm) - { - Log() << "Received unknown mode prefix " << ch << " in SJOIN string"; - continue; - } - - if (keep_their_modes) - Status.push_back(cm); - } - - User *u = finduser(buf); - if (!u) - { - Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << c->name; - continue; - } - - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); - } - - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) - { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); - } - + IRCD->SendPing(Config->ServerName, params[0]); return true; } }; struct IRCDMessageTBurst : IRCDMessage { - IRCDMessageTBurst() : IRCDMessage("TBURST", 4) { } + IRCDMessageTBurst(Module *creator) : IRCDMessage(creator, "TB", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + /* + * params[0] = channel + * params[1] = ts + * params[2] = topic OR who set the topic + * params[3] = topic if params[2] isnt the topic + */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Anope::string setter = myStrGetToken(params[2], '!', 0); time_t topic_time = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime; - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (!c) return true; - c->ChangeTopicInternal(setter, params[3], topic_time); - - return true; - } -}; - -struct IRCDMessageTMode : IRCDMessage -{ - IRCDMessageTMode() : IRCDMessage("TMODE", 3) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } - - bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override - { - time_t ts = 0; - try - { - ts = convertTo<time_t>(params[0]); - } - catch (const ConvertException &) { } - Channel *c = findchan(params[1]); - Anope::string modes = params[2]; - for (unsigned i = 3; i < params.size(); ++i) - modes += " " + params[i]; + const Anope::string &setter = params.size() == 4 ? params[2] : "", + topic = params.size() == 4 ? params[3] : params[2]; - if (c) - c->SetModesInternal(source, modes, ts); + c->ChangeTopicInternal(setter, topic, topic_time); return true; } @@ -527,15 +170,15 @@ struct IRCDMessageTMode : IRCDMessage struct IRCDMessageUID : IRCDMessage { - IRCDMessageUID() : IRCDMessage("UID", 9) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageUID(Module *creator) : IRCDMessage(creator, "UID", 9) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } // :42X UID Adam 1 1348535644 +aow Adam 192.168.0.5 192.168.0.5 42XAAAAAB :Adam bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { /* Source is always the server */ User *user = new User(params[0], params[4], params[5], "", params[6], source.GetServer(), params[8], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, params[3], params[7]); - if (user && user->server->IsSynced() && nickserv) - nickserv->Validate(user); + if (user && user->server->IsSynced() && NickServService) + NickServService->Validate(user); return true; } @@ -543,99 +186,105 @@ struct IRCDMessageUID : IRCDMessage class ProtoRatbox : public Module { + Module *m_hybrid; + RatboxProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageCapab core_message_capab; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - CoreIRCDMessageWhois core_message_whois; + Message::Away message_away; + Message::Capab message_capab; + Message::Error message_error; + Message::Kick message_kick; + Message::Kill message_kill; + Message::Mode message_mode; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Topic message_topic; + Message::Version message_version; + Message::Whois message_whois; + + /* Hybrid message handlers */ + ServiceAlias message_bmask, message_join, message_nick, message_pong, message_sid, + message_sjoin, message_tmode; /* Our message handlers */ - IRCDMessageBMask message_bmask; IRCDMessageEncap message_encap; - IRCDMessageJoin message_join; - IRCDMessageMode message_mode; - IRCDMessageNick message_nick; IRCDMessagePass message_pass; - IRCDMessagePong message_pong; IRCDMessageServer message_server; - IRCDMessageSID message_sid; - IRCDMessageSjoin message_sjoin; IRCDMessageTBurst message_tburst; - IRCDMessageTMode message_tmode; IRCDMessageUID message_uid; void AddModes() { - /* Add user modes */ - ModeManager::AddUserMode(new UserMode(UMODE_ADMIN, 'a')); - ModeManager::AddUserMode(new UserMode(UMODE_INVIS, 'i')); - ModeManager::AddUserMode(new UserMode(UMODE_OPER, 'o')); - ModeManager::AddUserMode(new UserMode(UMODE_SNOMASK, 's')); - ModeManager::AddUserMode(new UserMode(UMODE_WALLOPS, 'w')); - - /* b/e/I */ - ModeManager::AddChannelMode(new ChannelModeList(CMODE_BAN, 'b')); - ModeManager::AddChannelMode(new ChannelModeList(CMODE_EXCEPT, 'e')); - ModeManager::AddChannelMode(new ChannelModeList(CMODE_INVITEOVERRIDE, 'I')); + /* user modes */ + ModeManager::RemoveUserMode(ModeManager::FindUserModeByName(UMODE_HIDEOPER)); + ModeManager::RemoveUserMode(ModeManager::FindUserModeByName(UMODE_REGPRIV)); /* v/h/o/a/q */ - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_VOICE, 'v', '+', 0)); - ModeManager::AddChannelMode(new ChannelModeStatus(CMODE_OP, 'o', '@', 1)); - - /* Add channel modes */ - ModeManager::AddChannelMode(new ChannelMode(CMODE_INVITE, 'i')); - ModeManager::AddChannelMode(new ChannelModeKey('k')); - ModeManager::AddChannelMode(new ChannelModeParam(CMODE_LIMIT, 'l')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_MODERATED, 'm')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_NOEXTERNAL, 'n')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_PRIVATE, 'p')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_SECRET, 's')); - ModeManager::AddChannelMode(new ChannelMode(CMODE_TOPIC, 't')); + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_HALFOP)); + + /* channel modes */ + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_REGISTERED)); + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_OPERONLY)); + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_REGISTEREDONLY)); + ModeManager::RemoveChannelMode(ModeManager::FindChannelModeByName(CMODE_SSL)); } public: - ProtoRatbox(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL) + ProtoRatbox(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), + message_away(this), message_capab(this), message_error(this), message_kick(this), message_kill(this), + message_mode(this), message_motd(this), message_part(this), message_ping(this), message_privmsg(this), + message_quit(this), message_squit(this), message_stats(this), message_time(this), message_topic(this), + message_version(this), message_whois(this), + + message_bmask("IRCDMessage", "ratbox/bmask", "hybrid/bmask"), message_join("IRCDMessage", "ratbox/join", "hybrid/join"), + message_nick("IRCDMessage", "ratbox/nick", "hybrid/nick"), message_pong("IRCDMessage", "ratbox/pong", "hybrid/pong"), + message_sid("IRCDMessage", "ratbox/sid", "hybrid/sid"), message_sjoin("IRCDMessage", "ratbox/sjoin", "hybrid/sjoin"), + message_tmode("IRCDMessage", "ratbox/tmode", "hybrid/tmode"), + + message_encap(this), message_pass(this), message_server(this), message_tburst(this), message_uid(this) { this->SetAuthor("Anope"); + if (ModuleManager::LoadModule("hybrid", User::Find(creator)) != MOD_ERR_OK) + throw ModuleException("Unable to load hybrid"); + m_hybrid = ModuleManager::FindModule("hybrid"); + if (!m_hybrid) + throw ModuleException("Unable to find hybrid"); + hybrid = m_hybrid->GetIRCDProto(); + if (!hybrid) + throw ModuleException("No protocol interface for hybrid"); + this->AddModes(); Implementation i[] = { I_OnServerSync }; ModuleManager::Attach(i, this, sizeof(i) / sizeof(Implementation)); + } - if (Config->Numeric.empty()) - { - Anope::string numeric = ts6_sid_retrieve(); - Me->SetSID(numeric); - Config->Numeric = numeric; - } + ~ProtoRatbox() + { + ModuleManager::UnloadModule(m_hybrid, NULL); + } - for (botinfo_map::iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) - it->second->GenerateUID(); + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; } void OnServerSync(Server *s) anope_override { - if (nickserv) + if (NickServService) for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) { User *u = it->second; if (u->server == s && !u->IsIdentified()) - nickserv->Validate(u); + NickServService->Validate(u); } } }; diff --git a/modules/protocol/unreal.cpp b/modules/protocol/unreal.cpp index d07c5eaec..5e7a9f194 100644 --- a/modules/protocol/unreal.cpp +++ b/modules/protocol/unreal.cpp @@ -48,7 +48,7 @@ class UnrealIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLineDel(x); + IRCD->SendSZLineDel(x); return; } } @@ -74,11 +74,10 @@ class UnrealIRCdProto : public IRCDProto void SendVhostDel(User *u) anope_override { - const BotInfo *bi = findbot(Config->HostServ); - u->RemoveMode(bi, UMODE_CLOAK); - u->RemoveMode(bi, UMODE_VHOST); + u->RemoveMode(HostServ, UMODE_CLOAK); + u->RemoveMode(HostServ, UMODE_VHOST); ModeManager::ProcessModes(); - u->SetMode(bi, UMODE_CLOAK); + u->SetMode(HostServ, UMODE_CLOAK); } void SendAkill(User *u, XLine *x) anope_override @@ -100,11 +99,11 @@ class UnrealIRCdProto : public IRCDProto return; /* We can't akill x as it has a nick and/or realname included, so create a new akill for *@host */ - XLine *xline = new XLine("*@" + u->host, old->By, old->Expires, old->Reason, old->UID); + XLine *xline = new XLine("*@" + u->host, old->by, old->expires, old->reason, old->id); old->manager->AddXLine(xline); x = xline; - Log(findbot(Config->OperServ), "akill") << "AKILL: Added an akill for " << x->Mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->Mask; + Log(OperServ, "akill") << "AKILL: Added an akill for " << x->mask << " because " << u->GetMask() << "#" << u->realname << " matches " << old->mask; } /* ZLine if we can instead */ @@ -113,17 +112,17 @@ class UnrealIRCdProto : public IRCDProto if (x->GetUser() == "*") { sockaddrs(x->GetHost()); - ircdproto->SendSZLine(u, x); + IRCD->SendSZLine(u, x); return; } } catch (const SocketException &) { } // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message() << "BD + G " << x->GetUser() << " " << x->GetHost() << " " << x->By << " " << Anope::CurTime + timeleft << " " << x->Created << " :" << x->GetReason(); + UplinkSocket::Message() << "BD + G " << x->GetUser() << " " << x->GetHost() << " " << x->by << " " << Anope::CurTime + timeleft << " " << x->created << " :" << x->GetReason(); } void SendSVSKillInternal(const BotInfo *source, User *user, const Anope::string &buf) anope_override @@ -165,11 +164,11 @@ class UnrealIRCdProto : public IRCDProto */ UserContainer *uc = c->FindUser(user); if (uc != NULL) - uc->Status->ClearFlags(); + uc->status->ClearFlags(); - BotInfo *setter = findbot(user->nick); + BotInfo *setter = BotInfo::Find(user->nick); for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) - if (cs.HasFlag(ModeManager::ChannelModes[i]->Name)) + if (cs.HasFlag(ModeManager::ChannelModes[i]->name)) c->SetMode(setter, ModeManager::ChannelModes[i], user->GetUID(), false); } } @@ -178,7 +177,7 @@ class UnrealIRCdProto : public IRCDProto */ void SendSQLineDel(const XLine *x) anope_override { - UplinkSocket::Message() << "d " << x->Mask; + UplinkSocket::Message() << "d " << x->mask; } /* SQLINE */ @@ -188,7 +187,7 @@ class UnrealIRCdProto : public IRCDProto */ void SendSQLine(User *, const XLine *x) anope_override { - UplinkSocket::Message() << "c " << x->Mask << " :" << x->GetReason(); + UplinkSocket::Message() << "c " << x->mask << " :" << x->GetReason(); } /* @@ -239,7 +238,7 @@ class UnrealIRCdProto : public IRCDProto UplinkSocket::Message() << "PROTOCTL NICKv2 VHP UMODE2 NICKIP SJOIN SJOIN2 SJ3 NOQUIT TKLEXT ESVID MLOCK VL"; else UplinkSocket::Message() << "PROTOCTL NICKv2 VHP UMODE2 NICKIP SJOIN SJOIN2 SJ3 NOQUIT TKLEXT ESVID MLOCK"; - UplinkSocket::Message() << "PASS :" << Config->Uplinks[CurrentUplink]->password; + UplinkSocket::Message() << "PASS :" << Config->Uplinks[Anope::CurrentUplink]->password; SendServer(Me); } @@ -261,7 +260,7 @@ class UnrealIRCdProto : public IRCDProto */ void SendSGLineDel(const XLine *x) anope_override { - UplinkSocket::Message() << "BR - :" << x->Mask; + UplinkSocket::Message() << "BR - :" << x->mask; } /* UNSZLINE */ @@ -274,10 +273,10 @@ class UnrealIRCdProto : public IRCDProto void SendSZLine(User *, const XLine *x) anope_override { // Calculate the time left before this would expire, capping it at 2 days - time_t timeleft = x->Expires - Anope::CurTime; - if (timeleft > 172800 || !x->Expires) + time_t timeleft = x->expires - Anope::CurTime; + if (timeleft > 172800 || !x->expires) timeleft = 172800; - UplinkSocket::Message() << "BD + Z * " << x->GetHost() << " " << x->By << " " << Anope::CurTime + timeleft << " " << x->Created << " :" << x->GetReason(); + UplinkSocket::Message() << "BD + Z * " << x->GetHost() << " " << x->by << " " << Anope::CurTime + timeleft << " " << x->created << " :" << x->GetReason(); } /* SGLINE */ @@ -288,7 +287,7 @@ class UnrealIRCdProto : public IRCDProto { Anope::string edited_reason = x->GetReason(); edited_reason = edited_reason.replace_all_cs(" ", "_"); - UplinkSocket::Message() << "BR + " << edited_reason << " :" << x->Mask; + UplinkSocket::Message() << "BR + " << edited_reason << " :" << x->mask; } /* svsjoin @@ -323,7 +322,7 @@ class UnrealIRCdProto : public IRCDProto if (nick.equals_ci("ircd") || nick.equals_ci("irc")) return false; - return true; + return IRCDProto::IsNickValid(nick); } bool IsChannelValid(const Anope::string &chan) anope_override @@ -339,17 +338,15 @@ class UnrealIRCdProto : public IRCDProto if (!u->Account()) return; - const BotInfo *ns = findbot(Config->NickServ); - if (Capab.count("ESVID") > 0) - ircdproto->SendMode(ns, u, "+d %s", u->Account()->display.c_str()); + if (Servers::Capab.count("ESVID") > 0) + IRCD->SendMode(NickServ, u, "+d %s", u->Account()->display.c_str()); else - ircdproto->SendMode(ns, u, "+d %d", u->timestamp); + IRCD->SendMode(NickServ, u, "+d %d", u->timestamp); } void SendLogout(User *u) anope_override { - const BotInfo *ns = findbot(Config->NickServ); - ircdproto->SendMode(ns, u, "+d 0"); + IRCD->SendMode(NickServ, u, "+d 0"); } void SendChannel(Channel *c) anope_override @@ -392,16 +389,16 @@ class UnrealExtBan : public ChannelModeList char modeChar = ModeManager::GetStatusChar(channel[0]); channel.erase(channel.begin()); cm = ModeManager::FindChannelModeByChar(modeChar); - if (cm != NULL && cm->Type != MODE_STATUS) + if (cm != NULL && cm->type != MODE_STATUS) cm = NULL; } - Channel *c = findchan(channel); + Channel *c = Channel::Find(channel); if (c != NULL) { UserContainer *uc = c->FindUser(u); if (uc != NULL) - if (cm == NULL || uc->Status->HasFlag(cm->Name)) + if (cm == NULL || uc->status->HasFlag(cm->name)) return true; } } @@ -409,7 +406,7 @@ class UnrealExtBan : public ChannelModeList { Anope::string real_mask = mask.substr(3); - Entry en(this->Name, real_mask); + Entry en(this->name, real_mask); if (en.Matches(u)) return true; } @@ -494,9 +491,9 @@ class ChannelModeUnrealSSL : public ChannelMode } }; -struct IRCDMessageCapab : CoreIRCDMessageCapab +struct IRCDMessageCapab : Message::Capab { - IRCDMessageCapab() : CoreIRCDMessageCapab("PROTOCTL") { } + IRCDMessageCapab(Module *creator) : Message::Capab(creator, "PROTOCTL") { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -645,17 +642,17 @@ struct IRCDMessageCapab : CoreIRCDMessageCapab } } - return CoreIRCDMessageCapab::Run(source, params); + return Message::Capab::Run(source, params); } }; struct IRCDMessageChgHost : IRCDMessage { - IRCDMessageChgHost() : IRCDMessage("CHGHOST", 2) { } + IRCDMessageChgHost(Module *creator) : IRCDMessage(creator, "CHGHOST", 2) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetDisplayedHost(params[1]); return true; @@ -664,11 +661,11 @@ struct IRCDMessageChgHost : IRCDMessage struct IRCDMessageChgIdent : IRCDMessage { - IRCDMessageChgIdent() : IRCDMessage("CHGIDENT", 2) { } + IRCDMessageChgIdent(Module *creator) : IRCDMessage(creator, "CHGIDENT", 2) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetVIdent(params[1]); return true; @@ -677,11 +674,11 @@ struct IRCDMessageChgIdent : IRCDMessage struct IRCDMessageChgName : IRCDMessage { - IRCDMessageChgName() : IRCDMessage("CHGNAME", 2) { } + IRCDMessageChgName(Module *creator) : IRCDMessage(creator, "CHGNAME", 2) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetRealname(params[1]); return true; @@ -690,7 +687,7 @@ struct IRCDMessageChgName : IRCDMessage struct IRCDMessageMode : IRCDMessage { - IRCDMessageMode(const Anope::string &mname) : IRCDMessage(mname, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageMode(Module *creator, const Anope::string &mname) : IRCDMessage(creator, mname, 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -699,10 +696,11 @@ struct IRCDMessageMode : IRCDMessage for (unsigned i = 2; i < params.size() - (server_source ? 1 : 0); ++i) modes += " " + params[i]; - if (ircdproto->IsChannelValid(params[0])) + if (IRCD->IsChannelValid(params[0])) { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); time_t ts = 0; + try { if (server_source) @@ -715,7 +713,7 @@ struct IRCDMessageMode : IRCDMessage } else { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetModesInternal("%s", params[1].c_str()); } @@ -736,18 +734,18 @@ struct IRCDMessageMode : IRCDMessage */ struct IRCDMessageNetInfo : IRCDMessage { - IRCDMessageNetInfo() : IRCDMessage("NETINFO", 8) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageNetInfo(Module *creator) : IRCDMessage(creator, "NETINFO", 8) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - UplinkSocket::Message() << "AO " << maxusercnt << " " << Anope::CurTime << " " << convertTo<int>(params[2]) << " " << params[3] << " 0 0 0 :" << params[7]; + UplinkSocket::Message() << "AO " << MaxUserCount << " " << Anope::CurTime << " " << convertTo<int>(params[2]) << " " << params[3] << " 0 0 0 :" << params[7]; return true; } }; struct IRCDMessageNick : IRCDMessage { - IRCDMessageNick() : IRCDMessage("NICK", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageNick(Module *creator) : IRCDMessage(creator, "NICK", 2) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); } /* ** NICK - new @@ -807,21 +805,21 @@ struct IRCDMessageNick : IRCDMessage else if (params[6].is_pos_number_only()) { if (convertTo<time_t>(params[6]) == user->timestamp) - na = findnick(user->nick); + na = NickAlias::Find(user->nick); } else { - na = findnick(params[6]); + na = NickAlias::Find(params[6]); } if (na) { user->Login(na->nc); - if (!Config->NoNicknameOwnership && na->nc->HasFlag(NI_UNCONFIRMED) == false && nickserv) - user->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + if (!Config->NoNicknameOwnership && na->nc->HasFlag(NI_UNCONFIRMED) == false) + user->SetMode(NickServ, UMODE_REGISTERED); } - else if (nickserv) - nickserv->Validate(user); + else if (NickServService) + NickServService->Validate(user); } else source.GetUser()->ChangeNick(params[0]); @@ -841,7 +839,7 @@ struct IRCDMessageNick : IRCDMessage */ struct IRCDMessagePong : IRCDMessage { - IRCDMessagePong() : IRCDMessage("PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessagePong(Module *creator) : IRCDMessage(creator, "PONG", 0) { SetFlag(IRCDMESSAGE_SOFT_LIMIT); SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -878,13 +876,11 @@ struct IRCDMessageSASL : IRCDMessage UplinkSocket::Message() << "SASL " << this->uid.substr(0, p) << " " << this->uid << " D F"; - Log(findbot(Config->NickServ)) << "A user failed to identify for account " << this->GetAccount() << " using SASL"; + Log(NickServ) << "A user failed to identify for account " << this->GetAccount() << " using SASL"; } }; - Module *me; - - IRCDMessageSASL(Module *m) : IRCDMessage("SASL", 4), me(m) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageSASL(Module *creator) : IRCDMessage(creator, "SASL", 4) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } /* Received: :irc.foonet.com SASL services.localhost.net irc.foonet.com!1.57290 S PLAIN * uid @@ -920,7 +916,7 @@ struct IRCDMessageSASL : IRCDMessage if (acc.empty() || pass.empty()) return true; - IdentifyRequest *req = new UnrealSASLIdentifyRequest(me, params[1], acc, pass); + IdentifyRequest *req = new UnrealSASLIdentifyRequest(this->owner, params[1], acc, pass); FOREACH_MOD(I_OnCheckAuthentication, OnCheckAuthentication(NULL, req)); req->Dispatch(); } @@ -931,7 +927,7 @@ struct IRCDMessageSASL : IRCDMessage struct IRCDMessageSDesc : IRCDMessage { - IRCDMessageSDesc() : IRCDMessage("SDESC", 1) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageSDesc(Module *creator) : IRCDMessage(creator, "SDESC", 1) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -942,7 +938,7 @@ struct IRCDMessageSDesc : IRCDMessage struct IRCDMessageSetHost : IRCDMessage { - IRCDMessageSetHost() : IRCDMessage("SETHOST", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageSetHost(Module *creator) : IRCDMessage(creator, "SETHOST", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -960,7 +956,7 @@ struct IRCDMessageSetHost : IRCDMessage struct IRCDMessageSetIdent : IRCDMessage { - IRCDMessageSetIdent() : IRCDMessage("SETIDENT", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageSetIdent(Module *creator) : IRCDMessage(creator, "SETIDENT", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -972,11 +968,11 @@ struct IRCDMessageSetIdent : IRCDMessage struct IRCDMessageSetName : IRCDMessage { - IRCDMessageSetName() : IRCDMessage("SETNAME", 1) { } + IRCDMessageSetName(Module *creator) : IRCDMessage(creator, "SETNAME", 1) { } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u) u->SetRealname(params[1]); return true; @@ -985,7 +981,7 @@ struct IRCDMessageSetName : IRCDMessage struct IRCDMessageServer : IRCDMessage { - IRCDMessageServer() : IRCDMessage("SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } + IRCDMessageServer(Module *creator) : IRCDMessage(creator, "SERVER", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -993,16 +989,15 @@ struct IRCDMessageServer : IRCDMessage if (params[1].equals_cs("1")) { - Anope::string vl = myStrGetToken(params[2], ' ', 0); - Anope::string upnumeric = myStrGetToken(vl, '-', 2); - Anope::string desc = myStrGetTokenRemainder(params[2], ' ', 1); + Anope::string desc; + spacesepstream(params[2]).GetTokenRemainder(desc, 1); new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, desc); } else new Server(source.GetServer(), params[0], hops, params[2]); - ircdproto->SendPing(Config->ServerName, params[0]); + IRCD->SendPing(Config->ServerName, params[0]); return true; } @@ -1010,44 +1005,20 @@ struct IRCDMessageServer : IRCDMessage struct IRCDMessageSJoin : IRCDMessage { - IRCDMessageSJoin() : IRCDMessage("SJOIN", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } + IRCDMessageSJoin(Module *creator) : IRCDMessage(creator, "SJOIN", 3) { SetFlag(IRCDMESSAGE_REQUIRE_SERVER); SetFlag(IRCDMESSAGE_SOFT_LIMIT); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[1]); - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : 0; - bool keep_their_modes = true; - - if (!c) - { - c = new Channel(params[1], ts); - c->SetFlag(CH_SYNCING); - } - /* Our creation time is newer than what the server gave us */ - else if (c->creation_time > ts) - { - c->creation_time = ts; - c->Reset(); - } - /* Their TS is newer than ours, our modes > theirs, unset their modes if need be */ - else if (ts > c->creation_time) - keep_their_modes = false; - - /* If we need to keep their modes, and this SJOIN string contains modes */ - if (keep_their_modes && params.size() >= 4) - { - Anope::string modes; + Anope::string modes; + if (params.size() >= 4) for (unsigned i = 2; i < params.size() - 1; ++i) modes += " " + params[i]; - if (!modes.empty()) - modes.erase(modes.begin()); - /* Set the modes internally */ - c->SetModesInternal(source, modes); - } + if (!modes.empty()) + modes.erase(modes.begin()); + + std::list<Anope::string> bans, excepts, invites; + std::list<Message::Join::SJoinUser> users; - ChannelMode *ban = ModeManager::FindChannelModeByName(CMODE_BAN), - *except = ModeManager::FindChannelModeByName(CMODE_EXCEPT), - *invex = ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE); spacesepstream sep(params[params.size() - 1]); Anope::string buf; while (sep.GetToken(buf)) @@ -1056,82 +1027,72 @@ struct IRCDMessageSJoin : IRCDMessage if (buf[0] == '&') { buf.erase(buf.begin()); - if (keep_their_modes && ban) - c->SetModeInternal(source, ban, buf); + bans.push_back(buf); } /* Except */ else if (buf[0] == '"') { buf.erase(buf.begin()); - if (keep_their_modes && except) - c->SetModeInternal(source, except, buf); + excepts.push_back(buf); } /* Invex */ else if (buf[0] == '\'') { buf.erase(buf.begin()); - if (keep_their_modes && invex) - c->SetModeInternal(source, invex, buf); + invites.push_back(buf); } else { - std::list<ChannelMode *> Status; - char ch; + Message::Join::SJoinUser sju; /* Get prefixes from the nick */ - while ((ch = ModeManager::GetStatusChar(buf[0]))) + for (char ch; (ch = ModeManager::GetStatusChar(buf[0]));) { buf.erase(buf.begin()); ChannelMode *cm = ModeManager::FindChannelModeByChar(ch); if (!cm) { - Log() << "Received unknown mode prefix " << ch << " in SJOIN string"; + Log(LOG_DEBUG) << "Received unknown mode prefix " << ch << " in SJOIN string"; continue; } - if (keep_their_modes) - Status.push_back(cm); + sju.first.SetFlag(cm->name); } - User *u = finduser(buf); - if (!u) + sju.second = User::Find(buf); + if (!sju.second) { - Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << c->name; + Log(LOG_DEBUG) << "SJOIN for nonexistant user " << buf << " on " << params[1]; continue; } - EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); - - /* Add the user to the channel */ - c->JoinUser(u); - - /* Update their status internally on the channel - * This will enforce secureops etc on the user - */ - for (std::list<ChannelMode *>::iterator it = Status.begin(), it_end = Status.end(); it != it_end; ++it) - c->SetModeInternal(source, *it, buf); - - /* Now set whatever modes this user is allowed to have on the channel */ - chan_set_correct_modes(u, c, 1, true); - - /* Check to see if modules want the user to join, if they do - * check to see if they are allowed to join (CheckKick will kick/ban them) - * Don't trigger OnJoinChannel event then as the user will be destroyed - */ - if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) - continue; - - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); + users.push_back(sju); } } + + time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + Message::Join::SJoin(source, params[1], ts, modes, users); - /* Channel is done syncing */ - if (c->HasFlag(CH_SYNCING)) + if (!bans.empty() || !excepts.empty() || !invites.empty()) { - /* Unset the syncing flag */ - c->UnsetFlag(CH_SYNCING); - c->Sync(); + Channel *c = Channel::Find(params[1]); + + if (!c || c->creation_time != ts) + return true; + + ChannelMode *ban = ModeManager::FindChannelModeByName(CMODE_BAN), + *except = ModeManager::FindChannelModeByName(CMODE_EXCEPT), + *invex = ModeManager::FindChannelModeByName(CMODE_INVITEOVERRIDE); + + if (ban) + for (std::list<Anope::string>::iterator it = bans.begin(), it_end = bans.end(); it != it_end; ++it) + c->SetModeInternal(source, ban, *it); + if (except) + for (std::list<Anope::string>::iterator it = excepts.begin(), it_end = excepts.end(); it != it_end; ++it) + c->SetModeInternal(source, except, *it); + if (invex) + for (std::list<Anope::string>::iterator it = invites.begin(), it_end = invites.end(); it != it_end; ++it) + c->SetModeInternal(source, invex, *it); } return true; @@ -1140,7 +1101,7 @@ struct IRCDMessageSJoin : IRCDMessage struct IRCDMessageTopic : IRCDMessage { - IRCDMessageTopic() : IRCDMessage("TOPIC", 4) { } + IRCDMessageTopic(Module *creator) : IRCDMessage(creator, "TOPIC", 4) { } /* ** source = sender prefix @@ -1151,7 +1112,7 @@ struct IRCDMessageTopic : IRCDMessage */ bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c) c->ChangeTopicInternal(params[1], params[3], Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); @@ -1162,7 +1123,7 @@ struct IRCDMessageTopic : IRCDMessage struct IRCDMessageUmode2 : IRCDMessage { - IRCDMessageUmode2() : IRCDMessage("UMODE2", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } + IRCDMessageUmode2(Module *creator) : IRCDMessage(creator, "UMODE2", 1) { SetFlag(IRCDMESSAGE_REQUIRE_USER); } bool Run(MessageSource &source, const std::vector<Anope::string> ¶ms) anope_override { @@ -1176,22 +1137,21 @@ class ProtoUnreal : public Module UnrealIRCdProto ircd_proto; /* Core message handlers */ - CoreIRCDMessageAway core_message_away; - CoreIRCDMessageError core_message_error; - CoreIRCDMessageJoin core_message_join; - CoreIRCDMessageKick core_message_kick; - CoreIRCDMessageKill core_message_kill; - CoreIRCDMessageMOTD core_message_motd; - CoreIRCDMessagePart core_message_part; - CoreIRCDMessagePing core_message_ping; - CoreIRCDMessagePrivmsg core_message_privmsg; - CoreIRCDMessageQuit core_message_quit; - CoreIRCDMessageSQuit core_message_squit; - CoreIRCDMessageStats core_message_stats; - CoreIRCDMessageTime core_message_time; - CoreIRCDMessageTopic core_message_topic; - CoreIRCDMessageVersion core_message_version; - CoreIRCDMessageWhois core_message_whois; + Message::Away message_away; + Message::Error message_error; + Message::Join message_join; + Message::Kick message_kick; + Message::Kill message_kill; + Message::MOTD message_motd; + Message::Part message_part; + Message::Ping message_ping; + Message::Privmsg message_privmsg; + Message::Quit message_quit; + Message::SQuit message_squit; + Message::Stats message_stats; + Message::Time message_time; + Message::Version message_version; + Message::Whois message_whois; /* Our message handlers */ IRCDMessageCapab message_capab; @@ -1252,7 +1212,15 @@ class ProtoUnreal : public Module public: ProtoUnreal(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, PROTOCOL), - message_mode("MODE"), message_svsmode("SVSMODE"), message_svs2mode("SVS2MODE"), message_sasl(this) + message_away(this), message_error(this), message_join(this), message_kick(this), message_kill(this), + message_motd(this), message_part(this), message_ping(this), message_privmsg(this), message_quit(this), + message_squit(this), message_stats(this), message_time(this), message_version(this), + message_whois(this), + + message_capab(this), message_chghost(this), message_chgident(this), message_chgname(this), message_mode(this, "MODE"), + message_svsmode(this, "SVSMODE"), message_svs2mode(this, "SVS2MODE"), message_netinfo(this), message_nick(this), message_pong(this), + message_sasl(this), message_sdesc(this), message_sethost(this), message_setident(this), message_setname(this), message_server(this), + message_sjoin(this), message_topic(this), message_umode2(this) { this->SetAuthor("Anope"); @@ -1263,15 +1231,21 @@ class ProtoUnreal : public Module ModuleManager::SetPriority(this, PRIORITY_FIRST); } + IRCDProto *GetIRCDProto() anope_override + { + return &ircd_proto; + } + void OnUserNickChange(User *u, const Anope::string &) anope_override { u->RemoveModeInternal(ModeManager::FindUserModeByName(UMODE_REGISTERED)); - ircdproto->SendLogout(u); + if (Servers::Capab.count("ESVID") == 0) + IRCD->SendLogout(u); } void OnChannelCreate(Channel *c) anope_override { - if (Config->UseServerSideMLock && Capab.count("MLOCK") > 0 && c->ci) + if (Config->UseServerSideMLock && Servers::Capab.count("MLOCK") > 0 && c->ci) { Anope::string modes = c->ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", ""); UplinkSocket::Message(Me) << "MLOCK " << static_cast<long>(c->creation_time) << " " << c->ci->name << " " << modes; @@ -1296,9 +1270,9 @@ class ProtoUnreal : public Module EventReturn OnMLock(ChannelInfo *ci, ModeLock *lock) anope_override { ChannelMode *cm = ModeManager::FindChannelModeByName(lock->name); - if (cm && ci->c && (cm->Type == MODE_REGULAR || cm->Type == MODE_PARAM) && Capab.count("MLOCK") > 0 && Config->UseServerSideMLock) + if (cm && ci->c && (cm->type == MODE_REGULAR || cm->type == MODE_PARAM) && Servers::Capab.count("MLOCK") > 0 && Config->UseServerSideMLock) { - Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "") + cm->ModeChar; + Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "") + cm->mchar; UplinkSocket::Message(Me) << "MLOCK " << static_cast<long>(ci->c->creation_time) << " " << ci->name << " " << modes; } @@ -1308,9 +1282,9 @@ class ProtoUnreal : public Module EventReturn OnUnMLock(ChannelInfo *ci, ModeLock *lock) anope_override { ChannelMode *cm = ModeManager::FindChannelModeByName(lock->name); - if (cm && ci->c && (cm->Type == MODE_REGULAR || cm->Type == MODE_PARAM) && Capab.count("MLOCK") > 0 && Config->UseServerSideMLock) + if (cm && ci->c && (cm->type == MODE_REGULAR || cm->type == MODE_PARAM) && Servers::Capab.count("MLOCK") > 0 && Config->UseServerSideMLock) { - Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "").replace_all_cs(cm->ModeChar, ""); + Anope::string modes = ci->GetMLockAsString(false).replace_all_cs("+", "").replace_all_cs("-", "").replace_all_cs(cm->mchar, ""); UplinkSocket::Message(Me) << "MLOCK " << static_cast<long>(ci->c->creation_time) << " " << ci->name << " " << modes; } diff --git a/modules/pseudoclients/botserv.cpp b/modules/pseudoclients/botserv.cpp index e653e7d3e..f78d0a6de 100644 --- a/modules/pseudoclients/botserv.cpp +++ b/modules/pseudoclients/botserv.cpp @@ -20,8 +20,8 @@ class BotServCore : public Module { this->SetAuthor("Anope"); - const BotInfo *BotServ = findbot(Config->BotServ); - if (BotServ == NULL) + BotServ = BotInfo::Find(Config->BotServ); + if (!BotServ) throw ModuleException("No bot named " + Config->BotServ); Implementation i[] = { I_OnPrivmsg, I_OnJoinChannel, I_OnLeaveChannel, @@ -41,7 +41,7 @@ class BotServCore : public Module Anope::string ctcp = msg; ctcp.erase(ctcp.begin()); ctcp.erase(ctcp.length() - 1); - ircdproto->SendCTCP(c->ci->bi, u->nick, "%s", ctcp.c_str()); + IRCD->SendCTCP(c->ci->bi, u->nick, "%s", ctcp.c_str()); } Anope::string realbuf = msg; @@ -56,7 +56,8 @@ class BotServCore : public Module if (realbuf.empty() || !c->ci->botflags.HasFlag(BS_FANTASY)) return; - std::vector<Anope::string> params = BuildStringVector(realbuf); + std::vector<Anope::string> params; + spacesepstream(realbuf).GetTokens(params); if (!realbuf.find(c->ci->bi->nick)) params.erase(params.begin()); @@ -87,7 +88,7 @@ class BotServCore : public Module return; const CommandInfo &info = it->second; - service_reference<Command> cmd("Command", info.name); + ServiceReference<Command> cmd("Command", info.name); if (!cmd) { Log(LOG_DEBUG) << "Fantasy command " << it->first << " exists for nonexistant service " << info.name << "!"; @@ -97,10 +98,10 @@ class BotServCore : public Module for (unsigned i = 0, j = params.size() - (count - 1); i < j; ++i) params.erase(params.begin()); - while (cmd->MaxParams > 0 && params.size() > cmd->MaxParams) + while (cmd->max_params > 0 && params.size() > cmd->max_params) { - params[cmd->MaxParams - 1] += " " + params[cmd->MaxParams]; - params.erase(params.begin() + cmd->MaxParams); + params[cmd->max_params - 1] += " " + params[cmd->max_params]; + params.erase(params.begin() + cmd->max_params); } /* All ChanServ commands take the channel as a first parameter */ @@ -111,7 +112,7 @@ class BotServCore : public Module if (!cmd->HasFlag(CFLAG_ALLOW_UNREGISTERED) && !u->Account()) return; - if (params.size() < cmd->MinParams) + if (params.size() < cmd->min_params) return; CommandSource source(u->nick, u, u->Account(), u, c->ci->bi); @@ -139,8 +140,8 @@ class BotServCore : public Module if (MOD_RESULT == EVENT_STOP) return; - dynamic_reference<User> user_reference(u); - dynamic_reference<NickCore> nc_reference(u->Account()); + Reference<User> user_reference(u); + Reference<NickCore> nc_reference(u->Account()); cmd->Execute(source, params); if (user_reference && nc_reference) @@ -160,14 +161,14 @@ class BotServCore : public Module * legit users - Rob **/ if (c->users.size() >= Config->BSMinUsers && !c->FindUser(c->ci->bi)) - c->ci->bi->Join(c, &Config->BotModeList); + c->ci->bi->Join(c, &ModeManager::DefaultBotModes); /* Only display the greet if the main uplink we're connected * to has synced, or we'll get greet-floods when the net * recovers from a netsplit. -GD */ if (c->FindUser(c->ci->bi) && c->ci->botflags.HasFlag(BS_GREET) && user->Account() && !user->Account()->greet.empty() && c->ci->AccessFor(user).HasPriv("GREET") && user->server->IsSynced()) { - ircdproto->SendPrivmsg(c->ci->bi, c->name, "[%s] %s", user->Account()->display.c_str(), user->Account()->greet.c_str()); + IRCD->SendPrivmsg(c->ci->bi, c->name, "[%s] %s", user->Account()->display.c_str(), user->Account()->greet.c_str()); c->ci->bi->lastmsg = Anope::CurTime; } } diff --git a/modules/pseudoclients/botserv.h b/modules/pseudoclients/botserv.h new file mode 100644 index 000000000..9757e5d4e --- /dev/null +++ b/modules/pseudoclients/botserv.h @@ -0,0 +1,6 @@ +#ifndef BOTSERV_H +#define BOTSERV_H + +static Reference<BotInfo> BotServ; + +#endif // BOTSERV_H diff --git a/modules/pseudoclients/chanserv.cpp b/modules/pseudoclients/chanserv.cpp index c3a6e6479..7a5b482bb 100644 --- a/modules/pseudoclients/chanserv.cpp +++ b/modules/pseudoclients/chanserv.cpp @@ -20,7 +20,7 @@ class ExpireCallback : public CallBack void Tick(time_t) anope_override { - if (!Config->CSExpire || noexpire || readonly) + if (!Config->CSExpire || Anope::NoExpire || Anope::ReadOnly) return; for (registered_channel_map::const_iterator it = RegisteredChannelList->begin(), it_end = RegisteredChannelList->end(); it != it_end; ) @@ -30,7 +30,7 @@ class ExpireCallback : public CallBack bool expire = false; - if (!ci->c && Config->CSExpire && Anope::CurTime - ci->last_used >= Config->CSExpire) + if (!ci->c && Anope::CurTime - ci->last_used >= Config->CSExpire) expire = true; if (ci->HasFlag(CI_NO_EXPIRE)) @@ -46,7 +46,7 @@ class ExpireCallback : public CallBack Log(LOG_NORMAL, "chanserv/expire") << "Expiring " << extra << "channel " << ci->name << " (founder: " << (ci->GetFounder() ? ci->GetFounder()->display : "(none)") << ")"; FOREACH_MOD(I_OnChanExpire, OnChanExpire(ci)); - ci->destroy(); + ci->Destroy(); } } } @@ -61,8 +61,8 @@ class ChanServCore : public Module { this->SetAuthor("Anope"); - const BotInfo *ChanServ = findbot(Config->ChanServ); - if (ChanServ == NULL) + ChanServ = BotInfo::Find(Config->ChanServ); + if (!ChanServ) throw ModuleException("No bot named " + Config->ChanServ); Implementation i[] = { I_OnBotPrivmsg, I_OnDelCore, I_OnPreHelp, I_OnPostHelp, I_OnCheckModes }; @@ -99,7 +99,7 @@ class ChanServCore : public Module for (unsigned j = 0; j < ci->GetAccessCount(); ++j) { const ChanAccess *ca = ci->GetAccess(j); - const NickCore *anc = findcore(ca->mask); + const NickCore *anc = NickCore::Find(ca->mask); if (!anc || (!anc->IsServicesOper() && Config->CSMaxReg && anc->channelcount >= Config->CSMaxReg) || (anc == nc)) continue; @@ -107,7 +107,7 @@ class ChanServCore : public Module highest = ca; } if (highest) - newowner = findcore(highest->mask); + newowner = NickCore::Find(highest->mask); } if (newowner) @@ -120,7 +120,7 @@ class ChanServCore : public Module { Log(LOG_NORMAL, "chanserv/expire") << "Deleting channel " << ci->name << " owned by deleted nick " << nc->display; - ci->destroy(); + ci->Destroy(); continue; } } @@ -131,7 +131,7 @@ class ChanServCore : public Module for (unsigned j = 0; j < ci->GetAccessCount(); ++j) { const ChanAccess *ca = ci->GetAccess(j); - const NickCore *anc = findcore(ca->mask); + const NickCore *anc = NickCore::Find(ca->mask); if (anc && anc == nc) { diff --git a/modules/pseudoclients/chanserv.h b/modules/pseudoclients/chanserv.h new file mode 100644 index 000000000..6c9ccd6c6 --- /dev/null +++ b/modules/pseudoclients/chanserv.h @@ -0,0 +1,6 @@ +#ifndef CHANSERV_H +#define CHANSERV_H + +static Reference<BotInfo> ChanServ; + +#endif // CHANSERV_H diff --git a/modules/pseudoclients/global.cpp b/modules/pseudoclients/global.cpp index 13e7570ce..a5e1eb573 100644 --- a/modules/pseudoclients/global.cpp +++ b/modules/pseudoclients/global.cpp @@ -53,8 +53,8 @@ class GlobalCore : public Module { this->SetAuthor("Anope"); - const BotInfo *Global = findbot(Config->Global); - if (Global == NULL) + Global = BotInfo::Find(Config->Global); + if (!Global) throw ModuleException("No bot named " + Config->Global); Implementation i[] = { I_OnRestart, I_OnShutdown, I_OnNewServer, I_OnPreHelp }; @@ -64,19 +64,19 @@ class GlobalCore : public Module void OnRestart() anope_override { if (Config->GlobalOnCycle) - global->SendGlobal(findbot(Config->Global), "", Config->GlobalOnCycleMessage); + GlobalService->SendGlobal(Global, "", Config->GlobalOnCycleMessage); } void OnShutdown() anope_override { if (Config->GlobalOnCycle) - global->SendGlobal(findbot(Config->Global), "", Config->GlobalOnCycleMessage); + GlobalService->SendGlobal(Global, "", Config->GlobalOnCycleMessage); } void OnNewServer(Server *s) anope_override { if (Config->GlobalOnCycle && !Config->GlobalOnCycleUP.empty()) - s->Notice(findbot(Config->Global), Config->GlobalOnCycleUP); + s->Notice(Global, Config->GlobalOnCycleUP); } EventReturn OnPreHelp(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override diff --git a/modules/pseudoclients/global.h b/modules/pseudoclients/global.h index 75d783399..46bccef6d 100644 --- a/modules/pseudoclients/global.h +++ b/modules/pseudoclients/global.h @@ -14,7 +14,8 @@ class GlobalService : public Service virtual void SendGlobal(const BotInfo *sender, const Anope::string &source, const Anope::string &message) = 0; }; -static service_reference<GlobalService> global("GlobalService", "Global"); +static ServiceReference<GlobalService> GlobalService("GlobalService", "Global"); +static Reference<BotInfo> Global; #endif // GLOBAL_H diff --git a/modules/pseudoclients/hostserv.cpp b/modules/pseudoclients/hostserv.cpp index d0d078a79..47c4250c0 100644 --- a/modules/pseudoclients/hostserv.cpp +++ b/modules/pseudoclients/hostserv.cpp @@ -20,11 +20,11 @@ class HostServCore : public Module { this->SetAuthor("Anope"); - if (!ircdproto || !ircdproto->CanSetVHost) + if (!IRCD || !IRCD->CanSetVHost) throw ModuleException("Your IRCd does not support vhosts"); - const BotInfo *HostServ = findbot(Config->HostServ); - if (HostServ == NULL) + HostServ = BotInfo::Find(Config->HostServ); + if (!HostServ) throw ModuleException("No bot named " + Config->HostServ); Implementation i[] = { I_OnNickIdentify, I_OnNickUpdate, I_OnPreHelp }; @@ -33,29 +33,28 @@ class HostServCore : public Module void OnNickIdentify(User *u) anope_override { - const NickAlias *na = findnick(u->nick); + const NickAlias *na = NickAlias::Find(u->nick); if (!na || !na->HasVhost()) - na = findnick(u->Account()->display); - if (!ircdproto->CanSetVHost || !na || !na->HasVhost()) + na = NickAlias::Find(u->Account()->display); + if (!IRCD->CanSetVHost || !na || !na->HasVhost()) return; if (u->vhost.empty() || !u->vhost.equals_cs(na->GetVhostHost()) || (!na->GetVhostIdent().empty() && !u->GetVIdent().equals_cs(na->GetVhostIdent()))) { - ircdproto->SendVhost(u, na->GetVhostIdent(), na->GetVhostHost()); + IRCD->SendVhost(u, na->GetVhostIdent(), na->GetVhostHost()); u->vhost = na->GetVhostHost(); u->UpdateHost(); - if (ircdproto->CanSetVIdent && !na->GetVhostIdent().empty()) + if (IRCD->CanSetVIdent && !na->GetVhostIdent().empty()) u->SetVIdent(na->GetVhostIdent()); - const BotInfo *bi = findbot(Config->HostServ); - if (bi) + if (HostServ) { if (!na->GetVhostIdent().empty()) - u->SendMessage(bi, _("Your vhost of \002%s\002@\002%s\002 is now activated."), na->GetVhostIdent().c_str(), na->GetVhostHost().c_str()); + u->SendMessage(HostServ, _("Your vhost of \002%s\002@\002%s\002 is now activated."), na->GetVhostIdent().c_str(), na->GetVhostHost().c_str()); else - u->SendMessage(bi, _("Your vhost of \002%s\002 is now activated."), na->GetVhostHost().c_str()); + u->SendMessage(HostServ, _("Your vhost of \002%s\002 is now activated."), na->GetVhostHost().c_str()); } } } diff --git a/modules/pseudoclients/hostserv.h b/modules/pseudoclients/hostserv.h new file mode 100644 index 000000000..039e711c3 --- /dev/null +++ b/modules/pseudoclients/hostserv.h @@ -0,0 +1,6 @@ +#ifndef HOSTSERV_H +#define HOSTSERV_H + +static Reference<BotInfo> HostServ; + +#endif // HOSTSERV_H diff --git a/modules/pseudoclients/memoserv.cpp b/modules/pseudoclients/memoserv.cpp index 9cfca1af3..ee9c127f9 100644 --- a/modules/pseudoclients/memoserv.cpp +++ b/modules/pseudoclients/memoserv.cpp @@ -16,8 +16,8 @@ static bool SendMemoMail(NickCore *nc, MemoInfo *mi, Memo *m) { - Anope::string subject = translate(nc, Config->MailMemoSubject.c_str()); - Anope::string message = translate(nc, Config->MailMemoMessage.c_str()); + Anope::string subject = Language::Translate(nc, Config->MailMemoSubject.c_str()); + Anope::string message = Language::Translate(nc, Config->MailMemoMessage.c_str()); subject = subject.replace_all_cs("%n", nc->display); subject = subject.replace_all_cs("%s", m->sender); @@ -29,7 +29,7 @@ static bool SendMemoMail(NickCore *nc, MemoInfo *mi, Memo *m) message = message.replace_all_cs("%d", mi->GetIndex(m)); message = message.replace_all_cs("%t", m->text); - return Mail(nc, subject, message); + return Mail::Send(nc, subject, message); } class MyMemoServService : public MemoServService @@ -42,14 +42,14 @@ class MyMemoServService : public MemoServService if (!target.empty() && target[0] == '#') { ischan = true; - ChannelInfo *ci = cs_findchan(target); + ChannelInfo *ci = ChannelInfo::Find(target); if (ci != NULL) return &ci->memos; } else { ischan = false; - NickAlias *na = findnick(target); + NickAlias *na = NickAlias::Find(target); if (na != NULL) return &na->nc->memos; } @@ -65,7 +65,7 @@ class MyMemoServService : public MemoServService if (mi == NULL) return MEMO_INVALID_TARGET; - User *sender = finduser(source); + User *sender = User::Find(source); if (sender != NULL && !sender->HasPriv("memoserv/no-limit") && !force) { if (Config->MSSendDelay > 0 && sender->lastmemosend + Config->MSSendDelay > Anope::CurTime) @@ -93,7 +93,7 @@ class MyMemoServService : public MemoServService if (ischan) { - ChannelInfo *ci = cs_findchan(target); + ChannelInfo *ci = ChannelInfo::Find(target); if (ci->c) { @@ -104,25 +104,25 @@ class MyMemoServService : public MemoServService if (ci->AccessFor(cu->user).HasPriv("MEMO")) { if (cu->user->Account() && cu->user->Account()->HasFlag(NI_MEMO_RECEIVE)) - cu->user->SendMessage(findbot(Config->MemoServ), MEMO_NEW_X_MEMO_ARRIVED, ci->name.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), ci->name.c_str(), mi->memos->size()); + cu->user->SendMessage(MemoServ, MEMO_NEW_X_MEMO_ARRIVED, ci->name.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), ci->name.c_str(), mi->memos->size()); } } } } else { - NickCore *nc = findnick(target)->nc; + NickCore *nc = NickAlias::Find(target)->nc; if (nc->HasFlag(NI_MEMO_RECEIVE)) { - for (std::list<serialize_obj<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = nc->aliases.begin(), it_end = nc->aliases.end(); it != it_end;) { const NickAlias *na = *it++; if (!na) continue; - User *user = finduser(na->nick); + User *user = User::Find(na->nick); if (user && user->IsIdentified()) - user->SendMessage(findbot(Config->MemoServ), MEMO_NEW_MEMO_ARRIVED, source.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), mi->memos->size()); + user->SendMessage(MemoServ, MEMO_NEW_MEMO_ARRIVED, source.c_str(), Config->UseStrictPrivMsgString.c_str(), Config->MemoServ.c_str(), mi->memos->size()); } } @@ -139,20 +139,19 @@ class MyMemoServService : public MemoServService const NickCore *nc = u->Account(); if (!nc) return; - const BotInfo *ms = findbot(Config->MemoServ); unsigned i = 0, end = nc->memos.memos->size(), newcnt = 0; for (; i < end; ++i) if (nc->memos.GetMemo(i)->HasFlag(MF_UNREAD)) ++newcnt; if (newcnt > 0) - u->SendMessage(ms, newcnt == 1 ? _("You have 1 new memo.") : _("You have %d new memos."), newcnt); + u->SendMessage(MemoServ, newcnt == 1 ? _("You have 1 new memo.") : _("You have %d new memos."), newcnt); if (nc->memos.memomax > 0 && nc->memos.memos->size() >= static_cast<unsigned>(nc->memos.memomax)) { if (nc->memos.memos->size() > static_cast<unsigned>(nc->memos.memomax)) - u->SendMessage(ms, _("You are over your maximum number of memos (%d). You will be unable to receive any new memos until you delete some of your current ones."), nc->memos.memomax); + u->SendMessage(MemoServ, _("You are over your maximum number of memos (%d). You will be unable to receive any new memos until you delete some of your current ones."), nc->memos.memomax); else - u->SendMessage(ms, _("You have reached your maximum number of memos (%d). You will be unable to receive any new memos until you delete some of your current ones."), nc->memos.memomax); + u->SendMessage(MemoServ, _("You have reached your maximum number of memos (%d). You will be unable to receive any new memos until you delete some of your current ones."), nc->memos.memomax); } } }; @@ -166,7 +165,8 @@ class MemoServCore : public Module { this->SetAuthor("Anope"); - if (!findbot(Config->MemoServ)) + MemoServ = BotInfo::Find(Config->MemoServ); + if (!MemoServ) throw ModuleException("No bot named " + Config->MemoServ); Implementation i[] = { I_OnNickIdentify, I_OnJoinChannel, I_OnUserAway, I_OnNickUpdate, I_OnPreHelp, I_OnPostHelp }; @@ -183,9 +183,9 @@ class MemoServCore : public Module if (c->ci && c->ci->AccessFor(u).HasPriv("MEMO") && c->ci->memos.memos->size() > 0) { if (c->ci->memos.memos->size() == 1) - u->SendMessage(findbot(Config->MemoServ), _("There is \002%d\002 memo on channel %s."), c->ci->memos.memos->size(), c->ci->name.c_str()); + u->SendMessage(MemoServ, _("There is \002%d\002 memo on channel %s."), c->ci->memos.memos->size(), c->ci->name.c_str()); else - u->SendMessage(findbot(Config->MemoServ), _("There are \002%d\002 memos on channel %s."), c->ci->memos.memos->size(), c->ci->name.c_str()); + u->SendMessage(MemoServ, _("There are \002%d\002 memos on channel %s."), c->ci->memos.memos->size(), c->ci->name.c_str()); } } diff --git a/modules/pseudoclients/memoserv.h b/modules/pseudoclients/memoserv.h index aae7d26b5..25d453ab0 100644 --- a/modules/pseudoclients/memoserv.h +++ b/modules/pseudoclients/memoserv.h @@ -35,7 +35,8 @@ class MemoServService : public Service virtual void Check(User *u) = 0; }; -static service_reference<MemoServService> memoserv("MemoServService", "MemoServ"); +static ServiceReference<MemoServService> MemoServService("MemoServService", "MemoServ"); +static Reference<BotInfo> MemoServ; #endif // MEMOSERV_H diff --git a/modules/pseudoclients/nickserv.cpp b/modules/pseudoclients/nickserv.cpp index 637003682..95044f610 100644 --- a/modules/pseudoclients/nickserv.cpp +++ b/modules/pseudoclients/nickserv.cpp @@ -15,23 +15,20 @@ #include "nickserv.h" class NickServCollide; -class NickServRelease; typedef std::map<Anope::string, NickServCollide *> nickservcollides_map; -typedef std::map<Anope::string, NickServRelease *> nickservreleases_map; static nickservcollides_map NickServCollides; -static nickservreleases_map NickServReleases; /** Timer for colliding nicks to force people off of nicknames */ class NickServCollide : public Timer { - dynamic_reference<User> u; + Reference<User> u; Anope::string nick; public: - /** Default constructor + /** Constructor * @param nick The nick we're colliding * @param delay How long to delay before kicking the user off the nick */ @@ -45,8 +42,6 @@ class NickServCollide : public Timer NickServCollides.insert(std::make_pair(nick, this)); } - /** Default destructor - */ virtual ~NickServCollide() { NickServCollides.erase(this->nick); @@ -60,7 +55,7 @@ class NickServCollide : public Timer if (!u) return; /* If they identified or don't exist anymore, don't kill them. */ - NickAlias *na = findnick(u->nick); + NickAlias *na = NickAlias::Find(u->nick); if (!na || u->Account() == na->nc || u->timestamp > this->GetSetTime()) return; @@ -75,10 +70,9 @@ class MyNickServService : public NickServService void Validate(User *u) anope_override { - NickAlias *na = findnick(u->nick); + NickAlias *na = NickAlias::Find(u->nick); if (!na) return; - const BotInfo *NickServ = findbot(Config->NickServ); if (na->nc->HasFlag(NI_SUSPENDED)) { @@ -124,12 +118,12 @@ class MyNickServService : public NickServService } else if (na->nc->HasFlag(NI_KILL_QUICK)) { - u->SendMessage(NickServ, _("If you do not change within %s, I will change your nick."), duration(Config->NSKillQuick, u->Account()).c_str()); + u->SendMessage(NickServ, _("If you do not change within %s, I will change your nick."), Anope::Duration(Config->NSKillQuick, u->Account()).c_str()); new NickServCollide(u, Config->NSKillQuick); } else { - u->SendMessage(NickServ, _("If you do not change within %s, I will change your nick."), duration(Config->NSKill, u->Account()).c_str()); + u->SendMessage(NickServ, _("If you do not change within %s, I will change your nick."), Anope::Duration(Config->NSKill, u->Account()).c_str()); new NickServCollide(u, Config->NSKill); } } @@ -144,7 +138,7 @@ class ExpireCallback : public CallBack void Tick(time_t) anope_override { - if (noexpire || readonly) + if (Anope::NoExpire || Anope::ReadOnly) return; for (nickalias_map::const_iterator it = NickAliasList->begin(), it_end = NickAliasList->end(); it != it_end; ) @@ -152,7 +146,7 @@ class ExpireCallback : public CallBack NickAlias *na = it->second; ++it; - User *u = finduser(na->nick); + User *u = User::Find(na->nick); if (u && (na->nc->HasFlag(NI_SECURE) ? u->IsIdentified(true) : u->IsRecognized())) na->last_seen = Anope::CurTime; @@ -175,7 +169,7 @@ class ExpireCallback : public CallBack extra = "suspended "; Log(LOG_NORMAL, "expire") << "Expiring " << extra << "nickname " << na->nick << " (group: " << na->nc->display << ") (e-mail: " << (na->nc->email.empty() ? "none" : na->nc->email) << ")"; FOREACH_MOD(I_OnNickExpire, OnNickExpire(na)); - na->destroy(); + na->Destroy(); } } } @@ -191,7 +185,8 @@ class NickServCore : public Module { this->SetAuthor("Anope"); - if (!findbot(Config->NickServ)) + NickServ = BotInfo::Find(Config->NickServ); + if (!NickServ) throw ModuleException("No bot named " + Config->NickServ); Implementation i[] = { I_OnDelNick, I_OnDelCore, I_OnChangeCoreDisplay, I_OnNickIdentify, I_OnNickGroup, @@ -201,45 +196,41 @@ class NickServCore : public Module void OnDelNick(NickAlias *na) anope_override { - User *u = finduser(na->nick); + User *u = User::Find(na->nick); if (u && u->Account() == na->nc) { - ircdproto->SendLogout(u); - u->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + IRCD->SendLogout(u); + u->RemoveMode(NickServ, UMODE_REGISTERED); u->Logout(); } } void OnDelCore(NickCore *nc) anope_override { - Log(findbot(Config->NickServ), "nick") << "deleting nickname group " << nc->display; + Log(NickServ, "nick") << "deleting nickname group " << nc->display; - /* Clean up this nick core from any users online using it - * (ones that /nick but remain unidentified) - */ - for (std::list<User *>::iterator it = nc->Users.begin(); it != nc->Users.end();) + /* Clean up this nick core from any users online */ + for (std::list<User *>::iterator it = nc->users.begin(); it != nc->users.end();) { User *user = *it++; - ircdproto->SendLogout(user); - user->RemoveMode(findbot(Config->NickServ), UMODE_REGISTERED); + IRCD->SendLogout(user); + user->RemoveMode(NickServ, UMODE_REGISTERED); user->Logout(); FOREACH_MOD(I_OnNickLogout, OnNickLogout(user)); } - nc->Users.clear(); + nc->users.clear(); } void OnChangeCoreDisplay(NickCore *nc, const Anope::string &newdisplay) anope_override { - Log(LOG_NORMAL, "nick", findbot(Config->NickServ)) << "Changing " << nc->display << " nickname group display to " << newdisplay; + Log(LOG_NORMAL, "nick", NickServ) << "Changing " << nc->display << " nickname group display to " << newdisplay; } void OnNickIdentify(User *u) anope_override { - const BotInfo *NickServ = findbot(Config->NickServ); - if (!Config->NoNicknameOwnership) { - const NickAlias *this_na = findnick(u->nick); + const NickAlias *this_na = NickAlias::Find(u->nick); if (this_na && this_na->nc == u->Account() && u->Account()->HasFlag(NI_UNCONFIRMED) == false) u->SetMode(NickServ, UMODE_REGISTERED); } @@ -250,7 +241,7 @@ class NickServCore : public Module ChannelContainer *cc = *it; Channel *c = cc->chan; if (c) - chan_set_correct_modes(u, c, 1, true); + c->SetCorrectModes(u, true, true); } if (!Config->NSModesOnID.empty()) @@ -269,17 +260,17 @@ class NickServCore : public Module if (u->Account()->HasFlag(NI_UNCONFIRMED)) { u->SendMessage(NickServ, _("Your email address is not confirmed. To confirm it, follow the instructions that were emailed to you when you registered.")); - const NickAlias *this_na = findnick(u->Account()->display); + const NickAlias *this_na = NickAlias::Find(u->Account()->display); time_t time_registered = Anope::CurTime - this_na->time_registered; if (Config->NSUnconfirmedExpire > time_registered) - u->SendMessage(NickServ, _("Your account will expire, if not confirmed, in %s"), duration(Config->NSUnconfirmedExpire - time_registered).c_str()); + u->SendMessage(NickServ, _("Your account will expire, if not confirmed, in %s"), Anope::Duration(Config->NSUnconfirmedExpire - time_registered).c_str()); } } void OnNickGroup(User *u, NickAlias *target) anope_override { if (target->nc->HasFlag(NI_UNCONFIRMED) == false) - u->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + u->SetMode(NickServ, UMODE_REGISTERED); } void OnNickUpdate(User *u) anope_override @@ -289,14 +280,13 @@ class NickServCore : public Module ChannelContainer *cc = *it; Channel *c = cc->chan; if (c) - chan_set_correct_modes(u, c, 1, false); + c->SetCorrectModes(u, true, true); } } void OnUserNickChange(User *u, const Anope::string &oldnick) anope_override { - const NickAlias *na = findnick(u->nick); - const BotInfo *NickServ = findbot(Config->NickServ); + const NickAlias *na = NickAlias::Find(u->nick); /* If the new nick isnt registerd or its registerd and not yours */ if (!na || na->nc != u->Account()) { @@ -308,7 +298,7 @@ class NickServCore : public Module else { /* Reset +r and re-send account (even though it really should be set at this point) */ - ircdproto->SendLogin(u); + IRCD->SendLogin(u); if (!Config->NoNicknameOwnership && na->nc == u->Account() && na->nc->HasFlag(NI_UNCONFIRMED) == false) u->SetMode(NickServ, UMODE_REGISTERED); Log(NickServ) << u->GetMask() << " automatically identified for group " << u->Account()->display; @@ -318,7 +308,7 @@ class NickServCore : public Module void OnUserModeSet(User *u, UserModeName Name) anope_override { if (Name == UMODE_REGISTERED && !u->IsIdentified()) - u->RemoveMode(findbot(Config->NickServ), Name); + u->RemoveMode(NickServ, Name); } EventReturn OnPreHelp(CommandSource &source, const std::vector<Anope::string> ¶ms) anope_override @@ -357,10 +347,10 @@ class NickServCore : public Module "nickname(s)."), Config->NickServ.c_str()); } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { - if (!Config->NoNicknameOwnership && !Config->NSUnregisteredNotice.empty() && u && !findnick(u->nick)) - u->SendMessage(findbot(Config->NickServ), Config->NSUnregisteredNotice); + if (!Config->NoNicknameOwnership && !Config->NSUnregisteredNotice.empty() && u && !NickAlias::Find(u->nick)) + u->SendMessage(NickServ, Config->NSUnregisteredNotice); } }; diff --git a/modules/pseudoclients/nickserv.h b/modules/pseudoclients/nickserv.h index 750b77784..52934fe96 100644 --- a/modules/pseudoclients/nickserv.h +++ b/modules/pseudoclients/nickserv.h @@ -9,7 +9,8 @@ class NickServService : public Service virtual void Validate(User *u) = 0; }; -static service_reference<NickServService> nickserv("NickServService", "NickServ"); +static ServiceReference<NickServService> NickServService("NickServService", "NickServ"); +static Reference<BotInfo> NickServ; #endif // NICKSERV_H diff --git a/modules/pseudoclients/operserv.cpp b/modules/pseudoclients/operserv.cpp index cc051d685..8ee8c211b 100644 --- a/modules/pseudoclients/operserv.cpp +++ b/modules/pseudoclients/operserv.cpp @@ -25,28 +25,28 @@ class SGLineManager : public XLineManager void OnExpire(const XLine *x) anope_override { - Log(findbot(Config->OperServ), "expire/akill") << "AKILL on \2" << x->Mask << "\2 has expired"; + Log(OperServ, "expire/akill") << "AKILL on \2" << x->mask << "\2 has expired"; } void Send(User *u, XLine *x) anope_override { - ircdproto->SendAkill(u, x); + IRCD->SendAkill(u, x); } void SendDel(XLine *x) anope_override { try { - if (!ircdproto->CanSZLine) + if (!IRCD->CanSZLine) throw SocketException("SZLine is not supported"); else if (x->GetUser() != "*") throw SocketException("Can not ZLine a username"); sockaddrs(x->GetHost()); - ircdproto->SendSZLineDel(x); + IRCD->SendSZLineDel(x); } catch (const SocketException &) { - ircdproto->SendAkillDel(x); + IRCD->SendAkillDel(x); } } @@ -101,30 +101,30 @@ class SQLineManager : public XLineManager void OnExpire(const XLine *x) anope_override { - Log(findbot(Config->OperServ), "expire/sqline") << "SQLINE on \2" << x->Mask << "\2 has expired"; + Log(OperServ, "expire/sqline") << "SQLINE on \2" << x->mask << "\2 has expired"; } void Send(User *u, XLine *x) anope_override { - ircdproto->SendSQLine(u, x); + IRCD->SendSQLine(u, x); } void SendDel(XLine *x) anope_override { - ircdproto->SendSQLineDel(x); + IRCD->SendSQLineDel(x); } bool Check(User *u, const XLine *x) anope_override { if (x->regex) return x->regex->Matches(u->nick); - return Anope::Match(u->nick, x->Mask); + return Anope::Match(u->nick, x->mask); } bool CheckChannel(Channel *c) { for (std::vector<XLine *>::const_iterator it = this->GetList().begin(), it_end = this->GetList().end(); it != it_end; ++it) - if (Anope::Match(c->name, (*it)->Mask, false, true)) + if (Anope::Match(c->name, (*it)->mask, false, true)) return true; return false; } @@ -142,24 +142,24 @@ class SNLineManager : public XLineManager void OnExpire(const XLine *x) anope_override { - Log(findbot(Config->OperServ), "expire/snline") << "SNLINE on \2" << x->Mask << "\2 has expired"; + Log(OperServ, "expire/snline") << "SNLINE on \2" << x->mask << "\2 has expired"; } void Send(User *u, XLine *x) anope_override { - ircdproto->SendSGLine(u, x); + IRCD->SendSGLine(u, x); } void SendDel(XLine *x) anope_override { - ircdproto->SendSGLineDel(x); + IRCD->SendSGLineDel(x); } bool Check(User *u, const XLine *x) anope_override { if (x->regex) return x->regex->Matches(u->realname); - return Anope::Match(u->realname, x->Mask, false, true); + return Anope::Match(u->realname, x->mask, false, true); } }; @@ -175,7 +175,8 @@ class OperServCore : public Module { this->SetAuthor("Anope"); - if (!findbot(Config->OperServ)) + OperServ = BotInfo::Find(Config->OperServ); + if (!OperServ) throw ModuleException("No bot named " + Config->OperServ); Implementation i[] = { I_OnBotPrivmsg, I_OnServerQuit, I_OnUserModeSet, I_OnUserModeUnset, I_OnUserConnect, I_OnUserNickChange, I_OnPreHelp }; @@ -203,7 +204,7 @@ class OperServCore : public Module if (Config->OSOpersOnly && !u->HasMode(UMODE_OPER) && bi->nick == Config->OperServ) { u->SendMessage(bi, ACCESS_DENIED); - Log(findbot(Config->OperServ), "bados") << "Denied access to " << Config->OperServ << " from " << u->GetMask() << " (non-oper)"; + Log(OperServ, "bados") << "Denied access to " << Config->OperServ << " from " << u->GetMask() << " (non-oper)"; return EVENT_STOP; } @@ -213,22 +214,22 @@ class OperServCore : public Module void OnServerQuit(Server *server) anope_override { if (server->HasFlag(SERVER_JUPED)) - Log(server, "squit", findbot(Config->OperServ)) << "Received SQUIT for juped server " << server->GetName(); + Log(server, "squit", OperServ) << "Received SQUIT for juped server " << server->GetName(); } void OnUserModeSet(User *u, UserModeName Name) anope_override { if (Name == UMODE_OPER) - Log(u, "oper", findbot(Config->OperServ)) << "is now an IRC operator."; + Log(u, "oper", OperServ) << "is now an IRC operator."; } void OnUserModeUnset(User *u, UserModeName Name) anope_override { if (Name == UMODE_OPER) - Log(u, "oper", findbot(Config->OperServ)) << "is no longer an IRC operator"; + Log(u, "oper", OperServ) << "is no longer an IRC operator"; } - void OnUserConnect(dynamic_reference<User> &u, bool &exempt) anope_override + void OnUserConnect(Reference<User> &u, bool &exempt) anope_override { if (u && !exempt) XLineManager::CheckAll(u); @@ -236,7 +237,7 @@ class OperServCore : public Module void OnUserNickChange(User *u, const Anope::string &oldnick) anope_override { - if (ircdproto->CanSQLine && !u->HasMode(UMODE_OPER)) + if (IRCD->CanSQLine && !u->HasMode(UMODE_OPER)) this->sqlines.CheckAllXLines(u); } diff --git a/modules/pseudoclients/operserv.h b/modules/pseudoclients/operserv.h new file mode 100644 index 000000000..dd9dafc76 --- /dev/null +++ b/modules/pseudoclients/operserv.h @@ -0,0 +1,6 @@ +#ifndef OPERSERV_H +#define OPERSERV_H + +static Reference<BotInfo> OperServ; + +#endif // OPERSERV_H diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f1f383397..b9d58f367 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -119,7 +119,6 @@ add_to_cpack_ignored_files("${SERVICES_BINARY}$" TRUE) configure_file(${Anope_SOURCE_DIR}/include/sysconf.h.cmake ${Anope_BINARY_DIR}/include/sysconf.h) # Go into the following directories and run their CMakeLists.txt as well -add_subdirectory(bin) add_subdirectory(tools) # Set Anope to be installed to the bin directory diff --git a/src/access.cpp b/src/access.cpp index 6b22ba871..863e0d41d 100644 --- a/src/access.cpp +++ b/src/access.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "service.h" @@ -24,27 +25,27 @@ bool Privilege::operator==(const Privilege &other) const return this->name == other.name; } -std::vector<Privilege> PrivilegeManager::privs; +std::vector<Privilege> PrivilegeManager::Privileges; void PrivilegeManager::AddPrivilege(Privilege p) { unsigned i; - for (i = 0; i < privs.size(); ++i) + for (i = 0; i < Privileges.size(); ++i) { - Privilege &priv = privs[i]; + Privilege &priv = Privileges[i]; if (priv.rank > p.rank) break; } - privs.insert(privs.begin() + i, p); + Privileges.insert(Privileges.begin() + i, p); } void PrivilegeManager::RemovePrivilege(Privilege &p) { - std::vector<Privilege>::iterator it = std::find(privs.begin(), privs.end(), p); - if (it != privs.end()) - privs.erase(it); + std::vector<Privilege>::iterator it = std::find(Privileges.begin(), Privileges.end(), p); + if (it != Privileges.end()) + Privileges.erase(it); for (registered_channel_map::const_iterator cit = RegisteredChannelList->begin(), cit_end = RegisteredChannelList->end(); cit != cit_end; ++cit) { @@ -55,39 +56,39 @@ void PrivilegeManager::RemovePrivilege(Privilege &p) Privilege *PrivilegeManager::FindPrivilege(const Anope::string &name) { - for (unsigned i = privs.size(); i > 0; --i) - if (privs[i - 1].name.equals_ci(name)) - return &privs[i - 1]; + for (unsigned i = Privileges.size(); i > 0; --i) + if (Privileges[i - 1].name.equals_ci(name)) + return &Privileges[i - 1]; return NULL; } std::vector<Privilege> &PrivilegeManager::GetPrivileges() { - return privs; + return Privileges; } void PrivilegeManager::ClearPrivileges() { - privs.clear(); + Privileges.clear(); } AccessProvider::AccessProvider(Module *o, const Anope::string &n) : Service(o, "AccessProvider", n) { - providers.push_back(this); + Providers.push_back(this); } AccessProvider::~AccessProvider() { - std::list<AccessProvider *>::iterator it = std::find(providers.begin(), providers.end(), this); - if (it != providers.end()) - providers.erase(it); + std::list<AccessProvider *>::iterator it = std::find(Providers.begin(), Providers.end(), this); + if (it != Providers.end()) + Providers.erase(it); } -std::list<AccessProvider *> AccessProvider::providers; +std::list<AccessProvider *> AccessProvider::Providers; const std::list<AccessProvider *>& AccessProvider::GetProviders() { - return providers; + return Providers; } ChanAccess::ChanAccess(AccessProvider *p) : Serializable("ChanAccess"), provider(p) @@ -98,7 +99,7 @@ ChanAccess::~ChanAccess() { } -Serialize::Data ChanAccess::serialize() const +Serialize::Data ChanAccess::Serialize() const { Serialize::Data data; @@ -106,17 +107,17 @@ Serialize::Data ChanAccess::serialize() const data["ci"] << this->ci->name; data["mask"] << this->mask; data["creator"] << this->creator; - data["last_seen"].setType(Serialize::DT_INT) << this->last_seen; - data["created"].setType(Serialize::DT_INT) << this->created; - data["data"] << this->Serialize(); + data["last_seen"].SetType(Serialize::DT_INT) << this->last_seen; + data["created"].SetType(Serialize::DT_INT) << this->created; + data["data"] << this->AccessSerialize(); return data; } -Serializable* ChanAccess::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* ChanAccess::Unserialize(Serializable *obj, Serialize::Data &data) { - service_reference<AccessProvider> aprovider("AccessProvider", data["provider"].astr()); - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ServiceReference<AccessProvider> aprovider("AccessProvider", data["provider"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (!aprovider || !ci) return NULL; @@ -130,7 +131,7 @@ Serializable* ChanAccess::unserialize(Serializable *obj, Serialize::Data &data) data["creator"] >> access->creator; data["last_seen"] >> access->last_seen; data["created"] >> access->created; - access->Unserialize(data["data"].astr()); + access->AccessUnserialize(data["data"].astr()); if (!obj) ci->AddAccess(access); @@ -145,7 +146,7 @@ bool ChanAccess::Matches(const User *u, const NickCore *nc) const else if (u && Anope::Match(u->GetDisplayedMask(), this->mask)) return true; else if (nc) - for (std::list<serialize_obj<NickAlias> >::const_iterator it = nc->aliases.begin(); it != nc->aliases.end();) + for (std::list<Serialize::Reference<NickAlias> >::const_iterator it = nc->aliases.begin(); it != nc->aliases.end();) { const NickAlias *na = *it++; if (na && Anope::Match(na->nick, this->mask)) @@ -234,16 +235,16 @@ AccessGroup::AccessGroup() : std::vector<ChanAccess *>() { this->ci = NULL; this->nc = NULL; - this->SuperAdmin = this->Founder = false; + this->super_admin = this->founder = false; } bool AccessGroup::HasPriv(const Anope::string &name) const { - if (this->SuperAdmin) + if (this->super_admin) return true; else if (ci->GetLevel(name) == ACCESS_INVALID) return false; - else if (this->Founder) + else if (this->founder) return true; EventReturn MOD_RESULT; FOREACH_RESULT(I_OnGroupCheckPriv, OnGroupCheckPriv(this, name)); @@ -271,13 +272,13 @@ const ChanAccess *AccessGroup::Highest() const bool AccessGroup::operator>(const AccessGroup &other) const { - if (this->SuperAdmin) + if (this->super_admin) return true; - else if (other.SuperAdmin) + else if (other.super_admin) return false; - else if (this->Founder && !other.Founder) + else if (this->founder && !other.founder) return true; - else if (!this->Founder && other.Founder) + else if (!this->founder && other.founder) return false; const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); for (unsigned i = privs.size(); i > 0; --i) @@ -298,13 +299,13 @@ bool AccessGroup::operator>(const AccessGroup &other) const bool AccessGroup::operator<(const AccessGroup &other) const { - if (other.SuperAdmin) + if (other.super_admin) return true; - else if (this->SuperAdmin) + else if (this->super_admin) return false; - else if (other.Founder && !this->Founder) + else if (other.founder && !this->founder) return true; - else if (this->Founder && !other.Founder) + else if (this->founder && !other.founder) return false; const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); for (unsigned i = privs.size(); i > 0; --i) @@ -325,13 +326,13 @@ bool AccessGroup::operator<(const AccessGroup &other) const bool AccessGroup::operator>=(const AccessGroup &other) const { - if (this->SuperAdmin) + if (this->super_admin) return true; - else if (other.SuperAdmin) + else if (other.super_admin) return false; - else if (this->Founder) + else if (this->founder) return true; - else if (other.Founder) + else if (other.founder) return false; const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); for (unsigned i = privs.size(); i > 0; --i) @@ -352,13 +353,13 @@ bool AccessGroup::operator>=(const AccessGroup &other) const bool AccessGroup::operator<=(const AccessGroup &other) const { - if (other.SuperAdmin) + if (other.super_admin) return true; - else if (this->SuperAdmin) + else if (this->super_admin) return false; - else if (other.Founder) + else if (other.founder) return true; - else if (this->Founder) + else if (this->founder) return false; const std::vector<Privilege> &privs = PrivilegeManager::GetPrivileges(); for (unsigned i = privs.size(); i > 0; --i) diff --git a/src/account.cpp b/src/account.cpp new file mode 100644 index 000000000..b7dd5b51b --- /dev/null +++ b/src/account.cpp @@ -0,0 +1,80 @@ +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + +#include "services.h" +#include "account.h" +#include "modules.h" +#include "users.h" +#include "protocol.h" +#include "regchannel.h" + +std::set<IdentifyRequest *> IdentifyRequest::Requests; + +IdentifyRequest::IdentifyRequest(Module *o, const Anope::string &acc, const Anope::string &pass) : owner(o), account(acc), password(pass), dispatched(false), success(false) +{ + Requests.insert(this); +} + +IdentifyRequest::~IdentifyRequest() +{ + Requests.erase(this); +} + +void IdentifyRequest::Hold(Module *m) +{ + holds.insert(m); +} + +void IdentifyRequest::Release(Module *m) +{ + holds.erase(m); + if (holds.empty() && dispatched) + { + if (!success) + this->OnFail(); + delete this; + } +} + +void IdentifyRequest::Success(Module *m) +{ + if (!success) + { + this->OnSuccess(); + success = true; + } +} + +void IdentifyRequest::Dispatch() +{ + if (holds.empty()) + { + if (!success) + this->OnFail(); + delete this; + } + else + dispatched = true; +} + +void IdentifyRequest::ModuleUnload(Module *m) +{ + for (std::set<IdentifyRequest *>::iterator it = Requests.begin(), it_end = Requests.end(); it != it_end;) + { + IdentifyRequest *ir = *it; + ++it; + + ir->Release(m); + if (ir->owner == m) + delete ir; + } +} diff --git a/src/actions.cpp b/src/actions.cpp deleted file mode 100644 index 512a0fa52..000000000 --- a/src/actions.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* Various routines to perform simple actions. - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -#include "services.h" -#include "users.h" -#include "config.h" -#include "regchannel.h" -#include "channels.h" -#include "extern.h" - -/*************************************************************************/ - -/** - * Note a bad password attempt for the given user. If they've used up - * their limit, toss them off. - * @param u the User to check - * @return true if the user was killed, otherwise false - */ -bool bad_password(User *u) -{ - if (!u || !Config->BadPassLimit) - return false; - - if (Config->BadPassTimeout > 0 && u->invalid_pw_time > 0 && u->invalid_pw_time < Anope::CurTime - Config->BadPassTimeout) - u->invalid_pw_count = 0; - ++u->invalid_pw_count; - u->invalid_pw_time = Anope::CurTime; - if (u->invalid_pw_count >= Config->BadPassLimit) - { - u->Kill(Config->ServerName, "Too many invalid passwords"); - return true; - } - - return false; -} - -/*************************************************************************/ - - -/** - * Unban the user from a channel - * @param ci channel info for the channel - * @param u The user to unban - * @param full True to match against the users real host and IP - * @return void - */ -void common_unban(const ChannelInfo *ci, User *u, bool full) -{ - if (!u || !ci || !ci->c || !ci->c->HasMode(CMODE_BAN)) - return; - - std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> bans = ci->c->GetModeList(CMODE_BAN); - for (; bans.first != bans.second;) - { - Entry ban(CMODE_BAN, bans.first->second); - ++bans.first; - if (ban.Matches(u, full)) - ci->c->RemoveMode(NULL, CMODE_BAN, ban.GetMask()); - } -} - -/*************************************************************************/ diff --git a/src/base.cpp b/src/base.cpp index af2b38fde..5b8d828b6 100644 --- a/src/base.cpp +++ b/src/base.cpp @@ -1,20 +1,18 @@ -#include "services.h" -#include "modules.h" -#include "oper.h" -#include "account.h" -#include "regchannel.h" -#include "access.h" -#include "bots.h" +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + */ -std::map<Anope::string, std::map<Anope::string, Service *> > Service::services; +#include "services.h" +#include "anope.h" +#include "service.h" -void RegisterTypes() -{ - static SerializeType nc("NickCore", NickCore::unserialize), na("NickAlias", NickAlias::unserialize), bi("BotInfo", BotInfo::unserialize), - ci("ChannelInfo", ChannelInfo::unserialize), access("ChanAccess", ChanAccess::unserialize), logsetting("LogSetting", LogSetting::unserialize), - modelock("ModeLock", ModeLock::unserialize), akick("AutoKick", AutoKick::unserialize), badword("BadWord", BadWord::unserialize), - memo("Memo", Memo::unserialize), xline("XLine", XLine::unserialize); -} +std::map<Anope::string, std::map<Anope::string, Service *> > Service::Services; +std::map<Anope::string, std::map<Anope::string, Anope::string> > Service::Aliases; Base::Base() { @@ -22,19 +20,19 @@ Base::Base() Base::~Base() { - for (std::set<dynamic_reference_base *>::iterator it = this->References.begin(), it_end = this->References.end(); it != it_end; ++it) + for (std::set<ReferenceBase *>::iterator it = this->references.begin(), it_end = this->references.end(); it != it_end; ++it) { (*it)->Invalidate(); } } -void Base::AddReference(dynamic_reference_base *r) +void Base::AddReference(ReferenceBase *r) { - this->References.insert(r); + this->references.insert(r); } -void Base::DelReference(dynamic_reference_base *r) +void Base::DelReference(ReferenceBase *r) { - this->References.erase(r); + this->references.erase(r); } diff --git a/src/base64.cpp b/src/base64.cpp index df4189547..ae026d8ef 100644 --- a/src/base64.cpp +++ b/src/base64.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" diff --git a/src/bin/CMakeLists.txt b/src/bin/CMakeLists.txt deleted file mode 100644 index d1cdb5d06..000000000 --- a/src/bin/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -# If not on Windows, generate anoperc and install it along with mydbgen -if(NOT WIN32) - configure_file(${Anope_SOURCE_DIR}/src/bin/anoperc.in ${Anope_BINARY_DIR}/src/bin/anoperc) - install (PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/anoperc - DESTINATION ${BIN_DIR} - ) - -endif(NOT WIN32) diff --git a/src/bots.cpp b/src/bots.cpp index 7bb5ace5d..52753148f 100644 --- a/src/bots.cpp +++ b/src/bots.cpp @@ -1,8 +1,10 @@ /* + * * Copyright (C) 2008-2011 Robin Burchell <w00t@inspircd.org> * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #include "services.h" @@ -10,17 +12,27 @@ #include "bots.h" #include "servers.h" #include "protocol.h" -#include "oper.h" +#include "xline.h" #include "regchannel.h" #include "channels.h" #include "config.h" #include "language.h" -#include "extern.h" #include "serialize.h" -serialize_checker<botinfo_map> BotListByNick("BotInfo"), BotListByUID("BotInfo"); +Serialize::Checker<botinfo_map> BotListByNick("BotInfo"), BotListByUID("BotInfo"); + +static const Anope::string BotFlagString[] = { "BEGIN", "CORE", "PRIVATE", "CONF", "" }; +template<> const Anope::string* Flags<BotFlag>::flags_strings = BotFlagString; + +static const Anope::string BotServFlagStrings[] = { + "BEGIN", "DONTKICKOPS", "DONTKICKVOICES", "FANTASY", "GREET", "NOBOT", + "KICK_BOLDs", "KICK_COLORS", "KICK_REVERSES", "KICK_UNDERLINES", "KICK_BADWORDS", "KICK_CAPS", + "KICK_FLOOD", "KICK_REPEAT", "KICK_ITALICS", "KICK_AMSGS", "MSG_PRIVMSG", "MSG_NOTICE", + "MSG_NOTICEOPS", "" +}; +template<> const Anope::string* Flags<BotServFlag>::flags_strings = BotServFlagStrings; -BotInfo::BotInfo(const Anope::string &nnick, const Anope::string &nuser, const Anope::string &nhost, const Anope::string &nreal, const Anope::string &bmodes) : User(nnick, nuser, nhost, "", "", Me, nreal, Anope::CurTime, "", ts6_uid_retrieve()), Flags<BotFlag, BI_END>(BotFlagString), Serializable("BotInfo"), botmodes(bmodes) +BotInfo::BotInfo(const Anope::string &nnick, const Anope::string &nuser, const Anope::string &nhost, const Anope::string &nreal, const Anope::string &bmodes) : User(nnick, nuser, nhost, "", "", Me, nreal, Anope::CurTime, "", Servers::TS6_UID_Retrieve()), Serializable("BotInfo"), botmodes(bmodes) { this->lastmsg = this->created = Anope::CurTime; this->introduced = false; @@ -32,13 +44,13 @@ BotInfo::BotInfo(const Anope::string &nnick, const Anope::string &nuser, const A // If we're synchronised with the uplink already, send the bot. if (Me && Me->IsSynced()) { - Anope::string tmodes = !this->botmodes.empty() ? ("+" + this->botmodes) : (ircdproto ? ircdproto->DefaultPseudoclientModes : ""); + Anope::string tmodes = !this->botmodes.empty() ? ("+" + this->botmodes) : (IRCD ? IRCD->DefaultPseudoclientModes : ""); if (!tmodes.empty()) this->SetModesInternal(tmodes.c_str()); XLine x(this->nick, "Reserved for services"); - ircdproto->SendSQLine(NULL, &x); - ircdproto->SendClientIntroduction(this); + IRCD->SendSQLine(NULL, &x); + IRCD->SendClientIntroduction(this); this->introduced = true; } } @@ -48,10 +60,10 @@ BotInfo::~BotInfo() // If we're synchronised with the uplink already, send the bot. if (Me && Me->IsSynced()) { - ircdproto->SendQuit(this, ""); + IRCD->SendQuit(this, ""); this->introduced = false; XLine x(this->nick); - ircdproto->SendSQLineDel(&x); + IRCD->SendSQLineDel(&x); } for (registered_channel_map::const_iterator it = RegisteredChannelList->begin(), it_end = RegisteredChannelList->end(); it != it_end; ++it) @@ -70,11 +82,11 @@ BotInfo::~BotInfo() BotListByUID->erase(this->uid); } -Serialize::Data BotInfo::serialize() const +Serialize::Data BotInfo::Serialize() const { Serialize::Data data; - data["nick"].setMax(64) << this->nick; + data["nick"].SetMax(64)/*XXX*/ << this->nick; data["user"] << this->ident; data["host"] << this->host; data["realname"] << this->realname; @@ -84,12 +96,12 @@ Serialize::Data BotInfo::serialize() const return data; } -Serializable* BotInfo::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* BotInfo::Unserialize(Serializable *obj, Serialize::Data &data) { BotInfo *bi; if (obj) bi = anope_dynamic_static_cast<BotInfo *>(obj); - else if (!(bi = findbot(data["nick"].astr()))) + else if (!(bi = BotInfo::Find(data["nick"].astr()))) bi = new BotInfo(data["nick"].astr(), data["user"].astr(), data["host"].astr(), data["realname"].astr()); data["created"] >> bi->created; bi->FromString(data["flags"].astr()); @@ -100,7 +112,7 @@ void BotInfo::GenerateUID() { if (!this->uid.empty()) throw CoreException("Bot already has a uid?"); - this->uid = ts6_uid_retrieve(); + this->uid = Servers::TS6_UID_Retrieve(); (*BotListByUID)[this->uid] = this; UserListByUID[this->uid] = this; } @@ -139,7 +151,7 @@ void BotInfo::Assign(User *u, ChannelInfo *ci) ci->bi = this; if (ci->c && ci->c->users.size() >= Config->BSMinUsers) - this->Join(ci->c, &Config->BotModeList); + this->Join(ci->c, &ModeManager::DefaultBotModes); } void BotInfo::UnAssign(User *u, ChannelInfo *ci) @@ -178,7 +190,7 @@ void BotInfo::Join(Channel *c, ChannelStatus *status) if (c->FindUser(this) != NULL) return; - if (Config && ircdproto && Config->BSSmartJoin) + if (Config && IRCD && Config->BSSmartJoin) { std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> bans = c->GetModeList(CMODE_BAN); @@ -197,21 +209,21 @@ void BotInfo::Join(Channel *c, ChannelStatus *status) /* Should we be invited? */ if (c->HasMode(CMODE_INVITE) || (limit && c->users.size() >= limit)) - ircdproto->SendNotice(this, "@" + c->name, "%s invited %s into the channel.", this->nick.c_str(), this->nick.c_str()); + IRCD->SendNotice(this, "@" + c->name, "%s invited %s into the channel.", this->nick.c_str(), this->nick.c_str()); ModeManager::ProcessModes(); } c->JoinUser(this); - if (ircdproto) - ircdproto->SendJoin(this, c, status); + if (IRCD) + IRCD->SendJoin(this, c, status); FOREACH_MOD(I_OnBotJoin, OnBotJoin(c, this)); } void BotInfo::Join(const Anope::string &chname, ChannelStatus *status) { - Channel *c = findchan(chname); + Channel *c = Channel::Find(chname); return this->Join(c ? c : new Channel(chname), status); } @@ -220,7 +232,7 @@ void BotInfo::Part(Channel *c, const Anope::string &reason) if (c->FindUser(this) == NULL) return; - ircdproto->SendPart(this, c, "%s", !reason.empty() ? reason.c_str() : ""); + IRCD->SendPart(this, c, "%s", !reason.empty() ? reason.c_str() : ""); c->DeleteUser(this); } @@ -233,11 +245,6 @@ void BotInfo::OnMessage(User *u, const Anope::string &message) RunCommand(source, message); } -/** Link a command name to a command in services - * @param cname The command name - * @param sname The service name - * @param permission Permission required to execute the command, if any - */ void BotInfo::SetCommand(const Anope::string &cname, const Anope::string &sname, const Anope::string &permission) { CommandInfo ci; @@ -246,10 +253,6 @@ void BotInfo::SetCommand(const Anope::string &cname, const Anope::string &sname, this->commands[cname] = ci; } -/** Get command info for a command - * @param cname The command name - * @return A struct containing service name and permission - */ CommandInfo *BotInfo::GetCommand(const Anope::string &cname) { CommandInfo::map::iterator it = this->commands.find(cname); @@ -258,3 +261,24 @@ CommandInfo *BotInfo::GetCommand(const Anope::string &cname) return NULL; } +BotInfo* BotInfo::Find(const Anope::string &nick, bool nick_only) +{ + BotInfo *bi = NULL; + if (!nick_only && isdigit(nick[0]) && IRCD->RequiresID) + { + botinfo_map::iterator it = BotListByUID->find(nick); + if (it != BotListByUID->end()) + bi = it->second; + } + else + { + botinfo_map::iterator it = BotListByNick->find(nick); + if (it != BotListByNick->end()) + bi = it->second; + } + + if (bi) + bi->QueueUpdate(); + return bi; +} + diff --git a/src/botserv.cpp b/src/botserv.cpp deleted file mode 100644 index 04949b427..000000000 --- a/src/botserv.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* BotServ functions - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -/*************************************************************************/ - -#include "services.h" -#include "anope.h" -#include "protocol.h" -#include "bots.h" -#include "regchannel.h" -#include "language.h" -#include "extern.h" -#include "access.h" -#include "channels.h" -#include "account.h" - -BotInfo* findbot(const Anope::string &nick) -{ - BotInfo *bi = NULL; - if (isdigit(nick[0]) && ircdproto->RequiresID) - { - botinfo_map::iterator it = BotListByUID->find(nick); - if (it != BotListByUID->end()) - bi = it->second; - } - else - { - botinfo_map::iterator it = BotListByNick->find(nick); - if (it != BotListByNick->end()) - bi = it->second; - } - - if (bi) - bi->QueueUpdate(); - return bi; -} - - -/*************************************************************************/ - -/* Makes a simple ban and kicks the target - * @param requester The user requesting the kickban - * @param ci The channel - * @param u The user being kicked - * @param reason The reason - */ -void bot_raw_ban(User *requester, ChannelInfo *ci, User *u, const Anope::string &reason) -{ - if (!u || !ci) - return; - - if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u) - { - ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", translate(requester, ACCESS_DENIED)); - return; - } - - AccessGroup u_access = ci->AccessFor(u), req_access = ci->AccessFor(requester); - if (ci->HasFlag(CI_PEACE) && u != requester && u_access >= req_access) - return; - - if (matches_list(ci->c, u, CMODE_EXCEPT)) - { - ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", translate(requester, _("User matches channel except."))); - return; - } - - Anope::string mask; - get_idealban(ci, u, mask); - - ci->c->SetMode(NULL, CMODE_BAN, mask); - - /* Check if we need to do a signkick or not -GD */ - if (ci->HasFlag(CI_SIGNKICK) || (ci->HasFlag(CI_SIGNKICK_LEVEL) && !req_access.HasPriv("SIGNKICK"))) - ci->c->Kick(ci->bi, u, "%s (%s)", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str(), requester->nick.c_str()); - else - ci->c->Kick(ci->bi, u, "%s", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str()); -} - -/*************************************************************************/ - -/* Makes a kick with a "dynamic" reason ;) - * @param requester The user requesting the kick - * @param ci The channel - * @param u The user being kicked - * @param reason The reason for the kick - */ -void bot_raw_kick(User *requester, ChannelInfo *ci, User *u, const Anope::string &reason) -{ - if (!u || !ci || !ci->c || !ci->c->FindUser(u)) - return; - - if (ModeManager::FindUserModeByName(UMODE_PROTECTED) && u->IsProtected() && requester != u) - { - ircdproto->SendPrivmsg(ci->bi, ci->name, "%s", translate(requester, ACCESS_DENIED)); - return; - } - - AccessGroup u_access = ci->AccessFor(u), req_access = ci->AccessFor(requester); - if (ci->HasFlag(CI_PEACE) && requester != u && u_access >= req_access) - return; - - if (ci->HasFlag(CI_SIGNKICK) || (ci->HasFlag(CI_SIGNKICK_LEVEL) && !req_access.HasPriv("SIGNKICK"))) - ci->c->Kick(ci->bi, u, "%s (%s)", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str(), requester->nick.c_str()); - else - ci->c->Kick(ci->bi, u, "%s", !reason.empty() ? reason.c_str() : ci->bi->nick.c_str()); -} - diff --git a/src/channels.cpp b/src/channels.cpp index 501dd7146..41755b9c8 100644 --- a/src/channels.cpp +++ b/src/channels.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -21,16 +22,15 @@ #include "users.h" #include "config.h" #include "access.h" -#include "extern.h" #include "sockets.h" +#include "chanserv.h" channel_map ChannelList; -/** Default constructor - * @param name The channel name - * @param ts The time the channel was created - */ -Channel::Channel(const Anope::string &nname, time_t ts) : Flags<ChannelFlag, 3>(ChannelFlagString) +static const Anope::string ChannelFlagString[] = { "CH_INABIT", "CH_PERSIST", "CH_SYNCING", "" }; +template<> const Anope::string* Flags<ChannelFlag>::flags_strings = ChannelFlagString; + +Channel::Channel(const Anope::string &nname, time_t ts) { if (nname.empty()) throw CoreException("A channel without a name ?"); @@ -46,7 +46,7 @@ Channel::Channel(const Anope::string &nname, time_t ts) : Flags<ChannelFlag, 3>( this->server_modetime = this->chanserv_modetime = 0; this->server_modecount = this->chanserv_modecount = this->bouncy_modes = this->topic_ts = this->topic_time = 0; - this->ci = cs_findchan(this->name); + this->ci = ChannelInfo::Find(this->name); if (this->ci) this->ci->c = this; @@ -55,8 +55,6 @@ Channel::Channel(const Anope::string &nname, time_t ts) : Flags<ChannelFlag, 3>( FOREACH_MOD(I_OnChannelCreate, OnChannelCreate(this)); } -/** Default destructor - */ Channel::~Channel() { FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this)); @@ -79,16 +77,16 @@ void Channel::Reset() { UserContainer *uc = *it; - ChannelStatus flags = *uc->Status; - uc->Status->ClearFlags(); + ChannelStatus flags = *uc->status; + uc->status->ClearFlags(); - if (findbot(uc->user->nick)) + if (BotInfo::Find(uc->user->nick)) { for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (flags.HasFlag(cm->Name)) + if (flags.HasFlag(cm->name)) this->SetMode(NULL, cm, uc->user->GetUID(), false); } } @@ -97,7 +95,7 @@ void Channel::Reset() this->CheckModes(); for (CUserList::const_iterator it = this->users.begin(), it_end = this->users.end(); it != it_end; ++it) - chan_set_correct_modes((*it)->user, this, 1, false); + this->SetCorrectModes((*it)->user, true, false); if (this->ci && Me && Me->IsSynced()) this->ci->RestoreTopic(); @@ -151,32 +149,32 @@ void Channel::CheckModes() if (!cm) continue; - if (cm->Type == MODE_REGULAR) + if (cm->type == MODE_REGULAR) { - if (!this->HasMode(cm->Name) && ml->set) + if (!this->HasMode(cm->name) && ml->set) this->SetMode(NULL, cm); - else if (this->HasMode(cm->Name) && !ml->set) + else if (this->HasMode(cm->name) && !ml->set) this->RemoveMode(NULL, cm); } - else if (cm->Type == MODE_PARAM) + else if (cm->type == MODE_PARAM) { /* If the channel doesnt have the mode, or it does and it isn't set correctly */ if (ml->set) { Anope::string param; - this->GetParam(cm->Name, param); + this->GetParam(cm->name, param); - if (!this->HasMode(cm->Name) || (!param.empty() && !ml->param.empty() && !param.equals_cs(ml->param))) + if (!this->HasMode(cm->name) || (!param.empty() && !ml->param.empty() && !param.equals_cs(ml->param))) this->SetMode(NULL, cm, ml->param); } else { - if (this->HasMode(cm->Name)) + if (this->HasMode(cm->name)) this->RemoveMode(NULL, cm); } } - else if (cm->Type == MODE_LIST) + else if (cm->type == MODE_LIST) { if (ml->set) this->SetMode(NULL, cm, ml->param); @@ -186,36 +184,32 @@ void Channel::CheckModes() } } -void Channel::JoinUser(User *user) +UserContainer* Channel::JoinUser(User *user) { Log(user, this, "join"); - ChannelStatus *Status = new ChannelStatus(); + ChannelStatus *status = new ChannelStatus(); ChannelContainer *cc = new ChannelContainer(this); - cc->Status = Status; + cc->status = status; user->chans.push_back(cc); UserContainer *uc = new UserContainer(user); - uc->Status = Status; + uc->status = status; this->users.push_back(uc); if (this->ci && this->ci->HasFlag(CI_PERSIST) && this->creation_time > this->ci->time_registered) { Log(LOG_DEBUG) << "Changing TS of " << this->name << " from " << this->creation_time << " to " << this->ci->time_registered; this->creation_time = this->ci->time_registered; - ircdproto->SendChannel(this); + IRCD->SendChannel(this); this->Reset(); } + + return uc; } -/** Remove a user internally from the channel - * @param u The user - */ void Channel::DeleteUser(User *user) { - if (this->ci) - update_cs_lastseen(user, this->ci); - Log(user, this, "leaves"); FOREACH_MOD(I_OnLeaveChannel, OnLeaveChannel(user, this)); @@ -227,7 +221,7 @@ void Channel::DeleteUser(User *user) return; } - delete (*cit)->Status; + delete (*cit)->status; delete *cit; this->users.erase(cit); @@ -259,10 +253,6 @@ void Channel::DeleteUser(User *user) delete this; } -/** Check if the user is on the channel - * @param u The user - * @return A user container if found, else NULL - */ UserContainer *Channel::FindUser(const User *u) const { for (CUserList::const_iterator it = this->users.begin(), it_end = this->users.end(); it != it_end; ++it) @@ -271,14 +261,9 @@ UserContainer *Channel::FindUser(const User *u) const return NULL; } -/** Check if a user has a status on a channel - * @param u The user - * @param cms The status mode, or NULL to represent no status - * @return true or false - */ bool Channel::HasUserStatus(const User *u, ChannelModeStatus *cms) const { - if (!u || (cms && cms->Type != MODE_STATUS)) + if (!u || (cms && cms->type != MODE_STATUS)) throw CoreException("Channel::HasUserStatus got bad mode"); /* Usually its more efficient to search the users channels than the channels users */ @@ -286,31 +271,19 @@ bool Channel::HasUserStatus(const User *u, ChannelModeStatus *cms) const if (cc) { if (cms) - return cc->Status->HasFlag(cms->Name); + return cc->status->HasFlag(cms->name); else - return !cc->Status->FlagCount(); + return !cc->status->FlagCount(); } return false; } -/** Check if a user has a status on a channel - * Use the overloaded function for ChannelModeStatus* to check for no status - * @param u The user - * @param Name The Mode name, eg CMODE_OP, CMODE_VOICE - * @return true or false - */ bool Channel::HasUserStatus(const User *u, ChannelModeName Name) const { return HasUserStatus(u, anope_dynamic_static_cast<ChannelModeStatus *>(ModeManager::FindChannelModeByName(Name))); } -/** - * See if a channel has a mode - * @param Name The mode name - * @param param The optional mode param - * @return The number of modes set - */ size_t Channel::HasMode(ChannelModeName Name, const Anope::string ¶m) { if (param.empty()) @@ -322,80 +295,70 @@ size_t Channel::HasMode(ChannelModeName Name, const Anope::string ¶m) return 0; } -/** Get a list of modes on a channel - * @param Name A mode name to get the list of - * @return a pair of iterators for the beginning and end of the list - */ -std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> Channel::GetModeList(ChannelModeName Name) +std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> Channel::GetModeList(ChannelModeName mname) { - Channel::ModeList::iterator it = this->modes.find(Name), it_end = it; + Channel::ModeList::iterator it = this->modes.find(mname), it_end = it; if (it != this->modes.end()) - it_end = this->modes.upper_bound(Name); + it_end = this->modes.upper_bound(mname); return std::make_pair(it, it_end); } -/** Set a mode internally on a channel, this is not sent out to the IRCd - * @param setter The user who is setting the mode - * @param cm The mode - * @param param The param - * @param EnforeMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::SetModeInternal(MessageSource &setter, ChannelMode *cm, const Anope::string ¶m, bool EnforceMLock) +void Channel::SetModeInternal(MessageSource &setter, ChannelMode *cm, const Anope::string ¶m, bool enforce_mlock) { if (!cm) return; EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnChannelModeSet, OnChannelModeSet(this, setter, cm->Name, param)); + FOREACH_RESULT(I_OnChannelModeSet, OnChannelModeSet(this, setter, cm->name, param)); /* Setting v/h/o/a/q etc */ - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { if (param.empty()) { - Log() << "Channel::SetModeInternal() mode " << cm->ModeChar << " with no parameter for channel " << this->name; + Log() << "Channel::SetModeInternal() mode " << cm->mchar << " with no parameter for channel " << this->name; return; } - User *u = finduser(param); + User *u = User::Find(param); if (!u) { - Log() << "MODE " << this->name << " +" << cm->ModeChar << " for nonexistant user " << param; + Log() << "MODE " << this->name << " +" << cm->mchar << " for nonexistant user " << param; return; } - Log(LOG_DEBUG) << "Setting +" << cm->ModeChar << " on " << this->name << " for " << u->nick; + Log(LOG_DEBUG) << "Setting +" << cm->mchar << " on " << this->name << " for " << u->nick; /* Set the status on the user */ ChannelContainer *cc = u->FindChannel(this); if (cc) - cc->Status->SetFlag(cm->Name); + cc->status->SetFlag(cm->name); /* Enforce secureops, etc */ - if (EnforceMLock) - chan_set_correct_modes(u, this, 0, false); + if (enforce_mlock) + this->SetCorrectModes(u, false, false); return; } - if (cm->Type != MODE_LIST) - this->modes.erase(cm->Name); - this->modes.insert(std::make_pair(cm->Name, param)); + if (cm->type != MODE_LIST) + this->modes.erase(cm->name); + this->modes.insert(std::make_pair(cm->name, param)); - if (param.empty() && cm->Type != MODE_REGULAR) + if (param.empty() && cm->type != MODE_REGULAR) { - Log() << "Channel::SetModeInternal() mode " << cm->ModeChar << " for " << this->name << " with a paramater, but its not a param mode"; + Log() << "Channel::SetModeInternal() mode " << cm->mchar << " for " << this->name << " with a paramater, but its not a param mode"; return; } - if (cm->Type == MODE_LIST) + if (cm->type == MODE_LIST) { ChannelModeList *cml = anope_dynamic_static_cast<ChannelModeList *>(cm); cml->OnAdd(this, param); } /* Channel mode +P or so was set, mark this channel as persistent */ - if (cm->Name == CMODE_PERM) + if (cm->name == CMODE_PERM) { this->SetFlag(CH_PERSIST); if (this->ci) @@ -403,68 +366,62 @@ void Channel::SetModeInternal(MessageSource &setter, ChannelMode *cm, const Anop } /* Check if we should enforce mlock */ - if (!EnforceMLock || MOD_RESULT == EVENT_STOP) + if (!enforce_mlock || MOD_RESULT == EVENT_STOP) return; this->CheckModes(); } -/** Remove a mode internally on a channel, this is not sent out to the IRCd - * @param setter The user who is unsetting the mode - * @param cm The mode - * @param param The param - * @param EnforceMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::RemoveModeInternal(MessageSource &setter, ChannelMode *cm, const Anope::string ¶m, bool EnforceMLock) +void Channel::RemoveModeInternal(MessageSource &setter, ChannelMode *cm, const Anope::string ¶m, bool enforce_mlock) { if (!cm) return; EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnChannelModeUnset, OnChannelModeUnset(this, setter, cm->Name, param)); + FOREACH_RESULT(I_OnChannelModeUnset, OnChannelModeUnset(this, setter, cm->name, param)); /* Setting v/h/o/a/q etc */ - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { if (param.empty()) { - Log() << "Channel::RemoveModeInternal() mode " << cm->ModeChar << " with no parameter for channel " << this->name; + Log() << "Channel::RemoveModeInternal() mode " << cm->mchar << " with no parameter for channel " << this->name; return; } - BotInfo *bi = findbot(param); - User *u = bi ? bi : finduser(param); + BotInfo *bi = BotInfo::Find(param); + User *u = bi ? bi : User::Find(param); if (!u) { - Log() << "Channel::RemoveModeInternal() MODE " << this->name << "-" << cm->ModeChar << " for nonexistant user " << param; + Log() << "Channel::RemoveModeInternal() MODE " << this->name << "-" << cm->mchar << " for nonexistant user " << param; return; } - Log(LOG_DEBUG) << "Setting -" << cm->ModeChar << " on " << this->name << " for " << u->nick; + Log(LOG_DEBUG) << "Setting -" << cm->mchar << " on " << this->name << " for " << u->nick; /* Remove the status on the user */ ChannelContainer *cc = u->FindChannel(this); if (cc) - cc->Status->UnsetFlag(cm->Name); + cc->status->UnsetFlag(cm->name); - if (EnforceMLock) + if (enforce_mlock) { /* Reset modes on bots if we're supposed to */ if (this->ci && this->ci->bi && this->ci->bi == bi) { - if (Config->BotModeList.HasFlag(cm->Name)) + if (ModeManager::DefaultBotModes.HasFlag(cm->name)) this->SetMode(bi, cm, bi->GetUID()); } - chan_set_correct_modes(u, this, 0, false); + this->SetCorrectModes(u, false, false); } return; } - if (cm->Type == MODE_LIST && !param.empty()) + if (cm->type == MODE_LIST && !param.empty()) { - std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> its = this->GetModeList(cm->Name); + std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> its = this->GetModeList(cm->name); for (; its.first != its.second; ++its.first) if (Anope::Match(param, its.first->second)) { @@ -473,15 +430,15 @@ void Channel::RemoveModeInternal(MessageSource &setter, ChannelMode *cm, const A } } else - this->modes.erase(cm->Name); + this->modes.erase(cm->name); - if (cm->Type == MODE_LIST) + if (cm->type == MODE_LIST) { ChannelModeList *cml = anope_dynamic_static_cast<ChannelModeList *>(cm); cml->OnDel(this, param); } - if (cm->Name == CMODE_PERM) + if (cm->name == CMODE_PERM) { this->UnsetFlag(CH_PERSIST); @@ -497,123 +454,92 @@ void Channel::RemoveModeInternal(MessageSource &setter, ChannelMode *cm, const A /* Check for mlock */ - if (!EnforceMLock || MOD_RESULT == EVENT_STOP) + if (!enforce_mlock || MOD_RESULT == EVENT_STOP) return; this->CheckModes(); } -/** Set a mode on a channel - * @param bi The client setting the modes - * @param cm The mode - * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::SetMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m, bool EnforceMLock) +void Channel::SetMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m, bool enforce_mlock) { if (!cm) return; /* Don't set modes already set */ - if (cm->Type == MODE_REGULAR && HasMode(cm->Name)) + if (cm->type == MODE_REGULAR && HasMode(cm->name)) return; - else if (cm->Type == MODE_PARAM) + else if (cm->type == MODE_PARAM) { ChannelModeParam *cmp = anope_dynamic_static_cast<ChannelModeParam *>(cm); if (!cmp->IsValid(param)) return; Anope::string cparam; - if (GetParam(cm->Name, cparam) && cparam.equals_cs(param)) + if (GetParam(cm->name, cparam) && cparam.equals_cs(param)) return; } - else if (cm->Type == MODE_STATUS) + else if (cm->type == MODE_STATUS) { - User *u = finduser(param); + User *u = User::Find(param); if (!u || HasUserStatus(u, anope_dynamic_static_cast<ChannelModeStatus *>(cm))) return; } - else if (cm->Type == MODE_LIST) + else if (cm->type == MODE_LIST) { ChannelModeList *cml = anope_dynamic_static_cast<ChannelModeList *>(cm); - if (this->HasMode(cm->Name, param) || !cml->IsValid(param)) + if (this->HasMode(cm->name, param) || !cml->IsValid(param)) return; } ModeManager::StackerAdd(bi, this, cm, true, param); MessageSource ms(bi); - SetModeInternal(ms, cm, param, EnforceMLock); + SetModeInternal(ms, cm, param, enforce_mlock); } -/** - * Set a mode on a channel - * @param bi The client setting the modes - * @param Name The mode name - * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::SetMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m, bool EnforceMLock) +void Channel::SetMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m, bool enforce_mlock) { - SetMode(bi, ModeManager::FindChannelModeByName(Name), param, EnforceMLock); + SetMode(bi, ModeManager::FindChannelModeByName(Name), param, enforce_mlock); } -/** Remove a mode from a channel - * @param bi The client setting the modes - * @param cm The mode - * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::RemoveMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m, bool EnforceMLock) +void Channel::RemoveMode(BotInfo *bi, ChannelMode *cm, const Anope::string ¶m, bool enforce_mlock) { if (!cm) return; /* Don't unset modes that arent set */ - if ((cm->Type == MODE_REGULAR || cm->Type == MODE_PARAM) && !HasMode(cm->Name)) + if ((cm->type == MODE_REGULAR || cm->type == MODE_PARAM) && !HasMode(cm->name)) return; /* Don't unset status that aren't set */ - else if (cm->Type == MODE_STATUS) + else if (cm->type == MODE_STATUS) { - User *u = finduser(param); + User *u = User::Find(param); if (!u || !HasUserStatus(u, anope_dynamic_static_cast<ChannelModeStatus *>(cm))) return; } - else if (cm->Type == MODE_LIST) + else if (cm->type == MODE_LIST) { - if (!this->HasMode(cm->Name, param)) + if (!this->HasMode(cm->name, param)) return; } /* Get the param to send, if we need it */ Anope::string realparam = param; - if (cm->Type == MODE_PARAM) + if (cm->type == MODE_PARAM) { realparam.clear(); ChannelModeParam *cmp = anope_dynamic_static_cast<ChannelModeParam *>(cm); - if (!cmp->MinusNoArg) - this->GetParam(cmp->Name, realparam); + if (!cmp->minus_no_arg) + this->GetParam(cmp->name, realparam); } ModeManager::StackerAdd(bi, this, cm, false, realparam); MessageSource ms(bi); - RemoveModeInternal(ms, cm, realparam, EnforceMLock); + RemoveModeInternal(ms, cm, realparam, enforce_mlock); } -/** - * Remove a mode from a channel - * @param bi The client setting the modes - * @param Name The mode name - * @param param Optional param arg for the mode - * @param EnforceMLock true if mlocks should be enforced, false to override mlock - */ -void Channel::RemoveMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m, bool EnforceMLock) +void Channel::RemoveMode(BotInfo *bi, ChannelModeName Name, const Anope::string ¶m, bool enforce_mlock) { - RemoveMode(bi, ModeManager::FindChannelModeByName(Name), param, EnforceMLock); + RemoveMode(bi, ModeManager::FindChannelModeByName(Name), param, enforce_mlock); } -/** Get a param from the channel - * @param Name The mode - * @param Target a string to put the param into - * @return true on success - */ bool Channel::GetParam(ChannelModeName Name, Anope::string &Target) const { std::multimap<ChannelModeName, Anope::string>::const_iterator it = this->modes.find(Name); @@ -629,14 +555,7 @@ bool Channel::GetParam(ChannelModeName Name, Anope::string &Target) const return false; } -/*************************************************************************/ - -/** Set a string of modes on the channel - * @param bi The client setting the modes - * @param EnforceMLock Should mlock be enforced on this mode change - * @param cmodes The modes to set - */ -void Channel::SetModes(BotInfo *bi, bool EnforceMLock, const char *cmodes, ...) +void Channel::SetModes(BotInfo *bi, bool enforce_mlock, const char *cmodes, ...) { char buf[BUFSIZE] = ""; va_list args; @@ -670,38 +589,38 @@ void Channel::SetModes(BotInfo *bi, bool EnforceMLock, const char *cmodes, ...) if (add) { - if (cm->Type != MODE_REGULAR && sep.GetToken(sbuf)) + if (cm->type != MODE_REGULAR && sep.GetToken(sbuf)) { - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { - User *targ = finduser(sbuf); + User *targ = User::Find(sbuf); if (targ != NULL) sbuf = targ->GetUID(); } - this->SetMode(bi, cm, sbuf, EnforceMLock); + this->SetMode(bi, cm, sbuf, enforce_mlock); } else - this->SetMode(bi, cm, "", EnforceMLock); + this->SetMode(bi, cm, "", enforce_mlock); } else if (!add) { - if (cm->Type != MODE_REGULAR && sep.GetToken(sbuf)) + if (cm->type != MODE_REGULAR && sep.GetToken(sbuf)) { - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { - User *targ = finduser(sbuf); + User *targ = User::Find(sbuf); if (targ != NULL) sbuf = targ->GetUID(); } - this->RemoveMode(bi, cm, sbuf, EnforceMLock); + this->RemoveMode(bi, cm, sbuf, enforce_mlock); } else - this->RemoveMode(bi, cm, "", EnforceMLock); + this->RemoveMode(bi, cm, "", enforce_mlock); } } } -void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, time_t ts, bool EnforceMLock) +void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, time_t ts, bool enforce_mlock) { if (source.GetServer()) { @@ -727,7 +646,7 @@ void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, User *setter = source.GetUser(); /* Removing channel modes *may* delete this channel */ - dynamic_reference<Channel> this_reference(this); + Reference<Channel> this_reference(this); spacesepstream sep_modes(mode); Anope::string m; @@ -760,24 +679,24 @@ void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, Log(LOG_DEBUG) << "Channel::SetModeInternal: Unknown mode char " << m[i]; continue; } - modestring += cm->ModeChar; + modestring += cm->mchar; } - if (cm->Type == MODE_REGULAR) + if (cm->type == MODE_REGULAR) { if (add) - this->SetModeInternal(source, cm, "", EnforceMLock); + this->SetModeInternal(source, cm, "", enforce_mlock); else - this->RemoveModeInternal(source, cm, "", EnforceMLock); + this->RemoveModeInternal(source, cm, "", enforce_mlock); continue; } - else if (cm->Type == MODE_PARAM) + else if (cm->type == MODE_PARAM) { ChannelModeParam *cmp = anope_dynamic_static_cast<ChannelModeParam *>(cm); - if (!add && cmp->MinusNoArg) + if (!add && cmp->minus_no_arg) { - this->RemoveModeInternal(source, cm, "", EnforceMLock); + this->RemoveModeInternal(source, cm, "", enforce_mlock); continue; } } @@ -785,15 +704,15 @@ void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, if (sep_modes.GetToken(token)) { User *u = NULL; - if (cm->Type == MODE_STATUS && (u = finduser(token))) + if (cm->type == MODE_STATUS && (u = User::Find(token))) paramstring += " " + u->nick; else paramstring += " " + token; if (add) - this->SetModeInternal(source, cm, token, EnforceMLock); + this->SetModeInternal(source, cm, token, enforce_mlock); else - this->RemoveModeInternal(source, cm, token, EnforceMLock); + this->RemoveModeInternal(source, cm, token, enforce_mlock); } else Log() << "warning: Channel::SetModesInternal() recieved more modes requiring params than params, modes: " << mode; @@ -808,15 +727,27 @@ void Channel::SetModesInternal(MessageSource &source, const Anope::string &mode, Log(LOG_DEBUG) << source.GetName() << " is setting " << this->name << " to " << modestring << paramstring; } -/** Kick a user from a channel internally - * @param source The sender of the kick - * @param nick The nick being kicked - * @param reason The reason for the kick - */ +bool Channel::MatchesList(User *u, ChannelModeName mode) +{ + if (!this->HasMode(mode)) + return false; + + + std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> m = this->GetModeList(mode); + for (; m.first != m.second; ++m.first) + { + Entry e(mode, m.first->second); + if (e.Matches(u)) + return true; + } + + return false; +} + void Channel::KickInternal(MessageSource &source, const Anope::string &nick, const Anope::string &reason) { User *sender = source.GetUser(); - User *target = finduser(nick); + User *target = User::Find(nick); if (!target) { Log() << "Channel::KickInternal got a nonexistent user " << nick << " on " << this->name << ": " << reason; @@ -825,7 +756,7 @@ void Channel::KickInternal(MessageSource &source, const Anope::string &nick, con BotInfo *bi = NULL; if (target->server == Me) - bi = findbot(nick); + bi = BotInfo::Find(nick); if (sender) Log(sender, this, "kick") << "kicked " << target->nick << " (" << reason << ")"; @@ -847,17 +778,11 @@ void Channel::KickInternal(MessageSource &source, const Anope::string &nick, con /* Bots get rejoined */ if (bi) { - bi->Join(this, &Config->BotModeList); + bi->Join(this, &ModeManager::DefaultBotModes); this->UnsetFlag(CH_INHABIT); } } -/** Kick a user from the channel - * @param bi The sender, can be NULL for the service bot for this channel - * @param u The user being kicked - * @param reason The reason for the kick - * @return true if the kick was scucessful, false if a module blocked the kick - */ bool Channel::Kick(BotInfo *bi, User *u, const char *reason, ...) { va_list args; @@ -881,7 +806,7 @@ bool Channel::Kick(BotInfo *bi, User *u, const char *reason, ...) FOREACH_RESULT(I_OnBotKick, OnBotKick(bi, this, u, buf)); if (MOD_RESULT == EVENT_STOP) return false; - ircdproto->SendKick(bi, this, u, "%s", buf); + IRCD->SendKick(bi, this, u, "%s", buf); MessageSource ms(bi); this->KickInternal(ms, u->nick, buf); return true; @@ -894,16 +819,16 @@ Anope::string Channel::GetModes(bool complete, bool plus) for (std::multimap<ChannelModeName, Anope::string>::const_iterator it = this->modes.begin(), it_end = this->modes.end(); it != it_end; ++it) { ChannelMode *cm = ModeManager::FindChannelModeByName(it->first); - if (!cm || cm->Type == MODE_LIST) + if (!cm || cm->type == MODE_LIST) continue; - res += cm->ModeChar; + res += cm->mchar; if (complete && !it->second.empty()) { ChannelModeParam *cmp = anope_dynamic_static_cast<ChannelModeParam *>(cm); - if (plus || !cmp->MinusNoArg) + if (plus || !cmp->minus_no_arg) params += " " + it->second; } } @@ -913,7 +838,7 @@ Anope::string Channel::GetModes(bool complete, bool plus) void Channel::ChangeTopicInternal(const Anope::string &user, const Anope::string &newtopic, time_t ts) { - User *u = finduser(user); + User *u = User::Find(user); this->topic = newtopic; this->topic_setter = u ? u->nick : user; @@ -930,13 +855,13 @@ void Channel::ChangeTopicInternal(const Anope::string &user, const Anope::string void Channel::ChangeTopic(const Anope::string &user, const Anope::string &newtopic, time_t ts) { - User *u = finduser(user); + User *u = User::Find(user); this->topic = newtopic; this->topic_setter = u ? u->nick : user; this->topic_ts = ts; - ircdproto->SendTopic(this->ci->WhoSends(), this); + IRCD->SendTopic(this->ci->WhoSends(), this); /* Now that the topic is set update the time set. This is *after* we set it so the protocol modules are able to tell the old last set time */ this->topic_time = Anope::CurTime; @@ -947,97 +872,55 @@ void Channel::ChangeTopic(const Anope::string &user, const Anope::string &newtop this->ci->CheckTopic(); } -/** A timer used to keep the BotServ bot/ChanServ in the channel - * after kicking the last user in a channel - */ -class CoreExport ChanServTimer : public Timer +void Channel::Hold() { - private: - dynamic_reference<Channel> c; - - public: - /** Default constructor - * @param chan The channel - */ - ChanServTimer(Channel *chan) : Timer(Config->CSInhabit), c(chan) - { - BotInfo *bi = findbot(Config->ChanServ); - if (!bi || !c) - return; - c->SetFlag(CH_INHABIT); - if (!c->ci || !c->ci->bi) - bi->Join(c); - else if (!c->FindUser(c->ci->bi)) - c->ci->bi->Join(c); - } - - /** Called when the delay is up - * @param The current time + /** A timer used to keep the BotServ bot/ChanServ in the channel + * after kicking the last user in a channel */ - void Tick(time_t) + class ChanServTimer : public Timer { - if (!c) - return; + private: + Reference<Channel> c; - c->UnsetFlag(CH_INHABIT); - - if (!c->ci || !c->ci->bi) + public: + /** Constructor + * @param chan The channel + */ + ChanServTimer(Channel *chan) : Timer(Config->CSInhabit), c(chan) { - BotInfo *bi = findbot(Config->ChanServ); - if (bi) - bi->Part(c); + if (!ChanServ || !c) + return; + c->SetFlag(CH_INHABIT); + if (!c->ci || !c->ci->bi) + ChanServ->Join(c); + else if (!c->FindUser(c->ci->bi)) + c->ci->bi->Join(c); } - else if (c->users.size() == 1 || c->users.size() < Config->BSMinUsers) - c->ci->bi->Part(c); - } -}; -void Channel::Hold() -{ - new ChanServTimer(this); -} - -/*************************************************************************/ - -Channel *findchan(const Anope::string &chan) -{ - channel_map::const_iterator it = ChannelList.find(chan); - - if (it != ChannelList.end()) - return it->second; - return NULL; -} - -/*************************************************************************/ - -/* Is the given nick on the given channel? - This function supports links. */ + /** Called when the delay is up + * @param The current time + */ + void Tick(time_t) anope_override + { + if (!c) + return; -User *nc_on_chan(Channel *c, const NickCore *nc) -{ - if (!c || !nc) - return NULL; + c->UnsetFlag(CH_INHABIT); - for (CUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it) - { - UserContainer *uc = *it; + if (!c->ci || !c->ci->bi) + { + if (ChanServ) + ChanServ->Part(c); + } + else if (c->users.size() == 1 || c->users.size() < Config->BSMinUsers) + c->ci->bi->Part(c); + } + }; - if (uc->user->Account() == nc) - return uc->user; - } - return NULL; + new ChanServTimer(this); } -/** - * Set the correct modes, or remove the ones granted without permission, - * for the specified user on ths specified channel. This doesn't give - * modes to ignored users, but does remove them if needed. - * @param user The user to give/remove modes to/from - * @param c The channel to give/remove modes on - * @param give_modes Set to 1 to give modes, 0 to not give modes - * @return void - **/ -void chan_set_correct_modes(const User *user, Channel *c, int give_modes, bool check_noop) +void Channel::SetCorrectModes(User *user, bool give_modes, bool check_noop) { ChannelMode *owner = ModeManager::FindChannelModeByName(CMODE_OWNER), *admin = ModeManager::FindChannelModeByName(CMODE_PROTECT), @@ -1045,46 +928,44 @@ void chan_set_correct_modes(const User *user, Channel *c, int give_modes, bool c *halfop = ModeManager::FindChannelModeByName(CMODE_HALFOP), *voice = ModeManager::FindChannelModeByName(CMODE_VOICE); - if (user == NULL || c == NULL) + if (user == NULL) return; - ChannelInfo *ci = c->ci; - - if (ci == NULL) + if (!this->ci) return; - Log(LOG_DEBUG) << "Setting correct user modes for " << user->nick << " on " << c->name << " (" << (give_modes ? "" : "not ") << "giving modes)"; + Log(LOG_DEBUG) << "Setting correct user modes for " << user->nick << " on " << this->name << " (" << (give_modes ? "" : "not ") << "giving modes)"; AccessGroup u_access = ci->AccessFor(user); if (give_modes && (!user->Account() || user->Account()->HasFlag(NI_AUTOOP)) && (!check_noop || !ci->HasFlag(CI_NOAUTOOP))) { if (owner && u_access.HasPriv("AUTOOWNER")) - c->SetMode(NULL, CMODE_OWNER, user->GetUID()); + this->SetMode(NULL, CMODE_OWNER, user->GetUID()); else if (admin && u_access.HasPriv("AUTOPROTECT")) - c->SetMode(NULL, CMODE_PROTECT, user->GetUID()); + this->SetMode(NULL, CMODE_PROTECT, user->GetUID()); if (op && u_access.HasPriv("AUTOOP")) - c->SetMode(NULL, CMODE_OP, user->GetUID()); + this->SetMode(NULL, CMODE_OP, user->GetUID()); else if (halfop && u_access.HasPriv("AUTOHALFOP")) - c->SetMode(NULL, CMODE_HALFOP, user->GetUID()); + this->SetMode(NULL, CMODE_HALFOP, user->GetUID()); else if (voice && u_access.HasPriv("AUTOVOICE")) - c->SetMode(NULL, CMODE_VOICE, user->GetUID()); + this->SetMode(NULL, CMODE_VOICE, user->GetUID()); } /* If this channel has secureops or the channel is syncing and they are not ulined, check to remove modes */ - if ((ci->HasFlag(CI_SECUREOPS) || (c->HasFlag(CH_SYNCING) && user->server->IsSynced())) && !user->server->IsULined()) + if ((ci->HasFlag(CI_SECUREOPS) || (this->HasFlag(CH_SYNCING) && user->server->IsSynced())) && !user->server->IsULined()) { if (owner && !u_access.HasPriv("AUTOOWNER") && !u_access.HasPriv("OWNERME")) - c->RemoveMode(NULL, CMODE_OWNER, user->GetUID()); + this->RemoveMode(NULL, CMODE_OWNER, user->GetUID()); if (admin && !u_access.HasPriv("AUTOPROTECT") && !u_access.HasPriv("PROTECTME")) - c->RemoveMode(NULL, CMODE_PROTECT, user->GetUID()); + this->RemoveMode(NULL, CMODE_PROTECT, user->GetUID()); - if (op && c->HasUserStatus(user, CMODE_OP) && !u_access.HasPriv("AUTOOP") && !u_access.HasPriv("OPDEOPME")) - c->RemoveMode(NULL, CMODE_OP, user->GetUID()); + if (op && this->HasUserStatus(user, CMODE_OP) && !u_access.HasPriv("AUTOOP") && !u_access.HasPriv("OPDEOPME")) + this->RemoveMode(NULL, CMODE_OP, user->GetUID()); if (halfop && !u_access.HasPriv("AUTOHALFOP") && !u_access.HasPriv("HALFOPME")) - c->RemoveMode(NULL, CMODE_HALFOP, user->GetUID()); + this->RemoveMode(NULL, CMODE_HALFOP, user->GetUID()); } // Check mlock @@ -1092,171 +973,43 @@ void chan_set_correct_modes(const User *user, Channel *c, int give_modes, bool c { const ModeLock *ml = it->second; ChannelMode *cm = ModeManager::FindChannelModeByName(ml->name); - if (!cm || cm->Type != MODE_STATUS) + if (!cm || cm->type != MODE_STATUS) continue; if (Anope::Match(user->nick, ml->param) || Anope::Match(user->GetDisplayedMask(), ml->param)) { - if ((ml->set && !c->HasUserStatus(user, ml->name)) || (!ml->set && c->HasUserStatus(user, ml->name))) + if (ml->set != this->HasUserStatus(user, ml->name)) { if (ml->set) - c->SetMode(NULL, cm, user->GetUID(), false); + this->SetMode(NULL, cm, user->GetUID(), false); else if (!ml->set) - c->RemoveMode(NULL, cm, user->GetUID(), false); + this->RemoveMode(NULL, cm, user->GetUID(), false); } } } } -/*************************************************************************/ - -static const Anope::string EntryFlagString[] = { "ENTRYTYPE_NONE", "ENTRYTYPE_CIDR", "ENTRYTYPE_NICK_WILD", "ENTRYTYPE_NICK", "ENTRYTYPE_USER_WILD", "ENTRYTYPE_USER", "ENTRYTYPE_HOST_WILD", "ENTRYTYPE_HOST", "" }; - -/** Constructor - * @param mode What mode this host is for - can be CMODE_BEGIN for unknown/no mode - * @param _host A full nick!ident@host/cidr mask - */ -Entry::Entry(ChannelModeName mode, const Anope::string &_host) : Flags<EntryType>(EntryFlagString), modename(mode) +void Channel::Unban(const User *u, bool full) { - this->SetFlag(ENTRYTYPE_NONE); - this->cidr_len = 0; - this->mask = _host; - - Anope::string _nick, _user, _realhost; - size_t at = _host.find('@'); - if (at != Anope::string::npos) - { - _realhost = _host.substr(at + 1); - Anope::string _nickident = _host.substr(0, at); - - size_t ex = _nickident.find('!'); - if (ex != Anope::string::npos) - { - _user = _nickident.substr(ex + 1); - _nick = _nickident.substr(0, ex); - } - else - _user = _nickident; - } - else - _realhost = _host; - - if (!_nick.empty() && !str_is_pure_wildcard(_nick)) - { - this->nick = _nick; - if (str_is_wildcard(_nick)) - this->SetFlag(ENTRYTYPE_NICK_WILD); - else - this->SetFlag(ENTRYTYPE_NICK); - } + if (!this->HasMode(CMODE_BAN)) + return; - if (!_user.empty() && !str_is_pure_wildcard(_user)) + std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> bans = this->GetModeList(CMODE_BAN); + for (; bans.first != bans.second;) { - this->user = _user; - if (str_is_wildcard(_user)) - this->SetFlag(ENTRYTYPE_USER_WILD); - else - this->SetFlag(ENTRYTYPE_USER); - } - - if (!_realhost.empty() && !str_is_pure_wildcard(_realhost)) - { - size_t sl = _realhost.find_last_of('/'); - if (sl != Anope::string::npos) - { - try - { - sockaddrs addr(_realhost.substr(0, sl)); - /* If we got here, _realhost is a valid IP */ - - Anope::string cidr_range = _realhost.substr(sl + 1); - if (cidr_range.is_pos_number_only()) - { - _realhost = _realhost.substr(0, sl); - this->cidr_len = convertTo<unsigned int>(cidr_range); - this->SetFlag(ENTRYTYPE_CIDR); - Log(LOG_DEBUG) << "Ban " << _realhost << " has cidr " << static_cast<unsigned int>(this->cidr_len); - } - } - catch (const SocketException &) { } - } - - this->host = _realhost; - - if (!this->HasFlag(ENTRYTYPE_CIDR)) - { - if (str_is_wildcard(_realhost)) - this->SetFlag(ENTRYTYPE_HOST_WILD); - else - this->SetFlag(ENTRYTYPE_HOST); - } + Entry ban(CMODE_BAN, bans.first->second); + ++bans.first; + if (ban.Matches(u, full)) + this->RemoveMode(NULL, CMODE_BAN, ban.GetMask()); } } -/** Get the banned mask for this entry - * @return The mask - */ -const Anope::string Entry::GetMask() +Channel* Channel::Find(const Anope::string &name) { - return this->mask; -} - -/** Check if this entry matches a user - * @param u The user - * @param full True to match against a users real host and IP - * @return true on match - */ -bool Entry::Matches(const User *u, bool full) const -{ - bool ret = true; - - if (this->HasFlag(ENTRYTYPE_CIDR)) - { - try - { - if (full) - { - cidr cidr_mask(this->host, this->cidr_len); - sockaddrs addr(u->ip); - if (!cidr_mask.match(addr)) - ret = false; - } - /* If we're not matching fully and their displayed host isnt their IP */ - else if (u->ip != u->GetDisplayedHost()) - ret = false; - } - catch (const SocketException &) - { - ret = false; - } - } - if (this->HasFlag(ENTRYTYPE_NICK) && !this->nick.equals_ci(u->nick)) - ret = false; - if (this->HasFlag(ENTRYTYPE_USER) && !this->user.equals_ci(u->GetVIdent()) && (!full || - !this->user.equals_ci(u->GetIdent()))) - ret = false; - if (this->HasFlag(ENTRYTYPE_HOST) && !this->host.equals_ci(u->GetDisplayedHost()) && (!full || - (!this->host.equals_ci(u->host) && !this->host.equals_ci(u->chost) && !this->host.equals_ci(u->vhost) && - !this->host.equals_ci(u->ip)))) - ret = false; - if (this->HasFlag(ENTRYTYPE_NICK_WILD) && !Anope::Match(u->nick, this->nick)) - ret = false; - if (this->HasFlag(ENTRYTYPE_USER_WILD) && !Anope::Match(u->GetVIdent(), this->user) && (!full || - !Anope::Match(u->GetIdent(), this->user))) - ret = false; - if (this->HasFlag(ENTRYTYPE_HOST_WILD) && !Anope::Match(u->GetDisplayedHost(), this->host) && (!full || - (!Anope::Match(u->host, this->host) && !Anope::Match(u->chost, this->host) && - !Anope::Match(u->vhost, this->host) && !Anope::Match(u->ip, this->host)))) - ret = false; - - ChannelMode *cm = ModeManager::FindChannelModeByName(this->modename); - if (cm != NULL && cm->Type == MODE_LIST) - { - ChannelModeList *cml = anope_dynamic_static_cast<ChannelModeList *>(cm); - if (cml->Matches(u, this)) - ret = true; - } + channel_map::const_iterator it = ChannelList.find(name); - return ret; + if (it != ChannelList.end()) + return it->second; + return NULL; } diff --git a/src/chanserv.cpp b/src/chanserv.cpp deleted file mode 100644 index 4456ce37c..000000000 --- a/src/chanserv.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* ChanServ functions. - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -/*************************************************************************/ - -#include "services.h" -#include "anope.h" -#include "regchannel.h" -#include "users.h" -#include "channels.h" -#include "access.h" -#include "account.h" - -ChannelInfo* cs_findchan(const Anope::string &chan) -{ - registered_channel_map::const_iterator it = RegisteredChannelList->find(chan); - if (it != RegisteredChannelList->end()) - { - it->second->QueueUpdate(); - return it->second; - } - - return NULL; -} - -/*************************************************************************/ - -/** Is the user the real founder? - * @param user The user - * @param ci The channel - * @return true or false - */ -bool IsFounder(const User *user, const ChannelInfo *ci) -{ - if (!user || !ci) - return false; - - if (user->SuperAdmin) - return true; - - if (user->Account() && user->Account() == ci->GetFounder()) - return true; - - return false; -} - -/*************************************************************************/ - -void update_cs_lastseen(User *user, ChannelInfo *ci) -{ - if (!ci || !user) - return; - - AccessGroup u_access = ci->AccessFor(user); - for (unsigned i = u_access.size(); i > 0; --i) - u_access[i - 1]->last_seen = Anope::CurTime; -} - -/*************************************************************************/ - -/* Returns the best ban possible for a user depending of the bantype - value. */ - -int get_idealban(const ChannelInfo *ci, User *u, Anope::string &ret) -{ - Anope::string mask; - - if (!ci || !u) - return 0; - - Anope::string vident = u->GetIdent(); - - switch (ci->bantype) - { - case 0: - ret = "*!" + vident + "@" + u->GetDisplayedHost(); - return 1; - case 1: - if (vident[0] == '~') - ret = "*!*" + vident + "@" + u->GetDisplayedHost(); - else - ret = "*!" + vident + "@" + u->GetDisplayedHost(); - - return 1; - case 2: - ret = "*!*@" + u->GetDisplayedHost(); - return 1; - case 3: - mask = create_mask(u); - ret = "*!" + mask; - return 1; - - default: - return 0; - } -} - diff --git a/src/command.cpp b/src/command.cpp index 6ae9275ca..92991e38b 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -1,13 +1,14 @@ /* + * * Copyright (C) 2008-2011 Robin Burchell <w00t@inspircd.org> * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #include "services.h" #include "commands.h" -#include "extern.h" #include "users.h" #include "language.h" #include "config.h" @@ -17,6 +18,9 @@ #include "regchannel.h" #include "channels.h" +static const Anope::string CommandFlagString[] = { "CFLAG_ALLOW_UNREGISTERED", "CFLAG_STRIP_CHANNEL", "" }; +template<> const Anope::string* Flags<CommandFlag>::flags_strings = CommandFlagString; + CommandSource::CommandSource(const Anope::string &n, User *user, NickCore *core, CommandReply *r, BotInfo *bi) : nick(n), u(user), nc(core), reply(r), c(NULL), service(bi) { @@ -97,7 +101,7 @@ void CommandSource::Reply(const char *message, ...) va_list args; char buf[4096]; // Messages can be really big. - const char *translated_message = translate(this->nc, message); + const char *translated_message = Language::Translate(this->nc, message); va_start(args, message); vsnprintf(buf, sizeof(buf), translated_message, args); @@ -109,7 +113,7 @@ void CommandSource::Reply(const char *message, ...) void CommandSource::Reply(const Anope::string &message) { - const char *translated_message = translate(this->nc, message.c_str()); + const char *translated_message = Language::Translate(this->nc, message.c_str()); sepstream sep(translated_message, '\n'); Anope::string tok; @@ -117,7 +121,7 @@ void CommandSource::Reply(const Anope::string &message) this->reply->SendMessage(this->service, tok); } -Command::Command(Module *o, const Anope::string &sname, size_t min_params, size_t max_params) : Service(o, "Command", sname), Flags<CommandFlag>(CommandFlagStrings), MaxParams(max_params), MinParams(min_params), module(owner) +Command::Command(Module *o, const Anope::string &sname, size_t minparams, size_t maxparams) : Service(o, "Command", sname), max_params(maxparams), min_params(minparams), module(owner) { } @@ -163,7 +167,7 @@ const Anope::string &Command::GetDesc() const void Command::OnServHelp(CommandSource &source) { - source.Reply(" %-14s %s", source.command.c_str(), translate(source.nc, (this->GetDesc().c_str()))); + source.Reply(" %-14s %s", source.command.c_str(), Language::Translate(source.nc, this->GetDesc().c_str())); } bool Command::OnHelp(CommandSource &source, const Anope::string &subcommand) { return false; } @@ -176,7 +180,8 @@ void Command::OnSyntaxError(CommandSource &source, const Anope::string &subcomma void RunCommand(CommandSource &source, const Anope::string &message) { - std::vector<Anope::string> params = BuildStringVector(message); + std::vector<Anope::string> params; + spacesepstream(message).GetTokens(params); bool has_help = source.service->commands.find("HELP") != source.service->commands.end(); CommandInfo::map::const_iterator it = source.service->commands.end(); @@ -202,7 +207,7 @@ void RunCommand(CommandSource &source, const Anope::string &message) } const CommandInfo &info = it->second; - service_reference<Command> c("Command", info.name); + ServiceReference<Command> c("Command", info.name); if (!c) { if (has_help) @@ -225,10 +230,10 @@ void RunCommand(CommandSource &source, const Anope::string &message) for (unsigned i = 0, j = params.size() - (count - 1); i < j; ++i) params.erase(params.begin()); - while (c->MaxParams > 0 && params.size() > c->MaxParams) + while (c->max_params > 0 && params.size() > c->max_params) { - params[c->MaxParams - 1] += " " + params[c->MaxParams]; - params.erase(params.begin() + c->MaxParams); + params[c->max_params - 1] += " " + params[c->max_params]; + params.erase(params.begin() + c->max_params); } source.command = it->first; @@ -239,7 +244,7 @@ void RunCommand(CommandSource &source, const Anope::string &message) if (MOD_RESULT == EVENT_STOP) return; - if (params.size() < c->MinParams) + if (params.size() < c->min_params) { c->OnSyntaxError(source, !params.empty() ? params[params.size() - 1] : ""); return; @@ -255,8 +260,8 @@ void RunCommand(CommandSource &source, const Anope::string &message) } bool had_u = source.GetUser(), had_nc = source.nc; - dynamic_reference<User> user_reference(source.GetUser()); - dynamic_reference<NickCore> nc_reference(source.nc); + Reference<User> user_reference(source.GetUser()); + Reference<NickCore> nc_reference(source.nc); c->Execute(source, params); if (had_u == user_reference && had_nc == nc_reference) { diff --git a/src/config.cpp b/src/config.cpp index be12c3479..48126cf7d 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -7,11 +7,11 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "config.h" -#include "extern.h" #include "bots.h" #include "access.h" #include "opertype.h" @@ -28,7 +28,7 @@ /*************************************************************************/ -ConfigurationFile services_conf("services.conf", false); // Services configuration file name +ConfigurationFile ServicesConf("services.conf", false); // Services configuration file name ServerConfig *Config = NULL; static Anope::string UlineServers; @@ -38,7 +38,7 @@ static Anope::string NSDefaults; /*************************************************************************/ -ServerConfig::ServerConfig() : config_data(), NSDefFlags(NickCoreFlagStrings), CSDefFlags(ChannelInfoFlagStrings), BSDefFlags(BotServFlagStrings) +ServerConfig::ServerConfig() { this->Read(); @@ -173,7 +173,7 @@ ServerConfig::ServerConfig() : config_data(), NSDefFlags(NickCoreFlagStrings), C if (this->Seed == 0) Log() << "Configuration option options:seed should be set. It's for YOUR safety! Remember that!"; - SetDefaultMLock(this); + ModeManager::UpdateDefaultMLock(this); if (IsFile(this->NameServer)) { @@ -208,8 +208,8 @@ ServerConfig::ServerConfig() : config_data(), NSDefFlags(NickCoreFlagStrings), C this->NameServer = "127.0.0.1"; } } - delete DNSEngine; - DNSEngine = new DNSManager(this->NameServer, this->DNSIP, this->DNSPort); + delete DNS::Engine; + DNS::Engine = new DNS::Manager(this->NameServer, this->DNSIP, this->DNSPort); if (this->CaseMap == "ascii") Anope::casemap = std::locale(std::locale(), new Anope::ascii_ctype<char>()); @@ -363,27 +363,27 @@ void ServerConfig::ValidateHostname(const Anope::string &p, const Anope::string } } -bool ValidateNotEmpty(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateNotEmpty(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (data.GetValue().empty()) throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty!"); return true; } -bool ValidateNotZero(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateNotZero(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) { - if (!data.GetInteger() && dotime(data.GetValue()) <= 0) + if (!data.GetInteger() && Anope::DoTime(data.GetValue()) <= 0) throw ConfigException("The value for <" + tag + ":" + value + "> must be non-zero!"); return true; } -bool ValidateEmailReg(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateEmailReg(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (!config->NSRegistration.equals_ci("none") && !config->NSRegistration.equals_ci("disable")) { if (value.equals_ci("unconfirmedexpire")) { - if (!data.GetInteger() && dotime(data.GetValue()) <= 0) + if (!data.GetInteger() && Anope::DoTime(data.GetValue()) <= 0) throw ConfigException("The value for <" + tag + ":" + value + "> must be non-zero when e-mail or admin registration is enabled!"); } else @@ -395,7 +395,7 @@ bool ValidateEmailReg(ServerConfig *config, const Anope::string &tag, const Anop return true; } -bool ValidatePort(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidatePort(ServerConfig *, const Anope::string &tag, const Anope::string &value, ValueItem &data) { int port = data.GetInteger(); if (!port) @@ -405,7 +405,7 @@ bool ValidatePort(ServerConfig *, const Anope::string &tag, const Anope::string return true; } -bool ValidateBantype(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data) +static bool ValidateBantype(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data) { int bantype = data.GetInteger(); if (bantype < 0 || bantype > 3) @@ -413,7 +413,7 @@ bool ValidateBantype(ServerConfig *, const Anope::string &, const Anope::string return true; } -bool ValidateNickServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateNickServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (!config->NickServ.empty()) { @@ -434,7 +434,7 @@ bool ValidateNickServ(ServerConfig *config, const Anope::string &tag, const Anop return true; } -bool ValidateChanServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateChanServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (!config->ChanServ.empty()) { @@ -448,31 +448,13 @@ bool ValidateChanServ(ServerConfig *config, const Anope::string &tag, const Anop return true; } -bool ValidateMemoServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) -{ - if (!config->MemoServ.empty()) - { - if (value.equals_ci("description")) - { - if (data.GetValue().empty()) - throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty when MemoServ is enabled!"); - } - } - return true; -} - -bool ValidateBotServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateBotServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (!config->BotServ.empty()) { - if (value.equals_ci("description")) + if (value.equals_ci("badwordsmax") || value.equals_ci("keepdata")) { - if (data.GetValue().empty()) - throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty when BotServ is enabled!"); - } - else if (value.equals_ci("badwordsmax") || value.equals_ci("keepdata")) - { - if (!data.GetInteger() && dotime(data.GetValue()) <= 0) + if (!data.GetInteger() && Anope::DoTime(data.GetValue()) <= 0) throw ConfigException("The value for <" + tag + ":" + value + "> must be non-zero when BotServ is enabled!"); } else if (value.equals_ci("minusers")) @@ -484,36 +466,24 @@ bool ValidateBotServ(ServerConfig *config, const Anope::string &tag, const Anope return true; } -bool ValidateHostServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) -{ - if (!config->HostServ.empty()) - { - if (value.equals_ci("description") && data.GetValue().empty()) - throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty when HostServ is enabled!"); - } - return true; -} - -bool ValidateLimitSessions(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateLimitSessions(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (config->LimitSessions) { if (value.equals_ci("maxsessionlimit") || value.equals_ci("exceptionexpiry")) { - if (!data.GetInteger() && dotime(data.GetValue()) <= 0) + if (!data.GetInteger() && Anope::DoTime(data.GetValue()) <= 0) throw ConfigException("The value for <" + tag + ":" + value + "> must be non-zero when session limiting is enabled!"); } } return true; } -bool ValidateOperServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateOperServ(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (!config->OperServ.empty()) { - if (value.equals_ci("description") && data.GetValue().empty()) - throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty when OperServ is enabled!"); - else if (value.equals_ci("autokillexpiry") || value.equals_ci("chankillexpiry") || value.equals_ci("snlineexpiry") || value.equals_ci("sqlineexpiry")) + if (value.equals_ci("autokillexpiry") || value.equals_ci("chankillexpiry") || value.equals_ci("snlineexpiry") || value.equals_ci("sqlineexpiry")) return ValidateNotZero(config, tag, value, data); else if (value.equals_ci("maxsessionlimit") || value.equals_ci("exceptionexpiry")) return ValidateLimitSessions(config, tag, value, data); @@ -521,17 +491,7 @@ bool ValidateOperServ(ServerConfig *config, const Anope::string &tag, const Anop return true; } -bool ValidateGlobal(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) -{ - if (!config->Global.empty()) - { - if (value.equals_ci("description") && data.GetValue().empty()) - throw ConfigException("The value for <" + tag + ":" + value + "> cannot be empty when Global is enabled!"); - } - return true; -} - -bool ValidateNickLen(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data) +static bool ValidateNickLen(ServerConfig *, const Anope::string &, const Anope::string &, ValueItem &data) { int nicklen = data.GetInteger(); if (!nicklen) @@ -548,7 +508,7 @@ bool ValidateNickLen(ServerConfig *, const Anope::string &, const Anope::string return true; } -bool ValidateMail(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateMail(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (config->UseMail) { @@ -561,7 +521,7 @@ bool ValidateMail(ServerConfig *config, const Anope::string &tag, const Anope::s return true; } -bool ValidateGlobalOnCycle(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) +static bool ValidateGlobalOnCycle(ServerConfig *config, const Anope::string &tag, const Anope::string &value, ValueItem &data) { if (config->GlobalOnCycle) { @@ -574,7 +534,7 @@ bool ValidateGlobalOnCycle(ServerConfig *config, const Anope::string &tag, const return true; } -bool InitUplinks(ServerConfig *config, const Anope::string &) +static bool InitUplinks(ServerConfig *config, const Anope::string &) { if (!config->Uplinks.empty()) { @@ -722,7 +682,7 @@ static bool DoOper(ServerConfig *config, const Anope::string &, const Anope::str o->config = true; o->password = password; o->certfp = certfp; - o->hosts = BuildStringVector(host); + spacesepstream(host).GetTokens(o->hosts); o->vhost = vhost; config->Opers.push_back(o); @@ -735,7 +695,7 @@ static bool DoneOpers(ServerConfig *config, const Anope::string &) { Oper *o = config->Opers[i]; - const NickAlias *na = findnick(o->name); + const NickAlias *na = NickAlias::Find(o->name); if (!na) // Nonexistant nick continue; @@ -796,7 +756,7 @@ static bool DoneInclude(ServerConfig *config, const Anope::string &) /*************************************************************************/ -bool InitModules(ServerConfig *, const Anope::string &) +static bool InitModules(ServerConfig *, const Anope::string &) { return true; } @@ -826,7 +786,7 @@ static bool DoneModules(ServerConfig *config, const Anope::string &) return true; } -bool InitLogs(ServerConfig *config, const Anope::string &) +static bool InitLogs(ServerConfig *config, const Anope::string &) { config->LogInfos.clear(); return true; @@ -853,15 +813,15 @@ static bool DoLogs(ServerConfig *config, const Anope::string &, const Anope::str bool ldebug = values[11].GetBool(); LogInfo *l = new LogInfo(logage, rawio, ldebug); - l->Targets = BuildStringList(targets); - l->Sources = BuildStringList(source); - l->Admin = BuildStringList(admin); - l->Override = BuildStringList(override); - l->Commands = BuildStringList(commands); - l->Servers = BuildStringList(servers); - l->Channels = BuildStringList(channels); - l->Users = BuildStringList(users); - l->Normal = BuildStringList(normal); + spacesepstream(targets).GetTokens(l->targets); + spacesepstream(source).GetTokens(l->sources); + spacesepstream(admin).GetTokens(l->admin); + spacesepstream(override).GetTokens(l->override); + spacesepstream(commands).GetTokens(l->commands); + spacesepstream(servers).GetTokens(l->servers); + spacesepstream(channels).GetTokens(l->channels); + spacesepstream(users).GetTokens(l->users); + spacesepstream(normal).GetTokens(l->normal); config->LogInfos.push_back(l); @@ -909,7 +869,7 @@ static bool DoCommands(ServerConfig *config, const Anope::string &, const Anope: if (!ValidateNotEmpty(config, "command", "command", vi)) throw ConfigException("One or more values in your configuration file failed to validate. Please see your log for more information."); - BotInfo *bi = findbot(service); + BotInfo *bi = BotInfo::Find(service); if (bi == NULL) throw ConfigException("Command " + name + " exists for nonexistant service " + service); @@ -992,7 +952,7 @@ static bool DoServices(ServerConfig *config, const Anope::string &, const Anope: throw ConfigException("One or more values in your configuration file failed to validate. Please see your log for more information."); services.insert(nick); - BotInfo* bi = findbot(nick); + BotInfo* bi = BotInfo::Find(nick); if (!bi) bi = new BotInfo(nick, user, host, gecos, modes); bi->SetFlag(BI_CONF); @@ -1014,7 +974,7 @@ static bool DoServices(ServerConfig *config, const Anope::string &, const Anope: chname = token.substr(ch); } bi->Join(chname); - Channel *c = findchan(chname); + Channel *c = Channel::Find(chname); if (!c) continue; // Can't happen @@ -1022,7 +982,7 @@ static bool DoServices(ServerConfig *config, const Anope::string &, const Anope: for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm && cm->Type == MODE_STATUS) + if (cm && cm->type == MODE_STATUS) c->RemoveMode(bi, cm, bi->nick); } /* Set the new modes */ @@ -1031,7 +991,7 @@ static bool DoServices(ServerConfig *config, const Anope::string &, const Anope: ChannelMode *cm = ModeManager::FindChannelModeByChar(want_modes[j]); if (cm == NULL) cm = ModeManager::FindChannelModeByChar(ModeManager::GetStatusChar(want_modes[j])); - if (cm && cm->Type == MODE_STATUS) + if (cm && cm->type == MODE_STATUS) c->SetMode(bi, cm, bi->GetUID()); } } @@ -1053,7 +1013,7 @@ static bool DoServices(ServerConfig *config, const Anope::string &, const Anope: if (found) continue; - Channel *c = findchan(chname); + Channel *c = Channel::Find(chname); if (c) bi->Part(c); } @@ -1069,7 +1029,7 @@ static bool DoneServices(ServerConfig *config, const Anope::string &) ++it; if (bi->HasFlag(BI_CONF) && services.count(bi->nick) == 0) - bi->destroy(); + bi->Destroy(); } services.clear(); return true; @@ -1123,7 +1083,7 @@ bool ConfigurationFile::IsOpen() const bool ConfigurationFile::Open() { this->Close(); - this->fp = (this->executable ? popen(this->name.c_str(), "r") : fopen((conf_dir + "/" + this->name).c_str(), "r")); + this->fp = (this->executable ? popen(this->name.c_str(), "r") : fopen((Anope::ConfigDir + "/" + this->name).c_str(), "r")); return this->fp != NULL; } @@ -1464,7 +1424,7 @@ void ServerConfig::Read() // These tags MUST occur and must ONLY occur once in the config file static const Anope::string Once[] = {"serverinfo", "networkinfo", "options", ""}; - this->LoadConf(services_conf); + this->LoadConf(ServicesConf); ConfigItems configitems(this); @@ -1550,9 +1510,9 @@ void ServerConfig::Read() if (has_value) { #ifdef _WIN32 - long time = static_cast<long>(dotime(item)); + long time = static_cast<long>(Anope::DoTime(item)); #else - time_t time = dotime(item); + time_t time = Anope::DoTime(item); #endif vl.push_back(ValueItem(time)); } @@ -1648,7 +1608,7 @@ void ServerConfig::Read() } case DT_TIME: { - time_t time = dotime(vi.GetValue()); + time_t time = Anope::DoTime(vi.GetValue()); ValueContainerTime *vci = anope_dynamic_static_cast<ValueContainerTime *>(configitems.Values[Index].val); vci->Set(&time, sizeof(time_t)); break; @@ -1665,10 +1625,10 @@ void ServerConfig::Read() } } - Log(LOG_DEBUG) << "End config " << services_conf.GetName(); + Log(LOG_DEBUG) << "End config " << ServicesConf.GetName(); for (int Index = 0; !Once[Index].empty(); ++Index) CheckOnce(Once[Index]); - Log() << "Done reading configuration file " << services_conf.GetName(); + Log() << "Done reading configuration file " << ServicesConf.GetName(); } void ServerConfig::LoadConf(ConfigurationFile &file) diff --git a/src/configreader.cpp b/src/configreader.cpp index 0bbdb0e49..ddcacfd26 100644 --- a/src/configreader.cpp +++ b/src/configreader.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ /* Taken from: diff --git a/src/dns.cpp b/src/dns.cpp index 29c3134f7..d295aabf0 100644 --- a/src/dns.cpp +++ b/src/dns.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -21,11 +22,13 @@ #include <netdb.h> #endif -DNSManager *DNSEngine = NULL; +using namespace DNS; + +Manager *DNS::Engine = NULL; Question::Question() { - this->type = DNS_QUERY_NONE; + this->type = QUERY_NONE; this->qclass = 0; } @@ -45,22 +48,22 @@ ResourceRecord::ResourceRecord(const Question &q) : Question(q) this->created = Anope::CurTime; } -DNSQuery::DNSQuery() +Query::Query() { - this->error = DNS_ERROR_NONE; + this->error = ERROR_NONE; } -DNSQuery::DNSQuery(const Question &q) +Query::Query(const Question &q) { this->questions.push_back(q); - this->error = DNS_ERROR_NONE; + this->error = ERROR_NONE; } -DNSRequest::DNSRequest(const Anope::string &addr, QueryType qt, bool cache, Module *c) : Timer(Config->DNSTimeout), Question(addr, qt), use_cache(cache), id(0), creator(c) +Request::Request(const Anope::string &addr, QueryType qt, bool cache, Module *c) : Timer(Config->DNSTimeout), Question(addr, qt), use_cache(cache), id(0), creator(c) { - if (!DNSEngine || !DNSEngine->udpsock) - throw SocketException("No DNSEngine"); - if (DNSEngine->udpsock->GetPackets().size() == 65535) + if (!DNS::Engine || !DNS::Engine->udpsock) + throw SocketException("No DNS::Engine"); + if (DNS::Engine->udpsock->GetPackets().size() == 65535) throw SocketException("DNS queue full"); do @@ -68,51 +71,51 @@ DNSRequest::DNSRequest(const Anope::string &addr, QueryType qt, bool cache, Modu static unsigned short cur_id = rand(); this->id = cur_id++; } - while (DNSEngine->requests.count(this->id)); + while (DNS::Engine->requests.count(this->id)); - DNSEngine->requests[this->id] = this; + DNS::Engine->requests[this->id] = this; } -DNSRequest::~DNSRequest() +Request::~Request() { - DNSEngine->requests.erase(this->id); + DNS::Engine->requests.erase(this->id); } -void DNSRequest::Process() +void Request::Process() { Log(LOG_DEBUG_2) << "Resolver: Processing request to lookup " << this->name << ", of type " << this->type; - if (!DNSEngine || !DNSEngine->udpsock) - throw SocketException("DNSEngine has not been initialized"); + if (!DNS::Engine || !DNS::Engine->udpsock) + throw SocketException("DNS::Engine has not been initialized"); - if (this->use_cache && DNSEngine->CheckCache(this)) + if (this->use_cache && DNS::Engine->CheckCache(this)) { Log(LOG_DEBUG_2) << "Resolver: Using cached result"; delete this; return; } - DNSPacket *p = new DNSPacket(&DNSEngine->addrs); - p->flags = DNS_QUERYFLAGS_RD; + Packet *p = new Packet(&DNS::Engine->addrs); + p->flags = QUERYFLAGS_RD; p->id = this->id; p->questions.push_back(*this); - DNSEngine->udpsock->Reply(p); + DNS::Engine->udpsock->Reply(p); } -void DNSRequest::OnError(const DNSQuery *r) +void Request::OnError(const Query *r) { } -void DNSRequest::Tick(time_t) +void Request::Tick(time_t) { Log(LOG_DEBUG_2) << "Resolver: timeout for query " << this->name; - DNSQuery rr(*this); - rr.error = DNS_ERROR_TIMEOUT; + Query rr(*this); + rr.error = ERROR_TIMEOUT; this->OnError(&rr); } -void DNSPacket::PackName(unsigned char *output, unsigned short output_size, unsigned short &pos, const Anope::string &name) +void Packet::PackName(unsigned char *output, unsigned short output_size, unsigned short &pos, const Anope::string &name) { if (name.length() + 2 > output_size) throw SocketException("Unable to pack name"); @@ -132,7 +135,7 @@ void DNSPacket::PackName(unsigned char *output, unsigned short output_size, unsi output[pos++] = 0; } -Anope::string DNSPacket::UnpackName(const unsigned char *input, unsigned short input_size, unsigned short &pos) +Anope::string Packet::UnpackName(const unsigned char *input, unsigned short input_size, unsigned short &pos) { Anope::string name; unsigned short pos_ptr = pos, lowest_ptr = input_size; @@ -145,9 +148,9 @@ Anope::string DNSPacket::UnpackName(const unsigned char *input, unsigned short i { unsigned short offset = input[pos_ptr]; - if (offset & DNS_POINTER) + if (offset & POINTER) { - if ((offset & DNS_POINTER) != DNS_POINTER) + if ((offset & POINTER) != POINTER) throw SocketException("Unable to unpack name - bogus compression header"); if (pos_ptr + 1 >= input_size) throw SocketException("Unable to unpack name - bogus compression header"); @@ -159,7 +162,7 @@ Anope::string DNSPacket::UnpackName(const unsigned char *input, unsigned short i compressed = true; } - pos_ptr = (offset & DNS_LABEL) << 8 | input[pos_ptr + 1]; + pos_ptr = (offset & LABEL) << 8 | input[pos_ptr + 1]; /* Pointers can only go back */ if (pos_ptr >= lowest_ptr) @@ -190,7 +193,7 @@ Anope::string DNSPacket::UnpackName(const unsigned char *input, unsigned short i return name; } -Question DNSPacket::UnpackQuestion(const unsigned char *input, unsigned short input_size, unsigned short &pos) +Question Packet::UnpackQuestion(const unsigned char *input, unsigned short input_size, unsigned short &pos) { Question question; @@ -208,7 +211,7 @@ Question DNSPacket::UnpackQuestion(const unsigned char *input, unsigned short in return question; } -ResourceRecord DNSPacket::UnpackResourceRecord(const unsigned char *input, unsigned short input_size, unsigned short &pos) +ResourceRecord Packet::UnpackResourceRecord(const unsigned char *input, unsigned short input_size, unsigned short &pos) { ResourceRecord record = static_cast<ResourceRecord>(this->UnpackQuestion(input, input_size, pos)); @@ -223,7 +226,7 @@ ResourceRecord DNSPacket::UnpackResourceRecord(const unsigned char *input, unsig switch (record.type) { - case DNS_QUERY_A: + case QUERY_A: { if (pos + 4 > input_size) throw SocketException("Unable to unpack resource record"); @@ -238,7 +241,7 @@ ResourceRecord DNSPacket::UnpackResourceRecord(const unsigned char *input, unsig record.rdata = addrs.addr(); break; } - case DNS_QUERY_AAAA: + case QUERY_AAAA: { if (pos + 16 > input_size) throw SocketException("Unable to unpack resource record"); @@ -254,8 +257,8 @@ ResourceRecord DNSPacket::UnpackResourceRecord(const unsigned char *input, unsig record.rdata = addrs.addr(); break; } - case DNS_QUERY_CNAME: - case DNS_QUERY_PTR: + case QUERY_CNAME: + case QUERY_PTR: { record.rdata = this->UnpackName(input, input_size, pos); break; @@ -269,15 +272,15 @@ ResourceRecord DNSPacket::UnpackResourceRecord(const unsigned char *input, unsig return record; } -DNSPacket::DNSPacket(sockaddrs *a) : DNSQuery(), id(0), flags(0) +Packet::Packet(sockaddrs *a) : Query(), id(0), flags(0) { if (a) addr = *a; } -void DNSPacket::Fill(const unsigned char *input, const unsigned short len) +void Packet::Fill(const unsigned char *input, const unsigned short len) { - if (len < DNSPacket::HEADER_LENGTH) + if (len < Packet::HEADER_LENGTH) throw SocketException("Unable to fill packet"); unsigned short packet_pos = 0; @@ -315,9 +318,9 @@ void DNSPacket::Fill(const unsigned char *input, const unsigned short len) this->additional.push_back(this->UnpackResourceRecord(input, len, packet_pos)); } -unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size) +unsigned short Packet::Pack(unsigned char *output, unsigned short output_size) { - if (output_size < DNSPacket::HEADER_LENGTH) + if (output_size < Packet::HEADER_LENGTH) throw SocketException("Unable to pack packet"); unsigned short pos = 0; @@ -339,7 +342,7 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size { Question &q = this->questions[i]; - if (q.type == DNS_QUERY_PTR) + if (q.type == QUERY_PTR) { sockaddrs ip(q.name); @@ -411,7 +414,7 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size switch (rr.type) { - case DNS_QUERY_A: + case QUERY_A: { if (pos + 6 > output_size) throw SocketException("Unable to pack packet"); @@ -426,7 +429,7 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size pos += 4; break; } - case DNS_QUERY_AAAA: + case QUERY_AAAA: { if (pos + 18 > output_size) throw SocketException("Unable to pack packet"); @@ -441,9 +444,9 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size pos += 16; break; } - case DNS_QUERY_NS: - case DNS_QUERY_CNAME: - case DNS_QUERY_PTR: + case QUERY_NS: + case QUERY_CNAME: + case QUERY_PTR: { if (pos + 2 >= output_size) throw SocketException("Unable to pack packet"); @@ -457,7 +460,7 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size memcpy(&output[packet_pos_save], &s, 2); break; } - case DNS_QUERY_SOA: + case QUERY_SOA: { if (pos + 2 >= output_size) throw SocketException("Unable to pack packet"); @@ -471,7 +474,7 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size if (pos + 20 >= output_size) throw SocketException("Unable to pack SOA"); - l = htonl(DNSEngine->GetSerial()); + l = htonl(DNS::Engine->GetSerial()); memcpy(&output[pos], &l, 4); pos += 4; @@ -504,25 +507,25 @@ unsigned short DNSPacket::Pack(unsigned char *output, unsigned short output_size return pos; } -DNSManager::TCPSocket::Client::Client(TCPSocket *ls, int fd, const sockaddrs &addr) : Socket(fd, ls->IsIPv6()), ClientSocket(ls, addr), Timer(5), tcpsock(ls), packet(NULL), length(0) +Manager::TCPSocket::Client::Client(TCPSocket *l, int fd, const sockaddrs &addr) : Socket(fd, l->IsIPv6()), ClientSocket(l, addr), Timer(5), tcpsock(l), packet(NULL), length(0) { Log(LOG_DEBUG_2) << "Resolver: New client from " << addr.addr(); } -DNSManager::TCPSocket::Client::~Client() +Manager::TCPSocket::Client::~Client() { Log(LOG_DEBUG_2) << "Resolver: Exiting client from " << clientaddr.addr(); delete packet; } -void DNSManager::TCPSocket::Client::Reply(DNSPacket *p) +void Manager::TCPSocket::Client::Reply(Packet *p) { delete packet; packet = p; SocketEngine::Change(this, true, SF_WRITABLE); } -bool DNSManager::TCPSocket::Client::ProcessRead() +bool Manager::TCPSocket::Client::ProcessRead() { Log(LOG_DEBUG_2) << "Resolver: Reading from DNS TCP socket"; @@ -536,12 +539,12 @@ bool DNSManager::TCPSocket::Client::ProcessRead() if (length >= want_len - 2) { SocketEngine::Change(this, false, SF_READABLE); - return DNSEngine->HandlePacket(this, packet_buffer + 2, length - 2, NULL); + return DNS::Engine->HandlePacket(this, packet_buffer + 2, length - 2, NULL); } return true; } -bool DNSManager::TCPSocket::Client::ProcessWrite() +bool Manager::TCPSocket::Client::ProcessWrite() { Log(LOG_DEBUG_2) << "Resolver: Writing to DNS TCP socket"; @@ -568,32 +571,32 @@ bool DNSManager::TCPSocket::Client::ProcessWrite() return true; /* Do not return false here, bind is unhappy we close the connection so soon after sending */ } -DNSManager::TCPSocket::TCPSocket(const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos), ListenSocket(ip, port, ip.find(':') != Anope::string::npos) +Manager::TCPSocket::TCPSocket(const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos), ListenSocket(ip, port, ip.find(':') != Anope::string::npos) { } -ClientSocket *DNSManager::TCPSocket::OnAccept(int fd, const sockaddrs &addr) +ClientSocket *Manager::TCPSocket::OnAccept(int fd, const sockaddrs &addr) { return new Client(this, fd, addr); } -DNSManager::UDPSocket::UDPSocket(const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos, SOCK_DGRAM) +Manager::UDPSocket::UDPSocket(const Anope::string &ip, int port) : Socket(-1, ip.find(':') != Anope::string::npos, SOCK_DGRAM) { } -DNSManager::UDPSocket::~UDPSocket() +Manager::UDPSocket::~UDPSocket() { for (unsigned i = 0; i < packets.size(); ++i) delete packets[i]; } -void DNSManager::UDPSocket::Reply(DNSPacket *p) +void Manager::UDPSocket::Reply(Packet *p) { packets.push_back(p); SocketEngine::Change(this, true, SF_WRITABLE); } -bool DNSManager::UDPSocket::ProcessRead() +bool Manager::UDPSocket::ProcessRead() { Log(LOG_DEBUG_2) << "Resolver: Reading from DNS UDP socket"; @@ -601,14 +604,14 @@ bool DNSManager::UDPSocket::ProcessRead() sockaddrs from_server; socklen_t x = sizeof(from_server); int length = recvfrom(this->GetFD(), reinterpret_cast<char *>(&packet_buffer), sizeof(packet_buffer), 0, &from_server.sa, &x); - return DNSEngine->HandlePacket(this, packet_buffer, length, &from_server); + return DNS::Engine->HandlePacket(this, packet_buffer, length, &from_server); } -bool DNSManager::UDPSocket::ProcessWrite() +bool Manager::UDPSocket::ProcessWrite() { Log(LOG_DEBUG_2) << "Resolver: Writing to DNS UDP socket"; - DNSPacket *r = !packets.empty() ? packets.front() : NULL; + Packet *r = !packets.empty() ? packets.front() : NULL; if (r != NULL) { try @@ -630,7 +633,7 @@ bool DNSManager::UDPSocket::ProcessWrite() return true; } -DNSManager::DNSManager(const Anope::string &nameserver, const Anope::string &ip, int port) : Timer(300, Anope::CurTime, true), listen(false), serial(0), tcpsock(NULL), udpsock(NULL) +Manager::Manager(const Anope::string &nameserver, const Anope::string &ip, int port) : Timer(300, Anope::CurTime, true), listen(false), serial(0), tcpsock(NULL), udpsock(NULL) { this->addrs.pton(nameserver.find(':') != Anope::string::npos ? AF_INET6 : AF_INET, nameserver, port); @@ -640,7 +643,7 @@ DNSManager::DNSManager(const Anope::string &nameserver, const Anope::string &ip, } catch (const SocketException &ex) { - Log() << "Unable to create socket for DNSManager: " << ex.GetReason(); + Log() << "Unable to create socket for Manager: " << ex.GetReason(); } try @@ -652,23 +655,23 @@ DNSManager::DNSManager(const Anope::string &nameserver, const Anope::string &ip, catch (const SocketException &ex) { /* This error can be from normal operation as most people don't use services to handle DNS queries, so put it in debug log */ - Log(LOG_DEBUG) << "Unable to bind DNSManager to port " << port << ": " << ex.GetReason(); + Log(LOG_DEBUG) << "Unable to bind Manager to port " << port << ": " << ex.GetReason(); } this->UpdateSerial(); } -DNSManager::~DNSManager() +Manager::~Manager() { delete udpsock; delete tcpsock; - for (std::map<unsigned short, DNSRequest *>::iterator it = this->requests.begin(), it_end = this->requests.end(); it != it_end; ++it) + for (std::map<unsigned short, Request *>::iterator it = this->requests.begin(), it_end = this->requests.end(); it != it_end; ++it) { - DNSRequest *request = it->second; + Request *request = it->second; - DNSQuery rr(*request); - rr.error = DNS_ERROR_UNKNOWN; + Query rr(*request); + rr.error = ERROR_UNKNOWN; request->OnError(&rr); delete request; @@ -677,15 +680,15 @@ DNSManager::~DNSManager() this->cache.clear(); - DNSEngine = NULL; + DNS::Engine = NULL; } -bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_buffer, int length, sockaddrs *from) +bool Manager::HandlePacket(ReplySocket *s, const unsigned char *const packet_buffer, int length, sockaddrs *from) { - if (length < DNSPacket::HEADER_LENGTH) + if (length < Packet::HEADER_LENGTH) return true; - DNSPacket recv_packet(from); + Packet recv_packet(from); try { @@ -697,7 +700,7 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ return true; } - if (!(recv_packet.flags & DNS_QUERYFLAGS_QR)) + if (!(recv_packet.flags & QUERYFLAGS_QR)) { if (!listen) return true; @@ -707,9 +710,9 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ return true; } - DNSPacket *packet = new DNSPacket(recv_packet); - packet->flags |= DNS_QUERYFLAGS_QR; /* This is a reponse */ - packet->flags |= DNS_QUERYFLAGS_AA; /* And we are authoritative */ + Packet *packet = new Packet(recv_packet); + packet->flags |= QUERYFLAGS_QR; /* This is a reponse */ + packet->flags |= QUERYFLAGS_AA; /* And we are authoritative */ packet->answers.clear(); packet->authorities.clear(); @@ -719,14 +722,14 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ { const Question& q = recv_packet.questions[i]; - if (q.type == DNS_QUERY_AXFR || q.type == DNS_QUERY_SOA) + if (q.type == QUERY_AXFR || q.type == QUERY_SOA) { - ResourceRecord rr(q.name, DNS_QUERY_SOA); + ResourceRecord rr(q.name, QUERY_SOA); packet->answers.push_back(rr); - if (q.type == DNS_QUERY_AXFR) + if (q.type == QUERY_AXFR) { - ResourceRecord rr2(q.name, DNS_QUERY_NS); + ResourceRecord rr2(q.name, QUERY_NS); rr2.rdata = Config->DNSSOANS; packet->answers.push_back(rr2); } @@ -740,9 +743,9 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ { const Question& q = recv_packet.questions[i]; - if (q.type == DNS_QUERY_AXFR) + if (q.type == QUERY_AXFR) { - ResourceRecord rr(q.name, DNS_QUERY_SOA); + ResourceRecord rr(q.name, QUERY_SOA); packet->answers.push_back(rr); break; } @@ -763,45 +766,45 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ return true; } - std::map<unsigned short, DNSRequest *>::iterator it = DNSEngine->requests.find(recv_packet.id); - if (it == DNSEngine->requests.end()) + std::map<unsigned short, Request *>::iterator it = DNS::Engine->requests.find(recv_packet.id); + if (it == DNS::Engine->requests.end()) { Log(LOG_DEBUG_2) << "Resolver: Received an answer for something we didn't request"; return true; } - DNSRequest *request = it->second; + Request *request = it->second; - if (recv_packet.flags & DNS_QUERYFLAGS_OPCODE) + if (recv_packet.flags & QUERYFLAGS_OPCODE) { Log(LOG_DEBUG_2) << "Resolver: Received a nonstandard query"; - recv_packet.error = DNS_ERROR_NONSTANDARD_QUERY; + recv_packet.error = ERROR_NONSTANDARD_QUERY; request->OnError(&recv_packet); } - else if (recv_packet.flags & DNS_QUERYFLAGS_RCODE) + else if (recv_packet.flags & QUERYFLAGS_RCODE) { - DNSError error = DNS_ERROR_UNKNOWN; + Error error = ERROR_UNKNOWN; - switch (recv_packet.flags & DNS_QUERYFLAGS_RCODE) + switch (recv_packet.flags & QUERYFLAGS_RCODE) { case 1: Log(LOG_DEBUG_2) << "Resolver: format error"; - error = DNS_ERROR_FORMAT_ERROR; + error = ERROR_FORMAT_ERROR; break; case 2: Log(LOG_DEBUG_2) << "Resolver: server error"; - error = DNS_ERROR_SERVER_FAILURE; + error = ERROR_SERVER_FAILURE; break; case 3: Log(LOG_DEBUG_2) << "Resolver: domain not found"; - error = DNS_ERROR_DOMAIN_NOT_FOUND; + error = ERROR_DOMAIN_NOT_FOUND; break; case 4: Log(LOG_DEBUG_2) << "Resolver: not implemented"; - error = DNS_ERROR_NOT_IMPLEMENTED; + error = ERROR_NOT_IMPLEMENTED; break; case 5: Log(LOG_DEBUG_2) << "Resolver: refused"; - error = DNS_ERROR_REFUSED; + error = ERROR_REFUSED; break; default: break; @@ -813,21 +816,21 @@ bool DNSManager::HandlePacket(ReplySocket *s, const unsigned char *const packet_ else if (recv_packet.answers.empty()) { Log(LOG_DEBUG_2) << "Resolver: No resource records returned"; - recv_packet.error = DNS_ERROR_NO_RECORDS; + recv_packet.error = ERROR_NO_RECORDS; request->OnError(&recv_packet); } else { Log(LOG_DEBUG_2) << "Resolver: Lookup complete for " << request->name; request->OnLookupComplete(&recv_packet); - DNSEngine->AddCache(recv_packet); + DNS::Engine->AddCache(recv_packet); } delete request; return true; } -void DNSManager::AddCache(DNSQuery &r) +void Manager::AddCache(Query &r) { for (unsigned i = 0; i < r.answers.size(); ++i) { @@ -837,12 +840,12 @@ void DNSManager::AddCache(DNSQuery &r) } } -bool DNSManager::CheckCache(DNSRequest *request) +bool Manager::CheckCache(Request *request) { cache_map::iterator it = this->cache.find(request->name); if (it != this->cache.end()) { - DNSQuery record(*request); + Query record(*request); for (cache_map::iterator it_end = this->cache.upper_bound(request->name); it != it_end; ++it) { @@ -862,7 +865,7 @@ bool DNSManager::CheckCache(DNSRequest *request) return false; } -void DNSManager::Tick(time_t now) +void Manager::Tick(time_t now) { Log(LOG_DEBUG_2) << "Resolver: Purging DNS cache"; @@ -877,18 +880,18 @@ void DNSManager::Tick(time_t now) } } -void DNSManager::Cleanup(Module *mod) +void Manager::Cleanup(Module *mod) { - for (std::map<unsigned short, DNSRequest *>::iterator it = this->requests.begin(), it_end = this->requests.end(); it != it_end;) + for (std::map<unsigned short, Request *>::iterator it = this->requests.begin(), it_end = this->requests.end(); it != it_end;) { unsigned short id = it->first; - DNSRequest *req = it->second; + Request *req = it->second; ++it; if (req->creator && req->creator == mod) { - DNSQuery rr(*req); - rr.error = DNS_ERROR_UNLOADED; + Query rr(*req); + rr.error = ERROR_UNLOADED; req->OnError(&rr); delete req; @@ -897,25 +900,25 @@ void DNSManager::Cleanup(Module *mod) } } -void DNSManager::UpdateSerial() +void Manager::UpdateSerial() { serial = Anope::CurTime; } -uint32_t DNSManager::GetSerial() const +uint32_t Manager::GetSerial() const { return serial; } -DNSQuery DNSManager::BlockingQuery(const Anope::string &mask, QueryType qt) +Query Manager::BlockingQuery(const Anope::string &mask, QueryType qt) { Question question(mask, qt); - DNSQuery result(question); + Query result(question); int type = AF_UNSPEC; - if (qt == DNS_QUERY_A) + if (qt == QUERY_A) type = AF_INET; - else if (qt == DNS_QUERY_AAAA) + else if (qt == QUERY_AAAA) type = AF_INET6; addrinfo hints; diff --git a/src/encrypt.cpp b/src/encrypt.cpp index 154f600bf..0227be2ef 100644 --- a/src/encrypt.cpp +++ b/src/encrypt.cpp @@ -1,4 +1,4 @@ -/* Include file for high-level encryption routines. +/* * * (C) 2003-2012 Anope Team * Contact us at team@anope.org @@ -7,11 +7,11 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "modules.h" -#include "extern.h" /******************************************************************************/ @@ -19,7 +19,7 @@ * @param src The source string * @param dest The destination strnig */ -void enc_encrypt(const Anope::string &src, Anope::string &dest) +void Anope::Encrypt(const Anope::string &src, Anope::string &dest) { EventReturn MOD_RESULT; FOREACH_RESULT(I_OnEncrypt, OnEncrypt(src, dest)); @@ -30,12 +30,12 @@ void enc_encrypt(const Anope::string &src, Anope::string &dest) * @param desc The destination string * @return true on success */ -bool enc_decrypt(const Anope::string &src, Anope::string &dest) +bool Anope::Decrypt(const Anope::string &src, Anope::string &dest) { size_t pos = src.find(':'); if (pos == Anope::string::npos) { - Log() << "Error: enc_decrypt() called with invalid password string (" << src << ")"; + Log() << "Error: Anope::Decrypt() called with invalid password string (" << src << ")"; return false; } Anope::string hashm(src.begin(), src.begin() + pos); diff --git a/src/hashcomp.cpp b/src/hashcomp.cpp index 7ce28df13..2875a52df 100644 --- a/src/hashcomp.cpp +++ b/src/hashcomp.cpp @@ -1,11 +1,10 @@ /* + * * Copyright (C) 2002-2011 InspIRCd Development Team * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. * - * These classes have been copied from InspIRCd and modified - * for use in Anope. */ #include "services.h" @@ -70,11 +69,6 @@ const char *ci::ci_char_traits::find(const char *s1, int n, char c) return n >= 0 ? s1 : NULL; } -/** Compare two Anope::strings as ci::strings and find which one is less - * @param s1 The first string - * @param s2 The second string - * @return true if s1 < s2, else false - */ bool ci::less::operator()(const Anope::string &s1, const Anope::string &s2) const { return s1.ci_str().compare(s2.ci_str()) < 0; @@ -111,6 +105,34 @@ bool sepstream::GetToken(Anope::string &token) return false; } +bool sepstream::GetToken(Anope::string &token, int num) +{ + int i; + for (i = 0; i < num + 1 && !this->GetToken(token); ++i); + return i == num + 1; +} + +int sepstream::NumTokens() +{ + int i; + Anope::string token; + for (i = 0; this->GetToken(token); ++i); + return i; +} + +bool sepstream::GetTokenRemainder(Anope::string &token, int num) +{ + if (this->GetToken(token, num)) + { + if (!this->StreamEnd()) + token += sep + this->GetRemaining(); + + return true; + } + + return false; +} + const Anope::string sepstream::GetRemaining() { return Anope::string(n, tokens.end()); diff --git a/src/init.cpp b/src/init.cpp index 94ac7feb2..e831351ec 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -7,64 +7,26 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "config.h" -#include "extern.h" #include "users.h" #include "protocol.h" #include "bots.h" -#include "oper.h" +#include "xline.h" #include "signals.h" #include "socketengine.h" #include "servers.h" +#include "language.h" #ifndef _WIN32 #include <sys/wait.h> #include <sys/stat.h> #endif -Anope::string conf_dir = "conf", db_dir = "data", modules_dir = "lib", locale_dir = "locale", log_dir = "logs"; - -ServerConfig::Uplink *uplink_server; - -void introduce_user(const Anope::string &user) -{ - /* Watch out for infinite loops... */ - time_t now = Anope::CurTime; - static time_t lasttime = now - 4; - if (lasttime >= now - 3) - { - quitmsg = "introduce_user loop detected"; - quitting = true; - return; - } - lasttime = now; - - User *u = finduser(user); - if (u) - { - BotInfo *bi = findbot(u->nick); - if (bi) - { - XLine x(bi->nick, "Reserved for services"); - ircdproto->SendSQLine(NULL, &x); - } - - ircdproto->SendClientIntroduction(u); - - if (bi) - { - bi->introduced = true; - - for (UChannelList::const_iterator cit = bi->chans.begin(), cit_end = bi->chans.end(); cit != cit_end; ++cit) - ircdproto->SendJoin(bi, (*cit)->chan, &Config->BotModeList); - } - } -} - -/*************************************************************************/ +Anope::string Anope::ConfigDir = "conf", Anope::DataDir = "data", Anope::ModuleDir = "lib", Anope::LocaleDir = "locale", Anope::LogDir = "logs"; /* Vector of pairs of command line arguments and their params */ static std::vector<std::pair<Anope::string, Anope::string> > CommandLineArguments; @@ -96,24 +58,13 @@ static void ParseCommandLineArguments(int ac, char **av) } } -/** Check if an argument was given on startup - * @param name The argument name - * @param shortname A shorter name, eg --debug and -d - * @return true if name/shortname was found, false if not - */ -bool GetCommandLineArgument(const Anope::string &name, char shortname) -{ - Anope::string Unused; - return GetCommandLineArgument(name, shortname, Unused); -} - /** Check if an argument was given on startup and its parameter * @param name The argument name * @param shortname A shorter name, eg --debug and -d * @param param A string to put the param, if any, of the argument * @return true if name/shortname was found, false if not */ -bool GetCommandLineArgument(const Anope::string &name, char shortname, Anope::string ¶m) +static bool GetCommandLineArgument(const Anope::string &name, char shortname, Anope::string ¶m) { param.clear(); @@ -129,6 +80,17 @@ bool GetCommandLineArgument(const Anope::string &name, char shortname, Anope::st return false; } +/** Check if an argument was given on startup + * @param name The argument name + * @param shortname A shorter name, eg --debug and -d + * @return true if name/shortname was found, false if not + */ +static bool GetCommandLineArgument(const Anope::string &name, char shortname = 0) +{ + Anope::string Unused; + return GetCommandLineArgument(name, shortname, Unused); +} + /*************************************************************************/ /* Remove our PID file. Done at exit. */ @@ -156,7 +118,7 @@ static void write_pidfile() atexit(remove_pidfile); } else - throw FatalException("Can not write to PID file " + Config->PIDFilename); + throw CoreException("Can not write to PID file " + Config->PIDFilename); } /*************************************************************************/ @@ -170,7 +132,7 @@ class SignalReload : public Signal { Log() << "Received SIGHUP: Saving databases & rehashing configuration"; - save_databases(); + Anope::SaveDatabases(); ServerConfig *old_config = Config; try @@ -196,14 +158,13 @@ class SignalExit : public Signal { #ifndef _WIN32 Log() << "Received " << strsignal(this->signal) << " signal (" << this->signal << "), exiting."; - quitmsg = Anope::string("Services terminating via signal ") + strsignal(this->signal) + " (" + stringify(this->signal) + ")"; + Anope::QuitReason = Anope::string("Services terminating via signal ") + strsignal(this->signal) + " (" + stringify(this->signal) + ")"; #else Log() << "Received signal " << this->signal << ", exiting."; - quitmsg = Anope::string("Services terminating via signal ") + stringify(this->signal); + Anope::QuitReason = Anope::string("Services terminating via signal ") + stringify(this->signal); #endif - - quitting = true; - save_databases(); + Anope::SaveDatabases(); + Anope::Quitting = true; } }; @@ -215,12 +176,12 @@ class SignalNothing : public Signal void OnNotify() { } }; -bool AtTerm() +bool Anope::AtTerm() { return isatty(fileno(stdout)) && isatty(fileno(stdin)) && isatty(fileno(stderr)); } -void Fork() +void Anope::Fork() { #ifndef _WIN32 kill(getppid(), SIGUSR2); @@ -240,29 +201,28 @@ static void parent_signal_handler(int signal) { if (signal == SIGUSR2) { - quitting = true; - return_code = 0; + Anope::Quitting = true; } else if (signal == SIGCHLD) { - quitting = true; - return_code = -1; + Anope::ReturnValue = -1; + Anope::Quitting = true; int status = 0; wait(&status); if (WIFEXITED(status)) - return_code = WEXITSTATUS(status); + Anope::ReturnValue = WEXITSTATUS(status); } } #endif -void Init(int ac, char **av) +void Anope::Init(int ac, char **av) { /* Set file creation mask and group ID. */ #if defined(DEFUMASK) && HAVE_UMASK umask(DEFUMASK); #endif - RegisterTypes(); + Serialize::RegisterTypes(); /* Parse command line arguments */ ParseCommandLineArguments(ac, av); @@ -270,14 +230,14 @@ void Init(int ac, char **av) if (GetCommandLineArgument("version", 'v')) { Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString(); - throw FatalException(); + throw CoreException(); } if (GetCommandLineArgument("help", 'h')) { Log(LOG_TERMINAL) << "Anope-" << Anope::Version() << " -- " << Anope::VersionBuildString(); Log(LOG_TERMINAL) << "Anope IRC Services (http://www.anope.org)"; - Log(LOG_TERMINAL) << "Usage ./" << services_bin << " [options] ..."; + Log(LOG_TERMINAL) << "Usage ./" << Anope::ServicesBin << " [options] ..."; Log(LOG_TERMINAL) << "-c, --config=filename.conf"; Log(LOG_TERMINAL) << " --confdir=conf file direcory"; Log(LOG_TERMINAL) << " --dbdir=database directory"; @@ -296,98 +256,98 @@ void Init(int ac, char **av) Log(LOG_TERMINAL) << ""; Log(LOG_TERMINAL) << "Further support is available from http://www.anope.org"; Log(LOG_TERMINAL) << "Or visit us on IRC at irc.anope.org #anope"; - throw FatalException(); + throw CoreException(); } if (GetCommandLineArgument("nofork", 'n')) - nofork = true; + Anope::NoFork = true; if (GetCommandLineArgument("support", 's')) { - nofork = nothird = true; - ++debug; + Anope::NoFork = Anope::NoThird = true; + ++Anope::Debug; } if (GetCommandLineArgument("readonly", 'r')) - readonly = true; + Anope::ReadOnly = true; if (GetCommandLineArgument("nothird")) - nothird = true; + Anope::NoThird = true; if (GetCommandLineArgument("noexpire", 'e')) - noexpire = true; + Anope::NoExpire = true; if (GetCommandLineArgument("protocoldebug")) - protocoldebug = true; + Anope::ProtocolDebug = true; - Anope::string Arg; - if (GetCommandLineArgument("debug", 'd', Arg)) + Anope::string arg; + if (GetCommandLineArgument("debug", 'd', arg)) { - if (!Arg.empty()) + if (!arg.empty()) { - int level = Arg.is_number_only() ? convertTo<int>(Arg) : -1; + int level = arg.is_number_only() ? convertTo<int>(arg) : -1; if (level > 0) - debug = level; + Anope::Debug = level; else - throw FatalException("Invalid option given to --debug"); + throw CoreException("Invalid option given to --debug"); } else - ++debug; + ++Anope::Debug; } - if (GetCommandLineArgument("config", 'c', Arg)) + if (GetCommandLineArgument("config", 'c', arg)) { - if (Arg.empty()) - throw FatalException("The --config option requires a file name"); - services_conf = ConfigurationFile(Arg, false); + if (arg.empty()) + throw CoreException("The --config option requires a file name"); + ServicesConf = ConfigurationFile(arg, false); } - if (GetCommandLineArgument("confdir", 0, Arg)) + if (GetCommandLineArgument("confdir", 0, arg)) { - if (Arg.empty()) - throw FatalException("The --confdir option requires a path"); - conf_dir = Arg; + if (arg.empty()) + throw CoreException("The --confdir option requires a path"); + Anope::ConfigDir = arg; } - if (GetCommandLineArgument("dbdir", 0, Arg)) + if (GetCommandLineArgument("dbdir", 0, arg)) { - if (Arg.empty()) - throw FatalException("The --dbdir option requires a path"); - db_dir = Arg; + if (arg.empty()) + throw CoreException("The --dbdir option requires a path"); + Anope::DataDir = arg; } - if (GetCommandLineArgument("localedir", 0, Arg)) + if (GetCommandLineArgument("localedir", 0, arg)) { - if (Arg.empty()) - throw FatalException("The --localedir option requires a path"); - locale_dir = Arg; + if (arg.empty()) + throw CoreException("The --localedir option requires a path"); + Anope::LocaleDir = arg; } - if (GetCommandLineArgument("modulesdir", 0, Arg)) + if (GetCommandLineArgument("modulesdir", 0, arg)) { - if (Arg.empty()) - throw FatalException("The --modulesdir option requires a path"); - modules_dir = Arg; + if (arg.empty()) + throw CoreException("The --modulesdir option requires a path"); + Anope::ModuleDir = arg; } - if (GetCommandLineArgument("logdir", 0, Arg)) + if (GetCommandLineArgument("logdir", 0, arg)) { - if (Arg.empty()) - throw FatalException("The --logdir option requires a path"); - log_dir = Arg; + if (arg.empty()) + throw CoreException("The --logdir option requires a path"); + Anope::LogDir = arg; } /* Chdir to Services data directory. */ - if (chdir(services_dir.c_str()) < 0) + if (chdir(Anope::ServicesDir.c_str()) < 0) { - throw FatalException("Unable to chdir to " + services_dir + ": " + Anope::LastError()); + throw CoreException("Unable to chdir to " + Anope::ServicesDir + ": " + Anope::LastError()); } Log(LOG_TERMINAL) << "Anope " << Anope::Version() << ", " << Anope::VersionBuildString(); #ifdef _WIN32 - Log(LOG_TERMINAL) << "Using configuration file " << conf_dir << "\\" << services_conf.GetName(); + Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "\\" << ServicesConf.GetName(); #else - Log(LOG_TERMINAL) << "Using configuration file " << conf_dir << "/" << services_conf.GetName(); + Log(LOG_TERMINAL) << "Using configuration file " << Anope::ConfigDir << "/" << ServicesConf.GetName(); #endif /* Initialize the socket engine */ @@ -405,12 +365,12 @@ void Init(int ac, char **av) Log(LOG_TERMINAL) << "*** documentation. Read the documentation files found in the 'docs'"; Log(LOG_TERMINAL) << "*** folder. Visit our portal located at http://www.anope.org/. Join"; Log(LOG_TERMINAL) << "*** our support channel on /server irc.anope.org channel #anope."; - throw FatalException("Configuration file failed to validate"); + throw CoreException("Configuration file failed to validate"); } #ifdef _WIN32 if (!SupportedWindowsVersion()) - throw FatalException(GetWindowsVersion() + " is not a supported version of Windows"); + throw CoreException(GetWindowsVersion() + " is not a supported version of Windows"); #else /* If we're root, issue a warning now */ if (!getuid() && !getgid()) @@ -421,7 +381,7 @@ void Init(int ac, char **av) sleep(3); } - if (!nofork && AtTerm()) + if (!Anope::NoFork && Anope::AtTerm()) { /* Install these before fork() - it is possible for the child to * connect and kill() the parent before it is able to install the @@ -444,12 +404,12 @@ void Init(int ac, char **av) sigemptyset(&mask); sigsuspend(&mask); - exit(return_code); + exit(Anope::ReturnValue); } else if (i == -1) { Log() << "Error, unable to fork: " << Anope::LastError(); - nofork = true; + Anope::NoFork = true; } /* Child doesn't need these */ @@ -466,11 +426,11 @@ void Init(int ac, char **av) for (botinfo_map::const_iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) { it->second->server = Me; - ++Me->Users; + ++Me->users; } /* Announce ourselves to the logfile. */ - Log() << "Anope " << Anope::Version() << " starting up" << (debug || readonly ? " (options:" : "") << (debug ? " debug" : "") << (readonly ? " readonly" : "") << (debug || readonly ? ")" : ""); + Log() << "Anope " << Anope::Version() << " starting up" << (Anope::Debug || Anope::ReadOnly ? " (options:" : "") << (Anope::Debug ? " debug" : "") << (Anope::ReadOnly ? " readonly" : "") << (Anope::Debug || Anope::ReadOnly ? ")" : ""); new SignalReload(SIGHUP); new SignalExit(SIGTERM); @@ -478,8 +438,7 @@ void Init(int ac, char **av) new SignalNothing(SIGPIPE); /* Initialize multi-language support */ - Log(LOG_DEBUG) << "Loading Languages..."; - InitLanguages(); + Language::InitLanguages(); /* Initialize random number generator */ srand(Config->Seed); @@ -491,9 +450,9 @@ void Init(int ac, char **av) Module *protocol = ModuleManager::FindFirstOf(PROTOCOL); if (protocol == NULL) - throw FatalException("You must load a protocol module!"); + throw CoreException("You must load a protocol module!"); else if (ModuleManager::FindFirstOf(ENCRYPTION) == NULL) - throw FatalException("You must load at least one encryption module"); + throw CoreException("You must load at least one encryption module"); Log() << "Using IRCd protocol " << protocol->name; diff --git a/src/language.cpp b/src/language.cpp index c62a950aa..1e1f9e704 100644 --- a/src/language.cpp +++ b/src/language.cpp @@ -7,65 +7,71 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "modules.h" #include "commands.h" #include "config.h" -#include "extern.h" +#include "language.h" #if GETTEXT_FOUND # include <libintl.h> #endif -std::vector<Anope::string> languages; -std::vector<Anope::string> domains; +std::vector<Anope::string> Language::Languages; +std::vector<Anope::string> Language::Domains; -void InitLanguages() +void Language::InitLanguages() { #if GETTEXT_FOUND - languages.clear(); + Log(LOG_DEBUG) << "Initializing Languages..."; + + Languages.clear(); spacesepstream sep(Config->Languages); Anope::string language; while (sep.GetToken(language)) { - if (!IsFile(locale_dir + "/" + language + "/LC_MESSAGES/anope.mo")) + if (!IsFile(Anope::LocaleDir + "/" + language + "/LC_MESSAGES/anope.mo")) { Log() << "Error loading language " << language << ", file does not exist!"; } else { Log(LOG_DEBUG) << "Found language file " << language; - languages.push_back(language); + Languages.push_back(language); } } - if (!bindtextdomain("anope", locale_dir.c_str())) + if (!bindtextdomain("anope", Anope::LocaleDir.c_str())) Log() << "Error calling bindtextdomain, " << Anope::LastError(); else - Log(LOG_DEBUG) << "Successfully bound anope to " << locale_dir; + Log(LOG_DEBUG) << "Successfully bound anope to " << Anope::LocaleDir; setlocale(LC_ALL, ""); #else - Log() << "Can not load languages, gettext is not installed"; + Log() << "Unable to initialize languages, gettext is not installed"; #endif } -const char *translate(const char *string) +const char *Language::Translate(const char *string) { - return anope_gettext(Config->NSDefLanguage.c_str(), string); + return Translate(Config->NSDefLanguage.c_str(), string); } -const char *translate(User *u, const char *string) +const char *Language::Translate(User *u, const char *string) { - return translate(u ? u->Account() : NULL, string); + if (u && u->Account()) + return Translate(u->Account(), string); + else + return Translate(string); } -const char *translate(const NickCore *nc, const char *string) +const char *Language::Translate(const NickCore *nc, const char *string) { - return anope_gettext(nc ? nc->language.c_str() : Config->NSDefLanguage.c_str(), string); + return Translate(nc ? nc->language.c_str() : Config->NSDefLanguage.c_str(), string); } #if GETTEXT_FOUND @@ -73,7 +79,7 @@ const char *translate(const NickCore *nc, const char *string) /* Used by gettext to make it always dynamically load language strings (so we can drop them in while Anope is running) */ extern "C" int _nl_msg_cat_cntr; -const char *anope_gettext(const char *lang, const char *string) +const char *Language::Translate(const char *lang, const char *string) { if (!string || !*string || !lang || !*lang) return string ? string : ""; @@ -95,8 +101,8 @@ const char *anope_gettext(const char *lang, const char *string) setlocale(LC_ALL, "en_US"); #endif const char *translated_string = dgettext("anope", string); - for (unsigned i = 0; translated_string == string && i < domains.size(); ++i) - translated_string = dgettext(domains[i].c_str(), string); + for (unsigned i = 0; translated_string == string && i < Domains.size(); ++i) + translated_string = dgettext(Domains[i].c_str(), string); #ifdef _WIN32 SetThreadLocale(MAKELCID(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT)); #else @@ -108,7 +114,7 @@ const char *anope_gettext(const char *lang, const char *string) return translated_string; } #else -const char *anope_gettext(const char *lang, const char *string) +const char *Language::Translate(const char *lang, const char *string) { return string != NULL ? string : ""; } diff --git a/src/logger.cpp b/src/logger.cpp index a76430435..f6058ab42 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -15,12 +16,14 @@ #include "channels.h" #include "users.h" #include "logger.h" -#include "extern.h" #include "config.h" #include "bots.h" #include "servers.h" #include "uplink.h" #include "protocol.h" +#include "global.h" +#include "operserv.h" +#include "chanserv.h" #ifndef _WIN32 #include <sys/time.h> @@ -33,9 +36,10 @@ static Anope::string GetTimeStamp() time_t t; if (time(&t) < 0) - throw CoreException("time() failed"); + t = Anope::CurTime; + tm tm = *localtime(&t); - if (debug) + if (Anope::Debug) { char *s; struct timeval tv; @@ -59,7 +63,7 @@ static inline Anope::string CreateLogName(const Anope::string &file, time_t t = strftime(timestamp, sizeof(timestamp), "%Y%m%d", tm); - return log_dir + "/" + file + "." + timestamp; + return Anope::LogDir + "/" + file + "." + timestamp; } LogFile::LogFile(const Anope::string &name) : filename(name), stream(name.c_str(), std::ios_base::out | std::ios_base::app) @@ -71,15 +75,15 @@ Anope::string LogFile::GetName() const return this->filename; } -Log::Log(LogType type, const Anope::string &category, const BotInfo *b) : bi(b), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), Type(type), Category(category) +Log::Log(LogType t, const Anope::string &cat, const BotInfo *b) : bi(b), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), type(t), category(cat) { if (!bi && Config) - bi = findbot(Config->Global); + bi = Global; if (bi) - this->Sources.push_back(bi->nick); + this->sources.push_back(bi->nick); } -Log::Log(LogType type, CommandSource &source, Command *_c, const ChannelInfo *_ci) : nick(source.GetNick()), u(source.GetUser()), nc(source.nc), c(_c), chan(NULL), ci(_ci), s(NULL), m(NULL), Type(type) +Log::Log(LogType t, CommandSource &source, Command *_c, const ChannelInfo *_ci) : nick(source.GetNick()), u(source.GetUser()), nc(source.nc), c(_c), chan(NULL), ci(_ci), s(NULL), m(NULL), type(t) { if (!c) throw CoreException("Invalid pointers passed to Log::Log"); @@ -90,81 +94,80 @@ Log::Log(LogType type, CommandSource &source, Command *_c, const ChannelInfo *_c size_t sl = c->name.find('/'); this->bi = NULL; if (sl != Anope::string::npos) - this->bi = findbot(c->name.substr(0, sl)); + this->bi = BotInfo::Find(c->name.substr(0, sl)); if (this->bi == NULL && Config) - this->bi = findbot(Config->Global); - this->Category = c->name; + this->bi = Global; + this->category = c->name; if (this->bi) - this->Sources.push_back(this->bi->nick); + this->sources.push_back(this->bi->nick); if (u) - this->Sources.push_back(u->nick); - this->Sources.push_back(c->name); + this->sources.push_back(u->nick); + this->sources.push_back(c->name); if (ci) - this->Sources.push_back(ci->name); + this->sources.push_back(ci->name); } -Log::Log(const User *_u, Channel *ch, const Anope::string &category) : bi(NULL), u(_u), nc(NULL), c(NULL), chan(ch), ci(chan ? *chan->ci : NULL), s(NULL), m(NULL), Type(LOG_CHANNEL) +Log::Log(const User *_u, Channel *ch, const Anope::string &cat) : bi(NULL), u(_u), nc(NULL), c(NULL), chan(ch), ci(chan ? *chan->ci : NULL), s(NULL), m(NULL), type(LOG_CHANNEL), category(cat) { if (!chan) throw CoreException("Invalid pointers passed to Log::Log"); if (Config) - this->bi = findbot(Config->ChanServ); - this->Category = category; + this->bi = ChanServ; if (this->bi) - this->Sources.push_back(this->bi->nick); + this->sources.push_back(this->bi->nick); if (u) - this->Sources.push_back(u->nick); - this->Sources.push_back(chan->name); + this->sources.push_back(u->nick); + this->sources.push_back(chan->name); } -Log::Log(const User *_u, const Anope::string &category, const BotInfo *_bi) : bi(_bi), u(_u), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(NULL), Type(LOG_USER), Category(category) +Log::Log(const User *_u, const Anope::string &cat, const BotInfo *_bi) : bi(_bi), u(_u), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(NULL), type(LOG_USER), category(cat) { if (!u) throw CoreException("Invalid pointers passed to Log::Log"); if (!this->bi && Config) - this->bi = findbot(Config->Global); + this->bi = Global; if (this->bi) - this->Sources.push_back(this->bi->nick); - this->Sources.push_back(u->nick); + this->sources.push_back(this->bi->nick); + this->sources.push_back(u->nick); } -Log::Log(Server *serv, const Anope::string &category, const BotInfo *_bi) : bi(_bi), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(serv), m(NULL), Type(LOG_SERVER), Category(category) +Log::Log(Server *serv, const Anope::string &cat, const BotInfo *_bi) : bi(_bi), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(serv), m(NULL), type(LOG_SERVER), category(cat) { if (!s) throw CoreException("Invalid pointer passed to Log::Log"); if (!this->bi && Config) - this->bi = findbot(Config->OperServ); + this->bi = OperServ; if (!this->bi && Config) - this->bi = findbot(Config->Global); + this->bi = Global; if (this->bi) - this->Sources.push_back(this->bi->nick); - this->Sources.push_back(s->GetName()); + this->sources.push_back(this->bi->nick); + this->sources.push_back(s->GetName()); } -Log::Log(const BotInfo *b, const Anope::string &category) : bi(b), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(NULL), Type(LOG_NORMAL), Category(category) +Log::Log(const BotInfo *b, const Anope::string &cat) : bi(b), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(NULL), type(LOG_NORMAL), category(cat) { if (!this->bi && Config) - this->bi = findbot(Config->Global); + this->bi = Global; if (this->bi) - this->Sources.push_back(bi->nick); + this->sources.push_back(bi->nick); } -Log::Log(Module *mod, const Anope::string &category) : bi(NULL), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(mod), Type(LOG_MODULE), Category(category) +Log::Log(Module *mod, const Anope::string &cat) : bi(NULL), u(NULL), nc(NULL), c(NULL), chan(NULL), ci(NULL), s(NULL), m(mod), type(LOG_MODULE), category(cat) { if (m) - this->Sources.push_back(m->name); + this->sources.push_back(m->name); } Log::~Log() { - if (nofork && debug && this->Type >= LOG_NORMAL && this->Type <= LOG_DEBUG + debug - 1) + if (Anope::NoFork && Anope::Debug && this->type >= LOG_NORMAL && this->type <= LOG_DEBUG + Anope::Debug - 1) std::cout << GetTimeStamp() << " Debug: " << this->BuildPrefix() << this->buf.str() << std::endl; - else if (nofork && this->Type <= LOG_TERMINAL) + else if (Anope::NoFork && this->type <= LOG_TERMINAL) std::cout << GetTimeStamp() << " " << this->BuildPrefix() << this->buf.str() << std::endl; - else if (this->Type == LOG_TERMINAL) + else if (this->type == LOG_TERMINAL) std::cout << this->BuildPrefix() << this->buf.str() << std::endl; for (unsigned i = 0; Config && i < Config->LogInfos.size(); ++i) { @@ -178,7 +181,7 @@ Anope::string Log::BuildPrefix() const { Anope::string buffer; - switch (this->Type) + switch (this->type) { case LOG_ADMIN: { @@ -233,9 +236,9 @@ Anope::string Log::BuildPrefix() const break; buffer += "CHANNEL: "; if (this->u) - buffer += this->u->GetMask() + " " + this->Category + " " + this->chan->name + " "; + buffer += this->u->GetMask() + " " + this->category + " " + this->chan->name + " "; else - buffer += this->Category + " " + this->chan->name + " "; + buffer += this->category + " " + this->chan->name + " "; break; } case LOG_USER: @@ -263,13 +266,13 @@ Anope::string Log::BuildPrefix() const return buffer; } -LogInfo::LogInfo(int logage, bool rawio, bool ldebug) : LogAge(logage), RawIO(rawio), Debug(ldebug) +LogInfo::LogInfo(int la, bool rio, bool ldebug) : log_age(la), raw_io(rio), debug(ldebug) { } LogInfo::~LogInfo() { - for (std::map<Anope::string, LogFile *>::iterator it = this->Logfiles.begin(), it_end = this->Logfiles.end(); it != it_end; ++it) + for (std::map<Anope::string, LogFile *>::iterator it = this->logfiles.begin(), it_end = this->logfiles.end(); it != it_end; ++it) { LogFile *f = it->second; @@ -277,7 +280,7 @@ LogInfo::~LogInfo() f->stream.close(); delete f; } - this->Logfiles.clear(); + this->logfiles.clear(); } void LogInfo::AddType(std::list<Anope::string> &list, const Anope::string &type) @@ -300,29 +303,29 @@ bool LogInfo::HasType(LogType ltype, const Anope::string &type) const switch (ltype) { case LOG_ADMIN: - list = &this->Admin; + list = &this->admin; break; case LOG_OVERRIDE: - list = &this->Override; + list = &this->override; break; case LOG_COMMAND: - list = &this->Commands; + list = &this->commands; break; case LOG_SERVER: - list = &this->Servers; + list = &this->servers; break; case LOG_CHANNEL: - list = &this->Channels; + list = &this->channels; break; case LOG_USER: - list = &this->Users; + list = &this->users; break; case LOG_TERMINAL: return true; case LOG_RAWIO: - return debug ? true : this->RawIO; + return debug ? true : this->raw_io; case LOG_DEBUG: - return debug ? true : this->Debug; + return debug ? true : this->debug; case LOG_DEBUG_2: case LOG_DEBUG_3: case LOG_DEBUG_4: @@ -330,7 +333,7 @@ bool LogInfo::HasType(LogType ltype, const Anope::string &type) const case LOG_MODULE: case LOG_NORMAL: default: - list = &this->Normal; + list = &this->normal; break; } @@ -361,15 +364,15 @@ void LogInfo::ProcessMessage(const Log *l) if (!l) throw CoreException("Bad values passed to LogInfo::ProcessMessages"); - else if (!this->HasType(l->Type, l->Category)) + else if (!this->HasType(l->type, l->category)) return; - if (!this->Sources.empty()) + if (!this->sources.empty()) { bool log = false; - for (std::list<Anope::string>::const_iterator it = this->Sources.begin(), it_end = this->Sources.end(); it != it_end; ++it) + for (std::list<Anope::string>::const_iterator it = this->sources.begin(), it_end = this->sources.end(); it != it_end; ++it) { - if (std::find(l->Sources.begin(), l->Sources.end(), *it) != l->Sources.end()) + if (std::find(l->sources.begin(), l->sources.end(), *it) != l->sources.end()) { log = true; break; @@ -379,45 +382,45 @@ void LogInfo::ProcessMessage(const Log *l) return; } - for (std::list<Anope::string>::iterator it = this->Targets.begin(), it_end = this->Targets.end(); it != it_end; ++it) + for (std::list<Anope::string>::iterator it = this->targets.begin(), it_end = this->targets.end(); it != it_end; ++it) { const Anope::string &target = *it; Anope::string buffer = l->BuildPrefix() + l->buf.str(); if (target[0] == '#') { - if (UplinkSock && l->Type <= LOG_NORMAL && Me && Me->IsSynced()) + if (UplinkSock && l->type <= LOG_NORMAL && Me && Me->IsSynced()) { - Channel *c = findchan(target); + Channel *c = Channel::Find(target); if (!c || !l->bi) continue; - ircdproto->SendPrivmsg(l->bi, c->name, "%s", buffer.c_str()); + IRCD->SendPrivmsg(l->bi, c->name, "%s", buffer.c_str()); } } else if (target == "globops") { - if (UplinkSock && l->bi && l->Type <= LOG_NORMAL && Me && Me->IsSynced()) + if (UplinkSock && l->bi && l->type <= LOG_NORMAL && Me && Me->IsSynced()) { - ircdproto->SendGlobops(l->bi, "%s", buffer.c_str()); + IRCD->SendGlobops(l->bi, "%s", buffer.c_str()); } } else { LogFile *log = NULL; - std::map<Anope::string, LogFile *>::iterator lit = this->Logfiles.find(target); - if (lit != this->Logfiles.end()) + std::map<Anope::string, LogFile *>::iterator lit = this->logfiles.find(target); + if (lit != this->logfiles.end()) { log = lit->second; if (log && log->GetName() != CreateLogName(target)) { delete log; - this->Logfiles.erase(lit); + this->logfiles.erase(lit); log = new LogFile(CreateLogName(target)); - this->Logfiles[target] = log; + this->logfiles[target] = log; - if (this->LogAge) + if (this->log_age) { - Anope::string oldlog = CreateLogName(target, Anope::CurTime - 86400 * this->LogAge); + Anope::string oldlog = CreateLogName(target, Anope::CurTime - 86400 * this->log_age); if (IsFile(oldlog)) { unlink(oldlog.c_str()); @@ -433,11 +436,11 @@ void LogInfo::ProcessMessage(const Log *l) Log() << "Unable to open logfile " << log->GetName(); } delete log; - this->Logfiles.erase(lit); + this->logfiles.erase(lit); log = NULL; } } - else if (lit == this->Logfiles.end()) + else if (lit == this->logfiles.end()) { log = new LogFile(CreateLogName(target)); @@ -452,7 +455,7 @@ void LogInfo::ProcessMessage(const Log *l) log = NULL; } else - this->Logfiles[target] = log; + this->logfiles[target] = log; } if (log) diff --git a/src/mail.cpp b/src/mail.cpp index 152d525f5..030922f5c 100644 --- a/src/mail.cpp +++ b/src/mail.cpp @@ -7,28 +7,28 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ - #include "services.h" #include "mail.h" #include "config.h" -MailThread::MailThread(const Anope::string &smpath, const Anope::string &sf, const Anope::string &mailto, const Anope::string &addr, const Anope::string &subject, const Anope::string &message) : Thread(), SendMailPath(smpath), SendFrom(sf), MailTo(mailto), Addr(addr), Subject(subject), Message(message), DontQuoteAddresses(Config->DontQuoteAddresses), Success(false) +Mail::Message::Message(const Anope::string &sf, const Anope::string &mailto, const Anope::string &a, const Anope::string &s, const Anope::string &m) : Thread(), sendmail_path(Config->SendMailPath), send_from(sf), mail_to(mailto), addr(a), subject(s), message(m), dont_quote_addresses(Config->DontQuoteAddresses), success(false) { } -MailThread::~MailThread() +Mail::Message::~Message() { - if (Success) - Log(LOG_NORMAL, "mail") << "Successfully delivered mail for " << MailTo << " (" << Addr << ")"; + if (success) + Log(LOG_NORMAL, "mail") << "Successfully delivered mail for " << mail_to << " (" << addr << ")"; else - Log(LOG_NORMAL, "mail") << "Error delivering mail for " << MailTo << " (" << Addr << ")"; + Log(LOG_NORMAL, "mail") << "Error delivering mail for " << mail_to << " (" << addr << ")"; } -void MailThread::Run() +void Mail::Message::Run() { - FILE *pipe = popen(SendMailPath.c_str(), "w"); + FILE *pipe = popen(sendmail_path.c_str(), "w"); if (!pipe) { @@ -36,22 +36,22 @@ void MailThread::Run() return; } - fprintf(pipe, "From: %s\n", SendFrom.c_str()); - if (this->DontQuoteAddresses) - fprintf(pipe, "To: %s <%s>\n", MailTo.c_str(), Addr.c_str()); + fprintf(pipe, "From: %s\n", send_from.c_str()); + if (this->dont_quote_addresses) + fprintf(pipe, "To: %s <%s>\n", mail_to.c_str(), addr.c_str()); else - fprintf(pipe, "To: \"%s\" <%s>\n", MailTo.c_str(), Addr.c_str()); - fprintf(pipe, "Subject: %s\n", Subject.c_str()); - fprintf(pipe, "%s", Message.c_str()); + fprintf(pipe, "To: \"%s\" <%s>\n", mail_to.c_str(), addr.c_str()); + fprintf(pipe, "Subject: %s\n", subject.c_str()); + fprintf(pipe, "%s", message.c_str()); fprintf(pipe, "\n.\n"); pclose(pipe); - Success = true; + success = true; SetExitState(); } -bool Mail(User *u, NickCore *nc, const BotInfo *service, const Anope::string &subject, const Anope::string &message) +bool Mail::Send(User *u, NickCore *nc, const BotInfo *service, const Anope::string &subject, const Anope::string &message) { if (!nc || !service || subject.empty() || message.empty()) return false; @@ -64,7 +64,7 @@ bool Mail(User *u, NickCore *nc, const BotInfo *service, const Anope::string &su return false; nc->lastmail = Anope::CurTime; - Thread *t = new MailThread(Config->SendMailPath, Config->SendFrom, nc->display, nc->email, subject, message); + Thread *t = new Mail::Message(Config->SendFrom, nc->display, nc->email, subject, message); t->Start(); return true; } @@ -79,7 +79,7 @@ bool Mail(User *u, NickCore *nc, const BotInfo *service, const Anope::string &su else { u->lastmail = nc->lastmail = Anope::CurTime; - Thread *t = new MailThread(Config->SendMailPath, Config->SendFrom, nc->display, nc->email, subject, message); + Thread *t = new Mail::Message(Config->SendFrom, nc->display, nc->email, subject, message); t->Start(); return true; } @@ -88,13 +88,13 @@ bool Mail(User *u, NickCore *nc, const BotInfo *service, const Anope::string &su } } -bool Mail(NickCore *nc, const Anope::string &subject, const Anope::string &message) +bool Mail::Send(NickCore *nc, const Anope::string &subject, const Anope::string &message) { if (!Config->UseMail || !nc || nc->email.empty() || subject.empty() || message.empty()) return false; nc->lastmail = Anope::CurTime; - Thread *t = new MailThread(Config->SendMailPath, Config->SendFrom, nc->display, nc->email, subject, message); + Thread *t = new Mail::Message(Config->SendFrom, nc->display, nc->email, subject, message); t->Start(); return true; @@ -109,7 +109,7 @@ bool Mail(NickCore *nc, const Anope::string &subject, const Anope::string &messa * @param email Email to Validate * @return bool */ -bool MailValidate(const Anope::string &email) +bool Mail::Validate(const Anope::string &email) { bool has_period = false; diff --git a/src/main.cpp b/src/main.cpp index 2cbacbb0f..82cd1af90 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,32 +8,15 @@ * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program (see the file COPYING); if not, write to the - * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "services.h" #include "timers.h" -#include "extern.h" -#include "uplink.h" #include "config.h" -#include "protocol.h" -#include "servers.h" #include "bots.h" -#include "dns.h" #include "signals.h" #include "socketengine.h" +#include "uplink.h" #ifndef _WIN32 #include <limits.h> @@ -41,37 +24,23 @@ #include <process.h> #endif -/******** Global variables! ********/ - -/* Command-line options: (note that configuration variables are in config.c) */ -Anope::string services_dir; /* -dir dirname */ -Anope::string services_bin; /* Binary as specified by the user */ -Anope::string binary_dir; /* Used to store base path for Anope */ -int debug = 0; /* -debug */ -bool readonly = false; /* -readonly */ -bool nofork = false; /* -nofork */ -bool nothird = false; /* -nothrid */ -bool noexpire = false; /* -noexpire */ -bool protocoldebug = false; /* -protocoldebug */ - -/* Set to 1 if we are to quit */ -bool quitting = false; -int return_code = 0; - -/* Set to true if we are restarting */ -bool restarting = false; +/* Command-line options: */ +int Anope::Debug = 0; +bool Anope::ReadOnly = false, Anope::NoFork = false, Anope::NoThird = false, Anope::NoExpire = false, Anope::ProtocolDebug = false; +Anope::string Anope::ServicesDir; +Anope::string Anope::ServicesBin; -/* Contains a message as to why services is terminating */ -Anope::string quitmsg; +int Anope::ReturnValue = 0; +bool Anope::Quitting = false; +bool Anope::Restarting = false; +Anope::string Anope::QuitReason; -/* At what time were we started? */ -time_t start_time = time(NULL); +static Anope::string BinaryDir; /* Full path to services bin directory */ +time_t Anope::StartTime = time(NULL); time_t Anope::CurTime = time(NULL); -/******** Local variables! ********/ - -/*************************************************************************/ +int Anope::CurrentUplink = -1; class UpdateTimer : public Timer { @@ -80,202 +49,13 @@ class UpdateTimer : public Timer void Tick(time_t) { - save_databases(); - } -}; - -UplinkSocket *UplinkSock = NULL; -int CurrentUplink = -1; - -static void Connect(); - -class ReconnectTimer : public Timer -{ - public: - ReconnectTimer(int wait) : Timer(wait) { } - - void Tick(time_t) - { - try - { - Connect(); - } - catch (const SocketException &ex) - { - Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (CurrentUplink + 1) << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << "): " << ex.GetReason(); - } + Anope::SaveDatabases(); } }; -UplinkSocket::UplinkSocket() : Socket(-1, Config->Uplinks[CurrentUplink]->ipv6), ConnectionSocket(), BufferedSocket() -{ - UplinkSock = this; -} - -UplinkSocket::~UplinkSocket() +void Anope::SaveDatabases() { - if (ircdproto && Me && !Me->GetLinks().empty() && Me->GetLinks()[0]->IsSynced()) - { - FOREACH_MOD(I_OnServerDisconnect, OnServerDisconnect()); - - for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) - { - User *u = it->second; - - if (u->server == Me) - { - /* Don't use quitmsg here, it may contain information you don't want people to see */ - ircdproto->SendQuit(u, "Shutting down"); - BotInfo* bi = findbot(u->nick); - if (bi != NULL) - bi->introduced = false; - } - } - - ircdproto->SendSquit(Me, quitmsg); - - this->ProcessWrite(); // Write out the last bit - } - - for (unsigned i = Me->GetLinks().size(); i > 0; --i) - if (!Me->GetLinks()[i - 1]->HasFlag(SERVER_JUPED)) - Me->GetLinks()[i - 1]->Delete(Me->GetName() + " " + Me->GetLinks()[i - 1]->GetName()); - - UplinkSock = NULL; - - Me->SetFlag(SERVER_SYNCING); - - if (AtTerm()) - { - if (static_cast<unsigned>(CurrentUplink + 1) == Config->Uplinks.size()) - { - quitting = true; - quitmsg = "Unable to connect to any uplink"; - return_code = -1; - } - else - { - new ReconnectTimer(1); - } - } - else if (!quitting) - { - int Retry = Config->RetryWait; - if (Retry <= 0) - Retry = 60; - - Log() << "Disconnected, retrying in " << Retry << " seconds"; - new ReconnectTimer(Retry); - } -} - -bool UplinkSocket::Read(const Anope::string &buf) -{ - process(buf); - return true; -} - -void UplinkSocket::OnConnect() -{ - Log(LOG_TERMINAL) << "Successfully connected to uplink #" << (CurrentUplink + 1) << " " << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port; - ircdproto->SendConnect(); - FOREACH_MOD(I_OnServerConnect, OnServerConnect()); -} - -void UplinkSocket::OnError(const Anope::string &error) -{ - Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (CurrentUplink + 1) << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << ")" << (!error.empty() ? (": " + error) : ""); -} - -UplinkSocket::Message::Message() : server(NULL), user(NULL) -{ -} - -UplinkSocket::Message::Message(const Server *s) : server(s), user(NULL) -{ -} - -UplinkSocket::Message::Message(const User *u) : server(NULL), user(u) -{ - if (!u) - server = Me; -} - -UplinkSocket::Message::~Message() -{ - Anope::string message_source = ""; - - if (this->server != NULL) - { - if (this->server != Me && !this->server->HasFlag(SERVER_JUPED)) - { - Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->server->GetName() << " who is not from me?"; - return; - } - - message_source = this->server->GetSID(); - } - else if (this->user != NULL) - { - if (this->user->server != Me && !this->user->server->HasFlag(SERVER_JUPED)) - { - Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->user->nick << " who is not from me?"; - return; - } - - const BotInfo *bi = findbot(this->user->nick); - if (bi != NULL && bi->introduced == false) - { - Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << bi->nick << " when not introduced"; - return; - } - - message_source = this->user->GetUID(); - } - - if (!UplinkSock) - { - if (!message_source.empty()) - Log(LOG_DEBUG) << "Attempted to send \"" << message_source << " " << this->buffer.str() << "\" with UplinkSock NULL"; - else - Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" with UplinkSock NULL"; - return; - } - - if (!message_source.empty()) - { - UplinkSock->Write(":" + message_source + " " + this->buffer.str()); - Log(LOG_RAWIO) << "Sent: :" << message_source << " " << this->buffer.str(); - } - else - { - UplinkSock->Write(this->buffer.str()); - Log(LOG_RAWIO) << "Sent: " << this->buffer.str(); - } -} - -static void Connect() -{ - if (static_cast<unsigned>(++CurrentUplink) >= Config->Uplinks.size()) - CurrentUplink = 0; - - ServerConfig::Uplink *u = Config->Uplinks[CurrentUplink]; - - new UplinkSocket(); - if (!Config->LocalHost.empty()) - UplinkSock->Bind(Config->LocalHost); - FOREACH_MOD(I_OnPreServerConnect, OnPreServerConnect()); - DNSQuery rep = DNSManager::BlockingQuery(u->host, u->ipv6 ? DNS_QUERY_AAAA : DNS_QUERY_A); - Anope::string reply_ip = !rep.answers.empty() ? rep.answers.front().rdata : u->host; - Log(LOG_TERMINAL) << "Attempting to connect to uplink #" << (CurrentUplink + 1) << " " << u->host << " (" << reply_ip << "), port " << u->port; - UplinkSock->Connect(reply_ip, u->port); -} - -/*************************************************************************/ - -void save_databases() -{ - if (readonly) + if (Anope::ReadOnly) return; EventReturn MOD_RESULT; @@ -283,8 +63,6 @@ void save_databases() Log(LOG_DEBUG) << "Saving databases"; } -/*************************************************************************/ - std::vector<Signal *> Signal::SignalHandlers; void Signal::SignalHandler(int signal) @@ -321,7 +99,7 @@ Signal::~Signal() /** The following comes from InspIRCd to get the full path of the Anope executable */ -Anope::string GetFullProgDir(const Anope::string &argv0) +static Anope::string GetFullProgDir(const Anope::string &argv0) { char buffer[PATH_MAX]; #ifdef _WIN32 @@ -333,7 +111,7 @@ Anope::string GetFullProgDir(const Anope::string &argv0) { Anope::string fullpath = buffer; Anope::string::size_type n = fullpath.rfind("\\"); - services_bin = fullpath.substr(n + 1, fullpath.length()); + Anope::ServicesBin = fullpath.substr(n + 1, fullpath.length()); return fullpath.substr(0, n); } #else @@ -342,14 +120,14 @@ Anope::string GetFullProgDir(const Anope::string &argv0) { Anope::string remainder = argv0; - services_bin = remainder; - Anope::string::size_type n = services_bin.rfind("/"); + Anope::ServicesBin = remainder; + Anope::string::size_type n = Anope::ServicesBin.rfind("/"); Anope::string fullpath; - if (services_bin[0] == '/') - fullpath = services_bin.substr(0, n); + if (Anope::ServicesBin[0] == '/') + fullpath = Anope::ServicesBin.substr(0, n); else - fullpath = Anope::string(buffer) + "/" + services_bin.substr(0, n); - services_bin = services_bin.substr(n + 1, remainder.length()); + fullpath = Anope::string(buffer) + "/" + Anope::ServicesBin.substr(0, n); + Anope::ServicesBin = Anope::ServicesBin.substr(n + 1, remainder.length()); return fullpath; } #endif @@ -362,16 +140,16 @@ Anope::string GetFullProgDir(const Anope::string &argv0) int main(int ac, char **av, char **envp) { - binary_dir = GetFullProgDir(av[0]); - if (binary_dir[binary_dir.length() - 1] == '.') - binary_dir = binary_dir.substr(0, binary_dir.length() - 2); + BinaryDir = GetFullProgDir(av[0]); + if (BinaryDir[BinaryDir.length() - 1] == '.') + BinaryDir = BinaryDir.substr(0, BinaryDir.length() - 2); #ifdef _WIN32 - Anope::string::size_type n = binary_dir.rfind('\\'); + Anope::string::size_type n = BinaryDir.rfind('\\'); #else - Anope::string::size_type n = binary_dir.rfind('/'); + Anope::string::size_type n = BinaryDir.rfind('/'); #endif - services_dir = binary_dir.substr(0, n); + Anope::ServicesDir = BinaryDir.substr(0, n); /* Clean out the module runtime directory prior to running, just in case files were left behind during a previous run */ ModuleManager::CleanupRuntimeDirectory(); @@ -383,9 +161,9 @@ int main(int ac, char **av, char **envp) try { /* General initialization first */ - Init(ac, av); + Anope::Init(ac, av); } - catch (const FatalException &ex) + catch (const CoreException &ex) { Log() << ex.GetReason(); return -1; @@ -393,11 +171,11 @@ int main(int ac, char **av, char **envp) try { - Connect(); + Uplink::Connect(); } catch (const SocketException &ex) { - Log(LOG_TERMINAL) << "Unable to connect to uplink #" << CurrentUplink << " (" << Config->Uplinks[CurrentUplink]->host << ":" << Config->Uplinks[CurrentUplink]->port << "): " << ex.GetReason(); + Log(LOG_TERMINAL) << "Unable to connect to uplink #" << Anope::CurrentUplink << " (" << Config->Uplinks[Anope::CurrentUplink]->host << ":" << Config->Uplinks[Anope::CurrentUplink]->port << "): " << ex.GetReason(); } /* Set up timers */ @@ -405,7 +183,7 @@ int main(int ac, char **av, char **envp) UpdateTimer updateTimer(Config->UpdateTimeout); /*** Main loop. ***/ - while (!quitting) + while (!Anope::Quitting) { Log(LOG_DEBUG_2) << "Top of main loop"; @@ -420,7 +198,7 @@ int main(int ac, char **av, char **envp) SocketEngine::Process(); } - if (restarting) + if (Anope::Restarting) { FOREACH_MOD(I_OnRestart, OnRestart()); } @@ -429,9 +207,9 @@ int main(int ac, char **av, char **envp) FOREACH_MOD(I_OnShutdown, OnShutdown()); } - if (quitmsg.empty()) - quitmsg = "Terminating, reason unknown"; - Log() << quitmsg; + if (Anope::QuitReason.empty()) + Anope::QuitReason = "Terminating, reason unknown"; + Log() << Anope::QuitReason; delete UplinkSock; @@ -446,14 +224,15 @@ int main(int ac, char **av, char **envp) OnShutdown(); #endif - if (restarting) + if (Anope::Restarting) { - chdir(binary_dir.c_str()); - av[0] = const_cast<char *>(("./" + services_bin).c_str()); - execve(services_bin.c_str(), av, envp); + chdir(BinaryDir.c_str()); + Anope::string sbin = "./" + Anope::ServicesBin; + av[0] = const_cast<char *>(sbin.c_str()); + execve(Anope::ServicesBin.c_str(), av, envp); Log() << "Restart failed"; - return_code = -1; + Anope::ReturnValue = -1; } - return return_code; + return Anope::ReturnValue; } diff --git a/src/memoserv.cpp b/src/memos.cpp index 13d4d04d6..2b221b03a 100644 --- a/src/memoserv.cpp +++ b/src/memos.cpp @@ -7,9 +7,9 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ - #include "services.h" #include "modules.h" #include "service.h" @@ -19,14 +19,17 @@ #include "account.h" #include "regchannel.h" -Memo::Memo() : Flags<MemoFlag>(MemoFlagStrings), Serializable("Memo") { } +static const Anope::string MemoFlagString[] = { "MF_UNREAD", "MF_RECEIPT", "" }; +template<> const Anope::string* Flags<MemoFlag>::flags_strings = MemoFlagString; + +Memo::Memo() : Serializable("Memo") { } -Serialize::Data Memo::serialize() const +Serialize::Data Memo::Serialize() const { Serialize::Data data; data["owner"] << this->owner; - data["time"].setType(Serialize::DT_INT) << this->time; + data["time"].SetType(Serialize::DT_INT) << this->time; data["sender"] << this->sender; data["text"] << this->text; data["flags"] << this->ToString(); @@ -34,13 +37,13 @@ Serialize::Data Memo::serialize() const return data; } -Serializable* Memo::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* Memo::Unserialize(Serializable *obj, Serialize::Data &data) { - if (!memoserv) + if (!MemoServService) return NULL; bool ischan; - MemoInfo *mi = memoserv->GetMemoInfo(data["owner"].astr(), ischan); + MemoInfo *mi = MemoServService->GetMemoInfo(data["owner"].astr(), ischan); if (!mi) return NULL; @@ -85,7 +88,7 @@ void MemoInfo::Del(unsigned index) { if (index >= this->memos->size()) return; - this->GetMemo(index)->destroy(); + this->GetMemo(index)->Destroy(); this->memos->erase(this->memos->begin() + index); } @@ -95,7 +98,7 @@ void MemoInfo::Del(Memo *memo) if (it != this->memos->end()) { - memo->destroy(); + memo->Destroy(); this->memos->erase(it); } } diff --git a/src/messages.cpp b/src/messages.cpp index 774816e44..62170e24e 100644 --- a/src/messages.cpp +++ b/src/messages.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -14,43 +15,45 @@ #include "users.h" #include "protocol.h" #include "config.h" -#include "extern.h" #include "uplink.h" #include "opertype.h" #include "messages.h" #include "servers.h" #include "channels.h" -bool CoreIRCDMessageAway::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +using namespace Message; + +bool Away::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { FOREACH_MOD(I_OnUserAway, OnUserAway(source.GetUser(), params.empty() ? "" : params[0])); return true; } -bool CoreIRCDMessageCapab::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Capab::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { if (params.size() == 1) { spacesepstream sep(params[0]); Anope::string token; while (sep.GetToken(token)) - Capab.insert(token); + Servers::Capab.insert(token); } else for (unsigned i = 0; i < params.size(); ++i) - Capab.insert(params[i]); + Servers::Capab.insert(params[i]); return true; } -bool CoreIRCDMessageError::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Error::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { Log(LOG_TERMINAL) << "ERROR: " << params[0]; - quitmsg = "Received ERROR from uplink: " + params[0]; + Anope::QuitReason = "Received ERROR from uplink: " + params[0]; + Anope::Quitting = true; return true; } -bool CoreIRCDMessageJoin::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Join::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { User *user = source.GetUser(); const Anope::string &channels = params[0]; @@ -70,46 +73,94 @@ bool CoreIRCDMessageJoin::Run(MessageSource &source, const std::vector<Anope::st Anope::string channame = cc->chan->name; FOREACH_MOD(I_OnPrePartChannel, OnPrePartChannel(user, cc->chan)); cc->chan->DeleteUser(user); - FOREACH_MOD(I_OnPartChannel, OnPartChannel(user, findchan(channame), channame, "")); + FOREACH_MOD(I_OnPartChannel, OnPartChannel(user, Channel::Find(channame), channame, "")); } user->chans.clear(); continue; } - Channel *chan = findchan(channel); - /* Channel doesn't exist, create it */ - if (!chan) - chan = new Channel(channel, Anope::CurTime); + std::list<SJoinUser> users; + users.push_back(std::make_pair(ChannelStatus(), user)); + + Channel *chan = Channel::Find(channel); + SJoin(source, channel, chan ? chan->creation_time : Anope::CurTime, "", users); + } + + return true; +} + +void Join::SJoin(MessageSource &source, const Anope::string &chan, time_t ts, const Anope::string &modes, const std::list<SJoinUser> &users) +{ + Channel *c = Channel::Find(chan); + bool keep_their_modes = true; + + if (!c) + { + c = new Channel(chan, ts ? ts : Anope::CurTime); + c->SetFlag(CH_SYNCING); + } + /* Some IRCds do not include a TS */ + else if (!ts) + ; + /* Our creation time is newer than what the server gave us, so reset the channel to the older time */ + else if (c->creation_time > ts) + { + c->creation_time = ts; + c->Reset(); + } + /* Their TS is newer, don't accept any modes from them */ + else if (ts > c->creation_time) + keep_their_modes = false; + + /* Update the modes for the channel */ + if (keep_their_modes && !modes.empty()) + c->SetModesInternal(source, modes); + + for (std::list<SJoinUser>::const_iterator it = users.begin(), it_end = users.end(); it != it_end; ++it) + { + const ChannelStatus &status = it->first; + User *u = it->second; EventReturn MOD_RESULT; - FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(user, chan)); + FOREACH_RESULT(I_OnPreJoinChannel, OnPreJoinChannel(u, c)); + + /* Add the user to the channel */ + UserContainer *cc = c->JoinUser(u); - /* Join the user to the channel */ - chan->JoinUser(user); - /* Set the proper modes on the user */ - chan_set_correct_modes(user, chan, 1, true); + /* Update their status internally on the channel */ + *cc->status = status; - /* Modules may want to allow this user in the channel, check. - * If not, CheckKick will kick/ban them, don't call OnJoinChannel after this as the user will have - * been destroyed + /* Set whatever modes the user should have, and remove any that + * they aren't allowed to have (secureops etc). */ - if (MOD_RESULT != EVENT_STOP && chan && chan->ci && chan->ci->CheckKick(user)) + c->SetCorrectModes(u, true, true); + + /* Check to see if modules want the user to join, if they do + * check to see if they are allowed to join (CheckKick will kick/ban them + * if they aren't). + */ + if (MOD_RESULT != EVENT_STOP && c->ci && c->ci->CheckKick(u)) continue; - FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(user, chan)); + FOREACH_MOD(I_OnJoinChannel, OnJoinChannel(u, c)); } - return true; + /* Channel is done syncing */ + if (c->HasFlag(CH_SYNCING)) + { + c->UnsetFlag(CH_SYNCING); + /* Sync the channel (mode lock, topic, etc) */ + c->Sync(); + } } - -bool CoreIRCDMessageKick::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Kick::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { const Anope::string &channel = params[0]; const Anope::string &users = params[1]; const Anope::string &reason = params.size() > 2 ? params[2] : ""; - Channel *c = findchan(channel); + Channel *c = Channel::Find(channel); if (!c) return true; @@ -121,9 +172,9 @@ bool CoreIRCDMessageKick::Run(MessageSource &source, const std::vector<Anope::st return true; } -bool CoreIRCDMessageKill::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Kill::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); BotInfo *bi; if (!u) @@ -132,9 +183,22 @@ bool CoreIRCDMessageKill::Run(MessageSource &source, const std::vector<Anope::st /* Recover if someone kills us. */ if (u->server == Me && (bi = dynamic_cast<BotInfo *>(u))) { + static time_t last_time = 0; + + if (last_time == Anope::CurTime) + { + Anope::QuitReason = "Kill loop detected. Are Services U:Lined?"; + Anope::Quitting = true; + return true; + } + last_time = Anope::CurTime; + bi->introduced = false; - introduce_user(bi->nick); - bi->RejoinAll(); + IRCD->SendClientIntroduction(bi); + bi->introduced = true; + + for (UChannelList::const_iterator cit = bi->chans.begin(), cit_end = bi->chans.end(); cit != cit_end; ++cit) + IRCD->SendJoin(bi, (*cit)->chan, (*cit)->status); } else u->KillInternal(source.GetSource(), params[1]); @@ -142,8 +206,28 @@ bool CoreIRCDMessageKill::Run(MessageSource &source, const std::vector<Anope::st return true; } +bool Message::Mode::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +{ + if (IRCD->IsChannelValid(params[0])) + { + Channel *c = Channel::Find(params[0]); + + if (c) + c->SetModesInternal(source, params[2], 0); + } + else + { + User *u = User::Find(params[0]); + + if (u) + u->SetModesInternal("%s", params[1].c_str()); + } + + return true; +} + /* XXX We should cache the file somewhere not open/read/close it on every request */ -bool CoreIRCDMessageMOTD::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool MOTD::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { Server *s = Server::Find(params[0]); if (s != Me) @@ -152,23 +236,23 @@ bool CoreIRCDMessageMOTD::Run(MessageSource &source, const std::vector<Anope::st FILE *f = fopen(Config->MOTDFilename.c_str(), "r"); if (f) { - ircdproto->SendNumeric(375, source.GetSource(), ":- %s Message of the Day", Config->ServerName.c_str()); + IRCD->SendNumeric(375, source.GetSource(), ":- %s Message of the Day", Config->ServerName.c_str()); char buf[BUFSIZE]; while (fgets(buf, sizeof(buf), f)) { buf[strlen(buf) - 1] = 0; - ircdproto->SendNumeric(372, source.GetSource(), ":- %s", buf); + IRCD->SendNumeric(372, source.GetSource(), ":- %s", buf); } fclose(f); - ircdproto->SendNumeric(376, source.GetSource(), ":End of /MOTD command."); + IRCD->SendNumeric(376, source.GetSource(), ":End of /MOTD command."); } else - ircdproto->SendNumeric(422, source.GetSource(), ":- MOTD file not found! Please contact your IRC administrator."); + IRCD->SendNumeric(422, source.GetSource(), ":- MOTD file not found! Please contact your IRC administrator."); return true; } -bool CoreIRCDMessagePart::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Part::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { User *u = source.GetUser(); const Anope::string &reason = params.size() > 1 ? params[1] : ""; @@ -178,7 +262,7 @@ bool CoreIRCDMessagePart::Run(MessageSource &source, const std::vector<Anope::st while (sep.GetToken(channel)) { - dynamic_reference<Channel> c = findchan(channel); + Reference<Channel> c = Channel::Find(channel); if (!c || !u->FindChannel(c)) continue; @@ -193,22 +277,22 @@ bool CoreIRCDMessagePart::Run(MessageSource &source, const std::vector<Anope::st return true; } -bool CoreIRCDMessagePing::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Ping::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { - ircdproto->SendPong(params.size() > 1 ? params[1] : Me->GetSID(), params[0]); + IRCD->SendPong(params.size() > 1 ? params[1] : Me->GetSID(), params[0]); return true; } -bool CoreIRCDMessagePrivmsg::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Privmsg::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { const Anope::string &receiver = params[0]; Anope::string message = params[1]; User *u = source.GetUser(); - if (ircdproto->IsChannelValid(receiver)) + if (IRCD->IsChannelValid(receiver)) { - Channel *c = findchan(receiver); + Channel *c = Channel::Find(receiver); if (c) { FOREACH_MOD(I_OnPrivmsg, OnPrivmsg(u, c, message)); @@ -229,7 +313,7 @@ bool CoreIRCDMessagePrivmsg::Run(MessageSource &source, const std::vector<Anope: } else if (Config->UseStrictPrivMsg) { - const BotInfo *bi = findbot(receiver); + const BotInfo *bi = BotInfo::Find(receiver); if (!bi) return true; Log(LOG_DEBUG) << "Ignored PRIVMSG without @ from " << u->nick; @@ -237,7 +321,7 @@ bool CoreIRCDMessagePrivmsg::Run(MessageSource &source, const std::vector<Anope: return true; } - BotInfo *bi = findbot(botname); + BotInfo *bi = BotInfo::Find(botname); if (bi) { @@ -253,12 +337,12 @@ bool CoreIRCDMessagePrivmsg::Run(MessageSource &source, const std::vector<Anope: Anope::string buf = message; buf.erase(buf.begin()); buf.erase(buf.end() - 1); - ircdproto->SendCTCP(bi, u->nick, "%s", buf.c_str()); + IRCD->SendCTCP(bi, u->nick, "%s", buf.c_str()); } else if (message.substr(0, 9).equals_ci("\1VERSION\1")) { Module *enc = ModuleManager::FindFirstOf(ENCRYPTION); - ircdproto->SendCTCP(bi, u->nick, "VERSION Anope-%s %s :%s - (%s) -- %s", Anope::Version().c_str(), Config->ServerName.c_str(), ircdproto->GetProtocolName().c_str(), enc ? enc->name.c_str() : "unknown", Anope::VersionBuildString().c_str()); + IRCD->SendCTCP(bi, u->nick, "VERSION Anope-%s %s :%s - (%s) -- %s", Anope::Version().c_str(), Config->ServerName.c_str(), IRCD->GetProtocolName().c_str(), enc ? enc->name.c_str() : "unknown", Anope::VersionBuildString().c_str()); } return true; } @@ -270,14 +354,14 @@ bool CoreIRCDMessagePrivmsg::Run(MessageSource &source, const std::vector<Anope: return true; } -bool CoreIRCDMessageQuit::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Quit::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { const Anope::string &reason = params[0]; User *user = source.GetUser(); Log(user, "quit") << "quit (Reason: " << (!reason.empty() ? reason : "no reason") << ")"; - NickAlias *na = findnick(user->nick); + NickAlias *na = NickAlias::Find(user->nick); if (na && !na->nc->HasFlag(NI_SUSPENDED) && (user->IsRecognized() || user->IsIdentified(true))) { na->last_seen = Anope::CurTime; @@ -289,7 +373,7 @@ bool CoreIRCDMessageQuit::Run(MessageSource &source, const std::vector<Anope::st return true; } -bool CoreIRCDMessageSQuit::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool SQuit::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { Server *s = Server::Find(params[0]); @@ -306,7 +390,7 @@ bool CoreIRCDMessageSQuit::Run(MessageSource &source, const std::vector<Anope::s return true; } -bool CoreIRCDMessageStats::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Stats::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { User *u = source.GetUser(); @@ -315,92 +399,92 @@ bool CoreIRCDMessageStats::Run(MessageSource &source, const std::vector<Anope::s case 'l': if (u->HasMode(UMODE_OPER)) { - ircdproto->SendNumeric(211, source.GetSource(), "Server SendBuf SentBytes SentMsgs RecvBuf RecvBytes RecvMsgs ConnTime"); - ircdproto->SendNumeric(211, source.GetSource(), "%s %d %d %d %d %d %d %ld", Config->Uplinks[CurrentUplink]->host.c_str(), UplinkSock->WriteBufferLen(), TotalWritten, -1, UplinkSock->ReadBufferLen(), TotalRead, -1, static_cast<long>(Anope::CurTime - start_time)); + IRCD->SendNumeric(211, source.GetSource(), "Server SendBuf SentBytes SentMsgs RecvBuf RecvBytes RecvMsgs ConnTime"); + IRCD->SendNumeric(211, source.GetSource(), "%s %d %d %d %d %d %d %ld", Config->Uplinks[Anope::CurrentUplink]->host.c_str(), UplinkSock->WriteBufferLen(), TotalWritten, -1, UplinkSock->ReadBufferLen(), TotalRead, -1, static_cast<long>(Anope::CurTime - Anope::StartTime)); } - ircdproto->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); + IRCD->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); break; case 'o': case 'O': /* Check whether the user is an operator */ if (!u->HasMode(UMODE_OPER) && Config->HideStatsO) - ircdproto->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); + IRCD->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); else { for (unsigned i = 0; i < Config->Opers.size(); ++i) { Oper *o = Config->Opers[i]; - const NickAlias *na = findnick(o->name); + const NickAlias *na = NickAlias::Find(o->name); if (na) - ircdproto->SendNumeric(243, source.GetSource(), "O * * %s %s 0", o->name.c_str(), o->ot->GetName().c_str()); + IRCD->SendNumeric(243, source.GetSource(), "O * * %s %s 0", o->name.c_str(), o->ot->GetName().c_str()); } - ircdproto->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); + IRCD->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); } break; case 'u': { - time_t uptime = Anope::CurTime - start_time; - ircdproto->SendNumeric(242, source.GetSource(), ":Services up %d day%s, %02d:%02d:%02d", uptime / 86400, uptime / 86400 == 1 ? "" : "s", (uptime / 3600) % 24, (uptime / 60) % 60, uptime % 60); - ircdproto->SendNumeric(250, source.GetSource(), ":Current users: %d (%d ops); maximum %d", usercnt, opcnt, maxusercnt); - ircdproto->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); + time_t uptime = Anope::CurTime - Anope::StartTime; + IRCD->SendNumeric(242, source.GetSource(), ":Services up %d day%s, %02d:%02d:%02d", uptime / 86400, uptime / 86400 == 1 ? "" : "s", (uptime / 3600) % 24, (uptime / 60) % 60, uptime % 60); + IRCD->SendNumeric(250, source.GetSource(), ":Current users: %d (%d ops); maximum %d", UserListByNick.size(), OperCount, MaxUserCount); + IRCD->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); break; } /* case 'u' */ default: - ircdproto->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); + IRCD->SendNumeric(219, source.GetSource(), "%c :End of /STATS report.", params[0][0]); } return true; } -bool CoreIRCDMessageTime::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Time::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { time_t t; time(&t); struct tm *tm = localtime(&t); char buf[64]; strftime(buf, sizeof(buf), "%a %b %d %H:%M:%S %Y %Z", tm); - ircdproto->SendNumeric(391, source.GetSource(), "%s :%s", Config->ServerName.c_str(), buf); + IRCD->SendNumeric(391, source.GetSource(), "%s :%s", Config->ServerName.c_str(), buf); return true; } -bool CoreIRCDMessageTopic::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Topic::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { - Channel *c = findchan(params[0]); + Channel *c = Channel::Find(params[0]); if (c) c->ChangeTopicInternal(source.GetSource(), params[1], Anope::CurTime); return true; } -bool CoreIRCDMessageVersion::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Version::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { Module *enc = ModuleManager::FindFirstOf(ENCRYPTION); - ircdproto->SendNumeric(351, source.GetSource(), "Anope-%s %s :%s -(%s) -- %s", Anope::Version().c_str(), Config->ServerName.c_str(), ircdproto->GetProtocolName().c_str(), enc ? enc->name.c_str() : "unknown", Anope::VersionBuildString().c_str()); + IRCD->SendNumeric(351, source.GetSource(), "Anope-%s %s :%s -(%s) -- %s", Anope::Version().c_str(), Config->ServerName.c_str(), IRCD->GetProtocolName().c_str(), enc ? enc->name.c_str() : "unknown", Anope::VersionBuildString().c_str()); return true; } -bool CoreIRCDMessageWhois::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) +bool Whois::Run(MessageSource &source, const std::vector<Anope::string> ¶ms) { - User *u = finduser(params[0]); + User *u = User::Find(params[0]); if (u && u->server == Me) { - const BotInfo *bi = findbot(u->nick); - ircdproto->SendNumeric(311, source.GetSource(), "%s %s %s * :%s", u->nick.c_str(), u->GetIdent().c_str(), u->host.c_str(), u->realname.c_str()); + const BotInfo *bi = BotInfo::Find(u->nick); + IRCD->SendNumeric(311, source.GetSource(), "%s %s %s * :%s", u->nick.c_str(), u->GetIdent().c_str(), u->host.c_str(), u->realname.c_str()); if (bi) - ircdproto->SendNumeric(307, source.GetSource(), "%s :is a registered nick", bi->nick.c_str()); - ircdproto->SendNumeric(312, source.GetSource(), "%s %s :%s", u->nick.c_str(), Config->ServerName.c_str(), Config->ServerDesc.c_str()); + IRCD->SendNumeric(307, source.GetSource(), "%s :is a registered nick", bi->nick.c_str()); + IRCD->SendNumeric(312, source.GetSource(), "%s %s :%s", u->nick.c_str(), Config->ServerName.c_str(), Config->ServerDesc.c_str()); if (bi) - ircdproto->SendNumeric(317, source.GetSource(), "%s %ld %ld :seconds idle, signon time", bi->nick.c_str(), static_cast<long>(Anope::CurTime - bi->lastmsg), static_cast<long>(bi->signon)); - ircdproto->SendNumeric(318, source.GetSource(), "%s :End of /WHOIS list.", params[0].c_str()); + IRCD->SendNumeric(317, source.GetSource(), "%s %ld %ld :seconds idle, signon time", bi->nick.c_str(), static_cast<long>(Anope::CurTime - bi->lastmsg), static_cast<long>(bi->signon)); + IRCD->SendNumeric(318, source.GetSource(), "%s :End of /WHOIS list.", params[0].c_str()); } else - ircdproto->SendNumeric(401, source.GetSource(), "%s :No such user.", params[0].c_str()); + IRCD->SendNumeric(401, source.GetSource(), "%s :No such user.", params[0].c_str()); return true; } diff --git a/src/misc.cpp b/src/misc.cpp index cd7516b76..7196a1534 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -1,4 +1,3 @@ - /* Miscellaneous routines. * * (C) 2003-2012 Anope Team @@ -8,12 +7,12 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "version.h" #include "modules.h" -#include "extern.h" #include "lists.h" #include "config.h" #include "bots.h" @@ -24,37 +23,6 @@ #include <sys/types.h> #include <sys/stat.h> -ExtensibleItem::ExtensibleItem() -{ -} - -ExtensibleItem::~ExtensibleItem() -{ -} - -void ExtensibleItem::OnDelete() -{ - delete this; -} - -/*************************************************************************/ - -/** Check if a file exists - * @param filename The file - * @return true if the file exists, false if it doens't - */ -bool IsFile(const Anope::string &filename) -{ - struct stat fileinfo; - if (!stat(filename.c_str(), &fileinfo)) - return true; - - return false; -} - - -/*************************************************************************/ - NumberList::NumberList(const Anope::string &list, bool descending) : is_valid(true), desc(descending) { Anope::string error; @@ -134,18 +102,18 @@ bool NumberList::InvalidRange(const Anope::string &) return true; } -ListFormatter &ListFormatter::addColumn(const Anope::string &name) +ListFormatter &ListFormatter::AddColumn(const Anope::string &name) { this->columns.push_back(name); return *this; } -void ListFormatter::addEntry(const ListEntry &entry) +void ListFormatter::AddEntry(const ListEntry &entry) { this->entries.push_back(entry); } -bool ListFormatter::isEmpty() const +bool ListFormatter::IsEmpty() const { return this->entries.empty(); } @@ -235,7 +203,7 @@ void InfoFormatter::Process(std::vector<Anope::string> &buffer) Anope::string s; for (unsigned i = it->first.length(); i < this->longest; ++i) s += " "; - s += Anope::string(translate(this->nc, it->first.c_str())) + ": " + it->second; + s += Anope::string(Language::Translate(this->nc, it->first.c_str())) + ": " + it->second; buffer.push_back(s); } @@ -249,18 +217,16 @@ Anope::string& InfoFormatter::operator[](const Anope::string &key) return this->replies.back().second; } -/** - * dotime: Return the number of seconds corresponding to the given time - * string. If the given string does not represent a valid time, - * return -1. - * - * A time string is either a plain integer (representing a number - * of seconds), or an integer followed by one of these characters: - * "s" (seconds), "m" (minutes), "h" (hours), or "d" (days). - * @param s String to convert - * @return time_t - */ -time_t dotime(const Anope::string &s) +bool Anope::IsFile(const Anope::string &filename) +{ + struct stat fileinfo; + if (!stat(filename.c_str(), &fileinfo)) + return true; + + return false; +} + +time_t Anope::DoTime(const Anope::string &s) { if (s.empty()) return -1; @@ -297,15 +263,7 @@ time_t dotime(const Anope::string &s) return 0; } -/*************************************************************************/ - -/** - * Expresses in a string the period of time represented by a given amount - * of seconds (with days/hours/minutes). - * @param seconds time in seconds - * @return buffer - */ -Anope::string duration(const time_t &t, const NickCore *nc) +Anope::string Anope::Duration(time_t t, const NickCore *nc) { /* We first calculate everything */ time_t days = (t / 86400); @@ -314,58 +272,50 @@ Anope::string duration(const time_t &t, const NickCore *nc) time_t seconds = (t) % 60; if (!days && !hours && !minutes) - return stringify(seconds) + " " + (seconds != 1 ? translate(nc, _("seconds")) : translate(nc, _("second"))); + return stringify(seconds) + " " + (seconds != 1 ? Language::Translate(nc, _("seconds")) : Language::Translate(nc, _("second"))); else { bool need_comma = false; Anope::string buffer; if (days) { - buffer = stringify(days) + " " + (days != 1 ? translate(nc, _("days")) : translate(nc, _("day"))); + buffer = stringify(days) + " " + (days != 1 ? Language::Translate(nc, _("days")) : Language::Translate(nc, _("day"))); need_comma = true; } if (hours) { buffer += need_comma ? ", " : ""; - buffer += stringify(hours) + " " + (hours != 1 ? translate(nc, _("hours")) : translate(nc, _("hour"))); + buffer += stringify(hours) + " " + (hours != 1 ? Language::Translate(nc, _("hours")) : Language::Translate(nc, _("hour"))); need_comma = true; } if (minutes) { buffer += need_comma ? ", " : ""; - buffer += stringify(minutes) + " " + (minutes != 1 ? translate(nc, _("minutes")) : translate(nc, _("minute"))); + buffer += stringify(minutes) + " " + (minutes != 1 ? Language::Translate(nc, _("minutes")) : Language::Translate(nc, _("minute"))); } return buffer; } } -Anope::string do_strftime(const time_t &t, const NickCore *nc, bool short_output) +Anope::string Anope::strftime(time_t t, const NickCore *nc, bool short_output) { tm tm = *localtime(&t); char buf[BUFSIZE]; - strftime(buf, sizeof(buf), translate(nc, _("%b %d %H:%M:%S %Y %Z")), &tm); + strftime(buf, sizeof(buf), Language::Translate(nc, _("%b %d %H:%M:%S %Y %Z")), &tm); if (short_output) return buf; if (t < Anope::CurTime) - return Anope::string(buf) + " " + Anope::printf(translate(nc, _("(%s ago)")), duration(Anope::CurTime - t).c_str(), nc); + return Anope::string(buf) + " " + Anope::printf(Language::Translate(nc, _("(%s ago)")), Duration(Anope::CurTime - t).c_str(), nc); else - return Anope::string(buf) + " " + Anope::printf(translate(nc, _("(%s from now)")), duration(t - Anope::CurTime).c_str(), nc); + return Anope::string(buf) + " " + Anope::printf(Language::Translate(nc, _("(%s from now)")), Duration(t - Anope::CurTime).c_str(), nc); } -/*************************************************************************/ - -/** - * Generates a human readable string of type "expires in ..." - * @param na Nick Alias - * @param seconds time in seconds - * @return buffer - */ -Anope::string expire_left(const NickCore *nc, time_t expires) +Anope::string Anope::Expires(time_t expires, const NickCore *nc) { if (!expires) - return translate(nc, NO_EXPIRE); + return Language::Translate(nc, NO_EXPIRE); else if (expires <= Anope::CurTime) - return translate(nc, _("expires momentarily")); + return Language::Translate(nc, _("expires momentarily")); else { char buf[256]; @@ -374,21 +324,21 @@ Anope::string expire_left(const NickCore *nc, time_t expires) if (diff >= 86400) { int days = diff / 86400; - snprintf(buf, sizeof(buf), translate(nc, days == 1 ? _("expires in %d day") : _("expires in %d days")), days); + snprintf(buf, sizeof(buf), Language::Translate(nc, days == 1 ? _("expires in %d day") : _("expires in %d days")), days); } else { if (diff <= 3600) { int minutes = diff / 60; - snprintf(buf, sizeof(buf), translate(nc, minutes == 1 ? _("expires in %d minute") : _("expires in %d minutes")), minutes); + snprintf(buf, sizeof(buf), Language::Translate(nc, minutes == 1 ? _("expires in %d minute") : _("expires in %d minutes")), minutes); } else { int hours = diff / 3600, minutes; diff -= hours * 3600; minutes = diff / 60; - snprintf(buf, sizeof(buf), translate(nc, hours == 1 && minutes == 1 ? _("expires in %d hour, %d minute") : (hours == 1 && minutes != 1 ? _("expires in %d hour, %d minutes") : (hours != 1 && minutes == 1 ? _("expires in %d hours, %d minute") : _("expires in %d hours, %d minutes")))), hours, minutes); + snprintf(buf, sizeof(buf), Language::Translate(nc, hours == 1 && minutes == 1 ? _("expires in %d hour, %d minute") : (hours == 1 && minutes != 1 ? _("expires in %d hour, %d minutes") : (hours != 1 && minutes == 1 ? _("expires in %d hours, %d minute") : _("expires in %d hours, %d minutes")))), hours, minutes); } } @@ -396,181 +346,6 @@ Anope::string expire_left(const NickCore *nc, time_t expires) } } -/*************************************************************************/ - -/** Checks if a username is valid - * @param ident The username - * @return true if the ident is valid - */ -bool IsValidIdent(const Anope::string &ident) -{ - if (ident.empty() || ident.length() > Config->UserLen) - return false; - for (unsigned i = 0; i < ident.length(); ++i) - { - const char &c = ident[i]; - if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-') - ; - else - return false; - } - - return true; -} - -/** Checks if a host is valid - * @param host The host - * @param true if the host is valid - */ -bool IsValidHost(const Anope::string &host) -{ - if (host.empty() || host.length() > Config->HostLen) - return false; - - if (Config->VhostDisallowBE.find_first_of(host[0]) != Anope::string::npos) - return false; - else if (Config->VhostDisallowBE.find_first_of(host[host.length() - 1]) != Anope::string::npos) - return false; - - int dots = 0; - for (unsigned i = 0; i < host.length(); ++i) - { - if (host[i] == '.') - ++dots; - if (Config->VhostChars.find_first_of(host[i]) == Anope::string::npos) - return false; - } - - return Config->VhostUndotted || dots > 0; -} - -/*************************************************************************/ - -/** - * Get the token - * @param str String to search in - * @param dilim Character to search for - * @param token_number the token number - * @return token - */ -Anope::string myStrGetToken(const Anope::string &str, char dilim, int token_number) -{ - if (str.empty() || str.find(dilim) == Anope::string::npos) - return token_number ? "" : str; - - Anope::string substring; - sepstream sep(str, dilim); - - for (int i = 0; i < token_number + 1 && !sep.StreamEnd() && sep.GetToken(substring); ++i); - - return substring; -} - -/*************************************************************************/ - -/** - * Get the Remaining tokens - * @param str String to search in - * @param dilim Character to search for - * @param token_number the token number - * @return token - */ -Anope::string myStrGetTokenRemainder(const Anope::string &str, const char dilim, int token_number) -{ - if (str.empty() || str.find(dilim) == Anope::string::npos) - return token_number ? "" : str; - - Anope::string substring; - sepstream sep(str, dilim); - - for (int i = 0; i < token_number + 1 && !sep.StreamEnd() && sep.GetToken(substring); ++i); - - if (!sep.StreamEnd()) - substring += dilim + sep.GetRemaining(); - return substring; -} - -/*************************************************************************/ - -/** - * Is the given nick a network service - * @param nick to check - * @param int Check if botserv bots - * @return int - */ -bool nickIsServices(const Anope::string &tempnick, bool bot) -{ - if (tempnick.empty()) - return false; - - Anope::string nick = tempnick; - - size_t at = nick.find('@'); - if (at != Anope::string::npos) - { - Anope::string servername = nick.substr(at + 1); - if (!servername.equals_ci(Config->ServerName)) - return false; - nick = nick.substr(0, at); - } - - const BotInfo *bi = findbot(nick); - if (bi) - return bot ? true : bi->HasFlag(BI_CORE); - return false; -} - -/*************************************************************************/ - -/** - * Number of tokens in a string - * @param str String - * @param dilim Dilimiter - * @return number of tokens - */ -int myNumToken(const Anope::string &str, char dilim) -{ - if (str.empty()) - return 0; - int counter = 0; - for (size_t idx = 0, len = str.length(); idx <= len; ++idx) - if (str[idx] == dilim || idx == len) - ++counter; - return counter; -} - -/*************************************************************************/ - -/** Build a string list from a source string - * @param src The source string - * @return a list of strings - */ -std::list<Anope::string> BuildStringList(const Anope::string &src, char delim) -{ - sepstream tokens(src, delim); - Anope::string token; - std::list<Anope::string> Ret; - - while (tokens.GetToken(token)) - Ret.push_back(token); - - return Ret; -} - -std::vector<Anope::string> BuildStringVector(const Anope::string &src, char delim) -{ - sepstream tokens(src, delim); - Anope::string token; - std::vector<Anope::string> Ret; - - while (tokens.GetToken(token)) - Ret.push_back(token); - - return Ret; -} - -/*************************************************************************/ - bool Anope::Match(const Anope::string &str, const Anope::string &mask, bool case_sensitive, bool use_regex) { size_t s = 0, m = 0, str_len = str.length(), mask_len = mask.length(); @@ -583,7 +358,7 @@ bool Anope::Match(const Anope::string &str, const Anope::string &mask, bool case if (r == NULL || r->GetExpression() != stripped_mask) { - service_reference<RegexProvider> provider("Regex", Config->RegexEngine); + ServiceReference<RegexProvider> provider("Regex", Config->RegexEngine); if (provider) { try @@ -675,13 +450,6 @@ bool Anope::Match(const Anope::string &str, const Anope::string &mask, bool case return m == mask_len; } -/** Returns a sequence of data formatted as the format argument specifies. - ** After the format parameter, the function expects at least as many - ** additional arguments as specified in format. - * @param fmt Format of the Message - * @param ... any number of parameters - * @return a Anope::string - */ Anope::string Anope::printf(const char *fmt, ...) { va_list args; @@ -692,35 +460,6 @@ Anope::string Anope::printf(const char *fmt, ...) return buf; } - -/*************************************************************************/ - -/** - * Check if the given string is some sort of wildcard - * @param str String to check - * @return 1 for wildcard, 0 for anything else - */ -bool str_is_wildcard(const Anope::string &str) -{ - return str.find_first_of("*?") != Anope::string::npos; -} - -/** - * Check if the given string is a pure wildcard - * @param str String to check - * @return 1 for pure wildcard, 0 for anything else - */ -bool str_is_pure_wildcard(const Anope::string &str) -{ - return str.find_first_not_of('*') == Anope::string::npos; -} - -/*************************************************************************/ - -/** Converts a string to hex - * @param the data to be converted - * @return a anope::string containing the hex value - */ Anope::string Anope::Hex(const Anope::string &data) { const char hextable[] = "0123456789abcdef"; @@ -750,10 +489,6 @@ Anope::string Anope::Hex(const char *data, unsigned len) return rv; } -/** Converts a string from hex - * @param src The data to be converted - * @param dest The destination string - */ void Anope::Unhex(const Anope::string &src, Anope::string &dest) { size_t len = src.length(); @@ -827,12 +562,7 @@ int Anope::VersionMajor() { return VERSION_MAJOR; } int Anope::VersionMinor() { return VERSION_MINOR; } int Anope::VersionPatch() { return VERSION_PATCH; } -/** - * Normalize buffer stripping control characters and colors - * @param A string to be parsed for control and color codes - * @return A string stripped of control and color codes - */ -Anope::string normalizeBuffer(const Anope::string &buf) +Anope::string Anope::NormalizeBuffer(const Anope::string &buf) { Anope::string newbuf; diff --git a/src/modes.cpp b/src/modes.cpp index c14e09f70..ae550d788 100644 --- a/src/modes.cpp +++ b/src/modes.cpp @@ -4,11 +4,11 @@ * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #include "services.h" #include "modules.h" -#include "extern.h" #include "config.h" #include "sockets.h" #include "protocol.h" @@ -23,70 +23,52 @@ std::vector<ChannelMode *> ModeManager::ChannelModes; std::vector<UserMode *> ModeManager::UserModes; /* Number of generic modes we support */ -unsigned GenericChannelModes = 0, GenericUserModes = 0; -/* Default mlocked modes */ -ChannelInfo::ModeList def_mode_locks; +unsigned ModeManager::GenericChannelModes = 0, ModeManager::GenericUserModes = 0; -/** Parse the mode string from the config file and set the default mlocked modes - */ -void SetDefaultMLock(ServerConfig *config) -{ - for (ChannelInfo::ModeList::iterator it = def_mode_locks.begin(), it_end = def_mode_locks.end(); it != it_end; ++it) - delete it->second; - def_mode_locks.clear(); +/* Default channel mode lock */ +ChannelInfo::ModeList ModeManager::DefaultModeLocks; - Anope::string modes; - spacesepstream sep(config->MLock); - sep.GetToken(modes); +/* Default modes bots have on channels */ +ChannelStatus ModeManager::DefaultBotModes; - int adding = -1; - for (unsigned i = 0, end_mode = modes.length(); i < end_mode; ++i) - { - if (modes[i] == '+') - adding = 1; - else if (modes[i] == '-') - adding = 0; - else if (adding != -1) - { - ChannelMode *cm = ModeManager::FindChannelModeByChar(modes[i]); +static const Anope::string UserModeNameStrings[] = { + "UMODE_BEGIN", - if (cm && cm->Type != MODE_STATUS) - { - Anope::string param; - if (adding == 1 && cm->Type != MODE_REGULAR && !sep.GetToken(param)) // MODE_LIST OR MODE_PARAM - { - Log() << "Warning: Got default mlock mode " << cm->ModeChar << " with no param?"; - continue; - } + "UMODE_SERV_ADMIN", "UMODE_BOT", "UMODE_CO_ADMIN", "UMODE_FILTER", "UMODE_HIDEOPER", "UMODE_NETADMIN", + "UMODE_REGPRIV", "UMODE_PROTECTED", "UMODE_NOCTCP", "UMODE_WEBTV", "UMODE_WEBIRC", "UMODE_WHOIS", "UMODE_ADMIN", "UMODE_DEAF", + "UMODE_GLOBOPS", "UMODE_HELPOP", "UMODE_INVIS", "UMODE_OPER", "UMODE_PRIV", "UMODE_GOD", "UMODE_REGISTERED", + "UMODE_SNOMASK", "UMODE_VHOST", "UMODE_WALLOPS", "UMODE_CLOAK", "UMODE_SSL", "UMODE_SOFTCALLERID", "UMODE_CALLERID", + "UMODE_COMMONCHANS", "UMODE_HIDDEN", "UMODE_STRIPCOLOR", "UMODE_INVISIBLE_OPER", "UMODE_RESTRICTED", "UMODE_HIDEIDLE", - if (cm->Type != MODE_LIST) // Only MODE_LIST can have duplicates - { - ChannelInfo::ModeList::iterator it = def_mode_locks.find(cm->Name); - if (it != def_mode_locks.end()) - { - delete it->second; - def_mode_locks.erase(it); - } - } - def_mode_locks.insert(std::make_pair(cm->Name, new ModeLock(NULL, adding == 1, cm->Name, param))); - } - } - } + "" +}; +template<> const Anope::string* Flags<UserModeName>::flags_strings = UserModeNameStrings; - /* Set Bot Modes */ - config->BotModeList.ClearFlags(); - for (unsigned i = 0; i < config->BotModes.length(); ++i) - { - ChannelMode *cm = ModeManager::FindChannelModeByChar(config->BotModes[i]); +static const Anope::string ChannelModeNameStrings[] = { + "CMODE_BEGIN", - if (cm && cm->Type == MODE_STATUS) - config->BotModeList.SetFlag(cm->Name); - } -} + /* Channel modes */ + "CMODE_BLOCKCOLOR", "CMODE_FLOOD", "CMODE_INVITE", "CMODE_KEY", "CMODE_LIMIT", "CMODE_MODERATED", "CMODE_NOEXTERNAL", + "CMODE_PRIVATE", "CMODE_REGISTERED", "CMODE_SECRET", "CMODE_TOPIC", "CMODE_AUDITORIUM", "CMODE_SSL", "CMODE_ADMINONLY", + "CMODE_NOCTCP", "CMODE_FILTER", "CMODE_NOKNOCK", "CMODE_REDIRECT", "CMODE_REGMODERATED", "CMODE_NONICK", "CMODE_OPERONLY", + "CMODE_NOKICK", "CMODE_REGISTEREDONLY", "CMODE_STRIPCOLOR", "CMODE_NONOTICE", "CMODE_NOINVITE", "CMODE_ALLINVITE", + "CMODE_BLOCKCAPS", "CMODE_PERM", "CMODE_NICKFLOOD", "CMODE_JOINFLOOD", "CMODE_DELAYEDJOIN", "CMODE_NOREJOIN", + "CMODE_BANDWIDTH", -ChannelStatus::ChannelStatus() : Flags<ChannelModeName, CMODE_END * 2>(ChannelModeNameStrings) -{ -} + /* b/e/I */ + "CMODE_BAN", "CMODE_EXCEPT", + "CMODE_INVITEOVERRIDE", + + /* v/h/o/a/q */ + "CMODE_VOICE", "CMODE_HALFOP", "CMODE_OP", + "CMODE_PROTECT", "CMODE_OWNER", + + "" +}; +template<> const Anope::string* Flags<ChannelModeName>::flags_strings = ChannelModeNameStrings; + +static const Anope::string EntryFlagString[] = { "ENTRYTYPE_NONE", "ENTRYTYPE_CIDR", "ENTRYTYPE_NICK_WILD", "ENTRYTYPE_NICK", "ENTRYTYPE_USER_WILD", "ENTRYTYPE_USER", "ENTRYTYPE_HOST_WILD", "ENTRYTYPE_HOST", "" }; +template<> const Anope::string* Flags<EntryType>::flags_strings = EntryFlagString; Anope::string ChannelStatus::BuildCharPrefixList() const { @@ -96,8 +78,8 @@ Anope::string ChannelStatus::BuildCharPrefixList() const { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (this->HasFlag(cm->Name)) - ret += cm->ModeChar; + if (this->HasFlag(cm->name)) + ret += cm->mchar; } return ret; @@ -111,7 +93,7 @@ Anope::string ChannelStatus::BuildModePrefixList() const { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (this->HasFlag(cm->Name)) + if (this->HasFlag(cm->name)) { ChannelModeStatus *cms = anope_dynamic_static_cast<ChannelModeStatus *>(cm); ret += cms->Symbol; @@ -121,139 +103,83 @@ Anope::string ChannelStatus::BuildModePrefixList() const return ret; } -/** Default constructor - * @param mClass The type of mode this is - * @param modeChar The mode char - * @param modeType The mode type - */ -Mode::Mode(ModeClass mClass, char modeChar, ModeType modeType) : Class(mClass), ModeChar(modeChar), Type(modeType) +Mode::Mode(ModeClass mcl, char mch, ModeType mt) : mclass(mcl), mchar(mch), type(mt) { } -/** Default destructor - */ Mode::~Mode() { } -/** Default constructor - * @param mName The mode name - * @param modeChar The mode char - */ -UserMode::UserMode(UserModeName mName, char modeChar) : Mode(MC_USER, modeChar, MODE_REGULAR), Name(mName) +UserMode::UserMode(UserModeName un, char mch) : Mode(MC_USER, mch, MODE_REGULAR), name(un) { } -/** Default destructor - */ UserMode::~UserMode() { } -/** Returns the mode name as a string - */ const Anope::string UserMode::NameAsString() { - if (this->Name > UMODE_END) - return this->ModeChar; - return UserModeNameStrings[this->Name]; + if (this->name >= UMODE_END) + return this->mchar; + return UserModeNameStrings[this->name]; } -/** Default constructor - * @param mName The mode name - * @param modeChar The mode char - */ -UserModeParam::UserModeParam(UserModeName mName, char modeChar) : UserMode(mName, modeChar) +UserModeParam::UserModeParam(UserModeName un, char mch) : UserMode(un, mch) { - this->Type = MODE_PARAM; + this->type = MODE_PARAM; } -/** Default constrcutor - * @param mName The mode name - * @param modeChar The mode char - */ -ChannelMode::ChannelMode(ChannelModeName mName, char modeChar) : Mode(MC_CHANNEL, modeChar, MODE_REGULAR), Name(mName) +ChannelMode::ChannelMode(ChannelModeName cm, char mch) : Mode(MC_CHANNEL, mch, MODE_REGULAR), name(cm) { } -/** Default destructor - */ ChannelMode::~ChannelMode() { } -/** Can a user set this mode, used for mlock - * NOTE: User CAN be NULL, this is for checking if it can be locked with defcon - * @param u The user, or NULL - */ bool ChannelMode::CanSet(User *u) const { - if (Config->NoMLock.find(this->ModeChar) != Anope::string::npos || Config->CSRequire.find(this->ModeChar) != Anope::string::npos) + if (Config->NoMLock.find(this->mchar) != Anope::string::npos || Config->CSRequire.find(this->mchar) != Anope::string::npos) return false; return true; } -/** Returns the mode name as a string - */ const Anope::string ChannelMode::NameAsString() { - if (this->Name > CMODE_END) - return this->ModeChar; - return ChannelModeNameStrings[this->Name]; + if (this->name >= CMODE_END) + return this->mchar; + return ChannelModeNameStrings[this->name]; } -/** Default constructor - * @param mName The mode name - * @param modeChar The mode char - */ -ChannelModeList::ChannelModeList(ChannelModeName mName, char modeChar) : ChannelMode(mName, modeChar) +ChannelModeList::ChannelModeList(ChannelModeName cm, char mch) : ChannelMode(cm, mch) { - this->Type = MODE_LIST; + this->type = MODE_LIST; } -/** Default destructor - */ ChannelModeList::~ChannelModeList() { } -/** Default constructor - * @param mName The mode name - * @param modeChar The mode char - * @param MinusArg true if the mode sends no arg when unsetting - */ -ChannelModeParam::ChannelModeParam(ChannelModeName mName, char modeChar, bool MinusArg) : ChannelMode(mName, modeChar), MinusNoArg(MinusArg) +ChannelModeParam::ChannelModeParam(ChannelModeName cm, char mch, bool ma) : ChannelMode(cm, mch), minus_no_arg(ma) { - this->Type = MODE_PARAM; + this->type = MODE_PARAM; } -/** Default destructor - */ ChannelModeParam::~ChannelModeParam() { } -/** Default constructor - * @param mName The mode name - * @param modeChar The mode char - * @param mSymbol The symbol for the mode, eg @ % + - * @param mLevel A level for the mode, which is usually determined by the PREFIX capab - */ ChannelModeStatus::ChannelModeStatus(ChannelModeName mName, char modeChar, char mSymbol, unsigned short mLevel) : ChannelMode(mName, modeChar), Symbol(mSymbol), Level(mLevel) { - this->Type = MODE_STATUS; + this->type = MODE_STATUS; } -/** Default destructor - */ ChannelModeStatus::~ChannelModeStatus() { } -/** Is the key valid - * @param value The key - * @return true or false - */ bool ChannelModeKey::IsValid(const Anope::string &value) const { if (!value.empty() && value.find(':') == Anope::string::npos && value.find(',') == Anope::string::npos) @@ -262,10 +188,6 @@ bool ChannelModeKey::IsValid(const Anope::string &value) const return false; } -/** Can admin only mode be set by the user - * @param u The user - can be NULL if defcon is checking - * @return true or false - */ bool ChannelModeAdmin::CanSet(User *u) const { if (u && u->HasMode(UMODE_OPER)) @@ -274,10 +196,6 @@ bool ChannelModeAdmin::CanSet(User *u) const return false; } -/** Can oper only mode be set by the user - * @param u The user - can be NULL if defcon is checking - * @return true or false - */ bool ChannelModeOper::CanSet(User *u) const { if (u && u->HasMode(UMODE_OPER)) @@ -286,21 +204,17 @@ bool ChannelModeOper::CanSet(User *u) const return false; } -/** Can the user set the registered mode? - * No. - * @return false - */ bool ChannelModeRegistered::CanSet(User *u) const { return false; } -void StackerInfo::AddMode(Mode *mode, bool Set, const Anope::string &Param) +void StackerInfo::AddMode(Mode *mode, bool set, const Anope::string ¶m) { - bool IsParam = mode->Type == MODE_PARAM; + bool is_param = mode->type == MODE_PARAM; std::list<std::pair<Mode *, Anope::string> > *list, *otherlist; - if (Set) + if (set) { list = &AddModes; otherlist = &DelModes; @@ -318,7 +232,7 @@ void StackerInfo::AddMode(Mode *mode, bool Set, const Anope::string &Param) /* The param must match too (can have multiple status or list modes), but * if it is a param mode it can match no matter what the param is */ - if (it->first == mode && (Param.equals_cs(it->second) || IsParam)) + if (it->first == mode && (is_param || param.equals_cs(it->second))) { list->erase(it); /* It can only be on this list once */ @@ -331,7 +245,7 @@ void StackerInfo::AddMode(Mode *mode, bool Set, const Anope::string &Param) /* The param must match too (can have multiple status or list modes), but * if it is a param mode it can match no matter what the param is */ - if (it->first == mode && (Param.equals_cs(it->second) || IsParam)) + if (it->first == mode && (is_param || param.equals_cs(it->second))) { otherlist->erase(it); return; @@ -343,7 +257,7 @@ void StackerInfo::AddMode(Mode *mode, bool Set, const Anope::string &Param) } /* Add this mode and its param to our list */ - list->push_back(std::make_pair(mode, Param)); + list->push_back(std::make_pair(mode, param)); } static class ModePipe : public Pipe @@ -371,10 +285,6 @@ static StackerInfo *GetInfo(List &l, Object *o) return s; } -/** Build a list of mode strings to send to the IRCd from the mode stacker - * @param info The stacker info for a channel or user - * @return a list of strings - */ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) { std::list<Anope::string> ret; @@ -384,7 +294,7 @@ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) for (it = info->AddModes.begin(), it_end = info->AddModes.end(); it != it_end; ++it) { - if (++NModes > ircdproto->MaxModes) + if (++NModes > IRCD->MaxModes) { ret.push_back(buf + parambuf); buf = "+"; @@ -392,7 +302,7 @@ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) NModes = 1; } - buf += it->first->ModeChar; + buf += it->first->mchar; if (!it->second.empty()) parambuf += " " + it->second; @@ -404,7 +314,7 @@ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) buf += "-"; for (it = info->DelModes.begin(), it_end = info->DelModes.end(); it != it_end; ++it) { - if (++NModes > ircdproto->MaxModes) + if (++NModes > IRCD->MaxModes) { ret.push_back(buf + parambuf); buf = "-"; @@ -412,7 +322,7 @@ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) NModes = 1; } - buf += it->first->ModeChar; + buf += it->first->mchar; if (!it->second.empty()) parambuf += " " + it->second; @@ -427,19 +337,15 @@ std::list<Anope::string> ModeManager::BuildModeStrings(StackerInfo *info) return ret; } -/** Add a user mode to Anope - * @param um A UserMode or UserMode derived class - * @return true on success, false on error - */ bool ModeManager::AddUserMode(UserMode *um) { - if (ModeManager::FindUserModeByChar(um->ModeChar) != NULL) + if (ModeManager::FindUserModeByChar(um->mchar) != NULL) return false; - if (um->Name == UMODE_END) + if (um->name == UMODE_END) { - um->Name = static_cast<UserModeName>(UMODE_END + ++GenericUserModes); - Log() << "ModeManager: Added generic support for user mode " << um->ModeChar; + um->name = static_cast<UserModeName>(UMODE_END + ++GenericUserModes); + Log() << "ModeManager: Added generic support for user mode " << um->mchar; } ModeManager::UserModes.push_back(um); @@ -448,154 +354,145 @@ bool ModeManager::AddUserMode(UserMode *um) return true; } -/** Add a channel mode to Anope - * @param cm A ChannelMode or ChannelMode derived class - * @return true on success, false on error - */ bool ModeManager::AddChannelMode(ChannelMode *cm) { - if (ModeManager::FindChannelModeByChar(cm->ModeChar) != NULL) + if (ModeManager::FindChannelModeByChar(cm->mchar) != NULL) return false; - if (cm->Name == CMODE_END) + if (cm->name == CMODE_END) { - cm->Name = static_cast<ChannelModeName>(CMODE_END + ++GenericChannelModes); - Log() << "ModeManager: Added generic support for channel mode " << cm->ModeChar; + cm->name = static_cast<ChannelModeName>(CMODE_END + ++GenericChannelModes); + Log() << "ModeManager: Added generic support for channel mode " << cm->mchar; } ModeManager::ChannelModes.push_back(cm); /* Apply this mode to the new default mlock if its used */ - SetDefaultMLock(Config); + UpdateDefaultMLock(Config); FOREACH_MOD(I_OnChannelModeAdd, OnChannelModeAdd(cm)); return true; } -/** Find a channel mode - * @param Mode The mode - * @return The mode class - */ + +void ModeManager::RemoveUserMode(UserMode *um) +{ + for (unsigned i = 0; i < ModeManager::UserModes.size(); ++i) + { + UserMode *mode = ModeManager::UserModes[i]; + if (um == mode) + { + ModeManager::UserModes.erase(ModeManager::UserModes.begin() + i); + break; + } + } + + StackerDel(um); +} + +void ModeManager::RemoveChannelMode(ChannelMode *cm) +{ + for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) + { + ChannelMode *mode = ModeManager::ChannelModes[i]; + if (cm == mode) + { + ModeManager::ChannelModes.erase(ModeManager::ChannelModes.begin() + i); + break; + } + } + + StackerDel(cm); +} + ChannelMode *ModeManager::FindChannelModeByChar(char Mode) { for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm->ModeChar == Mode) + if (cm->mchar == Mode) return cm; } return NULL; } -/** Find a user mode - * @param Mode The mode - * @return The mode class - */ UserMode *ModeManager::FindUserModeByChar(char Mode) { for (unsigned i = 0; i < ModeManager::UserModes.size(); ++i) { UserMode *um = ModeManager::UserModes[i]; - if (um->ModeChar == Mode) + if (um->mchar == Mode) return um; } return NULL; } -/** Find a channel mode - * @param Mode The modename - * @return The mode class - */ ChannelMode *ModeManager::FindChannelModeByName(ChannelModeName Name) { for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm->Name == Name) + if (cm->name == Name) return cm; } return NULL; } -/** Find a user mode - * @param Mode The modename - * @return The mode class - */ UserMode *ModeManager::FindUserModeByName(UserModeName Name) { for (unsigned i = 0; i < ModeManager::UserModes.size(); ++i) { UserMode *um = ModeManager::UserModes[i]; - if (um->Name == Name) + if (um->name == Name) return um; } return NULL; } -/** Find channel mode by string - * @param name The mode name - * @return The mode - */ ChannelMode *ModeManager::FindChannelModeByString(const Anope::string &name) { for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm->NameAsString() == name || Anope::string(cm->ModeChar) == name) + if (cm->NameAsString() == name || Anope::string(cm->mchar) == name) return cm; } return NULL; } -/** Find user mode by string - * @param name The mode name - * @return The mode - */ UserMode *ModeManager::FindUserModeByString(const Anope::string &name) { for (size_t i = UMODE_BEGIN + 1; i != UMODE_END; ++i) { UserMode *um = ModeManager::FindUserModeByName(static_cast<UserModeName>(i)); - if (um != NULL && (um->NameAsString() == name || Anope::string(um->ModeChar) == name)) + if (um != NULL && (um->NameAsString() == name || Anope::string(um->mchar) == name)) return um; } return NULL; } - -/** Gets the channel mode char for a symbol (eg + returns v) - * @param Value The symbol - * @return The char - */ char ModeManager::GetStatusChar(char Value) { for (unsigned i = 0; i < ModeManager::ChannelModes.size(); ++i) { ChannelMode *cm = ModeManager::ChannelModes[i]; - if (cm->Type == MODE_STATUS) + if (cm->type == MODE_STATUS) { ChannelModeStatus *cms = anope_dynamic_static_cast<ChannelModeStatus *>(cm); if (Value == cms->Symbol) - return cms->ModeChar; + return cms->mchar; } } return 0; } -/** Add a mode to the stacker to be set on a channel - * @param bi The client to set the modes from - * @param c The channel - * @param cm The channel mode - * @param Set true for setting, false for removing - * @param Param The param, if there is one - */ void ModeManager::StackerAdd(const BotInfo *bi, Channel *c, ChannelMode *cm, bool Set, const Anope::string &Param) { StackerInfo *s = GetInfo(ChannelStackerObjects, c); @@ -610,13 +507,6 @@ void ModeManager::StackerAdd(const BotInfo *bi, Channel *c, ChannelMode *cm, boo modePipe->Notify(); } -/** Add a mode to the stacker to be set on a user - * @param bi The client to set the modes from - * @param u The user - * @param um The user mode - * @param Set true for setting, false for removing - * @param param The param, if there is one - */ void ModeManager::StackerAdd(const BotInfo *bi, User *u, UserMode *um, bool Set, const Anope::string &Param) { StackerInfo *s = GetInfo(UserStackerObjects, u); @@ -631,8 +521,6 @@ void ModeManager::StackerAdd(const BotInfo *bi, User *u, UserMode *um, bool Set, modePipe->Notify(); } -/** Process all of the modes in the stacker and send them to the IRCd to be set on channels/users - */ void ModeManager::ProcessModes() { if (!UserStackerObjects.empty()) @@ -644,7 +532,7 @@ void ModeManager::ProcessModes() std::list<Anope::string> ModeStrings = BuildModeStrings(s); for (std::list<Anope::string>::iterator lit = ModeStrings.begin(), lit_end = ModeStrings.end(); lit != lit_end; ++lit) - ircdproto->SendMode(s->bi, u, lit->c_str()); + IRCD->SendMode(s->bi, u, lit->c_str()); delete it->second; } UserStackerObjects.clear(); @@ -659,15 +547,13 @@ void ModeManager::ProcessModes() std::list<Anope::string> ModeStrings = BuildModeStrings(s); for (std::list<Anope::string>::iterator lit = ModeStrings.begin(), lit_end = ModeStrings.end(); lit != lit_end; ++lit) - ircdproto->SendMode(s->bi, c, lit->c_str()); + IRCD->SendMode(s->bi, c, lit->c_str()); delete it->second; } ChannelStackerObjects.clear(); } } -/** Delete a user or channel from the stacker - */ void ModeManager::StackerDel(User *u) { UserStackerObjects.erase(u); @@ -678,3 +564,245 @@ void ModeManager::StackerDel(Channel *c) ChannelStackerObjects.erase(c); } +void ModeManager::StackerDel(Mode *m) +{ + for (std::map<User *, StackerInfo *>::const_iterator it = UserStackerObjects.begin(), it_end = UserStackerObjects.end(); it != it_end;) + { + StackerInfo *si = it->second; + ++it; + + for (std::list<std::pair<Mode *, Anope::string> >::iterator it2 = si->AddModes.begin(), it2_end = si->AddModes.end(); it2 != it2_end;) + { + Mode *mode = it2->first; + ++it2; + + if (mode == m) + si->AddModes.erase(it2); + } + + for (std::list<std::pair<Mode *, Anope::string> >::iterator it2 = si->DelModes.begin(), it2_end = si->DelModes.end(); it2 != it2_end;) + { + Mode *mode = it2->first; + ++it2; + + if (mode == m) + si->DelModes.erase(it2); + } + } + + for (std::map<Channel *, StackerInfo *>::const_iterator it = ChannelStackerObjects.begin(), it_end = ChannelStackerObjects.end(); it != it_end;) + { + StackerInfo *si = it->second; + ++it; + + for (std::list<std::pair<Mode *, Anope::string> >::iterator it2 = si->AddModes.begin(), it2_end = si->AddModes.end(); it2 != it2_end;) + { + Mode *mode = it2->first; + ++it2; + + if (mode == m) + si->AddModes.erase(it2); + } + + for (std::list<std::pair<Mode *, Anope::string> >::iterator it2 = si->DelModes.begin(), it2_end = si->DelModes.end(); it2 != it2_end;) + { + Mode *mode = it2->first; + ++it2; + + if (mode == m) + si->DelModes.erase(it2); + } + } +} + +void ModeManager::UpdateDefaultMLock(ServerConfig *config) +{ + for (ChannelInfo::ModeList::iterator it = DefaultModeLocks.begin(), it_end = DefaultModeLocks.end(); it != it_end; ++it) + delete it->second; + DefaultModeLocks.clear(); + + Anope::string modes; + spacesepstream sep(config->MLock); + sep.GetToken(modes); + + int adding = -1; + for (unsigned i = 0, end_mode = modes.length(); i < end_mode; ++i) + { + if (modes[i] == '+') + adding = 1; + else if (modes[i] == '-') + adding = 0; + else if (adding != -1) + { + ChannelMode *cm = ModeManager::FindChannelModeByChar(modes[i]); + + if (cm && cm->type != MODE_STATUS) + { + Anope::string param; + if (adding == 1 && cm->type != MODE_REGULAR && !sep.GetToken(param)) // MODE_LIST OR MODE_PARAM + { + Log() << "Warning: Got default mlock mode " << cm->mchar << " with no param?"; + continue; + } + + if (cm->type != MODE_LIST) // Only MODE_LIST can have duplicates + { + ChannelInfo::ModeList::iterator it = DefaultModeLocks.find(cm->name); + if (it != DefaultModeLocks.end()) + { + delete it->second; + DefaultModeLocks.erase(it); + } + } + DefaultModeLocks.insert(std::make_pair(cm->name, new ModeLock(NULL, adding == 1, cm->name, param))); + } + } + } + + /* Set Bot Modes */ + DefaultBotModes.ClearFlags(); + for (unsigned i = 0; i < config->BotModes.length(); ++i) + { + ChannelMode *cm = ModeManager::FindChannelModeByChar(config->BotModes[i]); + + if (cm && cm->type == MODE_STATUS) + DefaultBotModes.SetFlag(cm->name); + } +} + +Entry::Entry(ChannelModeName mode, const Anope::string &_host) : modename(mode) +{ + this->SetFlag(ENTRYTYPE_NONE); + this->cidr_len = 0; + this->mask = _host; + + Anope::string _nick, _user, _realhost; + size_t at = _host.find('@'); + if (at != Anope::string::npos) + { + _realhost = _host.substr(at + 1); + Anope::string _nickident = _host.substr(0, at); + + size_t ex = _nickident.find('!'); + if (ex != Anope::string::npos) + { + _user = _nickident.substr(ex + 1); + _nick = _nickident.substr(0, ex); + } + else + _user = _nickident; + } + else + _realhost = _host; + + if (!_nick.empty() && _nick.find_first_not_of("*") != Anope::string::npos) + { + this->nick = _nick; + if (_nick.find_first_of("*?") != Anope::string::npos) + this->SetFlag(ENTRYTYPE_NICK_WILD); + else + this->SetFlag(ENTRYTYPE_NICK); + } + + if (!_user.empty() && _user.find_first_not_of("*") != Anope::string::npos) + { + this->user = _user; + if (_user.find_first_of("*?") != Anope::string::npos) + this->SetFlag(ENTRYTYPE_USER_WILD); + else + this->SetFlag(ENTRYTYPE_USER); + } + + if (!_realhost.empty() && _realhost.find_first_not_of("*") != Anope::string::npos) + { + size_t sl = _realhost.find_last_of('/'); + if (sl != Anope::string::npos) + { + try + { + sockaddrs addr(_realhost.substr(0, sl)); + /* If we got here, _realhost is a valid IP */ + + Anope::string cidr_range = _realhost.substr(sl + 1); + if (cidr_range.is_pos_number_only()) + { + _realhost = _realhost.substr(0, sl); + this->cidr_len = convertTo<unsigned int>(cidr_range); + this->SetFlag(ENTRYTYPE_CIDR); + Log(LOG_DEBUG) << "Ban " << _realhost << " has cidr " << static_cast<unsigned int>(this->cidr_len); + } + } + catch (const SocketException &) { } + } + + this->host = _realhost; + + if (!this->HasFlag(ENTRYTYPE_CIDR)) + { + if (_realhost.find_first_of("*?") != Anope::string::npos) + this->SetFlag(ENTRYTYPE_HOST_WILD); + else + this->SetFlag(ENTRYTYPE_HOST); + } + } +} + +const Anope::string Entry::GetMask() +{ + return this->mask; +} + +bool Entry::Matches(const User *u, bool full) const +{ + bool ret = true; + + if (this->HasFlag(ENTRYTYPE_CIDR)) + { + try + { + if (full) + { + cidr cidr_mask(this->host, this->cidr_len); + sockaddrs addr(u->ip); + if (!cidr_mask.match(addr)) + ret = false; + } + /* If we're not matching fully and their displayed host isnt their IP */ + else if (u->ip != u->GetDisplayedHost()) + ret = false; + } + catch (const SocketException &) + { + ret = false; + } + } + if (this->HasFlag(ENTRYTYPE_NICK) && !this->nick.equals_ci(u->nick)) + ret = false; + if (this->HasFlag(ENTRYTYPE_USER) && !this->user.equals_ci(u->GetVIdent()) && (!full || + !this->user.equals_ci(u->GetIdent()))) + ret = false; + if (this->HasFlag(ENTRYTYPE_HOST) && !this->host.equals_ci(u->GetDisplayedHost()) && (!full || + (!this->host.equals_ci(u->host) && !this->host.equals_ci(u->chost) && !this->host.equals_ci(u->vhost) && + !this->host.equals_ci(u->ip)))) + ret = false; + if (this->HasFlag(ENTRYTYPE_NICK_WILD) && !Anope::Match(u->nick, this->nick)) + ret = false; + if (this->HasFlag(ENTRYTYPE_USER_WILD) && !Anope::Match(u->GetVIdent(), this->user) && (!full || + !Anope::Match(u->GetIdent(), this->user))) + ret = false; + if (this->HasFlag(ENTRYTYPE_HOST_WILD) && !Anope::Match(u->GetDisplayedHost(), this->host) && (!full || + (!Anope::Match(u->host, this->host) && !Anope::Match(u->chost, this->host) && + !Anope::Match(u->vhost, this->host) && !Anope::Match(u->ip, this->host)))) + ret = false; + + ChannelMode *cm = ModeManager::FindChannelModeByName(this->modename); + if (cm != NULL && cm->type == MODE_LIST) + { + ChannelModeList *cml = anope_dynamic_static_cast<ChannelModeList *>(cm); + if (cml->Matches(u, this)) + ret = true; + } + + return ret; +} + diff --git a/src/module.cpp b/src/module.cpp index e69b7c6a3..3c3b8fdd1 100644 --- a/src/module.cpp +++ b/src/module.cpp @@ -4,13 +4,13 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ - #include "services.h" #include "modules.h" -#include "extern.h" #include "dns.h" +#include "language.h" #ifdef GETTEXT_FOUND # include <libintl.h> @@ -26,19 +26,19 @@ Module::Module(const Anope::string &modname, const Anope::string &, ModType modt if (ModuleManager::FindModule(this->name)) throw CoreException("Module already exists!"); - if (nothird && modtype == THIRD) + if (Anope::NoThird && modtype == THIRD) throw ModuleException("Third party modules may not be loaded"); - Modules.push_back(this); + ModuleManager::Modules.push_back(this); #if GETTEXT_FOUND - for (unsigned i = 0; i < languages.size(); ++i) - if (IsFile(locale_dir + "/" + languages[i] + "/LC_MESSAGES/" + modname + ".mo")) + for (unsigned i = 0; i < Language::Languages.size(); ++i) + if (Anope::IsFile(Anope::LocaleDir + "/" + Language::Languages[i] + "/LC_MESSAGES/" + modname + ".mo")) { - if (!bindtextdomain(this->name.c_str(), locale_dir.c_str())) + if (!bindtextdomain(this->name.c_str(), Anope::LocaleDir.c_str())) Log() << "Error calling bindtextdomain, " << Anope::LastError(); else - domains.push_back(modname); + Language::Domains.push_back(modname); break; } #endif @@ -46,22 +46,22 @@ Module::Module(const Anope::string &modname, const Anope::string &, ModType modt Module::~Module() { - if (DNSEngine) - DNSEngine->Cleanup(this); + if (DNS::Engine) + DNS::Engine->Cleanup(this); /* Detach all event hooks for this module */ ModuleManager::DetachAll(this); /* Clear any active callbacks this module has */ ModuleManager::ClearCallBacks(this); IdentifyRequest::ModuleUnload(this); - std::list<Module *>::iterator it = std::find(Modules.begin(), Modules.end(), this); - if (it != Modules.end()) - Modules.erase(it); + std::list<Module *>::iterator it = std::find(ModuleManager::Modules.begin(), ModuleManager::Modules.end(), this); + if (it != ModuleManager::Modules.end()) + ModuleManager::Modules.erase(it); #if GETTEXT_FOUND - std::vector<Anope::string>::iterator dit = std::find(domains.begin(), domains.end(), this->name); - if (dit != domains.end()) - domains.erase(dit); + std::vector<Anope::string>::iterator dit = std::find(Language::Domains.begin(), Language::Domains.end(), this->name); + if (dit != Language::Domains.end()) + Language::Domains.erase(dit); #endif } @@ -85,26 +85,38 @@ void Module::SetAuthor(const Anope::string &nauthor) this->author = nauthor; } -ModuleVersion::ModuleVersion(int vMajor, int vMinor, int vPatch) : Major(vMajor), Minor(vMinor), Patch(vPatch) +IRCDProto *Module::GetIRCDProto() { + return NULL; } -ModuleVersion::~ModuleVersion() +ModuleVersion::ModuleVersion(int maj, int min, int pa) : version_major(maj), version_minor(min), version_patch(pa) { } int ModuleVersion::GetMajor() const { - return this->Major; + return this->version_major; } int ModuleVersion::GetMinor() const { - return this->Minor; + return this->version_minor; } int ModuleVersion::GetPatch() const { - return this->Patch; + return this->version_patch; +} + +CallBack::CallBack(Module *mod, long time_from_now, time_t now, bool repeating) : Timer(time_from_now, now, repeating), m(mod) +{ +} + +CallBack::~CallBack() +{ + std::list<CallBack *>::iterator it = std::find(m->callbacks.begin(), m->callbacks.end(), this); + if (it != m->callbacks.end()) + m->callbacks.erase(it); } diff --git a/src/modulemanager.cpp b/src/modulemanager.cpp index 360a0d34b..5e2165e30 100644 --- a/src/modulemanager.cpp +++ b/src/modulemanager.cpp @@ -4,11 +4,11 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. + * */ #include "services.h" #include "modules.h" -#include "extern.h" #include "users.h" #include "regchannel.h" @@ -20,11 +20,12 @@ #include <dlfcn.h> #endif +std::list<Module *> ModuleManager::Modules; std::vector<Module *> ModuleManager::EventHandlers[I_END]; void ModuleManager::CleanupRuntimeDirectory() { - Anope::string dirbuf = db_dir + "/runtime"; + Anope::string dirbuf = Anope::DataDir + "/runtime"; Log(LOG_DEBUG) << "Cleaning out Module run time directory (" << dirbuf << ") - this may take a moment please wait"; @@ -59,7 +60,7 @@ void ModuleManager::CleanupRuntimeDirectory() */ static ModuleReturn moduleCopyFile(const Anope::string &name, Anope::string &output) { - Anope::string input = modules_dir + "/modules/" + name + ".so"; + Anope::string input = Anope::ModuleDir + "/modules/" + name + ".so"; struct stat s; if (stat(input.c_str(), &s) == -1) @@ -114,7 +115,7 @@ static ModuleReturn moduleCopyFile(const Anope::string &name, Anope::string &out * This function will take a pointer from either dlsym or GetProcAddress and cast it in * a way that won't cause C++ warnings/errors to come up. */ -template <class TYPE> TYPE function_cast(void *symbol) +template <class TYPE> static TYPE function_cast(void *symbol) { union { @@ -136,7 +137,7 @@ ModuleReturn ModuleManager::LoadModule(const Anope::string &modname, User *u) Log(LOG_DEBUG) << "trying to load [" << modname << "]"; /* Generate the filename for the temporary copy of the module */ - Anope::string pbuf = db_dir + "/runtime/" + modname + ".so.XXXXXX"; + Anope::string pbuf = Anope::DataDir + "/runtime/" + modname + ".so.XXXXXX"; /* Don't skip return value checking! -GD */ ModuleReturn ret = moduleCopyFile(modname, pbuf); @@ -219,12 +220,6 @@ ModuleReturn ModuleManager::LoadModule(const Anope::string &modname, User *u) else Log(LOG_DEBUG_2) << "Module " << modname << " is compiled against current version of Anope " << Anope::VersionShort(); - if (m->type == PROTOCOL && ModuleManager::FindFirstOf(PROTOCOL) != m) - { - DeleteModule(m); - Log() << "You cannot load two protocol modules"; - return MOD_ERR_UNKNOWN; - } Log(LOG_DEBUG) << "Module loaded."; FOREACH_MOD(I_OnModuleLoad, OnModuleLoad(u, m)); @@ -455,17 +450,12 @@ bool ModuleManager::SetPriority(Module *mod, Implementation i, Priority s, Modul return true; } -/** Delete all callbacks attached to a module - * @param m The module - */ void ModuleManager::ClearCallBacks(Module *m) { - while (!m->CallBacks.empty()) - delete m->CallBacks.front(); + while (!m->callbacks.empty()) + delete m->callbacks.front(); } -/** Unloading all modules except the protocol module. - */ void ModuleManager::UnloadAll() { std::vector<Anope::string> modules[MT_END]; diff --git a/src/modules.cpp b/src/modules.cpp deleted file mode 100644 index 453a89a1a..000000000 --- a/src/modules.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* Modular support - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - - -#include "services.h" -#include "modules.h" - -std::list<Module *> Modules; - -CallBack::CallBack(Module *mod, long time_from_now, time_t now, bool repeating) : Timer(time_from_now, now, repeating), m(mod) -{ -} - -CallBack::~CallBack() -{ - std::list<CallBack *>::iterator it = std::find(m->CallBacks.begin(), m->CallBacks.end(), this); - if (it != m->CallBacks.end()) - m->CallBacks.erase(it); -} - diff --git a/src/nickalias.cpp b/src/nickalias.cpp index 0268b98be..f163c145f 100644 --- a/src/nickalias.cpp +++ b/src/nickalias.cpp @@ -7,9 +7,9 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ - #include "services.h" #include "account.h" #include "modules.h" @@ -19,17 +19,9 @@ #include "servers.h" #include "config.h" -serialize_checker<nickalias_map> NickAliasList("NickAlias"); +Serialize::Checker<nickalias_map> NickAliasList("NickAlias"); -class NickServHeld; -typedef std::map<Anope::string, NickServHeld *> nickservheld_map; -static nickservheld_map NickServHelds; - -/** Default constructor - * @param nick The nick - * @param nickcore The nickcore for this nick - */ -NickAlias::NickAlias(const Anope::string &nickname, NickCore* nickcore) : Serializable("NickAlias"), Flags<NickNameFlag, NS_END>(NickNameFlagStrings) +NickAlias::NickAlias(const Anope::string &nickname, NickCore* nickcore) : Serializable("NickAlias") { if (nickname.empty()) throw CoreException("Empty nick passed to NickAlias constructor"); @@ -57,8 +49,6 @@ NickAlias::NickAlias(const Anope::string &nickname, NickCore* nickcore) : Serial } } -/** Default destructor - */ NickAlias::~NickAlias() { FOREACH_MOD(I_OnDelNick, OnDelNick(this)); @@ -67,19 +57,19 @@ NickAlias::~NickAlias() if (this->nc) { /* Next: see if our core is still useful. */ - std::list<serialize_obj<NickAlias> >::iterator it = std::find(this->nc->aliases.begin(), this->nc->aliases.end(), this); + std::list<Serialize::Reference<NickAlias> >::iterator it = std::find(this->nc->aliases.begin(), this->nc->aliases.end(), this); if (it != this->nc->aliases.end()) this->nc->aliases.erase(it); if (this->nc->aliases.empty()) { - this->nc->destroy(); + this->nc->Destroy(); this->nc = NULL; } else { /* Display updating stuff */ if (this->nick.equals_ci(this->nc->display)) - change_core_display(this->nc); + this->nc->SetDisplay(this->nc->aliases.front()); } } @@ -87,19 +77,15 @@ NickAlias::~NickAlias() NickAliasList->erase(this->nick); } -/** Release a nick from being held. This can be called from the core (ns_release) - * or from a timer used when forcing clients off of nicks. Note that if this is called - * from a timer, ircd->svshold is NEVER true - */ void NickAlias::Release() { if (this->HasFlag(NS_HELD)) { - if (ircdproto->CanSVSHold) - ircdproto->SendSVSHoldDel(this->nick); + if (IRCD->CanSVSHold) + IRCD->SendSVSHoldDel(this->nick); else { - User *u = finduser(this->nick); + User *u = User::Find(this->nick); if (u && u->server == Me) { delete u; @@ -114,12 +100,14 @@ void NickAlias::Release() */ class NickServHeld : public Timer { - dynamic_reference<NickAlias> na; + static std::map<Anope::string, NickServHeld *> NickServHelds; + + Reference<NickAlias> na; Anope::string nick; public: NickServHeld(NickAlias *n, long l) : Timer(l), na(n), nick(na->nick) { - nickservheld_map::iterator nit = NickServHelds.find(na->nick); + std::map<Anope::string, NickServHeld *>::iterator nit = NickServHelds.find(na->nick); if (nit != NickServHelds.end()) delete nit->second; @@ -137,6 +125,7 @@ class NickServHeld : public Timer na->UnsetFlag(NS_HELD); } }; +std::map<Anope::string, NickServHeld *> NickServHeld::NickServHelds; /** Timers for releasing nicks to be available for use */ @@ -146,27 +135,25 @@ class CoreExport NickServRelease : public User, public Timer Anope::string nick; public: - /** Default constructor + /** Constructor * @param na The nick * @param delay The delay before the nick is released */ - NickServRelease(NickAlias *na, time_t delay) : User(na->nick, Config->NSEnforcerUser, Config->NSEnforcerHost, "", "", Me, "Services Enforcer", Anope::CurTime, "", ts6_uid_retrieve()), Timer(delay), nick(na->nick) + NickServRelease(NickAlias *na, time_t delay) : User(na->nick, Config->NSEnforcerUser, Config->NSEnforcerHost, "", "", Me, "Services Enforcer", Anope::CurTime, "", Servers::TS6_UID_Retrieve()), Timer(delay), nick(na->nick) { /* Erase the current release timer and use the new one */ std::map<Anope::string, NickServRelease *>::iterator nit = NickServReleases.find(this->nick); if (nit != NickServReleases.end()) { - ircdproto->SendQuit(nit->second, ""); + IRCD->SendQuit(nit->second, ""); delete nit->second; } NickServReleases.insert(std::make_pair(this->nick, this)); - ircdproto->SendClientIntroduction(this); + IRCD->SendClientIntroduction(this); } - /** Default destructor - */ virtual ~NickServRelease() { NickServReleases.erase(this->nick); @@ -177,15 +164,11 @@ class CoreExport NickServRelease : public User, public Timer */ void Tick(time_t t) { - ircdproto->SendQuit(this, ""); + IRCD->SendQuit(this, ""); } }; std::map<Anope::string, NickServRelease *> NickServRelease::NickServReleases; -/** Called when a user gets off this nick - * See the comment in users.cpp for User::Collide() - * @param u The user - */ void NickAlias::OnCancel(User *) { if (this->HasFlag(NS_COLLIDED)) @@ -195,8 +178,8 @@ void NickAlias::OnCancel(User *) new NickServHeld(this, Config->NSReleaseTimeout); - if (ircdproto->CanSVSHold) - ircdproto->SendSVSHold(this->nick); + if (IRCD->CanSVSHold) + IRCD->SendSVSHold(this->nick); else new NickServRelease(this, Config->NSReleaseTimeout); } @@ -243,17 +226,29 @@ time_t NickAlias::GetVhostCreated() const return this->vhost_created; } -Serialize::Data NickAlias::serialize() const +NickAlias *NickAlias::Find(const Anope::string &nick) +{ + nickalias_map::const_iterator it = NickAliasList->find(nick); + if (it != NickAliasList->end()) + { + it->second->QueueUpdate(); + return it->second; + } + + return NULL; +} + +Serialize::Data NickAlias::Serialize() const { Serialize::Data data; - data["nick"].setMax(Config->NickLen) << this->nick; + data["nick"].SetMax(Config->NickLen) << this->nick; data["last_quit"] << this->last_quit; data["last_realname"] << this->last_realname; data["last_usermask"] << this->last_usermask; data["last_realhost"] << this->last_realhost; - data["time_registered"].setType(Serialize::DT_INT) << this->time_registered; - data["last_seen"].setType(Serialize::DT_INT) << this->last_seen; + data["time_registered"].SetType(Serialize::DT_INT) << this->time_registered; + data["last_seen"].SetType(Serialize::DT_INT) << this->last_seen; data["nc"] << this->nc->display; data["flags"] << this->ToString(); @@ -268,9 +263,9 @@ Serialize::Data NickAlias::serialize() const return data; } -Serializable* NickAlias::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* NickAlias::Unserialize(Serializable *obj, Serialize::Data &data) { - NickCore *core = findcore(data["nc"].astr()); + NickCore *core = NickCore::Find(data["nc"].astr()); if (core == NULL) return NULL; @@ -282,14 +277,14 @@ Serializable* NickAlias::unserialize(Serializable *obj, Serialize::Data &data) if (na->nc != core) { - std::list<serialize_obj<NickAlias> >::iterator it = std::find(na->nc->aliases.begin(), na->nc->aliases.end(), na); + std::list<Serialize::Reference<NickAlias> >::iterator it = std::find(na->nc->aliases.begin(), na->nc->aliases.end(), na); if (it != na->nc->aliases.end()) na->nc->aliases.erase(it); if (na->nc->aliases.empty()) delete na->nc; else if (na->nick.equals_ci(na->nc->display)) - change_core_display(na->nc); + na->nc->SetDisplay(na->nc->aliases.front()); na->nc = core; core->aliases.push_back(na); diff --git a/src/nickcore.cpp b/src/nickcore.cpp index 0e637d0cf..f9ac3ef6c 100644 --- a/src/nickcore.cpp +++ b/src/nickcore.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -14,12 +15,21 @@ #include "account.h" #include "config.h" -serialize_checker<nickcore_map> NickCoreList("NickCore"); +Serialize::Checker<nickcore_map> NickCoreList("NickCore"); -/** Default constructor - * @param display The display nick - */ -NickCore::NickCore(const Anope::string &coredisplay) : Serializable("NickCore"), Flags<NickCoreFlag, NI_END>(NickCoreFlagStrings) +static const Anope::string NickNameFlagStrings[] = { + "BEGIN", "NO_EXPIRE", "HELD", "COLLIDED", "" +}; +template<> const Anope::string* Flags<NickNameFlag>::flags_strings = NickNameFlagStrings; + +static const Anope::string NickCoreFlagStrings[] = { + "BEGIN", "KILLPROTECT", "SECURE", "MSG", "MEMO_HARDMAX", "MEMO_SIGNON", "MEMO_RECEIVE", + "PRIVATE", "HIDE_EMAIL", "HIDE_MASK", "HIDE_QUIT", "KILL_QUICK", "KILL_IMMED", + "MEMO_MAIL", "HIDE_STATUS", "SUSPENDED", "AUTOOP", "UNCONFIRMED", "STATS", "" +}; +template<> const Anope::string* Flags<NickCoreFlag>::flags_strings = NickCoreFlagStrings; + +NickCore::NickCore(const Anope::string &coredisplay) : Serializable("NickCore") { if (coredisplay.empty()) throw CoreException("Empty display passed to NickCore constructor"); @@ -43,12 +53,17 @@ NickCore::NickCore(const Anope::string &coredisplay) : Serializable("NickCore"), Log(LOG_DEBUG) << "Duplicate account " << coredisplay << " in nickcore table?"; } -/** Default destructor - */ NickCore::~NickCore() { FOREACH_MOD(I_OnDelCore, OnDelCore(this)); + for (std::list<User *>::iterator it = this->users.begin(); it != this->users.end();) + { + User *user = *it++; + user->Logout(); + } + this->users.clear(); + /* Remove the core from the list */ NickCoreList->erase(this->display); @@ -58,16 +73,16 @@ NickCore::~NickCore() if (!this->memos.memos->empty()) { for (unsigned i = 0, end = this->memos.memos->size(); i < end; ++i) - this->memos.GetMemo(i)->destroy(); + this->memos.GetMemo(i)->Destroy(); this->memos.memos->clear(); } } -Serialize::Data NickCore::serialize() const +Serialize::Data NickCore::Serialize() const { Serialize::Data data; - data["display"].setMax(Config->NickLen) << this->display; + data["display"].SetMax(Config->NickLen) << this->display; data["pass"] << this->pass; data["email"] << this->email; data["greet"] << this->greet; @@ -84,7 +99,7 @@ Serialize::Data NickCore::serialize() const return data; } -Serializable* NickCore::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* NickCore::Unserialize(Serializable *obj, Serialize::Data &data) { NickCore *nc; @@ -127,6 +142,21 @@ Serializable* NickCore::unserialize(Serializable *obj, Serialize::Data &data) return nc; } +void NickCore::SetDisplay(const NickAlias *na) +{ + if (na->nc != this || na->nick == this->display) + return; + + FOREACH_MOD(I_OnChangeCoreDisplay, OnChangeCoreDisplay(this, na->nick)); + + /* Remove the core from the list */ + NickCoreList->erase(this->display); + + this->display = na->nick; + + (*NickCoreList)[this->display] = this; +} + bool NickCore::IsServicesOper() const { return this->o != NULL; @@ -171,6 +201,23 @@ void NickCore::ClearAccess() this->access.clear(); } +bool NickCore::IsOnAccess(const User *u) const +{ + Anope::string buf = u->GetIdent() + "@" + u->host, buf2, buf3; + if (!u->vhost.empty()) + buf2 = u->GetIdent() + "@" + u->vhost; + if (!u->GetCloakedHost().empty()) + buf3 = u->GetIdent() + "@" + u->GetCloakedHost(); + + for (unsigned i = 0, end = this->access.size(); i < end; ++i) + { + Anope::string a = this->GetAccess(i); + if (Anope::Match(buf, a) || (!buf2.empty() && Anope::Match(buf2, a)) || (!buf3.empty() && Anope::Match(buf3, a))) + return true; + } + return false; +} + void NickCore::AddCert(const Anope::string &entry) { this->cert.push_back(entry); @@ -209,3 +256,16 @@ void NickCore::ClearCert() FOREACH_MOD(I_OnNickClearCert, OnNickClearCert(this)); this->cert.clear(); } + +NickCore* NickCore::Find(const Anope::string &nick) +{ + nickcore_map::const_iterator it = NickCoreList->find(nick); + if (it != NickCoreList->end()) + { + it->second->QueueUpdate(); + return it->second; + } + + return NULL; +} + diff --git a/src/nickserv.cpp b/src/nickserv.cpp deleted file mode 100644 index 8b5c41df9..000000000 --- a/src/nickserv.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* NickServ functions. - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - -#include "services.h" -#include "account.h" -#include "modules.h" -#include "users.h" -#include "protocol.h" -#include "regchannel.h" - -NickAlias* findnick(const Anope::string &nick) -{ - nickalias_map::const_iterator it = NickAliasList->find(nick); - if (it != NickAliasList->end()) - { - it->second->QueueUpdate(); - return it->second; - } - - return NULL; -} - -/*************************************************************************/ - -NickCore* findcore(const Anope::string &nick) -{ - nickcore_map::const_iterator it = NickCoreList->find(nick); - if (it != NickCoreList->end()) - { - it->second->QueueUpdate(); - return it->second; - } - - return NULL; -} - -/** Is the user's address on the nickcores access list? - * @param u The user - * @param nc The nickcore - * @return true or false - */ -bool is_on_access(const User *u, const NickCore *nc) -{ - if (!u || !nc || nc->access.empty()) - return false; - - Anope::string buf = u->GetIdent() + "@" + u->host, buf2, buf3; - if (!u->vhost.empty()) - buf2 = u->GetIdent() + "@" + u->vhost; - if (!u->GetCloakedHost().empty()) - buf3 = u->GetIdent() + "@" + u->GetCloakedHost(); - - for (unsigned i = 0, end = nc->access.size(); i < end; ++i) - { - Anope::string access = nc->GetAccess(i); - if (Anope::Match(buf, access) || (!buf2.empty() && Anope::Match(buf2, access)) || (!buf3.empty() && Anope::Match(buf3, access))) - return true; - } - return false; -} - -/*************************************************************************/ - -/* Sets nc->display to newdisplay. If newdisplay is NULL, it will change - * it to the first alias in the list. - */ - -void change_core_display(NickCore *nc, const Anope::string &newdisplay) -{ - FOREACH_MOD(I_OnChangeCoreDisplay, OnChangeCoreDisplay(nc, newdisplay)); - - /* Remove the core from the list */ - NickCoreList->erase(nc->display); - - nc->display = newdisplay; - - (*NickCoreList)[nc->display] = nc; -} - -void change_core_display(NickCore *nc) -{ - const NickAlias *na; - if (nc->aliases.empty()) - return; - na = nc->aliases.front(); - change_core_display(nc, na->nick); -} - -std::set<IdentifyRequest *> IdentifyRequest::requests; - -IdentifyRequest::IdentifyRequest(Module *o, const Anope::string &acc, const Anope::string &pass) : owner(o), account(acc), password(pass), dispatched(false), success(false) -{ - requests.insert(this); -} - -IdentifyRequest::~IdentifyRequest() -{ - requests.erase(this); -} - -void IdentifyRequest::Hold(Module *m) -{ - holds.insert(m); -} - -void IdentifyRequest::Release(Module *m) -{ - holds.erase(m); - if (holds.empty() && dispatched) - { - if (!success) - this->OnFail(); - delete this; - } -} - -void IdentifyRequest::Success(Module *m) -{ - if (!success) - { - this->OnSuccess(); - success = true; - } -} - -void IdentifyRequest::Dispatch() -{ - if (holds.empty()) - { - if (!success) - this->OnFail(); - delete this; - } - else - dispatched = true; -} - -void IdentifyRequest::ModuleUnload(Module *m) -{ - for (std::set<IdentifyRequest *>::iterator it = requests.begin(), it_end = requests.end(); it != it_end;) - { - IdentifyRequest *ir = *it; - ++it; - - ir->Release(m); - if (ir->owner == m) - delete ir; - } -} diff --git a/src/operserv.cpp b/src/operserv.cpp deleted file mode 100644 index f1c2edeea..000000000 --- a/src/operserv.cpp +++ /dev/null @@ -1,484 +0,0 @@ -/* OperServ functions. - * - * (C) 2003-2012 Anope Team - * Contact us at team@anope.org - * - * Please read COPYING and README for further details. - * - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. - */ - - -#include "services.h" -#include "modules.h" -#include "oper.h" -#include "users.h" -#include "extern.h" -#include "sockets.h" -#include "regexpr.h" -#include "config.h" -#include "commands.h" - -/* List of XLine managers we check users against in XLineManager::CheckAll */ -std::list<XLineManager *> XLineManager::XLineManagers; -serialize_checker<std::multimap<Anope::string, XLine *, ci::less> > XLineManager::XLinesByUID("XLine"); - -void XLine::InitRegex() -{ - if (!Config->RegexEngine.empty() && this->Mask.length() >= 2 && this->Mask[0] == '/' && this->Mask[this->Mask.length() - 1] == '/') - { - Anope::string stripped_mask = this->Mask.substr(1, this->Mask.length() - 2); - - service_reference<RegexProvider> provider("Regex", Config->RegexEngine); - if (provider) - { - try - { - this->regex = provider->Compile(stripped_mask); - } - catch (const RegexException &ex) - { - Log(LOG_DEBUG) << ex.GetReason(); - } - } - } -} - -XLine::XLine(const Anope::string &mask, const Anope::string &reason, const Anope::string &uid) : Serializable("XLine"), Mask(mask), By(Config->OperServ), Created(0), Expires(0), Reason(reason), UID(uid) -{ - regex = NULL; - manager = NULL; - - this->InitRegex(); -} - -XLine::XLine(const Anope::string &mask, const Anope::string &by, const time_t expires, const Anope::string &reason, const Anope::string &uid) : Serializable("XLine"), Mask(mask), By(by), Created(Anope::CurTime), Expires(expires), Reason(reason), UID(uid) -{ - regex = NULL; - manager = NULL; - - this->InitRegex(); -} - -XLine::~XLine() -{ - delete regex; -} - -Anope::string XLine::GetNick() const -{ - size_t nick_t = this->Mask.find('!'); - - if (nick_t == Anope::string::npos) - return ""; - - return this->Mask.substr(0, nick_t); -} - -Anope::string XLine::GetUser() const -{ - size_t user_t = this->Mask.find('!'), host_t = this->Mask.find('@'); - - if (host_t != Anope::string::npos) - { - if (user_t != Anope::string::npos && host_t > user_t) - return this->Mask.substr(user_t + 1, host_t - user_t - 1); - else - return this->Mask.substr(0, host_t); - } - else - return ""; -} - -Anope::string XLine::GetHost() const -{ - size_t host_t = this->Mask.find('@'), real_t = this->Mask.find('#'); - - if (host_t != Anope::string::npos) - { - if (real_t != Anope::string::npos && real_t > host_t) - return this->Mask.substr(host_t + 1, real_t - host_t - 1); - else - return this->Mask.substr(host_t + 1); - } - else - return ""; -} - -Anope::string XLine::GetReal() const -{ - size_t real_t = this->Mask.find('#'); - - if (real_t != Anope::string::npos) - return this->Mask.substr(real_t + 1); - else - return ""; -} - -Anope::string XLine::GetReason() const -{ - Anope::string r = this->Reason; - if (Config->AddAkiller && !this->By.empty()) - r = "[" + this->By + "] " + r; - if (!this->UID.empty()) - r += " (ID: " + this->UID + ")"; - return r; -} - -bool XLine::HasNickOrReal() const -{ - bool r = this->GetNick().find_first_not_of("?*") != Anope::string::npos; - r = r || this->GetReal().find_first_not_of("?*") != Anope::string::npos; - return r; -} - -bool XLine::IsRegex() const -{ - return !this->Mask.empty() && this->Mask[0] == '/' && this->Mask[this->Mask.length() - 1] == '/'; -} - -Serialize::Data XLine::serialize() const -{ - Serialize::Data data; - - data["mask"] << this->Mask; - data["by"] << this->By; - data["created"] << this->Created; - data["expires"] << this->Expires; - data["reason"] << this->Reason; - data["uid"] << this->UID; - if (this->manager) - data["manager"] << this->manager->name; - - return data; -} - -Serializable* XLine::unserialize(Serializable *obj, Serialize::Data &data) -{ - service_reference<XLineManager> xlm("XLineManager", data["manager"].astr()); - if (!xlm) - return NULL; - - XLine *xl; - if (obj) - { - xl = anope_dynamic_static_cast<XLine *>(obj); - data["mask"] >> xl->Mask; - data["by"] >> xl->By; - data["reason"] >> xl->Reason; - data["uid"] >> xl->UID; - - if (xlm != xl->manager) - { - xl->manager->DelXLine(xl); - xlm->AddXLine(xl); - } - } - else - { - time_t expires; - data["expires"] >> expires; - xl = new XLine(data["mask"].astr(), data["by"].astr(), expires, data["reason"].astr(), data["uid"].astr()); - xlm->AddXLine(xl); - } - - data["created"] >> xl->Created; - xl->manager = xlm; - - return xl; -} - -/** Register a XLineManager, places it in XLineManagers for use in XLineManager::CheckAll - * It is important XLineManagers are registered in the proper order. Eg, if you had one akilling - * clients and one handing them free olines, you would want the akilling one first. This way if a client - * matches an entry on both of the XLineManagers, they would be akilled. - * @param xlm THe XLineManager - */ -void XLineManager::RegisterXLineManager(XLineManager *xlm) -{ - XLineManagers.push_back(xlm); -} - -/** Unregister a XLineManager - * @param xlm The XLineManager - */ -void XLineManager::UnregisterXLineManager(XLineManager *xlm) -{ - std::list<XLineManager *>::iterator it = std::find(XLineManagers.begin(), XLineManagers.end(), xlm); - - if (it != XLineManagers.end()) - XLineManagers.erase(it); -} - -/* Check a user against all known XLineManagers - * @param u The user - * @return A pair of the XLineManager the user was found in and the XLine they matched, both may be NULL for no match - */ -void XLineManager::CheckAll(User *u) -{ - for (std::list<XLineManager *>::iterator it = XLineManagers.begin(), it_end = XLineManagers.end(); it != it_end; ++it) - { - XLineManager *xlm = *it; - - XLine *x = xlm->CheckAllXLines(u); - - if (x) - { - xlm->OnMatch(u, x); - break; - } - } -} - -Anope::string XLineManager::GenerateUID() -{ - Anope::string id; - int count = 0; - while (id.empty() || XLinesByUID->count(id) > 0) - { - if (++count > 10) - { - id.clear(); - Log(LOG_DEBUG) << "Unable to generate XLine UID"; - break; - } - - for (int i = 0; i < 10; ++i) - { - char c; - do - c = (rand() % 75) + 48; - while (!isupper(c) && !isdigit(c)); - id += c; - } - } - - return id; -} - -/** Constructor - */ -XLineManager::XLineManager(Module *creator, const Anope::string &xname, char t) : Service(creator, "XLineManager", xname), type(t), XLines("XLine") -{ -} - -/** Destructor - * Clears all XLines in this XLineManager - */ -XLineManager::~XLineManager() -{ - this->Clear(); -} - -/** The type of xline provided by this service - * @return The type - */ -const char &XLineManager::Type() -{ - return this->type; -} - -/** Get the number of XLines in this XLineManager - * @return The number of XLines - */ -size_t XLineManager::GetCount() const -{ - return this->XLines->size(); -} - -/** Get the XLine vector - * @return The vecotr - */ -const std::vector<XLine *> &XLineManager::GetList() const -{ - return this->XLines; -} - -/** Add an entry to this XLineManager - * @param x The entry - */ -void XLineManager::AddXLine(XLine *x) -{ - if (!x->UID.empty()) - XLinesByUID->insert(std::make_pair(x->UID, x)); - this->XLines->push_back(x); - x->manager = this; -} - -/** Delete an entry from this XLineManager - * @param x The entry - * @return true if the entry was found and deleted, else false - */ -bool XLineManager::DelXLine(XLine *x) -{ - std::vector<XLine *>::iterator it = std::find(this->XLines->begin(), this->XLines->end(), x); - - if (!x->UID.empty()) - { - std::multimap<Anope::string, XLine *, ci::less>::iterator it2 = XLinesByUID->find(x->UID), it3 = XLinesByUID->upper_bound(x->UID); - for (; it2 != XLinesByUID->end() && it2 != it3; ++it2) - if (it2->second == x) - { - XLinesByUID->erase(it2); - break; - } - } - - if (it != this->XLines->end()) - { - this->SendDel(x); - - x->destroy(); - this->XLines->erase(it); - - return true; - } - - return false; -} - -/** Gets an entry by index - * @param index The index - * @return The XLine, or NULL if the index is out of bounds - */ -XLine* XLineManager::GetEntry(unsigned index) -{ - if (index >= this->XLines->size()) - return NULL; - - XLine *x = this->XLines->at(index); - x->QueueUpdate(); - return x; -} - -/** Clear the XLine vector - */ -void XLineManager::Clear() -{ - for (unsigned i = 0; i < this->XLines->size(); ++i) - { - XLine *x = this->XLines->at(i); - if (!x->UID.empty()) - XLinesByUID->erase(x->UID); - x->destroy(); - } - this->XLines->clear(); -} - -/** Checks if a mask can/should be added to the XLineManager - * @param source The source adding the mask. - * @param mask The mask - * @param expires When the mask would expire - * @param reason the reason - * @return true if the mask can be added - */ -bool XLineManager::CanAdd(CommandSource &source, const Anope::string &mask, time_t expires, const Anope::string &reason) -{ - for (unsigned i = this->GetCount(); i > 0; --i) - { - XLine *x = this->GetEntry(i - 1); - - if (x->Mask.equals_ci(mask)) - { - if (!x->Expires || x->Expires >= expires) - { - if (x->Reason != reason) - { - x->Reason = reason; - source.Reply(_("Reason for %s updated."), x->Mask.c_str()); - } - else - source.Reply(_("%s already exists."), mask.c_str()); - } - else - { - x->Expires = expires; - if (x->Reason != reason) - { - x->Reason = reason; - source.Reply(_("Expiry and reason updated for %s."), x->Mask.c_str()); - } - else - source.Reply(_("Expiry for %s updated."), x->Mask.c_str()); - } - - return false; - } - else if (Anope::Match(mask, x->Mask) && (!x->Expires || x->Expires >= expires)) - { - source.Reply(_("%s is already covered by %s."), mask.c_str(), x->Mask.c_str()); - return false; - } - else if (Anope::Match(x->Mask, mask) && (!expires || x->Expires <= expires)) - { - source.Reply(_("Removing %s because %s covers it."), x->Mask.c_str(), mask.c_str()); - this->DelXLine(x); - } - } - - return true; -} - -/** Checks if this list has an entry - * @param mask The mask - * @return The XLine the user matches, or NULL - */ -XLine* XLineManager::HasEntry(const Anope::string &mask) -{ - std::multimap<Anope::string, XLine *, ci::less>::iterator it = XLinesByUID->find(mask); - if (it != XLinesByUID->end()) - for (std::multimap<Anope::string, XLine *, ci::less>::iterator it2 = XLinesByUID->upper_bound(mask); it != it2; ++it) - if (it->second->manager == NULL || it->second->manager == this) - { - it->second->QueueUpdate(); - return it->second; - } - for (unsigned i = 0, end = this->XLines->size(); i < end; ++i) - { - XLine *x = this->XLines->at(i); - - if (x->Mask.equals_ci(mask)) - { - x->QueueUpdate(); - return x; - } - } - - return NULL; -} - -/** Check a user against all of the xlines in this XLineManager - * @param u The user - * @return The xline the user marches, if any. - */ -XLine *XLineManager::CheckAllXLines(User *u) -{ - for (unsigned i = this->XLines->size(); i > 0; --i) - { - XLine *x = this->XLines->at(i - 1); - - if (x->Expires && x->Expires < Anope::CurTime) - { - this->OnExpire(x); - this->DelXLine(x); - continue; - } - - if (this->Check(u, x)) - { - this->OnMatch(u, x); - return x; - } - } - - return NULL; -} - -/** Called when an XLine expires - * @param x The xline - */ -void XLineManager::OnExpire(const XLine *x) -{ -} - diff --git a/src/opertype.cpp b/src/opertype.cpp index b719b4cc7..f468e0c13 100644 --- a/src/opertype.cpp +++ b/src/opertype.cpp @@ -1,8 +1,10 @@ /* + * * Copyright (C) 2008-2011 Robin Burchell <w00t@inspircd.org> * Copyright (C) 2008-2012 Anope Team <team@anope.org> * * Please read COPYING and README for further details. + * */ #include "services.h" diff --git a/src/process.cpp b/src/process.cpp index dfc4f5563..cc2b32a27 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -11,16 +11,12 @@ #include "services.h" #include "modules.h" -#include "extern.h" #include "protocol.h" #include "servers.h" #include "users.h" #include "regchannel.h" -/** Main process routine - * @param buffer A raw line from the uplink to do things with - */ -void process(const Anope::string &buffer) +void Anope::Process(const Anope::string &buffer) { /* If debugging, log the buffer */ Log(LOG_RAWIO) << "Received: " << buffer; @@ -46,12 +42,11 @@ void process(const Anope::string &buffer) } spacesepstream buf_sep(buf); - Anope::string buf_token; Anope::string command = buf; - if (buf_sep.GetToken(buf_token)) - command = buf_token; + buf_sep.GetToken(command); + Anope::string buf_token; std::vector<Anope::string> params; while (buf_sep.GetToken(buf_token)) { @@ -67,7 +62,7 @@ void process(const Anope::string &buffer) params.push_back(buf_token); } - if (protocoldebug) + if (Anope::ProtocolDebug) { Log() << "Source : " << (source.empty() ? "No source" : source); Log() << "Command: " << command; @@ -79,29 +74,26 @@ void process(const Anope::string &buffer) Log() << "params " << i << ": " << params[i]; } - const std::vector<IRCDMessage *> *messages = IRCDMessage::Find(command); + static const Anope::string proto_name = ModuleManager::FindFirstOf(PROTOCOL) ? ModuleManager::FindFirstOf(PROTOCOL)->name : ""; + + // event - if (messages && !messages->empty()) + ServiceReference<IRCDMessage> m("IRCDMessage", proto_name + "/" + command.lower()); + if (!m) { - MessageSource src(source); + Log(LOG_DEBUG) << "unknown message from server (" << buffer << ")"; + return; + } - bool retVal = true; - /* Newer messages take priority */ - for (unsigned i = messages->size(); retVal && i > 0; --i) - { - IRCDMessage *m = messages->at(i - 1); + MessageSource src(source); - if (m->HasFlag(IRCDMESSAGE_SOFT_LIMIT) ? (params.size() < m->GetParamCount()) : (params.size() != m->GetParamCount())) - Log(LOG_DEBUG) << "invalid parameters for " << command << ": " << params.size() << " != " << m->GetParamCount(); - else if (m->HasFlag(IRCDMESSAGE_REQUIRE_USER) && !src.GetUser()) - Log(LOG_DEBUG) << "unexpected non-user source " << source << " for " << command; - else if (m->HasFlag(IRCDMESSAGE_REQUIRE_SERVER) && !source.empty() && !src.GetServer()) - Log(LOG_DEBUG) << "unexpected non-server soruce " << source << " for " << command; - else - retVal = m->Run(src, params); - } - } + if (m->HasFlag(IRCDMESSAGE_SOFT_LIMIT) ? (params.size() < m->GetParamCount()) : (params.size() != m->GetParamCount())) + Log(LOG_DEBUG) << "invalid parameters for " << command << ": " << params.size() << " != " << m->GetParamCount(); + else if (m->HasFlag(IRCDMESSAGE_REQUIRE_USER) && !src.GetUser()) + Log(LOG_DEBUG) << "unexpected non-user source " << source << " for " << command; + else if (m->HasFlag(IRCDMESSAGE_REQUIRE_SERVER) && !source.empty() && !src.GetServer()) + Log(LOG_DEBUG) << "unexpected non-server soruce " << source << " for " << command; else - Log(LOG_DEBUG) << "unknown message from server (" << buffer << ")"; + m->Run(src, params); } diff --git a/src/protocol.cpp b/src/protocol.cpp index 5d836b7f4..d3372731c 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -17,10 +18,10 @@ #include "config.h" #include "uplink.h" #include "bots.h" -#include "extern.h" #include "channels.h" +#include "operserv.h" -IRCDProto *ircdproto; +IRCDProto *IRCD = NULL; IRCDProto::IRCDProto(const Anope::string &p) : proto_name(p) { @@ -29,13 +30,14 @@ IRCDProto::IRCDProto(const Anope::string &p) : proto_name(p) CanSVSO = CanCertFP = RequiresID = false; MaxModes = 3; - ircdproto = this; + if (IRCD == NULL) + IRCD = this; } IRCDProto::~IRCDProto() { - if (ircdproto == this) - ircdproto = NULL; + if (IRCD == this) + IRCD = NULL; } const Anope::string &IRCDProto::GetProtocolName() @@ -105,7 +107,7 @@ void IRCDProto::SendGlobopsInternal(const BotInfo *source, const Anope::string & void IRCDProto::SendCTCPInternal(const BotInfo *bi, const Anope::string &dest, const Anope::string &buf) { - Anope::string s = normalizeBuffer(buf); + Anope::string s = Anope::NormalizeBuffer(buf); this->SendNoticeInternal(bi, dest, "\1" + s + "\1"); } @@ -278,9 +280,9 @@ void IRCDProto::SendSquit(Server *s, const Anope::string &message) UplinkSocket::Message() << "SQUIT " << s->GetName() << " :" << message; } -void IRCDProto::SendChangeBotNick(const BotInfo *bi, const Anope::string &newnick) +void IRCDProto::SendNickChange(const User *u, const Anope::string &newnick) { - UplinkSocket::Message(bi) << "NICK " << newnick << " " << Anope::CurTime; + UplinkSocket::Message(u) << "NICK " << newnick << " " << Anope::CurTime; } void IRCDProto::SendForceNickChange(const User *u, const Anope::string &newnick, time_t when) @@ -308,6 +310,29 @@ void IRCDProto::SendNumeric(int numeric, const Anope::string &dest, const char * SendNumericInternal(numeric, dest, buf); } +bool IRCDProto::IsNickValid(const Anope::string &nick) +{ + /** + * RFC: defination of a valid nick + * nickname = ( letter / special ) ( letter / digit / special / "-" ) + * letter = A-Z / a-z + * digit = 0-9 + * special = [, ], \, `, _, ^, {, |, } + **/ + + if (nick.empty()) + return false; + + Anope::string special = "{}\\`_^{|}"; + + for (unsigned i = 0; i < nick.length(); ++i) + if (!(nick[i] >= 'A' && nick[i] <= 'Z') && !(nick[i] >= 'a' && nick[i] <= 'z') && special.find(nick[i]) == Anope::string::npos + && (!i || (!(nick[i] >= '0' && nick[i] <= '9') && nick[i] != '-'))) + return false; + + return true; +} + bool IRCDProto::IsChannelValid(const Anope::string &chan) { if (chan.empty() || chan[0] != '#' || chan.length() > Config->ChanLen) @@ -316,20 +341,59 @@ bool IRCDProto::IsChannelValid(const Anope::string &chan) return true; } +bool IRCDProto::IsIdentValid(const Anope::string &ident) +{ + if (ident.empty() || ident.length() > Config->UserLen) + return false; + + for (unsigned i = 0; i < ident.length(); ++i) + { + const char &c = ident[i]; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-') + ; + else + return false; + } + + return true; +} + +bool IRCDProto::IsHostValid(const Anope::string &host) +{ + if (host.empty() || host.length() > Config->HostLen) + return false; + + if (Config->VhostDisallowBE.find_first_of(host[0]) != Anope::string::npos) + return false; + else if (Config->VhostDisallowBE.find_first_of(host[host.length() - 1]) != Anope::string::npos) + return false; + + int dots = 0; + for (unsigned i = 0; i < host.length(); ++i) + { + if (host[i] == '.') + ++dots; + if (Config->VhostChars.find_first_of(host[i]) == Anope::string::npos) + return false; + } + + return Config->VhostUndotted || dots > 0; +} + void IRCDProto::SendOper(User *u) { SendNumericInternal(381, u->GetUID(), ":You are now an IRC operator (set by services)"); - u->SetMode(findbot(Config->OperServ), UMODE_OPER); + u->SetMode(OperServ, UMODE_OPER); } MessageSource::MessageSource(const Anope::string &src) : source(src), u(NULL), s(NULL) { if (src.empty()) this->s = !Me->GetLinks().empty() ? Me->GetLinks().front() : NULL; - else if (ircdproto->RequiresID || src.find('.') != Anope::string::npos) + else if (IRCD->RequiresID || src.find('.') != Anope::string::npos) this->s = Server::Find(src); if (this->s == NULL) - this->u = finduser(src); + this->u = User::Find(src); } MessageSource::MessageSource(User *_u) : source(_u ? _u->nick : ""), u(_u), s(NULL) @@ -365,26 +429,8 @@ Server *MessageSource::GetServer() return this->s; } -std::map<Anope::string, std::vector<IRCDMessage *> > IRCDMessage::messages; - -const std::vector<IRCDMessage *> *IRCDMessage::Find(const Anope::string &name) -{ - std::map<Anope::string, std::vector<IRCDMessage *> >::iterator it = messages.find(name); - if (it != messages.end()) - return &it->second; - return NULL; -} - -IRCDMessage::IRCDMessage(const Anope::string &n, unsigned p) : name(n), param_count(p) -{ - messages[n].insert(messages[n].begin(), this); -} - -IRCDMessage::~IRCDMessage() +IRCDMessage::IRCDMessage(Module *o, const Anope::string &n, unsigned p) : Service(o, "IRCDMessage", o->name + "/" + n.lower()), name(n), param_count(p) { - std::vector<IRCDMessage *>::iterator it = std::find(messages[this->name].begin(), messages[this->name].end(), this); - if (it != messages[this->name].end()) - messages[this->name].erase(it); } unsigned IRCDMessage::GetParamCount() const diff --git a/src/regchannel.cpp b/src/regchannel.cpp index a559d3127..3075ea301 100644 --- a/src/regchannel.cpp +++ b/src/regchannel.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -17,26 +18,36 @@ #include "channels.h" #include "config.h" #include "bots.h" -#include "extern.h" #include "language.h" #include "servers.h" +#include "chanserv.h" + +Serialize::Checker<registered_channel_map> RegisteredChannelList("ChannelInfo"); + +static const Anope::string ChannelInfoFlagStrings[] = { + "BEGIN", "KEEPTOPIC", "SECUREOPS", "PRIVATE", "TOPICLOCK", "RESTRICTED", + "PEACE", "SECURE", "NO_EXPIRE", "MEMO_HARDMAX", "SECUREFOUNDER", + "SIGNKICK", "SIGNKICK_LEVEL", "SUSPENDED", "PERSIST", "STATS", "NOAUTOOP", "" +}; +template<> const Anope::string* Flags<ChannelInfoFlag>::flags_strings = ChannelInfoFlagStrings; -serialize_checker<registered_channel_map> RegisteredChannelList("ChannelInfo"); +static const Anope::string AutoKickFlagString[] = { "AK_ISNICK", "" }; +template<> const Anope::string* Flags<AutoKickFlag>::flags_strings = AutoKickFlagString; -Serialize::Data BadWord::serialize() const +Serialize::Data BadWord::Serialize() const { Serialize::Data data; - data["ci"].setMax(64)/*XXX*/ << this->ci->name; - data["word"].setMax(512) << this->word; - data["type"].setType(Serialize::DT_INT) << this->type; + data["ci"].SetMax(64)/*XXX*/ << this->ci->name; + data["word"].SetMax(512) << this->word; + data["type"].SetType(Serialize::DT_INT) << this->type; return data; } -Serializable* BadWord::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* BadWord::Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (!ci) return NULL; @@ -56,42 +67,42 @@ Serializable* BadWord::unserialize(Serializable *obj, Serialize::Data &data) return bw; } -AutoKick::AutoKick() : Flags<AutoKickFlag>(AutoKickFlagString), Serializable("AutoKick") +AutoKick::AutoKick() : Serializable("AutoKick") { } -Serialize::Data AutoKick::serialize() const +Serialize::Data AutoKick::Serialize() const { Serialize::Data data; - data["ci"].setMax(64)/*XXX*/ << this->ci->name; + data["ci"].SetMax(64)/*XXX*/ << this->ci->name; if (this->HasFlag(AK_ISNICK) && this->nc) - data["nc"].setMax(Config->NickLen) << this->nc->display; + data["nc"].SetMax(Config->NickLen) << this->nc->display; else - data["mask"].setMax(Config->NickLen) << this->mask; + data["mask"].SetMax(Config->NickLen) << this->mask; data["reason"] << this->reason; data["creator"] << this->creator; - data["addtime"].setType(Serialize::DT_INT) << this->addtime; - data["last_used"].setType(Serialize::DT_INT) << this->last_used; + data["addtime"].SetType(Serialize::DT_INT) << this->addtime; + data["last_used"].SetType(Serialize::DT_INT) << this->last_used; data["flags"] << this->ToString(); return data; } -Serializable* AutoKick::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* AutoKick::Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (!ci) return NULL; AutoKick *ak; - NickCore *nc = findcore(data["nc"].astr()); + NickCore *nc = NickCore::Find(data["nc"].astr()); if (obj) { ak = anope_dynamic_static_cast<AutoKick *>(obj); data["creator"] >> ak->creator; data["reason"] >> ak->reason; - ak->nc = findcore(data["nc"].astr()); + ak->nc = NickCore::Find(data["nc"].astr()); data["mask"] >> ak->mask; data["addtime"] >> ak->addtime; data["last_used"] >> ak->last_used; @@ -115,31 +126,33 @@ ModeLock::ModeLock(ChannelInfo *ch, bool s, ChannelModeName n, const Anope::stri { } -Serialize::Data ModeLock::serialize() const +Serialize::Data ModeLock::Serialize() const { Serialize::Data data; if (!this->ci) return data; - data["ci"].setMax(64)/*XXX*/ << this->ci->name; - data["set"].setMax(5) << this->set; - data["name"].setMax(64) << ChannelModeNameStrings[this->name]; - data["param"].setMax(512) << this->param; + const Anope::string* ChannelModeNameStrings = Flags<ChannelModeName>::GetFlagStrings(); + data["ci"].SetMax(64)/*XXX*/ << this->ci->name; + data["set"].SetMax(5) << this->set; + data["name"].SetMax(64) << ChannelModeNameStrings[this->name]; + data["param"].SetMax(512) << this->param; data["setter"] << this->setter; - data["created"].setType(Serialize::DT_INT) << this->created; + data["created"].SetType(Serialize::DT_INT) << this->created; return data; } -Serializable* ModeLock::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* ModeLock::Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (!ci) return NULL; ChannelModeName name = CMODE_END; + const Anope::string* ChannelModeNameStrings = Flags<ChannelModeName>::GetFlagStrings(); for (unsigned i = 0; !ChannelModeNameStrings[i].empty(); ++i) if (ChannelModeNameStrings[i] == data["name"].astr()) { @@ -177,7 +190,7 @@ Serializable* ModeLock::unserialize(Serializable *obj, Serialize::Data &data) } } -Serialize::Data LogSetting::serialize() const +Serialize::Data LogSetting::Serialize() const { Serialize::Data data; @@ -191,14 +204,14 @@ Serialize::Data LogSetting::serialize() const data["method"] << method; data["extra"] << extra; data["creator"] << creator; - data["created"].setType(Serialize::DT_INT) << created; + data["created"].SetType(Serialize::DT_INT) << created; return data; } -Serializable* LogSetting::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* LogSetting::Unserialize(Serializable *obj, Serialize::Data &data) { - ChannelInfo *ci = cs_findchan(data["ci"].astr()); + ChannelInfo *ci = ChannelInfo::Find(data["ci"].astr()); if (ci == NULL) return NULL; @@ -223,19 +236,16 @@ Serializable* LogSetting::unserialize(Serializable *obj, Serialize::Data &data) return ls; } -/** Default constructor - * @param chname The channel name - */ -ChannelInfo::ChannelInfo(const Anope::string &chname) : Serializable("ChannelInfo"), Flags<ChannelInfoFlag, CI_END>(ChannelInfoFlagStrings), +ChannelInfo::ChannelInfo(const Anope::string &chname) : Serializable("ChannelInfo"), access("ChanAccess"), akick("AutoKick"), - badwords("BadWord"), mode_locks("ModeLock"), log_settings("LogSetting"), botflags(BotServFlagStrings) + badwords("BadWord"), mode_locks("ModeLock"), log_settings("LogSetting") { if (chname.empty()) throw CoreException("Empty channel passed to ChannelInfo constructor"); this->founder = NULL; this->successor = NULL; - this->c = findchan(chname); + this->c = Channel::Find(chname); if (this->c) this->c->ci = this; this->capsmin = this->capspercent = 0; @@ -274,12 +284,9 @@ ChannelInfo::ChannelInfo(const Anope::string &chname) : Serializable("ChannelInf FOREACH_MOD(I_OnCreateChan, OnCreateChan(this)); } -/** Copy constructor - * @param ci The ChannelInfo to copy settings to - */ -ChannelInfo::ChannelInfo(const ChannelInfo &ci) : Serializable("ChannelInfo"), Flags<ChannelInfoFlag, CI_END>(ChannelInfoFlagStrings), +ChannelInfo::ChannelInfo(const ChannelInfo &ci) : Serializable("ChannelInfo"), access("ChanAccess"), akick("AutoKick"), - badwords("BadWord"), mode_locks("ModeLock"), log_settings("LogSetting"), botflags(BotServFlagStrings) + badwords("BadWord"), mode_locks("ModeLock"), log_settings("LogSetting") { *this = ci; @@ -304,7 +311,7 @@ ChannelInfo::ChannelInfo(const ChannelInfo &ci) : Serializable("ChannelInfo"), F newaccess->creator = taccess->creator; newaccess->last_seen = taccess->last_seen; newaccess->created = taccess->created; - newaccess->Unserialize(taccess->Serialize()); + newaccess->AccessUnserialize(taccess->AccessSerialize()); this->AddAccess(newaccess); } @@ -331,8 +338,6 @@ ChannelInfo::ChannelInfo(const ChannelInfo &ci) : Serializable("ChannelInfo"), F } } -/** Default destructor, cleans up the channel complete and removes it from the internal list - */ ChannelInfo::~ChannelInfo() { FOREACH_MOD(I_OnDelChan, OnDelChan(this)); @@ -353,17 +358,17 @@ ChannelInfo::~ChannelInfo() this->ClearBadWords(); for (unsigned i = 0; i < this->log_settings->size(); ++i) - this->log_settings->at(i)->destroy(); + this->log_settings->at(i)->Destroy(); this->log_settings->clear(); for (ChannelInfo::ModeList::iterator it = this->mode_locks->begin(), it_end = this->mode_locks->end(); it != it_end; ++it) - it->second->destroy(); + it->second->Destroy(); this->mode_locks->clear(); if (!this->memos.memos->empty()) { for (unsigned i = 0, end = this->memos.memos->size(); i < end; ++i) - this->memos.GetMemo(i)->destroy(); + this->memos.GetMemo(i)->Destroy(); this->memos.memos->clear(); } @@ -371,22 +376,22 @@ ChannelInfo::~ChannelInfo() --this->founder->channelcount; } -Serialize::Data ChannelInfo::serialize() const +Serialize::Data ChannelInfo::Serialize() const { Serialize::Data data; - data["name"].setMax(255) << this->name; + data["name"].SetMax(255) << this->name; if (this->founder) data["founder"] << this->founder->display; if (this->successor) data["successor"] << this->successor->display; data["description"] << this->desc; - data["time_registered"].setType(Serialize::DT_INT) << this->time_registered; - data["last_used"].setType(Serialize::DT_INT) << this->last_used; + data["time_registered"].SetType(Serialize::DT_INT) << this->time_registered; + data["last_used"].SetType(Serialize::DT_INT) << this->last_used; data["last_topic"] << this->last_topic; data["last_topic_setter"] << this->last_topic_setter; - data["last_topic_time"].setType(Serialize::DT_INT) << this->last_topic_time; - data["bantype"].setType(Serialize::DT_INT) << this->bantype; + data["last_topic_time"].SetType(Serialize::DT_INT) << this->last_topic_time; + data["bantype"].SetType(Serialize::DT_INT) << this->bantype; data["flags"] << this->ToString(); data["botflags"] << this->botflags.ToString(); { @@ -399,11 +404,11 @@ Serialize::Data ChannelInfo::serialize() const data["bi"] << this->bi->nick; for (int i = 0; i < TTB_SIZE; ++i) data["ttb"] << this->ttb[i] << " "; - data["capsmin"].setType(Serialize::DT_INT) << this->capsmin; - data["capspercent"].setType(Serialize::DT_INT) << this->capspercent; - data["floodlines"].setType(Serialize::DT_INT) << this->floodlines; - data["floodsecs"].setType(Serialize::DT_INT) << this->floodsecs; - data["repeattimes"].setType(Serialize::DT_INT) << this->repeattimes; + data["capsmin"].SetType(Serialize::DT_INT) << this->capsmin; + data["capspercent"].SetType(Serialize::DT_INT) << this->capspercent; + data["floodlines"].SetType(Serialize::DT_INT) << this->floodlines; + data["floodsecs"].SetType(Serialize::DT_INT) << this->floodsecs; + data["repeattimes"].SetType(Serialize::DT_INT) << this->repeattimes; data["memomax"] << this->memos.memomax; for (unsigned i = 0; i < this->memos.ignores.size(); ++i) data["memoignores"] << this->memos.ignores[i] << " "; @@ -411,7 +416,7 @@ Serialize::Data ChannelInfo::serialize() const return data; } -Serializable* ChannelInfo::unserialize(Serializable *obj, Serialize::Data &data) +Serializable* ChannelInfo::Unserialize(Serializable *obj, Serialize::Data &data) { ChannelInfo *ci; if (obj) @@ -423,13 +428,13 @@ Serializable* ChannelInfo::unserialize(Serializable *obj, Serialize::Data &data) { if (ci->founder) --ci->founder->channelcount; - ci->founder = findcore(data["founder"].astr()); + ci->founder = NickCore::Find(data["founder"].astr()); if (ci->founder) ++ci->founder->channelcount; } if (data.count("successor") > 0) { - ci->successor = findcore(data["successor"].astr()); + ci->successor = NickCore::Find(data["successor"].astr()); if (ci->founder && *ci->founder == *ci->successor) ci->successor = NULL; } @@ -443,11 +448,12 @@ Serializable* ChannelInfo::unserialize(Serializable *obj, Serialize::Data &data) ci->FromString(data["flags"].astr()); ci->botflags.FromString(data["botflags"].astr()); { - std::vector<Anope::string> v = BuildStringVector(data["levels"].astr()); + std::vector<Anope::string> v; + spacesepstream(data["levels"].astr()).GetTokens(v); for (unsigned i = 0; i + 1 < v.size(); i += 2) ci->levels[v[i]] = convertTo<int16_t>(v[i + 1]); } - BotInfo *bi = findbot(data["bi"].astr()); + BotInfo *bi = BotInfo::Find(data["bi"].astr()); if (*ci->bi != bi) { if (ci->bi) @@ -475,9 +481,6 @@ Serializable* ChannelInfo::unserialize(Serializable *obj, Serialize::Data &data) } -/** Change the founder of the channek - * @params nc The new founder - */ void ChannelInfo::SetFounder(NickCore *nc) { if (this->founder) @@ -489,44 +492,27 @@ void ChannelInfo::SetFounder(NickCore *nc) this->successor = NULL; } -/** Get the founder of the channel - * @return The founder - */ NickCore *ChannelInfo::GetFounder() const { return this->founder; } -/** Find which bot should send mode/topic/etc changes for this channel - * @return The bot - */ BotInfo *ChannelInfo::WhoSends() const { if (this && this->bi) return this->bi; - BotInfo *tbi = findbot(Config->ChanServ); - if (tbi) - return tbi; + else if (ChanServ) + return ChanServ; else if (!BotListByNick->empty()) return BotListByNick->begin()->second; return NULL; } -/** Add an entry to the channel access list - * @param taccess The entry - */ void ChannelInfo::AddAccess(ChanAccess *taccess) { this->access->push_back(taccess); } -/** Get an entry from the channel access list by index - * - * @param index The index in the access list vector - * @return A ChanAccess struct corresponding to the index given, or NULL if outside the bounds - * - * Retrieves an entry from the access list that matches the given index. - */ ChanAccess *ChannelInfo::GetAccess(unsigned index) const { if (this->access->empty() || index >= this->access->size()) @@ -547,13 +533,13 @@ AccessGroup ChannelInfo::AccessFor(const User *u) const NickCore *nc = u->Account(); if (nc == NULL && u->IsRecognized()) { - const NickAlias *na = findnick(u->nick); + const NickAlias *na = NickAlias::Find(u->nick); if (na != NULL) nc = na->nc; } - group.SuperAdmin = u->SuperAdmin; - group.Founder = IsFounder(u, this); + group.super_admin = u->super_admin; + group.founder = IsFounder(u, this); group.ci = this; group.nc = nc; @@ -561,9 +547,14 @@ AccessGroup ChannelInfo::AccessFor(const User *u) if (this->GetAccess(i)->Matches(u, nc)) group.push_back(this->GetAccess(i)); - if (group.Founder || !group.empty()) + if (group.founder || !group.empty()) + { this->last_used = Anope::CurTime; + for (unsigned i = 0; i < group.size(); ++i) + group[i]->last_seen = Anope::CurTime; + } + return group; } @@ -571,7 +562,7 @@ AccessGroup ChannelInfo::AccessFor(const NickCore *nc) { AccessGroup group; - group.Founder = (this->founder && this->founder == nc); + group.founder = (this->founder && this->founder == nc); group.ci = this; group.nc = nc; @@ -579,41 +570,31 @@ AccessGroup ChannelInfo::AccessFor(const NickCore *nc) if (this->GetAccess(i)->Matches(NULL, nc)) group.push_back(this->GetAccess(i)); - if (group.Founder || !group.empty()) + if (group.founder || !group.empty()) + { this->last_used = Anope::CurTime; + for (unsigned i = 0; i < group.size(); ++i) + group[i]->last_seen = Anope::CurTime; + } + return group; } -/** Get the size of the accss vector for this channel - * @return The access vector size - */ unsigned ChannelInfo::GetAccessCount() const { return this->access->size(); } -/** Erase an entry from the channel access list - * - * @param index The index in the access list vector - * - * Clears the memory used by the given access entry and removes it from the vector. - */ void ChannelInfo::EraseAccess(unsigned index) { if (this->access->empty() || index >= this->access->size()) return; - this->access->at(index)->destroy(); + this->access->at(index)->Destroy(); this->access->erase(this->access->begin() + index); } -/** Erase an entry from the channel access list - * - * @param taccess The access to remove - * - * Clears the memory used by the given access entry and removes it from the vector. - */ void ChannelInfo::EraseAccess(const ChanAccess *taccess) { for (unsigned i = 0, end = this->access->size(); i < end; ++i) @@ -626,25 +607,13 @@ void ChannelInfo::EraseAccess(const ChanAccess *taccess) } } -/** Clear the entire channel access list - * - * Clears the entire access list by deleting every item and then clearing the vector. - */ void ChannelInfo::ClearAccess() { for (unsigned i = this->access->size(); i > 0; --i) - this->GetAccess(i - 1)->destroy(); + this->GetAccess(i - 1)->Destroy(); this->access->clear(); } -/** Add an akick entry to the channel by NickCore - * @param user The user who added the akick - * @param akicknc The nickcore being akicked - * @param reason The reason for the akick - * @param t The time the akick was added, defaults to now - * @param lu The time the akick was last used, defaults to never - * @return The AutoKick structure - */ AutoKick *ChannelInfo::AddAkick(const Anope::string &user, NickCore *akicknc, const Anope::string &reason, time_t t, time_t lu) { AutoKick *autokick = new AutoKick(); @@ -661,14 +630,6 @@ AutoKick *ChannelInfo::AddAkick(const Anope::string &user, NickCore *akicknc, co return autokick; } -/** Add an akick entry to the channel by reason - * @param user The user who added the akick - * @param mask The mask of the akick - * @param reason The reason for the akick - * @param t The time the akick was added, defaults to now - * @param lu The time the akick was last used, defaults to never - * @return The AutoKick structure - */ AutoKick *ChannelInfo::AddAkick(const Anope::string &user, const Anope::string &mask, const Anope::string &reason, time_t t, time_t lu) { AutoKick *autokick = new AutoKick(); @@ -685,10 +646,6 @@ AutoKick *ChannelInfo::AddAkick(const Anope::string &user, const Anope::string & return autokick; } -/** Get an entry from the channel akick list - * @param index The index in the akick vector - * @return The akick structure, or NULL if not found - */ AutoKick *ChannelInfo::GetAkick(unsigned index) const { if (this->akick->empty() || index >= this->akick->size()) @@ -699,39 +656,26 @@ AutoKick *ChannelInfo::GetAkick(unsigned index) const return ak; } -/** Get the size of the akick vector for this channel - * @return The akick vector size - */ unsigned ChannelInfo::GetAkickCount() const { return this->akick->size(); } -/** Erase an entry from the channel akick list - * @param index The index of the akick - */ void ChannelInfo::EraseAkick(unsigned index) { if (this->akick->empty() || index >= this->akick->size()) return; - this->GetAkick(index)->destroy(); + this->GetAkick(index)->Destroy(); this->akick->erase(this->akick->begin() + index); } -/** Clear the whole akick list - */ void ChannelInfo::ClearAkick() { while (!this->akick->empty()) EraseAkick(0); } -/** Add a badword to the badword list - * @param word The badword - * @param type The type (SINGLE START END) - * @return The badword - */ BadWord* ChannelInfo::AddBadWord(const Anope::string &word, BadWordType type) { BadWord *bw = new BadWord(); @@ -746,10 +690,6 @@ BadWord* ChannelInfo::AddBadWord(const Anope::string &word, BadWordType type) return bw; } -/** Get a badword structure by index - * @param index The index - * @return The badword - */ BadWord* ChannelInfo::GetBadWord(unsigned index) const { if (this->badwords->empty() || index >= this->badwords->size()) @@ -760,17 +700,11 @@ BadWord* ChannelInfo::GetBadWord(unsigned index) const return bw; } -/** Get how many badwords are on this channel - * @return The number of badwords in the vector - */ unsigned ChannelInfo::GetBadWordCount() const { return this->badwords->size(); } -/** Remove a badword - * @param index The index of the badword - */ void ChannelInfo::EraseBadWord(unsigned index) { if (this->badwords->empty() || index >= this->badwords->size()) @@ -782,28 +716,21 @@ void ChannelInfo::EraseBadWord(unsigned index) this->badwords->erase(this->badwords->begin() + index); } -/** Clear all badwords from the channel - */ void ChannelInfo::ClearBadWords() { while (!this->badwords->empty()) EraseBadWord(0); } -/** Check if a mode is mlocked - * @param mode The mode - * @param status True to check mlock on, false for mlock off - * @return true on success, false on fail - */ bool ChannelInfo::HasMLock(ChannelMode *mode, const Anope::string ¶m, bool status) const { - std::multimap<ChannelModeName, ModeLock *>::const_iterator it = this->mode_locks->find(mode->Name); + std::multimap<ChannelModeName, ModeLock *>::const_iterator it = this->mode_locks->find(mode->name); if (it != this->mode_locks->end()) { - if (mode->Type != MODE_REGULAR) + if (mode->type != MODE_REGULAR) { - std::multimap<ChannelModeName, ModeLock *>::const_iterator it_end = this->mode_locks->upper_bound(mode->Name); + std::multimap<ChannelModeName, ModeLock *>::const_iterator it_end = this->mode_locks->upper_bound(mode->name); for (; it != it_end; ++it) { @@ -818,17 +745,11 @@ bool ChannelInfo::HasMLock(ChannelMode *mode, const Anope::string ¶m, bool s return false; } -/** Set a mlock - * @param mode The mode - * @param status True for mlock on, false for mlock off - * @param param The param to use for this mode, if required - * @return true on success, false on failure (module blocking) - */ bool ChannelInfo::SetMLock(ChannelMode *mode, bool status, const Anope::string ¶m, Anope::string setter, time_t created) { if (setter.empty()) setter = this->founder ? this->founder->display : "Unknown"; - std::pair<ChannelModeName, ModeLock *> ml = std::make_pair(mode->Name, new ModeLock(this, status, mode->Name, param, setter, created)); + std::pair<ChannelModeName, ModeLock *> ml = std::make_pair(mode->name, new ModeLock(this, status, mode->name, param, setter, created)); EventReturn MOD_RESULT; FOREACH_RESULT(I_OnMLock, OnMLock(this, ml.second)); @@ -836,30 +757,30 @@ bool ChannelInfo::SetMLock(ChannelMode *mode, bool status, const Anope::string & return false; /* First, remove this */ - if (mode->Type == MODE_REGULAR || mode->Type == MODE_PARAM) + if (mode->type == MODE_REGULAR || mode->type == MODE_PARAM) { - ChannelInfo::ModeList::const_iterator it = this->mode_locks->find(mode->Name); + ChannelInfo::ModeList::const_iterator it = this->mode_locks->find(mode->name); if (it != this->mode_locks->end()) { - ChannelInfo::ModeList::const_iterator it_end = this->mode_locks->upper_bound(mode->Name); + ChannelInfo::ModeList::const_iterator it_end = this->mode_locks->upper_bound(mode->name); for (; it != it_end; ++it) - it->second->destroy(); + it->second->Destroy(); } - this->mode_locks->erase(mode->Name); + this->mode_locks->erase(mode->name); } else { // For list or status modes, we must check the parameter - ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->Name); + ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->name); if (it != this->mode_locks->end()) { - ChannelInfo::ModeList::iterator it_end = this->mode_locks->upper_bound(mode->Name); + ChannelInfo::ModeList::iterator it_end = this->mode_locks->upper_bound(mode->name); for (; it != it_end; ++it) { const ModeLock *modelock = it->second; if (modelock->param == param) { - it->second->destroy(); + it->second->Destroy(); this->mode_locks->erase(it); break; } @@ -872,17 +793,11 @@ bool ChannelInfo::SetMLock(ChannelMode *mode, bool status, const Anope::string & return true; } -/** Remove a mlock - * @param mode The mode - * @param status True for mlock on, false for mlock off - * @param param The param of the mode, required if it is a list or status mode - * @return true on success, false on failure - */ bool ChannelInfo::RemoveMLock(ChannelMode *mode, bool status, const Anope::string ¶m) { - if (mode->Type == MODE_REGULAR || mode->Type == MODE_PARAM) + if (mode->type == MODE_REGULAR || mode->type == MODE_PARAM) { - ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->Name), it_end = this->mode_locks->upper_bound(mode->Name), it_next = it; + ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->name), it_end = this->mode_locks->upper_bound(mode->name), it_next = it; if (it != this->mode_locks->end()) for (; it != it_end; it = it_next) { @@ -896,7 +811,7 @@ bool ChannelInfo::RemoveMLock(ChannelMode *mode, bool status, const Anope::strin FOREACH_RESULT(I_OnUnMLock, OnUnMLock(this, it->second)); if (MOD_RESULT != EVENT_STOP) { - it->second->destroy(); + it->second->Destroy(); this->mode_locks->erase(it); return true; } @@ -906,10 +821,10 @@ bool ChannelInfo::RemoveMLock(ChannelMode *mode, bool status, const Anope::strin else { // For list or status modes, we must check the parameter - ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->Name); + ChannelInfo::ModeList::iterator it = this->mode_locks->find(mode->name); if (it != this->mode_locks->end()) { - ChannelInfo::ModeList::iterator it_end = this->mode_locks->upper_bound(mode->Name); + ChannelInfo::ModeList::iterator it_end = this->mode_locks->upper_bound(mode->name); for (; it != it_end; ++it) { const ModeLock *ml = it->second; @@ -919,7 +834,7 @@ bool ChannelInfo::RemoveMLock(ChannelMode *mode, bool status, const Anope::strin FOREACH_RESULT(I_OnUnMLock, OnUnMLock(this, it->second)); if (MOD_RESULT == EVENT_STOP) return false; - it->second->destroy(); + it->second->Destroy(); this->mode_locks->erase(it); return true; } @@ -930,25 +845,16 @@ bool ChannelInfo::RemoveMLock(ChannelMode *mode, bool status, const Anope::strin } } -/** Clear all mlocks on the channel - */ void ChannelInfo::ClearMLock() { this->mode_locks->clear(); } -/** Get all of the mlocks for this channel - * @return The mlocks - */ const ChannelInfo::ModeList &ChannelInfo::GetMLock() const { return this->mode_locks; } -/** Get a list of modes on a channel - * @param Name The mode name to get a list of - * @return a pair of iterators for the beginning and end of the list - */ std::pair<ChannelInfo::ModeList::iterator, ChannelInfo::ModeList::iterator> ChannelInfo::GetModeList(ChannelModeName Name) { ChannelInfo::ModeList::iterator it = this->mode_locks->find(Name), it_end = it; @@ -957,11 +863,6 @@ std::pair<ChannelInfo::ModeList::iterator, ChannelInfo::ModeList::iterator> Chan return std::make_pair(it, it_end); } -/** Get details for a specific mlock - * @param mname The mode name - * @param param An optional param to match with - * @return The MLock, if any - */ const ModeLock *ChannelInfo::GetMLock(ChannelModeName mname, const Anope::string ¶m) { ChannelInfo::ModeList::iterator it = this->mode_locks->find(mname); @@ -991,15 +892,15 @@ Anope::string ChannelInfo::GetMLockAsString(bool complete) const { const ModeLock *ml = it->second; ChannelMode *cm = ModeManager::FindChannelModeByName(ml->name); - if (!cm || cm->Type == MODE_LIST || cm->Type == MODE_STATUS) + if (!cm || cm->type == MODE_LIST || cm->type == MODE_STATUS) continue; if (ml->set) - pos += cm->ModeChar; + pos += cm->mchar; else - neg += cm->ModeChar; + neg += cm->mchar; - if (complete && !ml->param.empty() && cm->Type == MODE_PARAM) + if (complete && !ml->param.empty() && cm->type == MODE_PARAM) params += " " + ml->param; } @@ -1011,16 +912,12 @@ Anope::string ChannelInfo::GetMLockAsString(bool complete) const return pos + neg + params; } -/** Check whether a user is permitted to be on this channel - * @param u The user - * @return true if they were banned, false if they are allowed - */ bool ChannelInfo::CheckKick(User *user) { if (!user || !this->c) return false; - if (user->SuperAdmin) + if (user->super_admin) return false; /* We don't enforce services restrictions on clients on ulined services @@ -1041,13 +938,13 @@ bool ChannelInfo::CheckKick(User *user) Anope::string mask, reason; if (!user->HasMode(UMODE_OPER) && this->HasFlag(CI_SUSPENDED)) { - get_idealban(this, user, mask); - reason = translate(user, _("This channel may not be used.")); + mask = this->GetIdealBan(user); + reason = Language::Translate(user, _("This channel may not be used.")); set_modes = true; do_kick = true; } - if (!do_kick && matches_list(this->c, user, CMODE_EXCEPT)) + if (!do_kick && !this->c->MatchesList(user, CMODE_EXCEPT)) return false; const NickCore *nc = user->Account() || user->IsRecognized() ? user->Account() : NULL; @@ -1074,7 +971,7 @@ bool ChannelInfo::CheckKick(User *user) Log(LOG_DEBUG_2) << user->nick << " matched akick " << (autokick->HasFlag(AK_ISNICK) ? autokick->nc->display : autokick->mask); autokick->last_used = Anope::CurTime; if (autokick->HasFlag(AK_ISNICK)) - get_idealban(this, user, mask); + mask = this->GetIdealBan(user); else mask = autokick->mask; reason = autokick->reason.empty() ? Config->CSAutokickReason : autokick->reason; @@ -1086,8 +983,8 @@ bool ChannelInfo::CheckKick(User *user) if (!do_kick && this->HasFlag(CI_RESTRICTED) && this->AccessFor(user).empty() && (!this->founder || user->Account() != this->founder)) { do_kick = true; - get_idealban(this, user, mask); - reason = translate(user->Account(), CHAN_NOT_ALLOWED_TO_JOIN); + mask = this->GetIdealBan(user); + reason = Language::Translate(user->Account(), CHAN_NOT_ALLOWED_TO_JOIN); } if (!do_kick) @@ -1183,3 +1080,48 @@ void ChannelInfo::ClearLevels() this->levels.clear(); } +Anope::string ChannelInfo::GetIdealBan(User *u) const +{ + switch (this->bantype) + { + case 0: + return "*!" + u->GetVIdent() + "@" + u->GetDisplayedHost(); + case 1: + if (u->GetVIdent()[0] == '~') + return "*!*" + u->GetVIdent() + "@" + u->GetDisplayedHost(); + else + return "*!" + u->GetVIdent() + "@" + u->GetDisplayedHost(); + case 3: + return "*!" + u->Mask(); + case 2: + default: + return "*!*@" + u->GetDisplayedHost(); + } +} + +ChannelInfo* ChannelInfo::Find(const Anope::string &name) +{ + registered_channel_map::const_iterator it = RegisteredChannelList->find(name); + if (it != RegisteredChannelList->end()) + { + it->second->QueueUpdate(); + return it->second; + } + + return NULL; +} + +bool IsFounder(const User *user, const ChannelInfo *ci) +{ + if (!user || !ci) + return false; + + if (user->super_admin) + return true; + + if (user->Account() && user->Account() == ci->GetFounder()) + return true; + + return false; +} + diff --git a/src/serialize.cpp b/src/serialize.cpp index a84d103f5..b6da2da67 100644 --- a/src/serialize.cpp +++ b/src/serialize.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ @@ -14,10 +15,25 @@ #include "anope.h" #include "serialize.h" #include "modules.h" +#include "account.h" +#include "bots.h" +#include "regchannel.h" +#include "xline.h" +#include "access.h" + +using namespace Serialize; + +std::vector<Anope::string> Type::TypeOrder; +std::map<Anope::string, Type *> Serialize::Type::Types; +std::list<Serializable *> *Serializable::SerializableItems; -std::vector<Anope::string> SerializeType::type_order; -std::map<Anope::string, SerializeType *> SerializeType::types; -std::list<Serializable *> *Serializable::serializable_items; +void Serialize::RegisterTypes() +{ + static Type nc("NickCore", NickCore::Unserialize), na("NickAlias", NickAlias::Unserialize), bi("BotInfo", BotInfo::Unserialize), + ci("ChannelInfo", ChannelInfo::Unserialize), access("ChanAccess", ChanAccess::Unserialize), logsetting("LogSetting", LogSetting::Unserialize), + modelock("ModeLock", ModeLock::Unserialize), akick("AutoKick", AutoKick::Unserialize), badword("BadWord", BadWord::Unserialize), + memo("Memo", Memo::Unserialize), xline("XLine", XLine::Unserialize); +} stringstream::stringstream() : std::stringstream(), type(Serialize::DT_TEXT), _max(0) { @@ -48,24 +64,24 @@ bool stringstream::operator!=(const stringstream &other) const return !(*this == other); } -stringstream &stringstream::setType(Serialize::DataType t) +stringstream &stringstream::SetType(Serialize::DataType t) { this->type = t; return *this; } -Serialize::DataType stringstream::getType() const +DataType Serialize::stringstream::GetType() const { return this->type; } -stringstream &stringstream::setMax(unsigned m) +stringstream &stringstream::SetMax(unsigned m) { this->_max = m; return *this; } -unsigned stringstream::getMax() const +unsigned stringstream::GetMax() const { return this->_max; } @@ -77,13 +93,13 @@ Serializable::Serializable() : last_commit_time(0), id(0) Serializable::Serializable(const Anope::string &serialize_type) : last_commit_time(0), id(0) { - if (serializable_items == NULL) - serializable_items = new std::list<Serializable *>(); - serializable_items->push_back(this); + if (SerializableItems == NULL) + SerializableItems = new std::list<Serializable *>(); + SerializableItems->push_back(this); - this->s_type = SerializeType::Find(serialize_type); + this->s_type = Type::Find(serialize_type); - this->s_iter = serializable_items->end(); + this->s_iter = SerializableItems->end(); --this->s_iter; FOREACH_MOD(I_OnSerializableConstruct, OnSerializableConstruct(this)); @@ -91,8 +107,8 @@ Serializable::Serializable(const Anope::string &serialize_type) : last_commit_ti Serializable::Serializable(const Serializable &other) : last_commit_time(0), id(0) { - serializable_items->push_back(this); - this->s_iter = serializable_items->end(); + SerializableItems->push_back(this); + this->s_iter = SerializableItems->end(); --this->s_iter; this->s_type = other.s_type; @@ -102,7 +118,7 @@ Serializable::Serializable(const Serializable &other) : last_commit_time(0), id( Serializable::~Serializable() { - serializable_items->erase(this->s_iter); + SerializableItems->erase(this->s_iter); } Serializable &Serializable::operator=(const Serializable &) @@ -110,7 +126,7 @@ Serializable &Serializable::operator=(const Serializable &) return *this; } -void Serializable::destroy() +void Serializable::Destroy() { if (!this) return; @@ -130,12 +146,12 @@ void Serializable::QueueUpdate() bool Serializable::IsCached() { - return this->last_commit == this->serialize(); + return this->last_commit == this->Serialize(); } void Serializable::UpdateCache() { - this->last_commit = this->serialize(); + this->last_commit = this->Serialize(); } bool Serializable::IsTSCached() @@ -148,70 +164,70 @@ void Serializable::UpdateTS() this->last_commit_time = Anope::CurTime; } -SerializeType* Serializable::GetSerializableType() const +Type* Serializable::GetSerializableType() const { return this->s_type; } const std::list<Serializable *> &Serializable::GetItems() { - return *serializable_items; + return *SerializableItems; } -SerializeType::SerializeType(const Anope::string &n, unserialize_func f, Module *o) : name(n), unserialize(f), owner(o), timestamp(0) +Type::Type(const Anope::string &n, unserialize_func f, Module *o) : name(n), unserialize(f), owner(o), timestamp(0) { - type_order.push_back(this->name); - types[this->name] = this; + TypeOrder.push_back(this->name); + Types[this->name] = this; } -SerializeType::~SerializeType() +Type::~Type() { - std::vector<Anope::string>::iterator it = std::find(type_order.begin(), type_order.end(), this->name); - if (it != type_order.end()) - type_order.erase(it); - types.erase(this->name); + std::vector<Anope::string>::iterator it = std::find(TypeOrder.begin(), TypeOrder.end(), this->name); + if (it != TypeOrder.end()) + TypeOrder.erase(it); + Types.erase(this->name); } -const Anope::string &SerializeType::GetName() +const Anope::string &Type::GetName() { return this->name; } -Serializable *SerializeType::Unserialize(Serializable *obj, Serialize::Data &data) +Serializable *Type::Unserialize(Serializable *obj, Serialize::Data &data) { return this->unserialize(obj, data); } -void SerializeType::Check() +void Type::Check() { FOREACH_MOD(I_OnSerializeCheck, OnSerializeCheck(this)); } -time_t SerializeType::GetTimestamp() const +time_t Type::GetTimestamp() const { return this->timestamp; } -void SerializeType::UpdateTimestamp() +void Type::UpdateTimestamp() { this->timestamp = Anope::CurTime; } -Module* SerializeType::GetOwner() const +Module* Type::GetOwner() const { return this->owner; } -SerializeType *SerializeType::Find(const Anope::string &name) +Type *Serialize::Type::Find(const Anope::string &name) { - std::map<Anope::string, SerializeType *>::iterator it = types.find(name); - if (it != types.end()) + std::map<Anope::string, Type *>::iterator it = Types.find(name); + if (it != Types.end()) return it->second; return NULL; } -const std::vector<Anope::string> &SerializeType::GetTypeOrder() +const std::vector<Anope::string> &Type::GetTypeOrder() { - return type_order; + return TypeOrder; } diff --git a/src/servers.cpp b/src/servers.cpp index 3a44c8e65..447633298 100644 --- a/src/servers.cpp +++ b/src/servers.cpp @@ -7,52 +7,47 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" #include "modules.h" -#include "oper.h" +#include "xline.h" #include "servers.h" #include "bots.h" #include "regchannel.h" #include "protocol.h" #include "config.h" #include "channels.h" -#include "extern.h" + +const Anope::string ServerFlagStrings[] = { "SERVER_NONE", "SERVER_SYNCING", "SERVER_JUPED", "" }; +template<> const Anope::string* Flags<ServerFlag>::flags_strings = ServerFlagStrings; /* Anope */ Server *Me = NULL; -std::set<Anope::string> Capab; +std::set<Anope::string> Servers::Capab; -/** Constructor - * @param uplink The uplink this server is from, is only NULL when creating Me - * @param name The server name - * @param hops Hops from services server - * @param description Server rdescription - * @param sid Server sid/numeric - * @param flag An optional server flag - */ -Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const Anope::string &description, const Anope::string &sid, ServerFlag flag) : Flags<ServerFlag>(ServerFlagStrings), Name(name), Hops(hops), Description(description), SID(sid), UplinkServer(uplink) +Server::Server(Server *up, const Anope::string &sname, unsigned shops, const Anope::string &desc, const Anope::string &ssid, ServerFlag flag) : name(sname), hops(shops), description(desc), sid(ssid), uplink(up) { this->SetFlag(SERVER_SYNCING); this->SetFlag(flag); - Log(this, "connect") << "uplinked to " << (this->UplinkServer ? this->UplinkServer->GetName() : "no uplink") << " connected to the network"; + Log(this, "connect") << "uplinked to " << (this->uplink ? this->uplink->GetName() : "no uplink") << " connected to the network"; /* Add this server to our uplinks leaf list */ - if (this->UplinkServer) + if (this->uplink) { - this->UplinkServer->AddLink(this); + this->uplink->AddLink(this); /* Check to be sure this isn't a juped server */ - if (Me == this->UplinkServer && !this->HasFlag(SERVER_JUPED)) + if (Me == this->uplink && !this->HasFlag(SERVER_JUPED)) { /* Now do mode related stuff as we know what modes exist .. */ for (botinfo_map::iterator it = BotListByNick->begin(), it_end = BotListByNick->end(); it != it_end; ++it) { BotInfo *bi = it->second; - Anope::string modes = !bi->botmodes.empty() ? ("+" + bi->botmodes) : ircdproto->DefaultPseudoclientModes; + Anope::string modes = !bi->botmodes.empty() ? ("+" + bi->botmodes) : IRCD->DefaultPseudoclientModes; bi->SetModesInternal(modes.c_str()); for (unsigned i = 0; i < bi->botchannels.size(); ++i) @@ -61,7 +56,7 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A if (h == Anope::string::npos) continue; Anope::string chname = bi->botchannels[i].substr(h); - Channel *c = findchan(chname); + Channel *c = Channel::Find(chname); if (c && c->FindUser(bi)) { Anope::string want_modes = bi->botchannels[i].substr(0, h); @@ -70,7 +65,7 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A ChannelMode *cm = ModeManager::FindChannelModeByChar(want_modes[j]); if (cm == NULL) cm = ModeManager::FindChannelModeByChar(ModeManager::GetStatusChar(want_modes[j])); - if (cm && cm->Type == MODE_STATUS) + if (cm && cm->type == MODE_STATUS) { MessageSource ms = bi; c->SetModeInternal(ms, cm, bi->nick); @@ -80,14 +75,14 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A } } - ircdproto->SendBOB(); + IRCD->SendBOB(); for (unsigned i = 0; i < Me->GetLinks().size(); ++i) { Server *s = Me->GetLinks()[i]; if (s->HasFlag(SERVER_JUPED)) - ircdproto->SendServer(s); + IRCD->SendServer(s); } /* We make the bots go online */ @@ -95,14 +90,14 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A { User *u = it->second; - BotInfo *bi = findbot(u->nick); + BotInfo *bi = BotInfo::Find(u->nick); if (bi) { XLine x(bi->nick, "Reserved for services"); - ircdproto->SendSQLine(NULL, &x); + IRCD->SendSQLine(NULL, &x); } - ircdproto->SendClientIntroduction(u); + IRCD->SendClientIntroduction(u); if (bi) bi->introduced = true; } @@ -111,10 +106,10 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A { Channel *c = it->second; if (c->users.empty()) - ircdproto->SendChannel(c); + IRCD->SendChannel(c); else for (CUserList::const_iterator cit = c->users.begin(), cit_end = c->users.end(); cit != cit_end; ++cit) - ircdproto->SendJoin((*cit)->user, c, (*cit)->Status); + IRCD->SendJoin((*cit)->user, c, (*cit)->status); } } } @@ -122,13 +117,11 @@ Server::Server(Server *uplink, const Anope::string &name, unsigned hops, const A FOREACH_MOD(I_OnNewServer, OnNewServer(this)); } -/** Destructor - */ Server::~Server() { - Log(this, "quit") << "quit from " << (this->UplinkServer ? this->UplinkServer->GetName() : "no uplink") << " for " << this->QReason; + Log(this, "quit") << "quit from " << (this->uplink ? this->uplink->GetName() : "no uplink") << " for " << this->quit_reason; - if (Capab.count("NOQUIT") > 0 || Capab.count("QS") > 0) + if (Servers::Capab.count("NOQUIT") > 0 || Servers::Capab.count("QS") > 0) { for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end();) { @@ -137,11 +130,11 @@ Server::~Server() if (u->server == this) { - NickAlias *na = findnick(u->nick); + NickAlias *na = NickAlias::Find(u->nick); if (na && !na->nc->HasFlag(NI_SUSPENDED) && (u->IsRecognized() || u->IsIdentified())) { na->last_seen = Anope::CurTime; - na->last_quit = this->QReason; + na->last_quit = this->quit_reason; } delete u; @@ -151,113 +144,80 @@ Server::~Server() Log(LOG_DEBUG) << "Finished removing all users for " << this->GetName(); } - if (this->UplinkServer) - this->UplinkServer->DelLink(this); + if (this->uplink) + this->uplink->DelLink(this); - for (unsigned i = this->Links.size(); i > 0; --i) - this->Links[i - 1]->Delete(this->QReason); + for (unsigned i = this->links.size(); i > 0; --i) + this->links[i - 1]->Delete(this->quit_reason); } -/** Delete this server with a reason - * @param reason The reason - */ void Server::Delete(const Anope::string &reason) { - this->QReason = reason; + this->quit_reason = reason; FOREACH_MOD(I_OnServerQuit, OnServerQuit(this)); delete this; } -/** Get the name for this server - * @return The name - */ const Anope::string &Server::GetName() const { - return this->Name; + return this->name; } -/** Get the number of hops this server is from services - * @return Number of hops - */ unsigned Server::GetHops() const { - return this->Hops; + return this->hops; } -/** Set the server description - * @param desc The new description - */ void Server::SetDescription(const Anope::string &desc) { - this->Description = desc; + this->description = desc; } -/** Get the server description - * @return The server description - */ const Anope::string &Server::GetDescription() const { - return this->Description; + return this->description; } -/** Change this servers SID - * @param sid The new SID - */ -void Server::SetSID(const Anope::string &sid) +void Server::SetSID(const Anope::string &nsid) { - this->SID = sid; + this->sid = nsid; } -/** Get the server numeric/SID - * @return The numeric/SID - */ const Anope::string &Server::GetSID() const { - if (!this->SID.empty() && ircdproto->RequiresID) - return this->SID; + if (!this->sid.empty() && IRCD->RequiresID) + return this->sid; else - return this->Name; + return this->name; } -/** Get the list of links this server has, or NULL if it has none - * @return A list of servers - */ const std::vector<Server *> &Server::GetLinks() const { - return this->Links; + return this->links; } -/** Get the uplink server for this server, if this is our uplink will be Me - * @return The servers uplink - */ Server *Server::GetUplink() { - return this->UplinkServer; + return this->uplink; } -/** Adds a link to this server - * @param s The linking server - */ void Server::AddLink(Server *s) { - this->Links.push_back(s); + this->links.push_back(s); Log(this, "connect") << "introduced " << s->GetName(); } -/** Delinks a server from this server - * @param s The server - */ void Server::DelLink(Server *s) { - if (this->Links.empty()) + if (this->links.empty()) throw CoreException("Server::DelLink called on " + this->GetName() + " for " + s->GetName() + " but we have no links?"); - for (unsigned i = 0, j = this->Links.size(); i < j; ++i) + for (unsigned i = 0, j = this->links.size(); i < j; ++i) { - if (this->Links[i] == s) + if (this->links[i] == s) { - this->Links.erase(this->Links.begin() + i); + this->links.erase(this->links.begin() + i); break; } } @@ -265,10 +225,7 @@ void Server::DelLink(Server *s) Log(this, "quit") << "quit " << s->GetName(); } -/** Finish syncing this server and optionally all links to it - * @param SyncLinks True to sync the links for this server too (if any) - */ -void Server::Sync(bool SyncLinks) +void Server::Sync(bool sync_links) { if (this->IsSynced()) return; @@ -279,10 +236,10 @@ void Server::Sync(bool SyncLinks) FOREACH_MOD(I_OnServerSync, OnServerSync(this)); - if (SyncLinks && !this->Links.empty()) + if (sync_links && !this->links.empty()) { - for (unsigned i = 0, j = this->Links.size(); i < j; ++i) - this->Links[i]->Sync(true); + for (unsigned i = 0, j = this->links.size(); i < j; ++i) + this->links[i]->Sync(true); } if (this->GetUplink() && this->GetUplink() == Me) @@ -302,7 +259,7 @@ void Server::Sync(bool SyncLinks) { ci->c->SetMode(NULL, CMODE_PERM); if (created) - ircdproto->SendChannel(ci->c); + IRCD->SendChannel(ci->c); } else { @@ -316,7 +273,7 @@ void Server::Sync(bool SyncLinks) FOREACH_MOD(I_OnPreUplinkSync, OnPreUplinkSync(this)); - ircdproto->SendEOB(); + IRCD->SendEOB(); Me->Sync(false); FOREACH_MOD(I_OnUplinkSync, OnUplinkSync(this)); @@ -329,25 +286,19 @@ void Server::Sync(bool SyncLinks) c->ci->RestoreTopic(); } - if (!nofork && AtTerm()) + if (!Anope::NoFork && Anope::AtTerm()) { Log(LOG_TERMINAL) << "Successfully linked, launching into background..."; - Fork(); + Anope::Fork(); } } } -/** Check if this server is synced - * @return true or false - */ bool Server::IsSynced() const { return !this->HasFlag(SERVER_SYNCING); } -/** Check if this server is ULined - * @return true or false - */ bool Server::IsULined() const { if (this == Me) @@ -359,24 +310,14 @@ bool Server::IsULined() const return false; } - -/** Send a message to alll users on this server - * @param source The source of the message - * @param message The message - */ void Server::Notice(const BotInfo *source, const Anope::string &message) { if (Config->NSDefFlags.HasFlag(NI_MSG)) - ircdproto->SendGlobalPrivmsg(source, this, message); + IRCD->SendGlobalPrivmsg(source, this, message); else - ircdproto->SendGlobalNotice(source, this, message); + IRCD->SendGlobalNotice(source, this, message); } -/** Find a server - * @param name The name or SID/numeric - * @param s The server list to search for this server on, defaults to our Uplink - * @return The server - */ Server *Server::Find(const Anope::string &name, Server *s) { Log(LOG_DEBUG_2) << "Server::Find called for " << name; @@ -417,17 +358,14 @@ static inline char& nextID(char &c) return c; } -/** Recieve the next UID in our list - * @return The UID - */ -const Anope::string ts6_uid_retrieve() +const Anope::string Servers::TS6_UID_Retrieve() { - if (!ircdproto || !ircdproto->RequiresID) + if (!IRCD || !IRCD->RequiresID) return ""; static Anope::string current_uid = "AAAAAA"; - while (finduser(Config->Numeric + current_uid) != NULL) + while (User::Find(Config->Numeric + current_uid) != NULL) { int current_len = current_uid.length() - 1; while (current_len >= 0 && nextID(current_uid[current_len--]) == 'A'); @@ -436,12 +374,9 @@ const Anope::string ts6_uid_retrieve() return Config->Numeric + current_uid; } -/** Return the next SID in our list - * @return The SID - */ -const Anope::string ts6_sid_retrieve() +const Anope::string Servers::TS6_SID_Retrieve() { - if (!ircdproto || !ircdproto->RequiresID) + if (!IRCD || !IRCD->RequiresID) return ""; static Anope::string current_sid; @@ -461,3 +396,11 @@ const Anope::string ts6_sid_retrieve() return current_sid; } +Server* Servers::GetUplink() +{ + for (unsigned i = 0; Me && i < Me->GetLinks().size(); ++i) + if (!Me->GetLinks()[i]->HasFlag(SERVER_JUPED)) + return Me->GetLinks()[i]; + return NULL; +} + diff --git a/src/socket_clients.cpp b/src/socket_clients.cpp index 44d4b873a..69700af4e 100644 --- a/src/socket_clients.cpp +++ b/src/socket_clients.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -22,7 +23,7 @@ ConnectionSocket::ConnectionSocket() : Socket() void ConnectionSocket::Connect(const Anope::string &TargetHost, int Port) { - this->IO->Connect(this, TargetHost, Port); + this->io->Connect(this, TargetHost, Port); } bool ConnectionSocket::Process() @@ -32,7 +33,7 @@ bool ConnectionSocket::Process() if (this->HasFlag(SF_CONNECTED)) return true; else if (this->HasFlag(SF_CONNECTING)) - this->SetFlag(this->IO->FinishConnect(this)); + this->SetFlag(this->io->FinishConnect(this)); else this->SetFlag(SF_DEAD); } @@ -61,7 +62,7 @@ void ConnectionSocket::OnError(const Anope::string &error) Log(LOG_DEBUG) << "Socket error: " << error; } -ClientSocket::ClientSocket(ListenSocket *ls, const sockaddrs &addr) : LS(ls), clientaddr(addr) +ClientSocket::ClientSocket(ListenSocket *l, const sockaddrs &addr) : ls(l), clientaddr(addr) { } @@ -72,7 +73,7 @@ bool ClientSocket::Process() if (this->HasFlag(SF_ACCEPTED)) return true; else if (this->HasFlag(SF_ACCEPTING)) - this->SetFlag(this->IO->FinishAccept(this)); + this->SetFlag(this->io->FinishAccept(this)); else this->SetFlag(SF_DEAD); } diff --git a/src/socket_transport.cpp b/src/socket_transport.cpp index 2297da2b2..4af3668a3 100644 --- a/src/socket_transport.cpp +++ b/src/socket_transport.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -25,28 +26,28 @@ bool BufferedSocket::ProcessRead() { char tbuffer[NET_BUFSIZE]; - this->RecvLen = 0; + this->recv_len = 0; - int len = this->IO->Recv(this, tbuffer, sizeof(tbuffer) - 1); + int len = this->io->Recv(this, tbuffer, sizeof(tbuffer) - 1); if (len <= 0) return false; tbuffer[len] = 0; - this->RecvLen = len; + this->recv_len = len; - Anope::string sbuffer = this->extrabuf; + Anope::string sbuffer = this->extra_buf; sbuffer += tbuffer; - this->extrabuf.clear(); + this->extra_buf.clear(); size_t lastnewline = sbuffer.rfind('\n'); if (lastnewline == Anope::string::npos) { - this->extrabuf = sbuffer; + this->extra_buf = sbuffer; return true; } if (lastnewline < sbuffer.length() - 1) { - this->extrabuf = sbuffer.substr(lastnewline); - this->extrabuf.trim(); + this->extra_buf = sbuffer.substr(lastnewline); + this->extra_buf.trim(); sbuffer = sbuffer.substr(0, lastnewline); } @@ -65,11 +66,11 @@ bool BufferedSocket::ProcessRead() bool BufferedSocket::ProcessWrite() { - int count = this->IO->Send(this, this->WriteBuffer); + int count = this->io->Send(this, this->write_buffer); if (count <= -1) return false; - this->WriteBuffer = this->WriteBuffer.substr(count); - if (this->WriteBuffer.empty()) + this->write_buffer = this->write_buffer.substr(count); + if (this->write_buffer.empty()) SocketEngine::Change(this, false, SF_WRITABLE); return true; @@ -82,7 +83,7 @@ bool BufferedSocket::Read(const Anope::string &buf) void BufferedSocket::Write(const char *buffer, size_t l) { - this->WriteBuffer += buffer + Anope::string("\r\n"); + this->write_buffer += buffer + Anope::string("\r\n"); SocketEngine::Change(this, true, SF_WRITABLE); } @@ -108,12 +109,12 @@ void BufferedSocket::Write(const Anope::string &message) int BufferedSocket::ReadBufferLen() const { - return RecvLen; + return recv_len; } int BufferedSocket::WriteBufferLen() const { - return this->WriteBuffer.length(); + return this->write_buffer.length(); } @@ -141,7 +142,7 @@ bool BinarySocket::ProcessRead() { char tbuffer[NET_BUFSIZE]; - int len = this->IO->Recv(this, tbuffer, sizeof(tbuffer)); + int len = this->io->Recv(this, tbuffer, sizeof(tbuffer)); if (len <= 0) return false; @@ -150,21 +151,21 @@ bool BinarySocket::ProcessRead() bool BinarySocket::ProcessWrite() { - if (this->WriteBuffer.empty()) + if (this->write_buffer.empty()) { SocketEngine::Change(this, false, SF_WRITABLE); return true; } - DataBlock *d = this->WriteBuffer.front(); + DataBlock *d = this->write_buffer.front(); - int len = this->IO->Send(this, d->buf, d->len); + int len = this->io->Send(this, d->buf, d->len); if (len <= -1) return false; else if (static_cast<size_t>(len) == d->len) { delete d; - this->WriteBuffer.pop_front(); + this->write_buffer.pop_front(); } else { @@ -172,7 +173,7 @@ bool BinarySocket::ProcessWrite() d->len -= len; } - if (this->WriteBuffer.empty()) + if (this->write_buffer.empty()) SocketEngine::Change(this, false, SF_WRITABLE); return true; @@ -180,7 +181,7 @@ bool BinarySocket::ProcessWrite() void BinarySocket::Write(const char *buffer, size_t l) { - this->WriteBuffer.push_back(new DataBlock(buffer, l)); + this->write_buffer.push_back(new DataBlock(buffer, l)); SocketEngine::Change(this, true, SF_WRITABLE); } diff --git a/src/socketengines/pipeengine_eventfd.cpp b/src/socketengines/pipeengine_eventfd.cpp index 19433d1c8..61fddd0af 100644 --- a/src/socketengines/pipeengine_eventfd.cpp +++ b/src/socketengines/pipeengine_eventfd.cpp @@ -16,7 +16,7 @@ Pipe::Pipe() : Socket(eventfd(0, EFD_NONBLOCK)) { - if (this->Sock < 0) + if (this->sock < 0) throw CoreException("Could not create pipe: " + Anope::LastError()); } diff --git a/src/sockets.cpp b/src/sockets.cpp index 861df6976..6aadb7802 100644 --- a/src/sockets.cpp +++ b/src/sockets.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -20,15 +21,18 @@ #include <fcntl.h> #endif +static const Anope::string SocketFlagStrings[] = { + "SF_DEAD", "SF_WRITABLE", "SF_CONNECTING", "SF_CONNECTED", "SF_ACCEPTING", "SF_ACCEPTED", "" +}; +template<> const Anope::string* Flags<SocketFlag>::flags_strings = SocketFlagStrings; + std::map<int, Socket *> SocketEngine::Sockets; uint32_t TotalRead = 0; uint32_t TotalWritten = 0; -SocketIO normalSocketIO; +SocketIO NormalSocketIO; -/** Construct the object, sets everything to 0 - */ sockaddrs::sockaddrs(const Anope::string &address) { this->clear(); @@ -36,16 +40,11 @@ sockaddrs::sockaddrs(const Anope::string &address) this->pton(address.find(':') != Anope::string::npos ? AF_INET6 : AF_INET, address); } -/** Memset the object to 0 - */ void sockaddrs::clear() { memset(this, 0, sizeof(*this)); } -/** Get the size of the sockaddr we represent - * @return The size - */ size_t sockaddrs::size() const { switch (sa.sa_family) @@ -61,9 +60,6 @@ size_t sockaddrs::size() const return 0; } -/** Get the port represented by this addr - * @return The port, or -1 on fail - */ int sockaddrs::port() const { switch (sa.sa_family) @@ -79,9 +75,6 @@ int sockaddrs::port() const return -1; } -/** Get the address represented by this addr - * @return The address - */ Anope::string sockaddrs::addr() const { char address[INET6_ADDRSTRLEN + 1] = ""; @@ -103,16 +96,11 @@ Anope::string sockaddrs::addr() const return address; } -/** Check if this sockaddr has data in it - */ bool sockaddrs::operator()() const { return this->sa.sa_family != 0; } -/** Compares with sockaddr with another. Compares address type, port, and address - * @return true if they are the same - */ bool sockaddrs::operator==(const sockaddrs &other) const { if (sa.sa_family != other.sa.sa_family) @@ -130,12 +118,6 @@ bool sockaddrs::operator==(const sockaddrs &other) const return false; } -/** The equivalent of inet_pton - * @param type AF_INET or AF_INET6 - * @param address The address to place in the sockaddr structures - * @param pport An option port to include in the sockaddr structures - * @throws A socket exception if given invalid IPs - */ void sockaddrs::pton(int type, const Anope::string &address, int pport) { switch (type) @@ -169,11 +151,6 @@ void sockaddrs::pton(int type, const Anope::string &address, int pport) throw CoreException("Invalid socket type"); } -/** The equivalent of inet_ntop - * @param type AF_INET or AF_INET6 - * @param address The in_addr or in_addr6 structure - * @throws A socket exception if given an invalid structure - */ void sockaddrs::ntop(int type, const void *src) { switch (type) @@ -333,12 +310,6 @@ size_t cidr::hash::operator()(const cidr &s) const } } -/** Receive something from the buffer - * @param s The socket - * @param buf The buf to read to - * @param sz How much to read - * @return Number of bytes received - */ int SocketIO::Recv(Socket *s, char *buf, size_t sz) { size_t i = recv(s->GetFD(), buf, sz, 0); @@ -346,26 +317,18 @@ int SocketIO::Recv(Socket *s, char *buf, size_t sz) return i; } -/** Write something to the socket - * @param s The socket - * @param buf The data to write - * @param size The length of the data - */ int SocketIO::Send(Socket *s, const char *buf, size_t sz) { size_t i = send(s->GetFD(), buf, sz, 0); TotalWritten += i; return i; } + int SocketIO::Send(Socket *s, const Anope::string &buf) { return this->Send(s, buf.c_str(), buf.length()); } -/** Accept a connection from a socket - * @param s The socket - * @return The new client socket - */ ClientSocket *SocketIO::Accept(ListenSocket *s) { sockaddrs conaddr; @@ -384,20 +347,11 @@ ClientSocket *SocketIO::Accept(ListenSocket *s) throw SocketException("Unable to accept connection: " + Anope::LastError()); } -/** Finished accepting a connection from a socket - * @param s The socket - * @return SF_ACCEPTED if accepted, SF_ACCEPTING if still in process, SF_DEAD on error - */ SocketFlag SocketIO::FinishAccept(ClientSocket *cs) { return SF_ACCEPTED; } -/** Bind a socket - * @param s The socket - * @param ip The IP to bind to - * @param port The optional port to bind to - */ void SocketIO::Bind(Socket *s, const Anope::string &ip, int port) { s->bindaddr.pton(s->IsIPv6() ? AF_INET6 : AF_INET, ip, port); @@ -405,11 +359,6 @@ void SocketIO::Bind(Socket *s, const Anope::string &ip, int port) throw SocketException("Unable to bind to address: " + Anope::LastError()); } -/** Connect the socket - * @param s THe socket - * @param target IP to connect to - * @param port to connect to - */ void SocketIO::Connect(ConnectionSocket *s, const Anope::string &target, int port) { s->UnsetFlag(SF_CONNECTING); @@ -433,10 +382,6 @@ void SocketIO::Connect(ConnectionSocket *s, const Anope::string &target, int por } } -/** Called to potentially finish a pending connection - * @param s The socket - * @return SF_CONNECTED on success, SF_CONNECTING if still pending, and SF_DEAD on error. - */ SocketFlag SocketIO::FinishConnect(ConnectionSocket *s) { if (s->HasFlag(SF_CONNECTED)) @@ -461,148 +406,102 @@ SocketFlag SocketIO::FinishConnect(ConnectionSocket *s) } } -/** Empty constructor, should not be called. - */ -Socket::Socket() : Flags<SocketFlag>(SocketFlagStrings) +Socket::Socket() { throw CoreException("Socket::Socket() ?"); } -/** Constructor - * @param sock The socket - * @param ipv6 IPv6? - * @param type The socket type, defaults to SOCK_STREAM - */ -Socket::Socket(int sock, bool ipv6, int type) : Flags<SocketFlag>(SocketFlagStrings) +Socket::Socket(int s, bool i, int type) { - this->IO = &normalSocketIO; - this->IPv6 = ipv6; - if (sock == -1) - this->Sock = socket(this->IPv6 ? AF_INET6 : AF_INET, type, 0); + this->io = &NormalSocketIO; + this->ipv6 = i; + if (s == -1) + this->sock = socket(this->ipv6 ? AF_INET6 : AF_INET, type, 0); else - this->Sock = sock; + this->sock = s; this->SetNonBlocking(); - SocketEngine::Sockets[this->Sock] = this; + SocketEngine::Sockets[this->sock] = this; SocketEngine::Change(this, true, SF_READABLE); } -/** Default destructor -*/ Socket::~Socket() { SocketEngine::Change(this, false, SF_READABLE); SocketEngine::Change(this, false, SF_WRITABLE); - anope_close(this->Sock); - this->IO->Destroy(); - SocketEngine::Sockets.erase(this->Sock); + anope_close(this->sock); + this->io->Destroy(); + SocketEngine::Sockets.erase(this->sock); } -/** Get the socket FD for this socket - * @return the fd - */ int Socket::GetFD() const { - return Sock; + return sock; } -/** Check if this socket is IPv6 - * @return true or false - */ bool Socket::IsIPv6() const { - return IPv6; + return ipv6; } -/** Mark a socket as blockig - * @return true if the socket is now blocking - */ bool Socket::SetBlocking() { int flags = fcntl(this->GetFD(), F_GETFL, 0); return !fcntl(this->GetFD(), F_SETFL, flags & ~O_NONBLOCK); } -/** Mark a socket as non-blocking - * @return true if the socket is now non-blocking - */ bool Socket::SetNonBlocking() { int flags = fcntl(this->GetFD(), F_GETFL, 0); return !fcntl(this->GetFD(), F_SETFL, flags | O_NONBLOCK); } -/** Bind the socket to an ip and port - * @param ip The ip - * @param port The port - */ void Socket::Bind(const Anope::string &ip, int port) { - this->IO->Bind(this, ip, port); + this->io->Bind(this, ip, port); } -/** Called when there either is a read or write event. - * @return true to continue to call ProcessRead/ProcessWrite, false to not continue - */ bool Socket::Process() { return true; } -/** Called when there is something to be received for this socket - * @return true on success, false to drop this socket - */ bool Socket::ProcessRead() { return true; } -/** Called when the socket is ready to be written to - * @return true on success, false to drop this socket - */ bool Socket::ProcessWrite() { return true; } -/** Called when there is an error for this socket - * @return true on success, false to drop this socket - */ void Socket::ProcessError() { } -/** Constructor - * @param bindip The IP to bind to - * @param port The port to listen on - * @param ipv6 true for ipv6 - */ -ListenSocket::ListenSocket(const Anope::string &bindip, int port, bool ipv6) +ListenSocket::ListenSocket(const Anope::string &bindip, int port, bool i) { this->SetNonBlocking(); const char op = 1; setsockopt(this->GetFD(), SOL_SOCKET, SO_REUSEADDR, &op, sizeof(op)); - this->bindaddr.pton(IPv6 ? AF_INET6 : AF_INET, bindip, port); - this->IO->Bind(this, bindip, port); + this->bindaddr.pton(i ? AF_INET6 : AF_INET, bindip, port); + this->io->Bind(this, bindip, port); - if (listen(Sock, SOMAXCONN) == -1) + if (listen(sock, SOMAXCONN) == -1) throw SocketException("Unable to listen: " + Anope::LastError()); } -/** Destructor - */ ListenSocket::~ListenSocket() { } -/** Accept a connection in this sockets queue - */ bool ListenSocket::ProcessRead() { try { - this->IO->Accept(this); + this->io->Accept(this); } catch (const SocketException &ex) { diff --git a/src/threadengine.cpp b/src/threadengine.cpp index c3ecdd1b5..12e14eb19 100644 --- a/src/threadengine.cpp +++ b/src/threadengine.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ #include "services.h" @@ -35,9 +36,6 @@ static inline pthread_attr_t *get_engine_attr() return &attr; } -/** Entry point used for the threads - * @param parameter A Thread* cast to a void* - */ static void *entry_point(void *parameter) { Thread *thread = static_cast<Thread *>(parameter); @@ -47,129 +45,92 @@ static void *entry_point(void *parameter) return NULL; } -/** Threads constructor - */ Thread::Thread() : exit(false) { } -/** Threads destructor - */ Thread::~Thread() { } -/** Join to the thread, sets the exit state to true - */ void Thread::Join() { this->SetExitState(); - pthread_join(Handle, NULL); + pthread_join(handle, NULL); } -/** Sets the exit state as true informing the thread we want it to shut down - */ void Thread::SetExitState() { this->Notify(); exit = true; } -/** Exit the thread. Note that the thread still must be joined to free resources! - */ void Thread::Exit() { this->SetExitState(); pthread_exit(0); } -/** Launch the thread - */ void Thread::Start() { - if (pthread_create(&this->Handle, get_engine_attr(), entry_point, this)) + if (pthread_create(&this->handle, get_engine_attr(), entry_point, this)) { this->SetFlag(SF_DEAD); throw CoreException("Unable to create thread: " + Anope::LastError()); } } -/** Returns the exit state of the thread - * @return true if we want to exit - */ bool Thread::GetExitState() const { return exit; } -/** Called when this thread should be joined to - */ void Thread::OnNotify() { this->Join(); this->SetFlag(SF_DEAD); } -/** Constructor - */ Mutex::Mutex() { pthread_mutex_init(&mutex, NULL); } -/** Destructor - */ Mutex::~Mutex() { pthread_mutex_destroy(&mutex); } -/** Attempt to lock the mutex, will hang until a lock can be achieved - */ void Mutex::Lock() { pthread_mutex_lock(&mutex); } -/** Unlock the mutex, it must be locked first - */ void Mutex::Unlock() { pthread_mutex_unlock(&mutex); } -/** Attempt to lock the mutex, will return true on success and false on fail - * Does not block - * @return true or false - */ bool Mutex::TryLock() { return pthread_mutex_trylock(&mutex) == 0; } -/** Constructor - */ Condition::Condition() : Mutex() { pthread_cond_init(&cond, NULL); } -/** Destructor - */ Condition::~Condition() { pthread_cond_destroy(&cond); } -/** Called to wakeup the waiter - */ void Condition::Wakeup() { pthread_cond_signal(&cond); } -/** Called to wait for a Wakeup() call - */ void Condition::Wait() { pthread_cond_wait(&cond, &mutex); diff --git a/src/timers.cpp b/src/timers.cpp index 267629aee..bc88afb01 100644 --- a/src/timers.cpp +++ b/src/timers.cpp @@ -4,21 +4,14 @@ * Contact us at team@anope.org * * Please read COPYING and README for further details. - * Based on the original code of Epona by Lara. - * Based on the original code of Services by Andy Church. + * */ - #include "services.h" #include "timers.h" std::vector<Timer *> TimerManager::Timers; -/** Default constructor, initializes the triggering time - * @param time_from_now The number of seconds from now to trigger the timer - * @param now The time now - * @param repeating Repeat this timer every time_from_now if this is true - */ Timer::Timer(long time_from_now, time_t now, bool repeating) { trigger = now + time_from_now; @@ -29,48 +22,31 @@ Timer::Timer(long time_from_now, time_t now, bool repeating) TimerManager::AddTimer(this); } -/** Default destructor, removes the timer from the list - */ Timer::~Timer() { TimerManager::DelTimer(this); } -/** Set the trigger time to a new value - * @param t The new time -*/ void Timer::SetTimer(time_t t) { trigger = t; } -/** Retrieve the triggering time - * @return The trigger time - */ time_t Timer::GetTimer() const { return trigger; } -/** Returns true if the timer is set to repeat - * @return Returns true if the timer is set to repeat - */ bool Timer::GetRepeat() const { return repeat; } -/** Returns the time this timer was created -* @return The time this timer was created -*/ time_t Timer::GetSetTime() const { return settime; } -/** Sets the interval between ticks - * @param t The new interval - */ void Timer::SetSecs(time_t t) { secs = t; @@ -80,37 +56,25 @@ void Timer::SetSecs(time_t t) TimerManager::AddTimer(this); } -/** Returns the interval between ticks -* @return The interval -*/ long Timer::GetSecs() const { return secs; } -/** Add a timer to the list - * @param T A Timer derived class to add - */ -void TimerManager::AddTimer(Timer *T) +void TimerManager::AddTimer(Timer *t) { - Timers.push_back(T); + Timers.push_back(t); sort(Timers.begin(), Timers.end(), TimerManager::TimerComparison); } -/** Deletes a timer - * @param T A Timer derived class to delete - */ -void TimerManager::DelTimer(Timer *T) +void TimerManager::DelTimer(Timer *t) { - std::vector<Timer *>::iterator i = std::find(Timers.begin(), Timers.end(), T); + std::vector<Timer *>::iterator i = std::find(Timers.begin(), Timers.end(), t); if (i != Timers.end()) Timers.erase(i); } -/** Tick all pending timers - * @param ctime The current time - */ void TimerManager::TickTimers(time_t ctime) { while (Timers.size() && ctime > Timers.front()->GetTimer()) @@ -129,8 +93,6 @@ void TimerManager::TickTimers(time_t ctime) } } -/** Compares two timers - */ bool TimerManager::TimerComparison(Timer *one, Timer *two) { return one->GetTimer() < two->GetTimer(); diff --git a/src/tools/CMakeLists.txt b/src/tools/CMakeLists.txt index 88fc37ffc..613e4ffc6 100644 --- a/src/tools/CMakeLists.txt +++ b/src/tools/CMakeLists.txt @@ -34,6 +34,14 @@ foreach(SRC ${TOOLS_SRCS}) endif(NOT SKIP) endforeach(SRC) +# If not on Windows, generate anoperc and install it along with mydbgen +if(NOT WIN32) + configure_file(${Anope_SOURCE_DIR}/src/tools/anoperc.in ${Anope_BINARY_DIR}/src/tools/anoperc) + install (PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/anoperc + DESTINATION ${BIN_DIR} + ) +endif(NOT WIN32) + # On non-Windows platforms, if RUNGROUP is set, change the permissions of the tools directory if(NOT WIN32 AND RUNGROUP) install(CODE "execute_process(COMMAND ${CHMOD} 2770 \"\${CMAKE_INSTALL_PREFIX}/bin\")") diff --git a/src/bin/anoperc.in b/src/tools/anoperc.in index 9a71a22c3..9a71a22c3 100644 --- a/src/bin/anoperc.in +++ b/src/tools/anoperc.in diff --git a/src/uplink.cpp b/src/uplink.cpp new file mode 100644 index 000000000..ac77672b2 --- /dev/null +++ b/src/uplink.cpp @@ -0,0 +1,204 @@ +/* + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + +#include "uplink.h" +#include "logger.h" +#include "config.h" +#include "protocol.h" +#include "servers.h" +#include "dns.h" + +UplinkSocket *UplinkSock = NULL; + +class ReconnectTimer : public Timer +{ + public: + ReconnectTimer(int wait) : Timer(wait) { } + + void Tick(time_t) + { + try + { + Uplink::Connect(); + } + catch (const SocketException &ex) + { + Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (Anope::CurrentUplink + 1) << " (" << Config->Uplinks[Anope::CurrentUplink]->host << ":" << Config->Uplinks[Anope::CurrentUplink]->port << "): " << ex.GetReason(); + } + } +}; + +void Uplink::Connect() +{ + if (static_cast<unsigned>(++Anope::CurrentUplink) >= Config->Uplinks.size()) + Anope::CurrentUplink = 0; + + ServerConfig::Uplink *u = Config->Uplinks[Anope::CurrentUplink]; + + new UplinkSocket(); + if (!Config->LocalHost.empty()) + UplinkSock->Bind(Config->LocalHost); + FOREACH_MOD(I_OnPreServerConnect, OnPreServerConnect()); + DNS::Query rep = DNS::Manager::BlockingQuery(u->host, u->ipv6 ? DNS::QUERY_AAAA : DNS::QUERY_A); + Anope::string reply_ip = !rep.answers.empty() ? rep.answers.front().rdata : u->host; + Log(LOG_TERMINAL) << "Attempting to connect to uplink #" << (Anope::CurrentUplink + 1) << " " << u->host << " (" << reply_ip << "), port " << u->port; + UplinkSock->Connect(reply_ip, u->port); +} + + +UplinkSocket::UplinkSocket() : Socket(-1, Config->Uplinks[Anope::CurrentUplink]->ipv6), ConnectionSocket(), BufferedSocket() +{ + UplinkSock = this; +} + +UplinkSocket::~UplinkSocket() +{ + if (IRCD && Servers::GetUplink() && Servers::GetUplink()->IsSynced()) + { + FOREACH_MOD(I_OnServerDisconnect, OnServerDisconnect()); + + for (user_map::const_iterator it = UserListByNick.begin(); it != UserListByNick.end(); ++it) + { + User *u = it->second; + + if (u->server == Me) + { + /* Don't use quitmsg here, it may contain information you don't want people to see */ + IRCD->SendQuit(u, "Shutting down"); + BotInfo* bi = BotInfo::Find(u->nick); + if (bi != NULL) + bi->introduced = false; + } + } + + IRCD->SendSquit(Me, Anope::QuitReason); + + this->ProcessWrite(); // Write out the last bit + } + + if (Me) + for (unsigned i = Me->GetLinks().size(); i > 0; --i) + if (!Me->GetLinks()[i - 1]->HasFlag(SERVER_JUPED)) + Me->GetLinks()[i - 1]->Delete(Me->GetName() + " " + Me->GetLinks()[i - 1]->GetName()); + + UplinkSock = NULL; + + Me->SetFlag(SERVER_SYNCING); + + if (Anope::AtTerm()) + { + if (static_cast<unsigned>(Anope::CurrentUplink + 1) == Config->Uplinks.size()) + { + Anope::QuitReason = "Unable to connect to any uplink"; + Anope::Quitting = true; + Anope::ReturnValue = -1; + } + else + { + new ReconnectTimer(1); + } + } + else if (!Anope::Quitting) + { + int retry = Config->RetryWait; + if (retry <= 0) + retry = 60; + + Log() << "Disconnected, retrying in " << retry << " seconds"; + new ReconnectTimer(retry); + } +} + +bool UplinkSocket::Read(const Anope::string &buf) +{ + Anope::Process(buf); + return true; +} + +void UplinkSocket::OnConnect() +{ + Log(LOG_TERMINAL) << "Successfully connected to uplink #" << (Anope::CurrentUplink + 1) << " " << Config->Uplinks[Anope::CurrentUplink]->host << ":" << Config->Uplinks[Anope::CurrentUplink]->port; + IRCD->SendConnect(); + FOREACH_MOD(I_OnServerConnect, OnServerConnect()); +} + +void UplinkSocket::OnError(const Anope::string &error) +{ + Log(LOG_TERMINAL) << "Unable to connect to uplink #" << (Anope::CurrentUplink + 1) << " (" << Config->Uplinks[Anope::CurrentUplink]->host << ":" << Config->Uplinks[Anope::CurrentUplink]->port << ")" << (!error.empty() ? (": " + error) : ""); +} + +UplinkSocket::Message::Message() : server(NULL), user(NULL) +{ +} + +UplinkSocket::Message::Message(const Server *s) : server(s), user(NULL) +{ +} + +UplinkSocket::Message::Message(const User *u) : server(NULL), user(u) +{ + if (!u) + server = Me; +} + +UplinkSocket::Message::~Message() +{ + Anope::string message_source = ""; + + if (this->server != NULL) + { + if (this->server != Me && !this->server->HasFlag(SERVER_JUPED)) + { + Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->server->GetName() << " who is not from me?"; + return; + } + + message_source = this->server->GetSID(); + } + else if (this->user != NULL) + { + if (this->user->server != Me && !this->user->server->HasFlag(SERVER_JUPED)) + { + Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << this->user->nick << " who is not from me?"; + return; + } + + const BotInfo *bi = BotInfo::Find(this->user->nick); + if (bi != NULL && bi->introduced == false) + { + Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" from " << bi->nick << " when not introduced"; + return; + } + + message_source = this->user->GetUID(); + } + + if (!UplinkSock) + { + if (!message_source.empty()) + Log(LOG_DEBUG) << "Attempted to send \"" << message_source << " " << this->buffer.str() << "\" with UplinkSock NULL"; + else + Log(LOG_DEBUG) << "Attempted to send \"" << this->buffer.str() << "\" with UplinkSock NULL"; + return; + } + + if (!message_source.empty()) + { + UplinkSock->Write(":" + message_source + " " + this->buffer.str()); + Log(LOG_RAWIO) << "Sent: :" << message_source << " " << this->buffer.str(); + } + else + { + UplinkSock->Write(this->buffer.str()); + Log(LOG_RAWIO) << "Sent: " << this->buffer.str(); + } +} diff --git a/src/users.cpp b/src/users.cpp index ea02566d4..628b0c464 100644 --- a/src/users.cpp +++ b/src/users.cpp @@ -7,6 +7,7 @@ * * Based on the original code of Epona by Lara. * Based on the original code of Services by Andy Church. + * */ @@ -20,16 +21,15 @@ #include "bots.h" #include "config.h" #include "opertype.h" -#include "extern.h" +#include "nickserv.h" +#include "operserv.h" +#include "language.h" user_map UserListByNick, UserListByUID; -int32_t opcnt = 0; -uint32_t usercnt = 0, maxusercnt = 0; -time_t maxusertime; - -/*************************************************************************/ -/*************************************************************************/ +int OperCount = 0; +unsigned MaxUserCount = 0; +time_t MaxUserTime = 0; User::User(const Anope::string &snick, const Anope::string &sident, const Anope::string &shost, const Anope::string &svhost, const Anope::string &sip, Server *sserver, const Anope::string &srealname, time_t ssignon, const Anope::string &smodes, const Anope::string &suid) { @@ -39,7 +39,7 @@ User::User(const Anope::string &snick, const Anope::string &sident, const Anope: /* we used to do this by calloc, no more. */ server = NULL; invalid_pw_count = invalid_pw_time = lastmemosend = lastnickreg = lastmail = 0; - OnAccess = false; + on_access = false; this->nick = snick; this->ident = sident; @@ -53,7 +53,7 @@ User::User(const Anope::string &snick, const Anope::string &sident, const Anope: this->timestamp = this->signon = ssignon; this->SetModesInternal("%s", smodes.c_str()); this->uid = suid; - this->SuperAdmin = false; + this->super_admin = false; size_t old = UserListByNick.size(); UserListByNick[snick] = this; @@ -66,22 +66,21 @@ User::User(const Anope::string &snick, const Anope::string &sident, const Anope: if (sserver) // Our bots are introduced on startup with no server { - ++sserver->Users; + ++sserver->users; Log(this, "connect") << (!svhost.empty() ? Anope::string("(") + svhost + ") " : "") << "(" << srealname << ") " << sip << " connected to the network (" << sserver->GetName() << ")"; } - ++usercnt; - if (usercnt > maxusercnt) + if (UserListByNick.size() > MaxUserCount) { - maxusercnt = usercnt; - maxusertime = Anope::CurTime; - Log(this, "maxusers") << "connected - new maximum user count: " << maxusercnt; + MaxUserCount = UserListByNick.size(); + MaxUserTime = Anope::CurTime; + Log(this, "maxusers") << "connected - new maximum user count: " << UserListByNick.size(); } bool exempt = false; if (server && server->IsULined()) exempt = true; - dynamic_reference<User> user = this; + Reference<User> user = this; FOREACH_MOD(I_OnUserConnect, OnUserConnect(user, exempt)); } @@ -91,7 +90,7 @@ void User::ChangeNick(const Anope::string &newnick, time_t ts) if (newnick.empty()) throw CoreException("User::ChangeNick() got a bad argument"); - this->SuperAdmin = false; + this->super_admin = false; Log(this, "nick") << "(" << this->realname << ") changed nick to " << newnick; Anope::string old = this->nick; @@ -101,7 +100,7 @@ void User::ChangeNick(const Anope::string &newnick, time_t ts) this->nick = newnick; else { - NickAlias *old_na = findnick(this->nick); + NickAlias *old_na = NickAlias::Find(this->nick); if (old_na && (this->IsIdentified(true) || this->IsRecognized())) old_na->last_seen = Anope::CurTime; @@ -109,10 +108,10 @@ void User::ChangeNick(const Anope::string &newnick, time_t ts) this->nick = newnick; UserListByNick[this->nick] = this; - OnAccess = false; - NickAlias *na = findnick(this->nick); + on_access = false; + NickAlias *na = NickAlias::Find(this->nick); if (na) - OnAccess = is_on_access(this, na->nc); + on_access = na->nc->IsOnAccess(this); if (old_na) old_na->OnCancel(this); @@ -139,9 +138,6 @@ void User::SetDisplayedHost(const Anope::string &shost) this->UpdateHost(); } -/** Get the displayed vhost of a user record. - * @return The displayed vhost of the user, where ircd-supported, or the user's real host. - */ const Anope::string &User::GetDisplayedHost() const { if (!this->vhost.empty()) @@ -152,9 +148,6 @@ const Anope::string &User::GetDisplayedHost() const return this->host; } -/** Update the cloaked host of a user - * @param host The cloaked host - */ void User::SetCloakedHost(const Anope::string &newhost) { if (newhost.empty()) @@ -167,9 +160,6 @@ void User::SetCloakedHost(const Anope::string &newhost) this->UpdateHost(); } -/** Get the cloaked host of a user - * @return The cloaked host - */ const Anope::string &User::GetCloakedHost() const { return chost; @@ -177,7 +167,7 @@ const Anope::string &User::GetCloakedHost() const const Anope::string &User::GetUID() const { - if (!this->uid.empty() && ircdproto->RequiresID) + if (!this->uid.empty() && IRCD->RequiresID) return this->uid; else return this->nick; @@ -230,7 +220,7 @@ void User::SetRealname(const Anope::string &srealname) throw CoreException("realname empty in SetRealname"); this->realname = srealname; - NickAlias *na = findnick(this->nick); + NickAlias *na = NickAlias::Find(this->nick); if (na && (this->IsIdentified(true) || this->IsRecognized())) na->last_realname = srealname; @@ -243,17 +233,15 @@ User::~User() Log(LOG_DEBUG_2) << "User::~User() called"; Log(this, "disconnect") << "(" << this->realname << ") " << "disconnected from the network (" << this->server->GetName() << ")"; - --this->server->Users; + --this->server->users; FOREACH_MOD(I_OnUserLogoff, OnUserLogoff(this)); ModeManager::StackerDel(this); this->Logout(); - --usercnt; - if (this->HasMode(UMODE_OPER)) - --opcnt; + --OperCount; while (!this->chans.empty()) this->chans.front()->chan->DeleteUser(this); @@ -262,7 +250,7 @@ User::~User() if (!this->uid.empty()) UserListByUID.erase(this->uid); - NickAlias *na = findnick(this->nick); + NickAlias *na = NickAlias::Find(this->nick); if (na) na->OnCancel(this); @@ -274,7 +262,7 @@ void User::SendMessage(const BotInfo *source, const char *fmt, ...) va_list args; char buf[BUFSIZE] = ""; - const char *translated_message = translate(this, fmt); + const char *translated_message = Language::Translate(this, fmt); va_start(args, fmt); vsnprintf(buf, BUFSIZE - 1, translated_message, args); @@ -286,7 +274,7 @@ void User::SendMessage(const BotInfo *source, const char *fmt, ...) void User::SendMessage(const BotInfo *source, const Anope::string &msg) { - const char *translated_message = translate(this, msg.c_str()); + const char *translated_message = Language::Translate(this, msg.c_str()); /* Send privmsg instead of notice if: * - UsePrivmsg is enabled @@ -298,9 +286,9 @@ void User::SendMessage(const BotInfo *source, const Anope::string &msg) while (sep.GetToken(tok)) { if (Config->UsePrivmsg && ((!this->nc && Config->NSDefFlags.HasFlag(NI_MSG)) || (this->nc && this->nc->HasFlag(NI_MSG)))) - ircdproto->SendPrivmsg(source, this->GetUID(), "%s", tok.c_str()); + IRCD->SendPrivmsg(source, this->GetUID(), "%s", tok.c_str()); else - ircdproto->SendNotice(source, this->GetUID(), "%s", tok.c_str()); + IRCD->SendNotice(source, this->GetUID(), "%s", tok.c_str()); } } @@ -362,13 +350,10 @@ void User::SendMessage(const BotInfo *source, const Anope::string &msg) */ void User::Collide(NickAlias *na) { - const BotInfo *bi = findbot(Config->NickServ); - if (!bi) - return; if (na) na->SetFlag(NS_COLLIDED); - if (ircdproto->CanSVSNick) + if (IRCD->CanSVSNick) { Anope::string guestnick; @@ -376,25 +361,21 @@ void User::Collide(NickAlias *na) do { guestnick = Config->NSGuestNickPrefix + stringify(static_cast<uint16_t>(rand())); - } while (finduser(guestnick) && i++ < 10); + } while (User::Find(guestnick) && i++ < 10); if (i == 11) this->Kill(Config->NickServ, "Services nickname-enforcer kill"); else { - this->SendMessage(bi, _("Your nickname is now being changed to \002%s\002"), guestnick.c_str()); - ircdproto->SendForceNickChange(this, guestnick, Anope::CurTime); + if (NickServ) + this->SendMessage(NickServ, _("Your nickname is now being changed to \002%s\002"), guestnick.c_str()); + IRCD->SendForceNickChange(this, guestnick, Anope::CurTime); } } else this->Kill(Config->NickServ, "Services nickname-enforcer kill"); } -/** Identify the user to the Nick - * updates last_seen, logs the user in, - * send messages, checks for mails, set vhost and more - * @param the NickAlias - */ void User::Identify(NickAlias *na) { if (!na) @@ -414,45 +395,41 @@ void User::Identify(NickAlias *na) } this->Login(na->nc); - ircdproto->SendLogin(this); + IRCD->SendLogin(this); - const NickAlias *this_na = findnick(this->nick); + const NickAlias *this_na = NickAlias::Find(this->nick); if (!Config->NoNicknameOwnership && this_na && this_na->nc == *na->nc && na->nc->HasFlag(NI_UNCONFIRMED) == false) - this->SetMode(findbot(Config->NickServ), UMODE_REGISTERED); + this->SetMode(NickServ, UMODE_REGISTERED); FOREACH_MOD(I_OnNickIdentify, OnNickIdentify(this)); if (this->IsServicesOper()) { - const BotInfo *bi = findbot(Config->OperServ); if (!this->nc->o->ot->modes.empty()) { - this->SetModes(bi, "%s", this->nc->o->ot->modes.c_str()); - if (bi != NULL) - this->SendMessage(bi, "Changing your usermodes to \002%s\002", this->nc->o->ot->modes.c_str()); + this->SetModes(OperServ, "%s", this->nc->o->ot->modes.c_str()); + if (OperServ) + this->SendMessage(OperServ, "Changing your usermodes to \002%s\002", this->nc->o->ot->modes.c_str()); UserMode *um = ModeManager::FindUserModeByName(UMODE_OPER); - if (um && !this->HasMode(UMODE_OPER) && this->nc->o->ot->modes.find(um->ModeChar) != Anope::string::npos) - ircdproto->SendOper(this); + if (um && !this->HasMode(UMODE_OPER) && this->nc->o->ot->modes.find(um->mchar) != Anope::string::npos) + IRCD->SendOper(this); } - if (ircdproto->CanSetVHost && !this->nc->o->vhost.empty()) + if (IRCD->CanSetVHost && !this->nc->o->vhost.empty()) { - if (bi != NULL) - this->SendMessage(bi, "Changing your vhost to \002%s\002", this->nc->o->vhost.c_str()); + if (OperServ) + this->SendMessage(OperServ, "Changing your vhost to \002%s\002", this->nc->o->vhost.c_str()); this->SetDisplayedHost(this->nc->o->vhost); - ircdproto->SendVhost(this, "", this->nc->o->vhost); + IRCD->SendVhost(this, "", this->nc->o->vhost); } } } -/** Login the user to a NickCore - * @param core The account the user is useing - */ void User::Login(NickCore *core) { this->Logout(); this->nc = core; - core->Users.push_back(this); + core->users.push_back(this); this->UpdateHost(); @@ -460,8 +437,6 @@ void User::Login(NickCore *core) Log(this, "account") << "is now identified as " << this->nc->display; } -/** Logout the user - */ void User::Logout() { if (!this->nc) @@ -469,30 +444,23 @@ void User::Logout() Log(this, "account") << "is no longer identified as " << this->nc->display; - std::list<User *>::iterator it = std::find(this->nc->Users.begin(), this->nc->Users.end(), this); - if (it != this->nc->Users.end()) - this->nc->Users.erase(it); + std::list<User *>::iterator it = std::find(this->nc->users.begin(), this->nc->users.end(), this); + if (it != this->nc->users.end()) + this->nc->users.erase(it); this->nc = NULL; } -/** Get the account the user is logged in using - * @reurn The account or NULL - */ NickCore *User::Account() const { return this->nc; } -/** Check if the user is identified for their nick - * @param CheckNick True to check if the user is identified to the nickname they are on too - * @return true or false - */ bool User::IsIdentified(bool CheckNick) const { if (CheckNick && this->nc) { - NickAlias *na = findnick(this->nc->display); + NickAlias *na = NickAlias::Find(this->nc->display); if (na && *na->nc == *this->nc) return true; @@ -503,26 +471,19 @@ bool User::IsIdentified(bool CheckNick) const return this->nc ? true : false; } -/** Check if the user is recognized for their nick (on the nicks access list) - * @param CheckSecure Only returns true if the user has secure off - * @return true or false - */ bool User::IsRecognized(bool CheckSecure) const { - if (CheckSecure && OnAccess) + if (CheckSecure && on_access) { - const NickAlias *na = findnick(this->nick); + const NickAlias *na = NickAlias::Find(this->nick); if (!na || na->nc->HasFlag(NI_SECURE)) return false; } - return OnAccess; + return on_access; } -/** Check if the user is a services oper - * @return true if they are an oper - */ bool User::IsServicesOper() { if (!this->nc || !this->nc->IsServicesOper()) @@ -552,10 +513,6 @@ bool User::IsServicesOper() return true; } -/** Check whether this user has access to run the given command string. - * @param cmdstr The string to check, e.g. botserv/set/private. - * @return True if this user may run the specified command, false otherwise. - */ bool User::HasCommand(const Anope::string &command) { if (this->IsServicesOper()) @@ -563,10 +520,6 @@ bool User::HasCommand(const Anope::string &command) return false; } -/** Check whether this user has access to the given special permission. - * @param privstr The priv to check for, e.g. users/auspex. - * @return True if this user has the specified priv, false otherwise. - */ bool User::HasPriv(const Anope::string &priv) { if (this->IsServicesOper()) @@ -574,17 +527,15 @@ bool User::HasPriv(const Anope::string &priv) return false; } -/** Update the last usermask stored for a user, and check to see if they are recognized - */ void User::UpdateHost() { if (this->host.empty()) return; - NickAlias *na = findnick(this->nick); - OnAccess = false; + NickAlias *na = NickAlias::Find(this->nick); + on_access = false; if (na) - OnAccess = is_on_access(this, na->nc); + on_access = na->nc->IsOnAccess(this); if (na && (this->IsIdentified(true) || this->IsRecognized())) { @@ -595,97 +546,64 @@ void User::UpdateHost() } } -/** Check if the user has a mode - * @param Name Mode name - * @return true or false - */ bool User::HasMode(UserModeName Name) const { return this->modes.HasFlag(Name); } -/** Set a mode internally on the user, the IRCd is not informed - * @param um The user mode - * @param Param The param, if there is one - */ -void User::SetModeInternal(UserMode *um, const Anope::string &Param) +void User::SetModeInternal(UserMode *um, const Anope::string ¶m) { if (!um) return; - this->modes.SetFlag(um->Name); - if (!Param.empty()) - Params.insert(std::make_pair(um->Name, Param)); + this->modes.SetFlag(um->name); + if (!param.empty()) + this->mode_params.insert(std::make_pair(um->name, param)); - FOREACH_MOD(I_OnUserModeSet, OnUserModeSet(this, um->Name)); + FOREACH_MOD(I_OnUserModeSet, OnUserModeSet(this, um->name)); } -/** Remove a mode internally on the user, the IRCd is not informed - * @param um The user mode - */ void User::RemoveModeInternal(UserMode *um) { if (!um) return; - this->modes.UnsetFlag(um->Name); - std::map<UserModeName, Anope::string>::iterator it = Params.find(um->Name); - if (it != Params.end()) - Params.erase(it); + this->modes.UnsetFlag(um->name); + std::map<UserModeName, Anope::string>::iterator it = this->mode_params.find(um->name); + if (it != this->mode_params.end()) + this->mode_params.erase(it); - FOREACH_MOD(I_OnUserModeUnset, OnUserModeUnset(this, um->Name)); + FOREACH_MOD(I_OnUserModeUnset, OnUserModeUnset(this, um->name)); } -/** Set a mode on the user - * @param bi The client setting the mode - * @param um The user mode - * @param Param Optional param for the mode - */ void User::SetMode(const BotInfo *bi, UserMode *um, const Anope::string &Param) { - if (!um || HasMode(um->Name)) + if (!um || HasMode(um->name)) return; ModeManager::StackerAdd(bi, this, um, true, Param); SetModeInternal(um, Param); } -/** Set a mode on the user - * @param bi The client setting the mode - * @param Name The mode name - * @param param Optional param for the mode - */ void User::SetMode(const BotInfo *bi, UserModeName Name, const Anope::string &Param) { SetMode(bi, ModeManager::FindUserModeByName(Name), Param); } -/** Remove a mode on the user - * @param bi The client setting the mode - * @param um The user mode - */ void User::RemoveMode(const BotInfo *bi, UserMode *um) { - if (!um || !HasMode(um->Name)) + if (!um || !HasMode(um->name)) return; ModeManager::StackerAdd(bi, this, um, false); RemoveModeInternal(um); } -/** Remove a mode from the user - * @param bi The client setting the mode - * @param Name The mode name - */ void User::RemoveMode(const BotInfo *bi, UserModeName Name) { RemoveMode(bi, ModeManager::FindUserModeByName(Name)); } -/** Set a string of modes on a user - * @param bi The client setting the mode - * @param umodes The modes - */ void User::SetModes(const BotInfo *bi, const char *umodes, ...) { char buf[BUFSIZE] = ""; @@ -720,7 +638,7 @@ void User::SetModes(const BotInfo *bi, const char *umodes, ...) if (add) { - if (um->Type == MODE_PARAM && sep.GetToken(sbuf)) + if (um->type == MODE_PARAM && sep.GetToken(sbuf)) this->SetMode(bi, um, sbuf); else this->SetMode(bi, um); @@ -766,7 +684,7 @@ void User::SetModesInternal(const char *umodes, ...) if (add) { - if (um->Type == MODE_PARAM && sep.GetToken(sbuf)) + if (um->type == MODE_PARAM && sep.GetToken(sbuf)) this->SetModeInternal(um, sbuf); else this->SetModeInternal(um); @@ -774,13 +692,13 @@ void User::SetModesInternal(const char *umodes, ...) else this->RemoveModeInternal(um); - switch (um->Name) + switch (um->name) { case UMODE_OPER: if (add) - ++opcnt; + ++OperCount; else - --opcnt; + --OperCount; break; case UMODE_CLOAK: case UMODE_VHOST: @@ -803,18 +721,12 @@ Anope::string User::GetModes() const UserMode *um = ModeManager::FindUserModeByName(static_cast<UserModeName>(i)); if (um == NULL) continue; - ret += um->ModeChar; + ret += um->mchar; } return ret; } -/** Find the channel container for Channel c that the user is on - * This is preferred over using FindUser in Channel, as there are usually more users in a channel - * than channels a user is in - * @param c The channel - * @return The channel container, or NULL - */ ChannelContainer *User::FindChannel(const Channel *c) const { for (UChannelList::const_iterator it = this->chans.begin(), it_end = this->chans.end(); it != it_end; ++it) @@ -823,9 +735,6 @@ ChannelContainer *User::FindChannel(const Channel *c) const return NULL; } -/** Check if the user is protected from kicks and negative mode changes - * @return true or false - */ bool User::IsProtected() const { if (this->HasMode(UMODE_PROTECTED) || this->HasMode(UMODE_GOD)) @@ -839,14 +748,14 @@ void User::Kill(const Anope::string &source, const Anope::string &reason) Anope::string real_source = source.empty() ? Config->ServerName : source; Anope::string real_reason = real_source + " (" + reason + ")"; - ircdproto->SendSVSKill(findbot(source), this, "%s", real_reason.c_str()); + IRCD->SendSVSKill(BotInfo::Find(source), this, "%s", real_reason.c_str()); } void User::KillInternal(const Anope::string &source, const Anope::string &reason) { Log(this, "killed") << "was killed by " << source << " (Reason: " << reason << ")"; - NickAlias *na = findnick(this->nick); + NickAlias *na = NickAlias::Find(this->nick); if (na && !na->nc->HasFlag(NI_SUSPENDED) && (this->IsRecognized() || this->IsIdentified(true))) { na->last_seen = Anope::CurTime; @@ -856,61 +765,12 @@ void User::KillInternal(const Anope::string &source, const Anope::string &reason delete this; } -User *finduser(const Anope::string &nick) -{ - if (isdigit(nick[0]) && ircdproto->RequiresID) - { - user_map::iterator it = UserListByUID.find(nick); - if (it != UserListByUID.end()) - return it->second; - } - else - { - user_map::iterator it = UserListByNick.find(nick); - if (it != UserListByNick.end()) - return it->second; - } - - return NULL; -} - -bool matches_list(Channel *c, User *user, ChannelModeName mode) -{ - if (!c || !c->HasMode(mode)) - return false; - - - std::pair<Channel::ModeList::iterator, Channel::ModeList::iterator> modes = c->GetModeList(mode); - for (; modes.first != modes.second; ++modes.first) - { - Entry e(mode, modes.first->second); - if (e.Matches(user)) - return true; - } - - return false; -} - -/*************************************************************************/ - -/* Given a user, return a mask that will most likely match any address the - * user will have from that location. For IP addresses, wildcards the - * appropriate subnet mask (e.g. 35.1.1.1 -> 35.*; 128.2.1.1 -> 128.2.*); - * for named addresses, wildcards the leftmost part of the name unless the - * name only contains two parts. If the username begins with a ~, delete - * it. - */ - -Anope::string create_mask(User *u) +Anope::string User::Mask() const { Anope::string mask; - Anope::string mident = u->GetIdent(); - Anope::string mhost = u->GetDisplayedHost(); + Anope::string mident = this->GetIdent(); + Anope::string mhost = this->GetDisplayedHost(); - /* Get us a buffer the size of the username plus hostname. The result - * will never be longer than this (and will often be shorter), thus we - * can use strcpy() and sprintf() safely. - */ if (mident[0] == '~') mask = "*" + mident + "@"; else @@ -930,6 +790,43 @@ Anope::string create_mask(User *u) else mask += mhost; } + return mask; } +bool User::BadPassword() +{ + if (!Config->BadPassLimit) + return false; + + if (Config->BadPassTimeout > 0 && this->invalid_pw_time > 0 && this->invalid_pw_time < Anope::CurTime - Config->BadPassTimeout) + this->invalid_pw_count = 0; + ++this->invalid_pw_count; + this->invalid_pw_time = Anope::CurTime; + if (this->invalid_pw_count >= Config->BadPassLimit) + { + this->Kill(Config->ServerName, "Too many invalid passwords"); + return true; + } + + return false; +} + +User* User::Find(const Anope::string &name, bool nick_only) +{ + if (!nick_only && isdigit(name[0]) && IRCD->RequiresID) + { + user_map::iterator it = UserListByUID.find(name); + if (it != UserListByUID.end()) + return it->second; + } + else + { + user_map::iterator it = UserListByNick.find(name); + if (it != UserListByNick.end()) + return it->second; + } + + return NULL; +} + diff --git a/src/win32/windows.cpp b/src/win32/windows.cpp index 785a38969..f24382f3f 100644 --- a/src/win32/windows.cpp +++ b/src/win32/windows.cpp @@ -43,7 +43,7 @@ static WSADATA wsa; void OnStartup() { if (WSAStartup(MAKEWORD(2, 0), &wsa)) - throw FatalException("Failed to initialize WinSock library"); + throw CoreException("Failed to initialize WinSock library"); } void OnShutdown() diff --git a/src/xline.cpp b/src/xline.cpp new file mode 100644 index 000000000..4ac6581a1 --- /dev/null +++ b/src/xline.cpp @@ -0,0 +1,425 @@ +/* XLine functions. + * + * (C) 2003-2012 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + * + */ + +#include "services.h" +#include "modules.h" +#include "xline.h" +#include "users.h" +#include "sockets.h" +#include "regexpr.h" +#include "config.h" +#include "commands.h" + +/* List of XLine managers we check users against in XLineManager::CheckAll */ +std::list<XLineManager *> XLineManager::XLineManagers; +Serialize::Checker<std::multimap<Anope::string, XLine *, ci::less> > XLineManager::XLinesByUID("XLine"); + +void XLine::InitRegex() +{ + if (!Config->RegexEngine.empty() && this->mask.length() >= 2 && this->mask[0] == '/' && this->mask[this->mask.length() - 1] == '/') + { + Anope::string stripped_mask = this->mask.substr(1, this->mask.length() - 2); + + ServiceReference<RegexProvider> provider("Regex", Config->RegexEngine); + if (provider) + { + try + { + this->regex = provider->Compile(stripped_mask); + } + catch (const RegexException &ex) + { + Log(LOG_DEBUG) << ex.GetReason(); + } + } + } +} + +XLine::XLine(const Anope::string &ma, const Anope::string &r, const Anope::string &uid) : Serializable("XLine"), mask(ma), by(Config->OperServ), created(0), expires(0), reason(r), id(uid) +{ + regex = NULL; + manager = NULL; + + this->InitRegex(); +} + +XLine::XLine(const Anope::string &ma, const Anope::string &b, const time_t ex, const Anope::string &r, const Anope::string &uid) : Serializable("XLine"), mask(ma), by(b), created(Anope::CurTime), expires(ex), reason(r), id(uid) +{ + regex = NULL; + manager = NULL; + + this->InitRegex(); +} + +XLine::~XLine() +{ + delete regex; +} + +Anope::string XLine::GetNick() const +{ + size_t nick_t = this->mask.find('!'); + + if (nick_t == Anope::string::npos) + return ""; + + return this->mask.substr(0, nick_t); +} + +Anope::string XLine::GetUser() const +{ + size_t user_t = this->mask.find('!'), host_t = this->mask.find('@'); + + if (host_t != Anope::string::npos) + { + if (user_t != Anope::string::npos && host_t > user_t) + return this->mask.substr(user_t + 1, host_t - user_t - 1); + else + return this->mask.substr(0, host_t); + } + else + return ""; +} + +Anope::string XLine::GetHost() const +{ + size_t host_t = this->mask.find('@'), real_t = this->mask.find('#'); + + if (host_t != Anope::string::npos) + { + if (real_t != Anope::string::npos && real_t > host_t) + return this->mask.substr(host_t + 1, real_t - host_t - 1); + else + return this->mask.substr(host_t + 1); + } + else + return ""; +} + +Anope::string XLine::GetReal() const +{ + size_t real_t = this->mask.find('#'); + + if (real_t != Anope::string::npos) + return this->mask.substr(real_t + 1); + else + return ""; +} + +Anope::string XLine::GetReason() const +{ + Anope::string r = this->reason; + if (Config->AddAkiller && !this->by.empty()) + r = "[" + this->by + "] " + r; + if (!this->id.empty()) + r += " (ID: " + this->id + ")"; + return r; +} + +bool XLine::HasNickOrReal() const +{ + bool r = this->GetNick().find_first_not_of("?*") != Anope::string::npos; + r = r || this->GetReal().find_first_not_of("?*") != Anope::string::npos; + return r; +} + +bool XLine::IsRegex() const +{ + return !this->mask.empty() && this->mask[0] == '/' && this->mask[this->mask.length() - 1] == '/'; +} + +Serialize::Data XLine::Serialize() const +{ + Serialize::Data data; + + data["mask"] << this->mask; + data["by"] << this->by; + data["created"] << this->created; + data["expires"] << this->expires; + data["reason"] << this->reason; + data["uid"] << this->id; + if (this->manager) + data["manager"] << this->manager->name; + + return data; +} + +Serializable* XLine::Unserialize(Serializable *obj, Serialize::Data &data) +{ + ServiceReference<XLineManager> xlm("XLineManager", data["manager"].astr()); + if (!xlm) + return NULL; + + XLine *xl; + if (obj) + { + xl = anope_dynamic_static_cast<XLine *>(obj); + data["mask"] >> xl->mask; + data["by"] >> xl->by; + data["reason"] >> xl->reason; + data["uid"] >> xl->id; + + if (xlm != xl->manager) + { + xl->manager->DelXLine(xl); + xlm->AddXLine(xl); + } + } + else + { + time_t expires; + data["expires"] >> expires; + xl = new XLine(data["mask"].astr(), data["by"].astr(), expires, data["reason"].astr(), data["uid"].astr()); + xlm->AddXLine(xl); + } + + data["created"] >> xl->created; + xl->manager = xlm; + + return xl; +} + +void XLineManager::RegisterXLineManager(XLineManager *xlm) +{ + XLineManagers.push_back(xlm); +} + +void XLineManager::UnregisterXLineManager(XLineManager *xlm) +{ + std::list<XLineManager *>::iterator it = std::find(XLineManagers.begin(), XLineManagers.end(), xlm); + + if (it != XLineManagers.end()) + XLineManagers.erase(it); +} + +void XLineManager::CheckAll(User *u) +{ + for (std::list<XLineManager *>::iterator it = XLineManagers.begin(), it_end = XLineManagers.end(); it != it_end; ++it) + { + XLineManager *xlm = *it; + + XLine *x = xlm->CheckAllXLines(u); + + if (x) + { + xlm->OnMatch(u, x); + break; + } + } +} + +Anope::string XLineManager::GenerateUID() +{ + Anope::string id; + int count = 0; + while (id.empty() || XLinesByUID->count(id) > 0) + { + if (++count > 10) + { + id.clear(); + Log(LOG_DEBUG) << "Unable to generate XLine UID"; + break; + } + + for (int i = 0; i < 10; ++i) + { + char c; + do + c = (rand() % 75) + 48; + while (!isupper(c) && !isdigit(c)); + id += c; + } + } + + return id; +} + +XLineManager::XLineManager(Module *creator, const Anope::string &xname, char t) : Service(creator, "XLineManager", xname), type(t), xlines("XLine") +{ +} + +XLineManager::~XLineManager() +{ + this->Clear(); +} + +const char &XLineManager::Type() +{ + return this->type; +} + +size_t XLineManager::GetCount() const +{ + return this->xlines->size(); +} + +const std::vector<XLine *> &XLineManager::GetList() const +{ + return this->xlines; +} + +void XLineManager::AddXLine(XLine *x) +{ + if (!x->id.empty()) + XLinesByUID->insert(std::make_pair(x->id, x)); + this->xlines->push_back(x); + x->manager = this; +} + +bool XLineManager::DelXLine(XLine *x) +{ + std::vector<XLine *>::iterator it = std::find(this->xlines->begin(), this->xlines->end(), x); + + if (!x->id.empty()) + { + std::multimap<Anope::string, XLine *, ci::less>::iterator it2 = XLinesByUID->find(x->id), it3 = XLinesByUID->upper_bound(x->id); + for (; it2 != XLinesByUID->end() && it2 != it3; ++it2) + if (it2->second == x) + { + XLinesByUID->erase(it2); + break; + } + } + + if (it != this->xlines->end()) + { + this->SendDel(x); + + x->Destroy(); + this->xlines->erase(it); + + return true; + } + + return false; +} + +XLine* XLineManager::GetEntry(unsigned index) +{ + if (index >= this->xlines->size()) + return NULL; + + XLine *x = this->xlines->at(index); + x->QueueUpdate(); + return x; +} + +void XLineManager::Clear() +{ + for (unsigned i = 0; i < this->xlines->size(); ++i) + { + XLine *x = this->xlines->at(i); + if (!x->id.empty()) + XLinesByUID->erase(x->id); + x->Destroy(); + } + this->xlines->clear(); +} + +bool XLineManager::CanAdd(CommandSource &source, const Anope::string &mask, time_t expires, const Anope::string &reason) +{ + for (unsigned i = this->GetCount(); i > 0; --i) + { + XLine *x = this->GetEntry(i - 1); + + if (x->mask.equals_ci(mask)) + { + if (!x->expires || x->expires >= expires) + { + if (x->reason != reason) + { + x->reason = reason; + source.Reply(_("Reason for %s updated."), x->mask.c_str()); + } + else + source.Reply(_("%s already exists."), mask.c_str()); + } + else + { + x->expires = expires; + if (x->reason != reason) + { + x->reason = reason; + source.Reply(_("Expiry and reason updated for %s."), x->mask.c_str()); + } + else + source.Reply(_("Expiry for %s updated."), x->mask.c_str()); + } + + return false; + } + else if (Anope::Match(mask, x->mask) && (!x->expires || x->expires >= expires)) + { + source.Reply(_("%s is already covered by %s."), mask.c_str(), x->mask.c_str()); + return false; + } + else if (Anope::Match(x->mask, mask) && (!expires || x->expires <= expires)) + { + source.Reply(_("Removing %s because %s covers it."), x->mask.c_str(), mask.c_str()); + this->DelXLine(x); + } + } + + return true; +} + +XLine* XLineManager::HasEntry(const Anope::string &mask) +{ + std::multimap<Anope::string, XLine *, ci::less>::iterator it = XLinesByUID->find(mask); + if (it != XLinesByUID->end()) + for (std::multimap<Anope::string, XLine *, ci::less>::iterator it2 = XLinesByUID->upper_bound(mask); it != it2; ++it) + if (it->second->manager == NULL || it->second->manager == this) + { + it->second->QueueUpdate(); + return it->second; + } + for (unsigned i = 0, end = this->xlines->size(); i < end; ++i) + { + XLine *x = this->xlines->at(i); + + if (x->mask.equals_ci(mask)) + { + x->QueueUpdate(); + return x; + } + } + + return NULL; +} + +XLine *XLineManager::CheckAllXLines(User *u) +{ + for (unsigned i = this->xlines->size(); i > 0; --i) + { + XLine *x = this->xlines->at(i - 1); + + if (x->expires && x->expires < Anope::CurTime) + { + this->OnExpire(x); + this->DelXLine(x); + continue; + } + + if (this->Check(u, x)) + { + this->OnMatch(u, x); + return x; + } + } + + return NULL; +} + +void XLineManager::OnExpire(const XLine *x) +{ +} + |