1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #ifndef __INSPIRCD_H__
15 #define __INSPIRCD_H__
20 #define printf_c printf
22 #include "inspircd_win32wrapper.h"
23 /** Windows defines these already */
31 #include "inspircd_config.h"
37 #include "socketengine.h"
38 #include "command_parse.h"
40 #include "cull_list.h"
41 #include "filelogger.h"
45 * Used to define the maximum number of parameters a command may have.
47 #define MAXPARAMETERS 127
49 /** Returned by some functions to indicate failure.
53 /** Support for librodent -
54 * see http://www.chatspike.net/index.php?z=64
56 #define ETIREDHAMSTERS EAGAIN
58 /** Delete a pointer, and NULL its value
60 template<typename T> inline void DELETE(T* x)
66 /** Template function to convert any input type to std::string
68 template<typename T> inline std::string ConvNumeric(const T &in)
70 if (in == 0) return "0";
75 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
82 std::reverse(res,out);
86 /** Template function to convert any input type to std::string
88 inline std::string ConvToStr(const int in)
90 return ConvNumeric(in);
93 /** Template function to convert any input type to std::string
95 inline std::string ConvToStr(const long in)
97 return ConvNumeric(in);
100 /** Template function to convert any input type to std::string
102 inline std::string ConvToStr(const unsigned long in)
104 return ConvNumeric(in);
107 /** Template function to convert any input type to std::string
109 inline std::string ConvToStr(const char* in)
114 /** Template function to convert any input type to std::string
116 inline std::string ConvToStr(const bool in)
118 return (in ? "1" : "0");
121 /** Template function to convert any input type to std::string
123 inline std::string ConvToStr(char in)
125 return std::string(in,1);
128 /** Template function to convert any input type to std::string
130 template <class T> inline std::string ConvToStr(const T &in)
132 std::stringstream tmp;
133 if (!(tmp << in)) return std::string();
137 /** Template function to convert any input type to any other type
138 * (usually an integer or numeric type)
140 template<typename T> inline long ConvToInt(const T &in)
142 std::stringstream tmp;
143 if (!(tmp << in)) return 0;
144 return atoi(tmp.str().c_str());
147 /** Template function to convert integer to char, storing result in *res and
148 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
149 * @param T input value
150 * @param V result value
151 * @param R base to convert to
153 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
155 if (base < 2 || base > 16) { *res = 0; return res; }
159 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
163 if ( in < 0 && base == 10) *out++ = '-';
164 std::reverse( res, out );
169 /** This class contains various STATS counters
170 * It is used by the InspIRCd class, which internally
171 * has an instance of it.
173 class serverstats : public classbase
176 /** Number of accepted connections
178 unsigned long statsAccept;
179 /** Number of failed accepts
181 unsigned long statsRefused;
182 /** Number of unknown commands seen
184 unsigned long statsUnknown;
185 /** Number of nickname collisions handled
187 unsigned long statsCollisions;
188 /** Number of DNS queries sent out
190 unsigned long statsDns;
191 /** Number of good DNS replies received
192 * NOTE: This may not tally to the number sent out,
193 * due to timeouts and other latency issues.
195 unsigned long statsDnsGood;
196 /** Number of bad (negative) DNS replies received
197 * NOTE: This may not tally to the number sent out,
198 * due to timeouts and other latency issues.
200 unsigned long statsDnsBad;
201 /** Number of inbound connections seen
203 unsigned long statsConnects;
204 /** Total bytes of data transmitted
207 /** Total bytes of data received
210 /** Cpu usage at last sample
213 /** Time last sample was read
216 /** The constructor initializes all the counts to zero
219 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
220 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
225 /** A list of failed port bindings, used for informational purposes on startup */
226 typedef std::vector<std::pair<std::string, long> > FailedPortList;
228 /** A list of ip addresses cross referenced against clone counts */
229 typedef std::map<irc::string, unsigned int> clonemap;
233 DEFINE_HANDLER1(ProcessUserHandler, void, userrec*);
234 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
235 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
236 DEFINE_HANDLER1(FindDescriptorHandler, userrec*, int);
237 DEFINE_HANDLER1(FloodQuitUserHandler, void, userrec*);
239 /* Forward declaration - required */
242 /** The main class of the irc server.
243 * This class contains instances of all the other classes
244 * in this software, with the exception of the base class,
245 * classbase. Amongst other things, it contains a ModeParser,
246 * a DNS object, a CommandParser object, and a list of active
247 * Module objects, and facilities for Module objects to
248 * interact with the core system it implements. You should
249 * NEVER attempt to instantiate a class of type InspIRCd
250 * yourself. If you do, this is equivalent to spawning a second
251 * IRC server, and could have catastrophic consequences for the
252 * program in terms of ram usage (basically, you could create
253 * an obese forkbomb built from recursively spawning irc servers!)
255 class CoreExport InspIRCd : public classbase
258 /** Holds the current UID. Used to generate the next one.
260 char current_uid[UUID_LENGTH];
262 /** Holds a string describing the last module error to occur
266 /** Remove a ModuleFactory pointer
267 * @param j Index number of the ModuleFactory to remove
269 void EraseFactory(int j);
271 /** Remove a Module pointer
272 * @param j Index number of the Module to remove
274 void EraseModule(int j);
276 /** Move a given module to a specific slot in the list
277 * @param modulename The module name to relocate
278 * @param slot The slot to move the module into
280 void MoveTo(std::string modulename,int slot);
282 /** Set up the signal handlers
286 /** Daemonize the ircd and close standard input/output streams
287 * @return True if the program daemonized succesfully
291 /** Moves the given module to the last slot in the list
292 * @param modulename The module name to relocate
294 void MoveToLast(std::string modulename);
296 /** Moves the given module to the first slot in the list
297 * @param modulename The module name to relocate
299 void MoveToFirst(std::string modulename);
301 /** Moves one module to be placed after another in the list
302 * @param modulename The module name to relocate
303 * @param after The module name to place the module after
305 void MoveAfter(std::string modulename, std::string after);
307 /** Moves one module to be placed before another in the list
308 * @param modulename The module name to relocate
309 * @param after The module name to place the module before
311 void MoveBefore(std::string modulename, std::string before);
313 /** Iterate the list of InspSocket objects, removing ones which have timed out
314 * @param TIME the current time
316 void DoSocketTimeouts(time_t TIME);
318 /** Perform background user events such as PING checks
319 * @param TIME the current time
321 void DoBackgroundUserStuff(time_t TIME);
323 /** Returns true when all modules have done pre-registration checks on a user
324 * @param user The user to verify
325 * @return True if all modules have finished checking this user
327 bool AllModulesReportReady(userrec* user);
329 /** Total number of modules loaded into the ircd, minus one
333 /** Logfile pathname specified on the commandline, or empty string
335 char LogFileName[MAXBUF];
337 /** The feature names published by various modules
339 featurelist Features;
341 /** The interface names published by various modules
343 interfacelist Interfaces;
345 /** Globally accessible fake user record. This is used to force mode changes etc across s2s, etc.. bit ugly, but.. better than how this was done in 1.1
349 /** The current time, updated in the mainloop
353 /** The time that was recorded last time around the mainloop
357 /** A 64k buffer used to read client lines into
359 char ReadBuffer[65535];
361 /** Used when connecting clients
363 insp_sockaddr client, server;
365 /** Used when connecting clients
369 /** Nonblocking file writer
373 /** Time offset in seconds
374 * This offset is added to all calls to Time(). Use SetTimeDelta() to update
384 /** Global cull list, will be processed on next iteration
386 CullList GlobalCulls;
391 ProcessUserHandler HandleProcessUser;
392 IsNickHandler HandleIsNick;
393 IsIdentHandler HandleIsIdent;
394 FindDescriptorHandler HandleFindDescriptor;
395 FloodQuitUserHandler HandleFloodQuitUser;
397 /** InspSocket classes pending deletion after being closed.
398 * We don't delete these immediately as this may cause a segmentation fault.
400 std::map<InspSocket*,InspSocket*> SocketCull;
402 /** Returns the next available UID for this server.
404 std::string GetUID();
406 /** Find a user in the UUID hash
407 * @param nick The nickname to find
408 * @return A pointer to the user, or NULL if the user does not exist
410 userrec *FindUUID(const std::string &);
412 /** Find a user in the UUID hash
413 * @param nick The nickname to find
414 * @return A pointer to the user, or NULL if the user does not exist
416 userrec *FindUUID(const char *);
418 /** Build the ISUPPORT string by triggering all modules On005Numeric events
420 void BuildISupport();
422 /** Number of unregistered users online right now.
423 * (Unregistered means before USER/NICK/dns)
425 int unregistered_count;
427 /** List of server names we've seen.
429 servernamelist servernames;
431 /** Time this ircd was booted
435 /** Config file pathname specified on the commandline or via ./configure
437 char ConfigFileName[MAXBUF];
439 /** Mode handler, handles mode setting and removal
443 /** Command parser, handles client to server commands
445 CommandParser* Parser;
447 /** Socket engine, handles socket activity events
451 /** Stats class, holds miscellaneous stats counters
455 /** Server Config class, holds configuration file data
457 ServerConfig* Config;
459 /** Snomask manager - handles routing of snomask messages
464 /** Client list, a hash_map containing all clients, local and remote
466 user_hash* clientlist;
468 /** Client list stored by UUID. Contains all clients, and is updated
469 * automatically by the constructor and destructor of userrec.
473 /** Channel list, a hash_map containing all channels
477 /** Local client list, a vector containing only local clients
479 std::vector<userrec*> local_users;
481 /** Oper list, a vector containing all local and remote opered users
483 std::vector<userrec*> all_opers;
485 /** Map of local ip addresses for clone counting
487 clonemap local_clones;
489 /** Map of global ip addresses for clone counting
491 clonemap global_clones;
493 /** DNS class, provides resolver facilities to the core and modules
497 /** Timer manager class, triggers InspTimer timer events
499 TimerManager* Timers;
501 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
503 XLineManager* XLines;
505 /** A list of Module* module classes
506 * Note that this list is always exactly 255 in size.
507 * The actual number of loaded modules is available from GetModuleCount()
511 /** A list of ModuleFactory* module factories
512 * Note that this list is always exactly 255 in size.
513 * The actual number of loaded modules is available from GetModuleCount()
517 /** The time we next call our ping timeout and reg timeout checks
521 /** Set to the current signal recieved
525 /** Get the current time
526 * Because this only calls time() once every time around the mainloop,
527 * it is much faster than calling time() directly.
528 * @param delta True to use the delta as an offset, false otherwise
529 * @return The current time as an epoch value (time_t)
531 time_t Time(bool delta = false);
533 /** Set the time offset in seconds
534 * This offset is added to Time() to offset the system time by the specified
536 * @param delta The number of seconds to offset
537 * @return The old time delta
539 int SetTimeDelta(int delta);
541 /** Add a user to the local clone map
542 * @param user The user to add
544 void AddLocalClone(userrec* user);
546 /** Add a user to the global clone map
547 * @param user The user to add
549 void AddGlobalClone(userrec* user);
551 /** Number of users with a certain mode set on them
553 int ModeCount(const char mode);
555 /** Get the time offset in seconds
556 * @return The current time delta (in seconds)
560 /** Process a user whos socket has been flagged as active
561 * @param cu The user to process
562 * @return There is no actual return value, however upon exit, the user 'cu' may have been
563 * marked for deletion in the global CullList.
565 caller1<void, userrec*> ProcessUser;
567 /** Get the total number of currently loaded modules
568 * @return The number of loaded modules
570 int GetModuleCount();
572 /** Find a module by name, and return a Module* to it.
573 * This is preferred over iterating the module lists yourself.
574 * @param name The module name to look up
575 * @return A pointer to the module, or NULL if the module cannot be found
577 Module* FindModule(const std::string &name);
579 /** Bind all ports specified in the configuration file.
580 * @param bail True if the function should bail back to the shell on failure
581 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
582 * @return The number of ports actually bound without error
584 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
586 /** Binds a socket on an already open file descriptor
587 * @param sockfd A valid file descriptor of an open socket
588 * @param port The port number to bind to
589 * @param addr The address to bind to (IP only)
590 * @return True if the port was bound successfully
592 bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
594 /** Adds a server name to the list of servers we've seen
595 * @param The servername to add
597 void AddServerName(const std::string &servername);
599 /** Finds a cached char* pointer of a server name,
600 * This is used to optimize userrec by storing only the pointer to the name
601 * @param The servername to find
602 * @return A pointer to this name, gauranteed to never become invalid
604 const char* FindServerNamePtr(const std::string &servername);
606 /** Returns true if we've seen the given server name before
607 * @param The servername to find
608 * @return True if we've seen this server name before
610 bool FindServerName(const std::string &servername);
612 /** Gets the GECOS (description) field of the given server.
613 * If the servername is not that of the local server, the name
614 * is passed to handling modules which will attempt to determine
615 * the GECOS that bleongs to the given servername.
616 * @param servername The servername to find the description of
617 * @return The description of this server, or of the local server
619 std::string GetServerDescription(const char* servername);
621 /** Write text to all opers connected to this server
622 * @param text The text format string
623 * @param ... Format args
625 void WriteOpers(const char* text, ...);
627 /** Write text to all opers connected to this server
628 * @param text The text to send
630 void WriteOpers(const std::string &text);
632 /** Find a user in the nick hash.
633 * If the user cant be found in the nick hash check the uuid hash
634 * @param nick The nickname to find
635 * @return A pointer to the user, or NULL if the user does not exist
637 userrec* FindNick(const std::string &nick);
639 /** Find a user in the nick hash.
640 * If the user cant be found in the nick hash check the uuid hash
641 * @param nick The nickname to find
642 * @return A pointer to the user, or NULL if the user does not exist
644 userrec* FindNick(const char* nick);
646 /** Find a user in the nick hash ONLY
648 userrec* FindNickOnly(const char* nick);
650 /** Find a user in the nick hash ONLY
652 userrec* FindNickOnly(const std::string &nick);
654 /** Find a channel in the channels hash
655 * @param chan The channel to find
656 * @return A pointer to the channel, or NULL if the channel does not exist
658 chanrec* FindChan(const std::string &chan);
660 /** Find a channel in the channels hash
661 * @param chan The channel to find
662 * @return A pointer to the channel, or NULL if the channel does not exist
664 chanrec* FindChan(const char* chan);
666 /** Called by the constructor to load all modules from the config file.
668 void LoadAllModules();
670 /** Check for a 'die' tag in the config file, and abort if found
671 * @return Depending on the configuration, this function may never return
675 /** Check we aren't running as root, and exit if we are
676 * @return Depending on the configuration, this function may never return
680 /** Determine the right path for, and open, the logfile
681 * @param argv The argv passed to main() initially, used to calculate program path
682 * @param argc The argc passed to main() initially, used to calculate program path
683 * @return True if the log could be opened, false if otherwise
685 bool OpenLog(char** argv, int argc);
687 /** Close the currently open log file
691 /** Send a server notice to all local users
692 * @param text The text format string to send
693 * @param ... The format arguments
695 void ServerNoticeAll(char* text, ...);
697 /** Send a server message (PRIVMSG) to all local users
698 * @param text The text format string to send
699 * @param ... The format arguments
701 void ServerPrivmsgAll(char* text, ...);
703 /** Send text to all users with a specific set of modes
704 * @param modes The modes to check against, without a +, e.g. 'og'
705 * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
706 * mode characters in the first parameter causes receipt of the message, and
707 * if you specify WM_OR, all the modes must be present.
708 * @param text The text format string to send
709 * @param ... The format arguments
711 void WriteMode(const char* modes, int flags, const char* text, ...);
713 /** Return true if a channel name is valid
714 * @param chname A channel name to verify
715 * @return True if the name is valid
717 bool IsChannel(const char *chname);
719 /** Rehash the local server
723 /** Handles incoming signals after being set
724 * @param signal the signal recieved
726 void SignalHandler(int signal);
728 /** Sets the signal recieved
729 * @param signal the signal recieved
731 static void SetSignal(int signal);
733 /** Causes the server to exit after unloading modules and
734 * closing all open file descriptors.
736 * @param The exit code to give to the operating system
737 * (See the ExitStatus enum for valid values)
739 void Exit(int status);
741 /** Causes the server to exit immediately with exit code 0.
742 * The status code is required for signal handlers, and ignored.
744 static void QuickExit(int status);
746 /** Return a count of users, unknown and known connections
747 * @return The number of users
751 /** Return a count of fully registered connections only
752 * @return The number of registered users
754 int RegisteredUserCount();
756 /** Return a count of invisible (umode +i) users only
757 * @return The number of invisible users
759 int InvisibleUserCount();
761 /** Return a count of opered (umode +o) users only
762 * @return The number of opers
766 /** Return a count of unregistered (before NICK/USER) users only
767 * @return The number of unregistered (unknown) connections
769 int UnregisteredUserCount();
771 /** Return a count of channels on the network
772 * @return The number of channels
776 /** Return a count of local users on this server only
777 * @return The number of local users
779 long LocalUserCount();
781 /** Send an error notice to all local users, opered and unopered
782 * @param s The error string to send
784 void SendError(const std::string &s);
786 /** For use with Module::Prioritize().
787 * When the return value of this function is returned from
788 * Module::Prioritize(), this specifies that the module wishes
789 * to be ordered exactly BEFORE 'modulename'. For more information
790 * please see Module::Prioritize().
791 * @param modulename The module your module wants to be before in the call list
792 * @returns a priority ID which the core uses to relocate the module in the list
794 long PriorityBefore(const std::string &modulename);
796 /** For use with Module::Prioritize().
797 * When the return value of this function is returned from
798 * Module::Prioritize(), this specifies that the module wishes
799 * to be ordered exactly AFTER 'modulename'. For more information please
800 * see Module::Prioritize().
801 * @param modulename The module your module wants to be after in the call list
802 * @returns a priority ID which the core uses to relocate the module in the list
804 long PriorityAfter(const std::string &modulename);
806 /** Publish a 'feature'.
807 * There are two ways for a module to find another module it depends on.
808 * Either by name, using InspIRCd::FindModule, or by feature, using this
809 * function. A feature is an arbitary string which identifies something this
810 * module can do. For example, if your module provides SSL support, but other
811 * modules provide SSL support too, all the modules supporting SSL should
812 * publish an identical 'SSL' feature. This way, any module requiring use
813 * of SSL functions can just look up the 'SSL' feature using FindFeature,
814 * then use the module pointer they are given.
815 * @param FeatureName The case sensitive feature name to make available
816 * @param Mod a pointer to your module class
817 * @returns True on success, false if the feature is already published by
820 bool PublishFeature(const std::string &FeatureName, Module* Mod);
822 /** Publish a module to an 'interface'.
823 * Modules which implement the same interface (the same way of communicating
824 * with other modules) can publish themselves to an interface, using this
825 * method. When they do so, they become part of a list of related or
826 * compatible modules, and a third module may then query for that list
827 * and know that all modules within that list offer the same API.
828 * A prime example of this is the hashing modules, which all accept the
829 * same types of Request class. Consider this to be similar to PublishFeature,
830 * except for that multiple modules may publish the same 'feature'.
831 * @param InterfaceName The case sensitive interface name to make available
832 * @param Mod a pointer to your module class
833 * @returns True on success, false on failure (there are currently no failure
836 bool PublishInterface(const std::string &InterfaceName, Module* Mod);
838 /** Return a pair saying how many other modules are currently using the
839 * interfaces provided by module m.
840 * @param m The module to count usage for
841 * @return A pair, where the first value is the number of uses of the interface,
842 * and the second value is the interface name being used.
844 std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
846 /** Mark your module as using an interface.
847 * If you mark your module as using an interface, then that interface
848 * module may not unload until your module has unloaded first.
849 * This can be used to prevent crashes by ensuring code you depend on
850 * is always in memory while your module is active.
851 * @param InterfaceName The interface to use
853 void UseInterface(const std::string &InterfaceName);
855 /** Mark your module as finished with an interface.
856 * If you used UseInterface() above, you should use this method when
857 * your module is finished with the interface (usually in its destructor)
858 * to allow the modules which implement the given interface to be unloaded.
859 * @param InterfaceName The interface you are finished with using.
861 void DoneWithInterface(const std::string &InterfaceName);
863 /** Unpublish a 'feature'.
864 * When your module exits, it must call this method for every feature it
865 * is providing so that the feature table is cleaned up.
866 * @param FeatureName the feature to remove
868 bool UnpublishFeature(const std::string &FeatureName);
870 /** Unpublish your module from an interface
871 * When your module exits, it must call this method for every interface
872 * it is part of so that the interfaces table is cleaned up. Only when
873 * the last item is deleted from an interface does the interface get
875 * @param InterfaceName the interface to be removed from
876 * @param Mod The module to remove from the interface list
878 bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
880 /** Find a 'feature'.
881 * There are two ways for a module to find another module it depends on.
882 * Either by name, using InspIRCd::FindModule, or by feature, using the
883 * InspIRCd::PublishFeature method. A feature is an arbitary string which
884 * identifies something this module can do. For example, if your module
885 * provides SSL support, but other modules provide SSL support too, all
886 * the modules supporting SSL should publish an identical 'SSL' feature.
887 * To find a module capable of providing the feature you want, simply
888 * call this method with the feature name you are looking for.
889 * @param FeatureName The feature name you wish to obtain the module for
890 * @returns A pointer to a valid module class on success, NULL on failure.
892 Module* FindFeature(const std::string &FeatureName);
894 /** Find an 'interface'.
895 * An interface is a list of modules which all implement the same API.
896 * @param InterfaceName The Interface you wish to obtain the module
898 * @return A pointer to a deque of Module*, or NULL if the interface
901 modulelist* FindInterface(const std::string &InterfaceName);
903 /** Given a pointer to a Module, return its filename
904 * @param m The module pointer to identify
905 * @return The module name or an empty string
907 const std::string& GetModuleName(Module* m);
909 /** Return true if a nickname is valid
910 * @param n A nickname to verify
911 * @return True if the nick is valid
913 caller1<bool, const char*> IsNick;
915 /** Return true if an ident is valid
916 * @param An ident to verify
917 * @return True if the ident is valid
919 caller1<bool, const char*> IsIdent;
921 /** Find a username by their file descriptor.
922 * It is preferred to use this over directly accessing the fd_ref_table array.
923 * @param socket The file descriptor of a user
924 * @return A pointer to the user if the user exists locally on this descriptor
926 caller1<userrec*, int> FindDescriptor;
928 /** Add a new mode to this server's mode parser
929 * @param mh The modehandler to add
930 * @param modechar The mode character this modehandler handles
931 * @return True if the mode handler was added
933 bool AddMode(ModeHandler* mh, const unsigned char modechar);
935 /** Add a new mode watcher to this server's mode parser
936 * @param mw The modewatcher to add
937 * @return True if the modewatcher was added
939 bool AddModeWatcher(ModeWatcher* mw);
941 /** Delete a mode watcher from this server's mode parser
942 * @param mw The modewatcher to delete
943 * @return True if the modewatcher was deleted
945 bool DelModeWatcher(ModeWatcher* mw);
947 /** Add a dns Resolver class to this server's active set
948 * @param r The resolver to add
949 * @param cached If this value is true, then the cache will
950 * be searched for the DNS result, immediately. If the value is
951 * false, then a request will be sent to the nameserver, and the
952 * result will not be immediately available. You should usually
953 * use the boolean value which you passed to the Resolver
954 * constructor, which Resolver will set appropriately depending
955 * on if cached results are available and haven't expired. It is
956 * however safe to force this value to false, forcing a remote DNS
957 * lookup, but not an update of the cache.
958 * @return True if the operation completed successfully. Note that
959 * if this method returns true, you should not attempt to access
960 * the resolver class you pass it after this call, as depending upon
961 * the request given, the object may be deleted!
963 bool AddResolver(Resolver* r, bool cached);
965 /** Add a command to this server's command parser
966 * @param f A command_t command handler object to add
967 * @throw ModuleException Will throw ModuleExcption if the command already exists
969 void AddCommand(command_t *f);
971 /** Send a modechange.
972 * The parameters provided are identical to that sent to the
973 * handler for class cmd_mode.
974 * @param parameters The mode parameters
975 * @param pcnt The number of items you have given in the first parameter
976 * @param user The user to send error messages to
978 void SendMode(const char **parameters, int pcnt, userrec *user);
980 /** Match two strings using pattern matching.
981 * This operates identically to the global function match(),
982 * except for that it takes std::string arguments rather than
984 * @param sliteral The literal string to match against
985 * @param spattern The pattern to match against. CIDR and globs are supported.
987 bool MatchText(const std::string &sliteral, const std::string &spattern);
989 /** Call the handler for a given command.
990 * @param commandname The command whos handler you wish to call
991 * @param parameters The mode parameters
992 * @param pcnt The number of items you have given in the first parameter
993 * @param user The user to execute the command as
994 * @return True if the command handler was called successfully
996 CmdResult CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
998 /** Return true if the command is a module-implemented command and the given parameters are valid for it
999 * @param parameters The mode parameters
1000 * @param pcnt The number of items you have given in the first parameter
1001 * @param user The user to test-execute the command as
1002 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
1004 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
1006 /** Add a gline and apply it
1007 * @param duration How long the line should last
1008 * @param source Who set the line
1009 * @param reason The reason for the line
1010 * @param hostmask The hostmask to set the line against
1012 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1014 /** Add a qline and apply it
1015 * @param duration How long the line should last
1016 * @param source Who set the line
1017 * @param reason The reason for the line
1018 * @param nickname The nickmask to set the line against
1020 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
1022 /** Add a zline and apply it
1023 * @param duration How long the line should last
1024 * @param source Who set the line
1025 * @param reason The reason for the line
1026 * @param ipaddr The ip-mask to set the line against
1028 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
1030 /** Add a kline and apply it
1031 * @param duration How long the line should last
1032 * @param source Who set the line
1033 * @param reason The reason for the line
1034 * @param hostmask The hostmask to set the line against
1036 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1039 * @param duration How long the line should last
1040 * @param source Who set the line
1041 * @param reason The reason for the line
1042 * @param hostmask The hostmask to set the line against
1044 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1047 * @param hostmask The gline to delete
1048 * @return True if the item was removed
1050 bool DelGLine(const std::string &hostmask);
1053 * @param nickname The qline to delete
1054 * @return True if the item was removed
1056 bool DelQLine(const std::string &nickname);
1059 * @param ipaddr The zline to delete
1060 * @return True if the item was removed
1062 bool DelZLine(const std::string &ipaddr);
1065 * @param hostmask The kline to delete
1066 * @return True if the item was removed
1068 bool DelKLine(const std::string &hostmask);
1071 * @param hostmask The kline to delete
1072 * @return True if the item was removed
1074 bool DelELine(const std::string &hostmask);
1076 /** Return true if the given parameter is a valid nick!user\@host mask
1077 * @param mask A nick!user\@host masak to match against
1078 * @return True i the mask is valid
1080 bool IsValidMask(const std::string &mask);
1082 /** Rehash the local server
1084 void RehashServer();
1086 /** Return the channel whos index number matches that provided
1087 * @param The index number of the channel to fetch
1088 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1090 chanrec* GetChannelIndex(long index);
1092 /** Dump text to a user target, splitting it appropriately to fit
1093 * @param User the user to dump the text to
1094 * @param LinePrefix text to prefix each complete line with
1095 * @param TextStream the text to send to the user
1097 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1099 /** Check if the given nickmask matches too many users, send errors to the given user
1100 * @param nick A nickmask to match against
1101 * @param user A user to send error text to
1102 * @return True if the nick matches too many users
1104 bool NickMatchesEveryone(const std::string &nick, userrec* user);
1106 /** Check if the given IP mask matches too many users, send errors to the given user
1107 * @param ip An ipmask to match against
1108 * @param user A user to send error text to
1109 * @return True if the ip matches too many users
1111 bool IPMatchesEveryone(const std::string &ip, userrec* user);
1113 /** Check if the given hostmask matches too many users, send errors to the given user
1114 * @param mask A hostmask to match against
1115 * @param user A user to send error text to
1116 * @return True if the host matches too many users
1118 bool HostMatchesEveryone(const std::string &mask, userrec* user);
1120 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1121 * @param str A string containing a time in the form 1y2w3d4h6m5s
1122 * (one year, two weeks, three days, four hours, six minutes and five seconds)
1123 * @return The total number of seconds
1125 long Duration(const std::string &str);
1127 /** Attempt to compare an oper password to a string from the config file.
1128 * This will be passed to handling modules which will compare the data
1129 * against possible hashed equivalents in the input string.
1130 * @param data The data from the config file
1131 * @param input The data input by the oper
1132 * @param tagnum the tag number of the oper's tag in the config file
1133 * @return 0 if the strings match, 1 or -1 if they do not
1135 int OperPassCompare(const char* data,const char* input, int tagnum);
1137 /** Check if a given server is a uline.
1138 * An empty string returns true, this is by design.
1139 * @param server The server to check for uline status
1140 * @return True if the server is a uline OR the string is empty
1142 bool ULine(const char* server);
1144 /** Returns true if the uline is 'silent' (doesnt generate
1145 * remote connect notices etc).
1147 bool SilentULine(const char* server);
1149 /** Returns the subversion revision ID of this ircd
1150 * @return The revision ID or an empty string
1152 std::string GetRevision();
1154 /** Returns the full version string of this ircd
1155 * @return The version string
1157 std::string GetVersionString();
1159 /** Attempt to write the process id to a given file
1160 * @param filename The PID file to attempt to write to
1161 * @return This function may bail if the file cannot be written
1163 void WritePID(const std::string &filename);
1165 /** Returns text describing the last module error
1166 * @return The last error message to occur
1168 char* ModuleError();
1170 /** Load a given module file
1171 * @param filename The file to load
1172 * @return True if the module was found and loaded
1174 bool LoadModule(const char* filename);
1176 /** Unload a given module file
1177 * @param filename The file to unload
1178 * @return True if the module was unloaded
1180 bool UnloadModule(const char* filename);
1182 /** This constructor initialises all the subsystems and reads the config file.
1183 * @param argc The argument count passed to main()
1184 * @param argv The argument list passed to main()
1185 * @throw <anything> If anything is thrown from here and makes it to
1186 * you, you should probably just give up and go home. Yes, really.
1187 * It's that bad. Higher level classes should catch any non-fatal exceptions.
1189 InspIRCd(int argc, char** argv);
1191 /** Do one iteration of the mainloop
1192 * @param process_module_sockets True if module sockets are to be processed
1193 * this time around the event loop. The is the default.
1195 void DoOneIteration(bool process_module_sockets = true);
1197 /** Output a log message to the ircd.log file
1198 * The text will only be output if the current loglevel
1199 * is less than or equal to the level you provide
1200 * @param level A log level from the DebugLevel enum
1201 * @param text Format string of to write to the log
1202 * @param ... Format arguments of text to write to the log
1204 void Log(int level, const char* text, ...);
1206 /** Output a log message to the ircd.log file
1207 * The text will only be output if the current loglevel
1208 * is less than or equal to the level you provide
1209 * @param level A log level from the DebugLevel enum
1210 * @param text Text to write to the log
1212 void Log(int level, const std::string &text);
1214 /** Send a line of WHOIS data to a user.
1215 * @param user user to send the line to
1216 * @param dest user being WHOISed
1217 * @param numeric Numeric to send
1218 * @param text Text of the numeric
1220 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1222 /** Send a line of WHOIS data to a user.
1223 * @param user user to send the line to
1224 * @param dest user being WHOISed
1225 * @param numeric Numeric to send
1226 * @param format Format string for the numeric
1227 * @param ... Parameters for the format string
1229 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1231 /** Quit a user for excess flood, and if they are not
1232 * fully registered yet, temporarily zline their IP.
1233 * @param current user to quit
1235 caller1<void, userrec*> FloodQuitUser;
1237 /** Restart the server.
1238 * This function will not return. If an error occurs,
1239 * it will throw an instance of CoreException.
1240 * @param reason The restart reason to show to all clients
1241 * @throw CoreException An instance of CoreException indicating the error from execv().
1243 void Restart(const std::string &reason);
1245 /** Prepare the ircd for restart or shutdown.
1246 * This function unloads all modules which can be unloaded,
1247 * closes all open sockets, and closes the logfile.
1251 /** This copies the user and channel hash_maps into new hash maps.
1252 * This frees memory used by the hash_map allocator (which it neglects
1253 * to free, most of the time, using tons of ram)
1255 void RehashUsersAndChans();
1257 /** Resets the cached max bans value on all channels.
1260 void ResetMaxBans();
1262 /** Return a time_t as a human-readable string.
1264 std::string TimeString(time_t curtime);
1266 /** Begin execution of the server.
1267 * NOTE: this function NEVER returns. Internally,
1268 * after performing some initialisation routines,
1269 * it will repeatedly call DoOneIteration in a loop.
1270 * @return The return value for this function is undefined.
1274 /** Force all InspSockets to be removed which are due to
1277 void InspSocketCull();
1279 char* GetReadBuffer()
1281 return this->ReadBuffer;