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"
30 #include "inspircd_config.h"
35 #include "socketengine.h"
36 #include "command_parse.h"
38 #include "cull_list.h"
40 /** Returned by some functions to indicate failure.
44 /** Support for librodent -
45 * see http://www.chatspike.net/index.php?z=64
47 #define ETIREDHAMSTERS EAGAIN
49 /** Debug levels for use with InspIRCd::Log()
61 * This define is used in place of strcmp when we
62 * want to check if a char* string contains only one
63 * letter. Pretty fast, its just two compares and an
66 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
68 /** Delete a pointer, and NULL its value
70 template<typename T> inline void DELETE(T* x)
76 /** Template functions to convert any input type to std::string
78 template<typename T> inline std::string ConvNumeric(const T &in)
80 if (in == 0) return "0";
85 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
92 std::reverse(res,out);
96 inline std::string ConvToStr(const int in)
98 return ConvNumeric(in);
101 inline std::string ConvToStr(const long in)
103 return ConvNumeric(in);
106 inline std::string ConvToStr(const unsigned long in)
108 return ConvNumeric(in);
111 inline std::string ConvToStr(const char* in)
116 inline std::string ConvToStr(const bool in)
118 return (in ? "1" : "0");
121 inline std::string ConvToStr(char in)
123 return std::string(in,1);
126 template <class T> inline std::string ConvToStr(const T &in)
128 std::stringstream tmp;
129 if (!(tmp << in)) return std::string();
133 template<typename T> inline long ConvToInt(const T &in)
135 std::stringstream tmp;
136 if (!(tmp << in)) return 0;
137 return atoi(tmp.str().c_str());
140 /** Template function to convert integer to char, storing result in *res and
141 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
143 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
145 if (base < 2 || base > 16) { *res = 0; return res; }
149 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
153 if ( in < 0 && base == 10) *out++ = '-';
154 std::reverse( res, out );
159 /** This class contains various STATS counters
160 * It is used by the InspIRCd class, which internally
161 * has an instance of it.
163 class serverstats : public classbase
166 /** Number of accepted connections
168 unsigned long statsAccept;
169 /** Number of failed accepts
171 unsigned long statsRefused;
172 /** Number of unknown commands seen
174 unsigned long statsUnknown;
175 /** Number of nickname collisions handled
177 unsigned long statsCollisions;
178 /** Number of DNS queries sent out
180 unsigned long statsDns;
181 /** Number of good DNS replies received
182 * NOTE: This may not tally to the number sent out,
183 * due to timeouts and other latency issues.
185 unsigned long statsDnsGood;
186 /** Number of bad (negative) DNS replies received
187 * NOTE: This may not tally to the number sent out,
188 * due to timeouts and other latency issues.
190 unsigned long statsDnsBad;
191 /** Number of inbound connections seen
193 unsigned long statsConnects;
194 /** Total bytes of data transmitted
197 /** Total bytes of data received
200 /** Cpu usage at last sample
203 /** Time last sample was read
206 /** The constructor initializes all the counts to zero
209 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
210 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
217 /** This class implements a nonblocking log-writer.
218 * Most people writing an ircd give little thought to their disk
219 * i/o. On a congested system, disk writes can block for long
220 * periods of time (e.g. if the system is busy and/or swapping
221 * a lot). If we just use a blocking fprintf() call, this could
222 * block for undesirable amounts of time (half of a second through
223 * to whole seconds). We DO NOT want this, so we make our logfile
224 * nonblocking and hook it into the SocketEngine.
225 * NB: If the operating system does not support nonblocking file
226 * I/O (linux seems to, as does freebsd) this will default to
227 * blocking behaviour.
229 class CoreExport FileLogger : public EventHandler
232 /** The creator/owner of this object
234 InspIRCd* ServerInstance;
235 /** The log file (fd is inside this somewhere,
236 * we get it out with fileno())
239 /** Buffer of pending log lines to be written
242 /** Number of write operations that have occured
246 /** The constructor takes an already opened logfile.
248 FileLogger(InspIRCd* Instance, FILE* logfile);
249 /** This returns false, logfiles are writeable.
251 virtual bool Readable();
252 /** Handle pending write events.
253 * This will flush any waiting data to disk.
254 * If any data remains after the fprintf call,
255 * another write event is scheduled to write
256 * the rest of the data when possible.
258 virtual void HandleEvent(EventType et, int errornum = 0);
259 /** Write one or more preformatted log lines.
260 * If the data cannot be written immediately,
261 * this class will insert itself into the
262 * SocketEngine, and register a write event,
263 * and when the write event occurs it will
264 * attempt again to write the data.
266 void WriteLogLine(const std::string &line);
267 /** Close the log file and cancel any events.
269 virtual void Close();
270 /** Close the log file and cancel any events.
271 * (indirectly call Close()
273 virtual ~FileLogger();
276 /** A list of failed port bindings, used for informational purposes on startup */
277 typedef std::vector<std::pair<std::string, long> > FailedPortList;
279 /** A list of ip addresses cross referenced against clone counts */
280 typedef std::map<irc::string, unsigned int> clonemap;
284 /** The main class of the irc server.
285 * This class contains instances of all the other classes
286 * in this software, with the exception of the base class,
287 * classbase. Amongst other things, it contains a ModeParser,
288 * a DNS object, a CommandParser object, and a list of active
289 * Module objects, and facilities for Module objects to
290 * interact with the core system it implements. You should
291 * NEVER attempt to instantiate a class of type InspIRCd
292 * yourself. If you do, this is equivalent to spawning a second
293 * IRC server, and could have catastrophic consequences for the
294 * program in terms of ram usage (basically, you could create
295 * an obese forkbomb built from recursively spawning irc servers!)
297 class CoreExport InspIRCd : public classbase
300 /** Holds a string describing the last module error to occur
304 /** Remove a ModuleFactory pointer
305 * @param j Index number of the ModuleFactory to remove
307 void EraseFactory(int j);
309 /** Remove a Module pointer
310 * @param j Index number of the Module to remove
312 void EraseModule(int j);
314 /** Move a given module to a specific slot in the list
315 * @param modulename The module name to relocate
316 * @param slot The slot to move the module into
318 void MoveTo(std::string modulename,int slot);
320 /** Display the startup banner
324 /** Set up the signal handlers
328 /** Daemonize the ircd and close standard input/output streams
329 * @return True if the program daemonized succesfully
333 /** Moves the given module to the last slot in the list
334 * @param modulename The module name to relocate
336 void MoveToLast(std::string modulename);
338 /** Moves the given module to the first slot in the list
339 * @param modulename The module name to relocate
341 void MoveToFirst(std::string modulename);
343 /** Moves one module to be placed after another in the list
344 * @param modulename The module name to relocate
345 * @param after The module name to place the module after
347 void MoveAfter(std::string modulename, std::string after);
349 /** Moves one module to be placed before another in the list
350 * @param modulename The module name to relocate
351 * @param after The module name to place the module before
353 void MoveBefore(std::string modulename, std::string before);
355 /** Iterate the list of InspSocket objects, removing ones which have timed out
356 * @param TIME the current time
358 void DoSocketTimeouts(time_t TIME);
360 /** Perform background user events such as PING checks
361 * @param TIME the current time
363 void DoBackgroundUserStuff(time_t TIME);
365 /** Returns true when all modules have done pre-registration checks on a user
366 * @param user The user to verify
367 * @return True if all modules have finished checking this user
369 bool AllModulesReportReady(userrec* user);
371 /** Total number of modules loaded into the ircd, minus one
375 /** Logfile pathname specified on the commandline, or empty string
377 char LogFileName[MAXBUF];
379 /** The feature names published by various modules
381 featurelist Features;
383 /** The interface names published by various modules
385 interfacelist Interfaces;
387 /** The current time, updated in the mainloop
391 /** The time that was recorded last time around the mainloop
395 /** A 64k buffer used to read client lines into
397 char ReadBuffer[65535];
399 /** Number of seconds in a minute
401 const long duration_m;
403 /** Number of seconds in an hour
405 const long duration_h;
407 /** Number of seconds in a day
409 const long duration_d;
411 /** Number of seconds in a week
413 const long duration_w;
415 /** Number of seconds in a year
417 const long duration_y;
419 /** Used when connecting clients
421 insp_sockaddr client, server;
423 /** Used when connecting clients
427 /** Nonblocking file writer
431 /** Time offset in seconds
432 * This offset is added to all calls to Time(). Use SetTimeDelta() to update
438 std::map<InspSocket*,InspSocket*> SocketCull;
440 /** Build the ISUPPORT string by triggering all modules On005Numeric events
442 void BuildISupport();
444 /** Number of unregistered users online right now.
445 * (Unregistered means before USER/NICK/dns)
447 int unregistered_count;
449 /** List of server names we've seen.
451 servernamelist servernames;
453 /** Time this ircd was booted
457 /** Config file pathname specified on the commandline or via ./configure
459 char ConfigFileName[MAXBUF];
461 /** Mode handler, handles mode setting and removal
465 /** Command parser, handles client to server commands
467 CommandParser* Parser;
469 /** Socket engine, handles socket activity events
473 /** Stats class, holds miscellaneous stats counters
477 /** Server Config class, holds configuration file data
479 ServerConfig* Config;
481 /** Snomask manager - handles routing of snomask messages
486 /** Client list, a hash_map containing all clients, local and remote
488 user_hash* clientlist;
490 /** Channel list, a hash_map containing all channels
494 /** Local client list, a vector containing only local clients
496 std::vector<userrec*> local_users;
498 /** Oper list, a vector containing all local and remote opered users
500 std::vector<userrec*> all_opers;
502 clonemap local_clones;
504 clonemap global_clones;
506 /** DNS class, provides resolver facilities to the core and modules
510 /** Timer manager class, triggers InspTimer timer events
512 TimerManager* Timers;
514 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
516 XLineManager* XLines;
518 /** A list of Module* module classes
519 * Note that this list is always exactly 255 in size.
520 * The actual number of loaded modules is available from GetModuleCount()
524 /** A list of ModuleFactory* module factories
525 * Note that this list is always exactly 255 in size.
526 * The actual number of loaded modules is available from GetModuleCount()
530 /** The time we next call our ping timeout and reg timeout checks
534 /** Global cull list, will be processed on next iteration
536 CullList GlobalCulls;
538 /** Get the current time
539 * Because this only calls time() once every time around the mainloop,
540 * it is much faster than calling time() directly.
541 * @param delta True to use the delta as an offset, false otherwise
542 * @return The current time as an epoch value (time_t)
544 time_t Time(bool delta = false);
546 /** Set the time offset in seconds
547 * This offset is added to Time() to offset the system time by the specified
549 * @param delta The number of seconds to offset
550 * @return The old time delta
552 int SetTimeDelta(int delta);
554 void AddLocalClone(userrec* user);
556 void AddGlobalClone(userrec* user);
558 /** Number of users with a certain mode set on them
560 int ModeCount(const char mode);
562 /** Get the time offset in seconds
563 * @return The current time delta (in seconds)
567 /** Process a user whos socket has been flagged as active
568 * @param cu The user to process
569 * @return There is no actual return value, however upon exit, the user 'cu' may have been deleted
571 void ProcessUser(userrec* cu);
573 /** Get the total number of currently loaded modules
574 * @return The number of loaded modules
576 int GetModuleCount();
578 /** Find a module by name, and return a Module* to it.
579 * This is preferred over iterating the module lists yourself.
580 * @param name The module name to look up
581 * @return A pointer to the module, or NULL if the module cannot be found
583 Module* FindModule(const std::string &name);
585 /** Bind all ports specified in the configuration file.
586 * @param bail True if the function should bail back to the shell on failure
587 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
588 * @return The number of ports actually bound without error
590 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
592 /** Binds a socket on an already open file descriptor
593 * @param sockfd A valid file descriptor of an open socket
594 * @param port The port number to bind to
595 * @param addr The address to bind to (IP only)
596 * @return True if the port was bound successfully
598 bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
600 /** Adds a server name to the list of servers we've seen
601 * @param The servername to add
603 void AddServerName(const std::string &servername);
605 /** Finds a cached char* pointer of a server name,
606 * This is used to optimize userrec by storing only the pointer to the name
607 * @param The servername to find
608 * @return A pointer to this name, gauranteed to never become invalid
610 const char* FindServerNamePtr(const std::string &servername);
612 /** Returns true if we've seen the given server name before
613 * @param The servername to find
614 * @return True if we've seen this server name before
616 bool FindServerName(const std::string &servername);
618 /** Gets the GECOS (description) field of the given server.
619 * If the servername is not that of the local server, the name
620 * is passed to handling modules which will attempt to determine
621 * the GECOS that bleongs to the given servername.
622 * @param servername The servername to find the description of
623 * @return The description of this server, or of the local server
625 std::string GetServerDescription(const char* servername);
627 /** Write text to all opers connected to this server
628 * @param text The text format string
629 * @param ... Format args
631 void WriteOpers(const char* text, ...);
633 /** Write text to all opers connected to this server
634 * @param text The text to send
636 void WriteOpers(const std::string &text);
638 /** Find a nickname in the nick hash
639 * @param nick The nickname to find
640 * @return A pointer to the user, or NULL if the user does not exist
642 userrec* FindNick(const std::string &nick);
644 /** Find a nickname in the nick hash
645 * @param nick The nickname to find
646 * @return A pointer to the user, or NULL if the user does not exist
648 userrec* FindNick(const char* nick);
650 /** Find a channel in the channels hash
651 * @param chan The channel to find
652 * @return A pointer to the channel, or NULL if the channel does not exist
654 chanrec* FindChan(const std::string &chan);
656 /** Find a channel in the channels hash
657 * @param chan The channel to find
658 * @return A pointer to the channel, or NULL if the channel does not exist
660 chanrec* FindChan(const char* chan);
662 /** Called by the constructor to load all modules from the config file.
664 void LoadAllModules();
666 /** Check for a 'die' tag in the config file, and abort if found
667 * @return Depending on the configuration, this function may never return
671 /** Check we aren't running as root, and exit if we are
672 * @return Depending on the configuration, this function may never return
676 /** Determine the right path for, and open, the logfile
677 * @param argv The argv passed to main() initially, used to calculate program path
678 * @param argc The argc passed to main() initially, used to calculate program path
680 void OpenLog(char** argv, int argc);
684 /** Send a server notice to all local users
685 * @param text The text format string to send
686 * @param ... The format arguments
688 void ServerNoticeAll(char* text, ...);
690 /** Send a server message (PRIVMSG) to all local users
691 * @param text The text format string to send
692 * @param ... The format arguments
694 void ServerPrivmsgAll(char* text, ...);
696 /** Send text to all users with a specific set of modes
697 * @param modes The modes to check against, without a +, e.g. 'og'
698 * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
699 * mode characters in the first parameter causes receipt of the message, and
700 * if you specify WM_OR, all the modes must be present.
701 * @param text The text format string to send
702 * @param ... The format arguments
704 void WriteMode(const char* modes, int flags, const char* text, ...);
706 /** Return true if a channel name is valid
707 * @param chname A channel name to verify
708 * @return True if the name is valid
710 bool IsChannel(const char *chname);
712 /** Rehash the local server
713 * @param status This value is unused, and required for signal handler functions
715 static void Rehash(int status);
717 /** Causes the server to exit after unloading modules and
718 * closing all open file descriptors.
720 * @param The exit code to give to the operating system
721 * (See the ExitStatus enum for valid values)
723 static void Exit(int status);
725 /** Causes the server to exit immediately with exit code 0.
726 * The status code is required for signal handlers, and ignored.
728 static void QuickExit(int status);
730 /** Return a count of users, unknown and known connections
731 * @return The number of users
735 /** Return a count of fully registered connections only
736 * @return The number of registered users
738 int RegisteredUserCount();
740 /** Return a count of invisible (umode +i) users only
741 * @return The number of invisible users
743 int InvisibleUserCount();
745 /** Return a count of opered (umode +o) users only
746 * @return The number of opers
750 /** Return a count of unregistered (before NICK/USER) users only
751 * @return The number of unregistered (unknown) connections
753 int UnregisteredUserCount();
755 /** Return a count of channels on the network
756 * @return The number of channels
760 /** Return a count of local users on this server only
761 * @return The number of local users
763 long LocalUserCount();
765 /** Send an error notice to all local users, opered and unopered
766 * @param s The error string to send
768 void SendError(const std::string &s);
770 /** For use with Module::Prioritize().
771 * When the return value of this function is returned from
772 * Module::Prioritize(), this specifies that the module wishes
773 * to be ordered exactly BEFORE 'modulename'. For more information
774 * please see Module::Prioritize().
775 * @param modulename The module your module wants to be before in the call list
776 * @returns a priority ID which the core uses to relocate the module in the list
778 long PriorityBefore(const std::string &modulename);
780 /** For use with Module::Prioritize().
781 * When the return value of this function is returned from
782 * Module::Prioritize(), this specifies that the module wishes
783 * to be ordered exactly AFTER 'modulename'. For more information please
784 * see Module::Prioritize().
785 * @param modulename The module your module wants to be after in the call list
786 * @returns a priority ID which the core uses to relocate the module in the list
788 long PriorityAfter(const std::string &modulename);
790 /** Publish a 'feature'.
791 * There are two ways for a module to find another module it depends on.
792 * Either by name, using InspIRCd::FindModule, or by feature, using this
793 * function. A feature is an arbitary string which identifies something this
794 * module can do. For example, if your module provides SSL support, but other
795 * modules provide SSL support too, all the modules supporting SSL should
796 * publish an identical 'SSL' feature. This way, any module requiring use
797 * of SSL functions can just look up the 'SSL' feature using FindFeature,
798 * then use the module pointer they are given.
799 * @param FeatureName The case sensitive feature name to make available
800 * @param Mod a pointer to your module class
801 * @returns True on success, false if the feature is already published by
804 bool PublishFeature(const std::string &FeatureName, Module* Mod);
806 /** Publish a module to an 'interface'.
807 * Modules which implement the same interface (the same way of communicating
808 * with other modules) can publish themselves to an interface, using this
809 * method. When they do so, they become part of a list of related or
810 * compatible modules, and a third module may then query for that list
811 * and know that all modules within that list offer the same API.
812 * A prime example of this is the hashing modules, which all accept the
813 * same types of Request class. Consider this to be similar to PublishFeature,
814 * except for that multiple modules may publish the same 'feature'.
815 * @param InterfaceName The case sensitive interface name to make available
816 * @param Mod a pointer to your module class
817 * @returns True on success, false on failure (there are currently no failure
820 bool PublishInterface(const std::string &InterfaceName, Module* Mod);
822 /** Return a pair saying how many other modules are currently using the
823 * interfaces provided by module m.
824 * @param m The module to count usage for
825 * @return A pair, where the first value is the number of uses of the interface,
826 * and the second value is the interface name being used.
828 std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
830 /** Mark your module as using an interface.
831 * If you mark your module as using an interface, then that interface
832 * module may not unload until your module has unloaded first.
833 * This can be used to prevent crashes by ensuring code you depend on
834 * is always in memory while your module is active.
835 * @param InterfaceName The interface to use
837 void UseInterface(const std::string &InterfaceName);
839 /** Mark your module as finished with an interface.
840 * If you used UseInterface() above, you should use this method when
841 * your module is finished with the interface (usually in its destructor)
842 * to allow the modules which implement the given interface to be unloaded.
843 * @param InterfaceName The interface you are finished with using.
845 void DoneWithInterface(const std::string &InterfaceName);
847 /** Unpublish a 'feature'.
848 * When your module exits, it must call this method for every feature it
849 * is providing so that the feature table is cleaned up.
850 * @param FeatureName the feature to remove
852 bool UnpublishFeature(const std::string &FeatureName);
854 /** Unpublish your module from an interface
855 * When your module exits, it must call this method for every interface
856 * it is part of so that the interfaces table is cleaned up. Only when
857 * the last item is deleted from an interface does the interface get
859 * @param InterfaceName the interface to be removed from
860 * @param Mod The module to remove from the interface list
862 bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
864 /** Find a 'feature'.
865 * There are two ways for a module to find another module it depends on.
866 * Either by name, using InspIRCd::FindModule, or by feature, using the
867 * InspIRCd::PublishFeature method. A feature is an arbitary string which
868 * identifies something this module can do. For example, if your module
869 * provides SSL support, but other modules provide SSL support too, all
870 * the modules supporting SSL should publish an identical 'SSL' feature.
871 * To find a module capable of providing the feature you want, simply
872 * call this method with the feature name you are looking for.
873 * @param FeatureName The feature name you wish to obtain the module for
874 * @returns A pointer to a valid module class on success, NULL on failure.
876 Module* FindFeature(const std::string &FeatureName);
878 /** Find an 'interface'.
879 * An interface is a list of modules which all implement the same API.
880 * @param InterfaceName The Interface you wish to obtain the module
882 * @return A pointer to a deque of Module*, or NULL if the interface
885 modulelist* FindInterface(const std::string &InterfaceName);
887 /** Given a pointer to a Module, return its filename
888 * @param m The module pointer to identify
889 * @return The module name or an empty string
891 const std::string& GetModuleName(Module* m);
893 /** Return true if a nickname is valid
894 * @param n A nickname to verify
895 * @return True if the nick is valid
897 bool IsNick(const char* n);
899 /** Return true if an ident is valid
900 * @param An ident to verify
901 * @return True if the ident is valid
903 bool IsIdent(const char* n);
905 /** Find a username by their file descriptor.
906 * It is preferred to use this over directly accessing the fd_ref_table array.
907 * @param socket The file descriptor of a user
908 * @return A pointer to the user if the user exists locally on this descriptor
910 userrec* FindDescriptor(int socket);
912 /** Add a new mode to this server's mode parser
913 * @param mh The modehandler to add
914 * @param modechar The mode character this modehandler handles
915 * @return True if the mode handler was added
917 bool AddMode(ModeHandler* mh, const unsigned char modechar);
919 /** Add a new mode watcher to this server's mode parser
920 * @param mw The modewatcher to add
921 * @return True if the modewatcher was added
923 bool AddModeWatcher(ModeWatcher* mw);
925 /** Delete a mode watcher from this server's mode parser
926 * @param mw The modewatcher to delete
927 * @return True if the modewatcher was deleted
929 bool DelModeWatcher(ModeWatcher* mw);
931 /** Add a dns Resolver class to this server's active set
932 * @param r The resolver to add
933 * @param cached If this value is true, then the cache will
934 * be searched for the DNS result, immediately. If the value is
935 * false, then a request will be sent to the nameserver, and the
936 * result will not be immediately available. You should usually
937 * use the boolean value which you passed to the Resolver
938 * constructor, which Resolver will set appropriately depending
939 * on if cached results are available and haven't expired. It is
940 * however safe to force this value to false, forcing a remote DNS
941 * lookup, but not an update of the cache.
942 * @return True if the operation completed successfully. Note that
943 * if this method returns true, you should not attempt to access
944 * the resolver class you pass it after this call, as depending upon
945 * the request given, the object may be deleted!
947 bool AddResolver(Resolver* r, bool cached);
949 /** Add a command to this server's command parser
950 * @param f A command_t command handler object to add
951 * @throw ModuleException Will throw ModuleExcption if the command already exists
953 void AddCommand(command_t *f);
955 /** Send a modechange.
956 * The parameters provided are identical to that sent to the
957 * handler for class cmd_mode.
958 * @param parameters The mode parameters
959 * @param pcnt The number of items you have given in the first parameter
960 * @param user The user to send error messages to
962 void SendMode(const char **parameters, int pcnt, userrec *user);
964 /** Match two strings using pattern matching.
965 * This operates identically to the global function match(),
966 * except for that it takes std::string arguments rather than
968 * @param sliteral The literal string to match against
969 * @param spattern The pattern to match against. CIDR and globs are supported.
971 bool MatchText(const std::string &sliteral, const std::string &spattern);
973 /** Call the handler for a given command.
974 * @param commandname The command whos handler you wish to call
975 * @param parameters The mode parameters
976 * @param pcnt The number of items you have given in the first parameter
977 * @param user The user to execute the command as
978 * @return True if the command handler was called successfully
980 bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
982 /** Return true if the command is a module-implemented command and the given parameters are valid for it
983 * @param parameters The mode parameters
984 * @param pcnt The number of items you have given in the first parameter
985 * @param user The user to test-execute the command as
986 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
988 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
990 /** Add a gline and apply it
991 * @param duration How long the line should last
992 * @param source Who set the line
993 * @param reason The reason for the line
994 * @param hostmask The hostmask to set the line against
996 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
998 /** Add a qline and apply it
999 * @param duration How long the line should last
1000 * @param source Who set the line
1001 * @param reason The reason for the line
1002 * @param nickname The nickmask to set the line against
1004 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
1006 /** Add a zline 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 ipaddr The ip-mask to set the line against
1012 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
1014 /** Add a kline 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 hostmask The hostmask to set the line against
1020 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
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 hostmask The hostmask to set the line against
1028 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1031 * @param hostmask The gline to delete
1032 * @return True if the item was removed
1034 bool DelGLine(const std::string &hostmask);
1037 * @param nickname The qline to delete
1038 * @return True if the item was removed
1040 bool DelQLine(const std::string &nickname);
1043 * @param ipaddr The zline to delete
1044 * @return True if the item was removed
1046 bool DelZLine(const std::string &ipaddr);
1049 * @param hostmask The kline to delete
1050 * @return True if the item was removed
1052 bool DelKLine(const std::string &hostmask);
1055 * @param hostmask The kline to delete
1056 * @return True if the item was removed
1058 bool DelELine(const std::string &hostmask);
1060 /** Return true if the given parameter is a valid nick!user\@host mask
1061 * @param mask A nick!user\@host masak to match against
1062 * @return True i the mask is valid
1064 bool IsValidMask(const std::string &mask);
1066 /** Rehash the local server
1068 void RehashServer();
1070 /** Return the channel whos index number matches that provided
1071 * @param The index number of the channel to fetch
1072 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1074 chanrec* GetChannelIndex(long index);
1076 /** Dump text to a user target, splitting it appropriately to fit
1077 * @param User the user to dump the text to
1078 * @param LinePrefix text to prefix each complete line with
1079 * @param TextStream the text to send to the user
1081 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1083 /** Check if the given nickmask matches too many users, send errors to the given user
1084 * @param nick A nickmask to match against
1085 * @param user A user to send error text to
1086 * @return True if the nick matches too many users
1088 bool NickMatchesEveryone(const std::string &nick, userrec* user);
1090 /** Check if the given IP mask matches too many users, send errors to the given user
1091 * @param ip An ipmask to match against
1092 * @param user A user to send error text to
1093 * @return True if the ip matches too many users
1095 bool IPMatchesEveryone(const std::string &ip, userrec* user);
1097 /** Check if the given hostmask matches too many users, send errors to the given user
1098 * @param mask A hostmask to match against
1099 * @param user A user to send error text to
1100 * @return True if the host matches too many users
1102 bool HostMatchesEveryone(const std::string &mask, userrec* user);
1104 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1105 * @param str A string containing a time in the form 1y2w3d4h6m5s
1106 * (one year, two weeks, three days, four hours, six minutes and five seconds)
1107 * @return The total number of seconds
1109 long Duration(const char* str);
1111 /** Attempt to compare an oper password to a string from the config file.
1112 * This will be passed to handling modules which will compare the data
1113 * against possible hashed equivalents in the input string.
1114 * @param data The data from the config file
1115 * @param input The data input by the oper
1116 * @param tagnum the tag number of the oper's tag in the config file
1117 * @return 0 if the strings match, 1 or -1 if they do not
1119 int OperPassCompare(const char* data,const char* input, int tagnum);
1121 /** Check if a given server is a uline.
1122 * An empty string returns true, this is by design.
1123 * @param server The server to check for uline status
1124 * @return True if the server is a uline OR the string is empty
1126 bool ULine(const char* server);
1128 /** Returns true if the uline is 'silent' (doesnt generate
1129 * remote connect notices etc).
1131 bool SilentULine(const char* server);
1133 /** Returns the subversion revision ID of this ircd
1134 * @return The revision ID or an empty string
1136 std::string GetRevision();
1138 /** Returns the full version string of this ircd
1139 * @return The version string
1141 std::string GetVersionString();
1143 /** Attempt to write the process id to a given file
1144 * @param filename The PID file to attempt to write to
1145 * @return This function may bail if the file cannot be written
1147 void WritePID(const std::string &filename);
1149 /** Returns text describing the last module error
1150 * @return The last error message to occur
1152 char* ModuleError();
1154 /** Load a given module file
1155 * @param filename The file to load
1156 * @return True if the module was found and loaded
1158 bool LoadModule(const char* filename);
1160 /** Unload a given module file
1161 * @param filename The file to unload
1162 * @return True if the module was unloaded
1164 bool UnloadModule(const char* filename);
1166 /** This constructor initialises all the subsystems and reads the config file.
1167 * @param argc The argument count passed to main()
1168 * @param argv The argument list passed to main()
1169 * @throw <anything> If anything is thrown from here and makes it to
1170 * you, you should probably just give up and go home. Yes, really.
1171 * It's that bad. Higher level classes should catch any non-fatal exceptions.
1173 InspIRCd(int argc, char** argv);
1175 /** Do one iteration of the mainloop
1176 * @param process_module_sockets True if module sockets are to be processed
1177 * this time around the event loop. The is the default.
1179 void DoOneIteration(bool process_module_sockets = true);
1181 /** Output a log message to the ircd.log file
1182 * The text will only be output if the current loglevel
1183 * is less than or equal to the level you provide
1184 * @param level A log level from the DebugLevel enum
1185 * @param text Format string of to write to the log
1186 * @param ... Format arguments of text to write to the log
1188 void Log(int level, const char* text, ...);
1190 /** Output a log message to the ircd.log file
1191 * The text will only be output if the current loglevel
1192 * is less than or equal to the level you provide
1193 * @param level A log level from the DebugLevel enum
1194 * @param text Text to write to the log
1196 void Log(int level, const std::string &text);
1198 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1200 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1202 /** Restart the server.
1203 * This function will not return. If an error occurs,
1204 * it will throw an instance of CoreException.
1205 * @param reason The restart reason to show to all clients
1206 * @throw CoreException An instance of CoreException indicating the error from execv().
1208 void Restart(const std::string &reason);
1210 /** Prepare the ircd for restart or shutdown.
1211 * This function unloads all modules which can be unloaded,
1212 * closes all open sockets, and closes the logfile.
1216 /** This copies the user and channel hash_maps into new hash maps.
1217 * This frees memory used by the hash_map allocator (which it neglects
1218 * to free, most of the time, using tons of ram)
1220 void RehashUsersAndChans();
1222 /** Resets the cached max bans value on all channels.
1225 void ResetMaxBans();
1227 /** Return a time_t as a human-readable string.
1229 std::string TimeString(time_t curtime);
1231 /** Begin execution of the server.
1232 * NOTE: this function NEVER returns. Internally,
1233 * after performing some initialisation routines,
1234 * it will repeatedly call DoOneIteration in a loop.
1235 * @return The return value for this function is undefined.