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 #include "inspircd_config.h"
25 #include "socketengine.h"
26 #include "command_parse.h"
28 #include "cull_list.h"
30 /** Returned by some functions to indicate failure.
34 /** Support for librodent -
35 * see http://www.chatspike.net/index.php?z=64
37 #define ETIREDHAMSTERS EAGAIN
39 /** Debug levels for use with InspIRCd::Log()
51 * This define is used in place of strcmp when we
52 * want to check if a char* string contains only one
53 * letter. Pretty fast, its just two compares and an
56 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
58 /** Delete a pointer, and NULL its value
60 template<typename T> inline void DELETE(T* x)
66 /** Template functions 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 inline std::string ConvToStr(const int in)
88 return ConvNumeric(in);
91 inline std::string ConvToStr(const long in)
93 return ConvNumeric(in);
96 inline std::string ConvToStr(const unsigned long in)
98 return ConvNumeric(in);
101 inline std::string ConvToStr(const char* in)
106 inline std::string ConvToStr(const bool in)
108 return (in ? "1" : "0");
111 inline std::string ConvToStr(char in)
113 return std::string(in,1);
116 template <class T> inline std::string ConvToStr(const T &in)
118 std::stringstream tmp;
119 if (!(tmp << in)) return std::string();
123 template<typename T> inline long ConvToInt(const T &in)
125 std::stringstream tmp;
126 if (!(tmp << in)) return 0;
127 return atoi(tmp.str().c_str());
130 /** Template function to convert integer to char, storing result in *res and
131 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
133 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
135 if (base < 2 || base > 16) { *res = 0; return res; }
139 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
143 if ( in < 0 && base == 10) *out++ = '-';
144 std::reverse( res, out );
149 /** This class contains various STATS counters
150 * It is used by the InspIRCd class, which internally
151 * has an instance of it.
153 class serverstats : public classbase
156 /** Number of accepted connections
158 unsigned long statsAccept;
159 /** Number of failed accepts
161 unsigned long statsRefused;
162 /** Number of unknown commands seen
164 unsigned long statsUnknown;
165 /** Number of nickname collisions handled
167 unsigned long statsCollisions;
168 /** Number of DNS queries sent out
170 unsigned long statsDns;
171 /** Number of good DNS replies received
172 * NOTE: This may not tally to the number sent out,
173 * due to timeouts and other latency issues.
175 unsigned long statsDnsGood;
176 /** Number of bad (negative) DNS replies received
177 * NOTE: This may not tally to the number sent out,
178 * due to timeouts and other latency issues.
180 unsigned long statsDnsBad;
181 /** Number of inbound connections seen
183 unsigned long statsConnects;
184 /** Total bytes of data transmitted
187 /** Total bytes of data received
190 /** Number of bound listening ports
192 unsigned long BoundPortCount;
194 /** Cpu usage at last sample
198 /** Time last sample was read
202 /** The constructor initializes all the counts to zero
205 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
206 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0),
214 /** This class implements a nonblocking log-writer.
215 * Most people writing an ircd give little thought to their disk
216 * i/o. On a congested system, disk writes can block for long
217 * periods of time (e.g. if the system is busy and/or swapping
218 * a lot). If we just use a blocking fprintf() call, this could
219 * block for undesirable amounts of time (half of a second through
220 * to whole seconds). We DO NOT want this, so we make our logfile
221 * nonblocking and hook it into the SocketEngine.
222 * NB: If the operating system does not support nonblocking file
223 * I/O (linux seems to, as does freebsd) this will default to
224 * blocking behaviour.
226 class FileLogger : public EventHandler
229 /** The creator/owner of this object
231 InspIRCd* ServerInstance;
232 /** The log file (fd is inside this somewhere,
233 * we get it out with fileno())
236 /** Buffer of pending log lines to be written
239 /** Number of write operations that have occured
243 /** The constructor takes an already opened logfile.
245 FileLogger(InspIRCd* Instance, FILE* logfile);
246 /** This returns false, logfiles are writeable.
248 virtual bool Readable();
249 /** Handle pending write events.
250 * This will flush any waiting data to disk.
251 * If any data remains after the fprintf call,
252 * another write event is scheduled to write
253 * the rest of the data when possible.
255 virtual void HandleEvent(EventType et, int errornum = 0);
256 /** Write one or more preformatted log lines.
257 * If the data cannot be written immediately,
258 * this class will insert itself into the
259 * SocketEngine, and register a write event,
260 * and when the write event occurs it will
261 * attempt again to write the data.
263 void WriteLogLine(const std::string &line);
264 /** Close the log file and cancel any events.
266 virtual void Close();
267 /** Close the log file and cancel any events.
268 * (indirectly call Close()
270 virtual ~FileLogger();
273 /** A list of failed port bindings, used for informational purposes on startup */
274 typedef std::vector<std::pair<std::string, long> > FailedPortList;
276 /** A list of ip addresses cross referenced against clone counts */
277 typedef std::map<irc::string, unsigned int> clonemap;
281 /** The main class of the irc server.
282 * This class contains instances of all the other classes
283 * in this software, with the exception of the base class,
284 * classbase. Amongst other things, it contains a ModeParser,
285 * a DNS object, a CommandParser object, and a list of active
286 * Module objects, and facilities for Module objects to
287 * interact with the core system it implements. You should
288 * NEVER attempt to instantiate a class of type InspIRCd
289 * yourself. If you do, this is equivalent to spawning a second
290 * IRC server, and could have catastrophic consequences for the
291 * program in terms of ram usage (basically, you could create
292 * an obese forkbomb built from recursively spawning irc servers!)
294 class InspIRCd : public classbase
297 /** Holds a string describing the last module error to occur
301 /** Remove a ModuleFactory pointer
302 * @param j Index number of the ModuleFactory to remove
304 void EraseFactory(int j);
306 /** Remove a Module pointer
307 * @param j Index number of the Module to remove
309 void EraseModule(int j);
311 /** Build the ISUPPORT string by triggering all modules On005Numeric events
313 void BuildISupport();
315 /** Move a given module to a specific slot in the list
316 * @param modulename The module name to relocate
317 * @param slot The slot to move the module into
319 void MoveTo(std::string modulename,int slot);
321 /** Display the startup banner
325 /** Set up the signal handlers
329 /** Daemonize the ircd and close standard input/output streams
330 * @return True if the program daemonized succesfully
334 /** Moves the given module to the last slot in the list
335 * @param modulename The module name to relocate
337 void MoveToLast(std::string modulename);
339 /** Moves the given module to the first slot in the list
340 * @param modulename The module name to relocate
342 void MoveToFirst(std::string modulename);
344 /** Moves one module to be placed after another in the list
345 * @param modulename The module name to relocate
346 * @param after The module name to place the module after
348 void MoveAfter(std::string modulename, std::string after);
350 /** Moves one module to be placed before another in the list
351 * @param modulename The module name to relocate
352 * @param after The module name to place the module before
354 void MoveBefore(std::string modulename, std::string before);
356 /** Iterate the list of InspSocket objects, removing ones which have timed out
357 * @param TIME the current time
359 void DoSocketTimeouts(time_t TIME);
361 /** Perform background user events such as PING checks
362 * @param TIME the current time
364 void DoBackgroundUserStuff(time_t TIME);
366 /** Returns true when all modules have done pre-registration checks on a user
367 * @param user The user to verify
368 * @return True if all modules have finished checking this user
370 bool AllModulesReportReady(userrec* user);
372 /** Total number of modules loaded into the ircd, minus one
376 /** Logfile pathname specified on the commandline, or empty string
378 char LogFileName[MAXBUF];
380 /** The feature names published by various modules
382 featurelist Features;
384 /** The interface names published by various modules
386 interfacelist Interfaces;
388 /** The current time, updated in the mainloop
392 /** The time that was recorded last time around the mainloop
396 /** A 64k buffer used to read client lines into
398 char ReadBuffer[65535];
400 /** Number of seconds in a minute
402 const long duration_m;
404 /** Number of seconds in an hour
406 const long duration_h;
408 /** Number of seconds in a day
410 const long duration_d;
412 /** Number of seconds in a week
414 const long duration_w;
416 /** Number of seconds in a year
418 const long duration_y;
420 /** Used when connecting clients
422 insp_sockaddr client, server;
424 /** Used when connecting clients
428 /** Nonblocking file writer
432 /** Time offset in seconds
433 * This offset is added to all calls to Time(). Use SetTimeDelta() to update
439 /** Number of unregistered users online right now.
440 * (Unregistered means before USER/NICK/dns)
442 int unregistered_count;
444 /** List of server names we've seen.
446 servernamelist servernames;
448 /** Time this ircd was booted
452 /** Mode handler, handles mode setting and removal
456 /** Command parser, handles client to server commands
458 CommandParser* Parser;
460 /** Socket engine, handles socket activity events
464 /** Stats class, holds miscellaneous stats counters
468 /** Server Config class, holds configuration file data
470 ServerConfig* Config;
472 /** Snomask manager - handles routing of snomask messages
477 /** Client list, a hash_map containing all clients, local and remote
479 user_hash* clientlist;
481 /** Channel list, a hash_map containing all channels
485 /** Local client list, a vector containing only local clients
487 std::vector<userrec*> local_users;
489 /** Oper list, a vector containing all local and remote opered users
491 std::vector<userrec*> all_opers;
493 clonemap local_clones;
495 clonemap global_clones;
497 /** DNS class, provides resolver facilities to the core and modules
501 /** Timer manager class, triggers InspTimer timer events
503 TimerManager* Timers;
505 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
507 XLineManager* XLines;
509 /** A list of Module* module classes
510 * Note that this list is always exactly 255 in size.
511 * The actual number of loaded modules is available from GetModuleCount()
515 /** A list of ModuleFactory* module factories
516 * Note that this list is always exactly 255 in size.
517 * The actual number of loaded modules is available from GetModuleCount()
521 /** The time we next call our ping timeout and reg timeout checks
525 /** Global cull list, will be processed on next iteration
527 CullList GlobalCulls;
529 /** Get the current time
530 * Because this only calls time() once every time around the mainloop,
531 * it is much faster than calling time() directly.
532 * @param delta True to use the delta as an offset, false otherwise
533 * @return The current time as an epoch value (time_t)
535 time_t Time(bool delta = false);
537 /** Set the time offset in seconds
538 * This offset is added to Time() to offset the system time by the specified
540 * @param delta The number of seconds to offset
541 * @return The old time delta
543 int SetTimeDelta(int delta);
545 void AddLocalClone(userrec* user);
547 void AddGlobalClone(userrec* user);
549 /** Number of users with a certain mode set on them
551 int ModeCount(const char mode);
553 /** Get the time offset in seconds
554 * @return The current time delta (in seconds)
558 /** Process a user whos socket has been flagged as active
559 * @param cu The user to process
560 * @return There is no actual return value, however upon exit, the user 'cu' may have been deleted
562 void ProcessUser(userrec* cu);
564 /** Get the total number of currently loaded modules
565 * @return The number of loaded modules
567 int GetModuleCount();
569 /** Find a module by name, and return a Module* to it.
570 * This is preferred over iterating the module lists yourself.
571 * @param name The module name to look up
572 * @return A pointer to the module, or NULL if the module cannot be found
574 Module* FindModule(const std::string &name);
576 /** Bind all ports specified in the configuration file.
577 * @param bail True if the function should bail back to the shell on failure
578 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
579 * @return The number of ports actually bound without error
581 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
583 /** Returns true if this server has the given port bound to the given address
584 * @param port The port number
585 * @param addr The address
586 * @return True if we have a port listening on this address
588 bool HasPort(int port, char* addr);
590 /** Binds a socket on an already open file descriptor
591 * @param sockfd A valid file descriptor of an open socket
592 * @param client A sockaddr to use as temporary storage
593 * @param server A sockaddr to use as temporary storage
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, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
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 /** Convert a user to a pseudoclient, disconnecting the real user
685 * @param user The user to convert
686 * @param message The quit message to display when exiting the user
687 * @return True if the operation succeeded
689 bool UserToPseudo(userrec* user, const std::string &message);
691 /** Convert a pseudoclient to a real user, discarding the pseudoclient
692 * @param alive A live client
693 * @param zombie A pseudoclient
694 * @param message The message to display when quitting the pseudoclient
695 * @return True if the operation succeeded
697 bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
699 /** Send a server notice to all local users
700 * @param text The text format string to send
701 * @param ... The format arguments
703 void ServerNoticeAll(char* text, ...);
705 /** Send a server message (PRIVMSG) to all local users
706 * @param text The text format string to send
707 * @param ... The format arguments
709 void ServerPrivmsgAll(char* text, ...);
711 /** Send text to all users with a specific set of modes
712 * @param modes The modes to check against, without a +, e.g. 'og'
713 * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
714 * mode characters in the first parameter causes receipt of the message, and
715 * if you specify WM_OR, all the modes must be present.
716 * @param text The text format string to send
717 * @param ... The format arguments
719 void WriteMode(const char* modes, int flags, const char* text, ...);
721 /** Return true if a channel name is valid
722 * @param chname A channel name to verify
723 * @return True if the name is valid
725 bool IsChannel(const char *chname);
727 /** Rehash the local server
728 * @param status This value is unused, and required for signal handler functions
730 static void Rehash(int status);
732 /** Causes the server to exit immediately
733 * @param The exit code to give to the operating system
734 * (See the ExitStatus enum for valid values)
736 static void Exit(int status);
738 /** Return a count of users, unknown and known connections
739 * @return The number of users
743 /** Return a count of fully registered connections only
744 * @return The number of registered users
746 int RegisteredUserCount();
748 /** Return a count of invisible (umode +i) users only
749 * @return The number of invisible users
751 int InvisibleUserCount();
753 /** Return a count of opered (umode +o) users only
754 * @return The number of opers
758 /** Return a count of unregistered (before NICK/USER) users only
759 * @return The number of unregistered (unknown) connections
761 int UnregisteredUserCount();
763 /** Return a count of channels on the network
764 * @return The number of channels
768 /** Return a count of local users on this server only
769 * @return The number of local users
771 long LocalUserCount();
773 /** Send an error notice to all local users, opered and unopered
774 * @param s The error string to send
776 void SendError(const std::string &s);
778 /** For use with Module::Prioritize().
779 * When the return value of this function is returned from
780 * Module::Prioritize(), this specifies that the module wishes
781 * to be ordered exactly BEFORE 'modulename'. For more information
782 * please see Module::Prioritize().
783 * @param modulename The module your module wants to be before in the call list
784 * @returns a priority ID which the core uses to relocate the module in the list
786 long PriorityBefore(const std::string &modulename);
788 /** For use with Module::Prioritize().
789 * When the return value of this function is returned from
790 * Module::Prioritize(), this specifies that the module wishes
791 * to be ordered exactly AFTER 'modulename'. For more information please
792 * see Module::Prioritize().
793 * @param modulename The module your module wants to be after in the call list
794 * @returns a priority ID which the core uses to relocate the module in the list
796 long PriorityAfter(const std::string &modulename);
798 /** Publish a 'feature'.
799 * There are two ways for a module to find another module it depends on.
800 * Either by name, using InspIRCd::FindModule, or by feature, using this
801 * function. A feature is an arbitary string which identifies something this
802 * module can do. For example, if your module provides SSL support, but other
803 * modules provide SSL support too, all the modules supporting SSL should
804 * publish an identical 'SSL' feature. This way, any module requiring use
805 * of SSL functions can just look up the 'SSL' feature using FindFeature,
806 * then use the module pointer they are given.
807 * @param FeatureName The case sensitive feature name to make available
808 * @param Mod a pointer to your module class
809 * @returns True on success, false if the feature is already published by
812 bool PublishFeature(const std::string &FeatureName, Module* Mod);
814 /** Publish a module to an 'interface'.
815 * Modules which implement the same interface (the same way of communicating
816 * with other modules) can publish themselves to an interface, using this
817 * method. When they do so, they become part of a list of related or
818 * compatible modules, and a third module may then query for that list
819 * and know that all modules within that list offer the same API.
820 * A prime example of this is the hashing modules, which all accept the
821 * same types of Request class. Consider this to be similar to PublishFeature,
822 * except for that multiple modules may publish the same 'feature'.
823 * @param InterfaceName The case sensitive interface name to make available
824 * @param Mod a pointer to your module class
825 * @returns True on success, false on failure (there are currently no failure
828 bool PublishInterface(const std::string &InterfaceName, Module* Mod);
830 /** Return a pair saying how many other modules are currently using the
831 * interfaces provided by module m.
832 * @param m The module to count usage for
833 * @return A pair, where the first value is the number of uses of the interface,
834 * and the second value is the interface name being used.
836 std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
838 /** Mark your module as using an interface.
839 * If you mark your module as using an interface, then that interface
840 * module may not unload until your module has unloaded first.
841 * This can be used to prevent crashes by ensuring code you depend on
842 * is always in memory while your module is active.
843 * @param InterfaceName The interface to use
845 void UseInterface(const std::string &InterfaceName);
847 /** Mark your module as finished with an interface.
848 * If you used UseInterface() above, you should use this method when
849 * your module is finished with the interface (usually in its destructor)
850 * to allow the modules which implement the given interface to be unloaded.
851 * @param InterfaceName The interface you are finished with using.
853 void DoneWithInterface(const std::string &InterfaceName);
855 /** Unpublish a 'feature'.
856 * When your module exits, it must call this method for every feature it
857 * is providing so that the feature table is cleaned up.
858 * @param FeatureName the feature to remove
860 bool UnpublishFeature(const std::string &FeatureName);
862 /** Unpublish your module from an interface
863 * When your module exits, it must call this method for every interface
864 * it is part of so that the interfaces table is cleaned up. Only when
865 * the last item is deleted from an interface does the interface get
867 * @param InterfaceName the interface to be removed from
868 * @param Mod The module to remove from the interface list
870 bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
872 /** Find a 'feature'.
873 * There are two ways for a module to find another module it depends on.
874 * Either by name, using InspIRCd::FindModule, or by feature, using the
875 * InspIRCd::PublishFeature method. A feature is an arbitary string which
876 * identifies something this module can do. For example, if your module
877 * provides SSL support, but other modules provide SSL support too, all
878 * the modules supporting SSL should publish an identical 'SSL' feature.
879 * To find a module capable of providing the feature you want, simply
880 * call this method with the feature name you are looking for.
881 * @param FeatureName The feature name you wish to obtain the module for
882 * @returns A pointer to a valid module class on success, NULL on failure.
884 Module* FindFeature(const std::string &FeatureName);
886 /** Find an 'interface'.
887 * An interface is a list of modules which all implement the same API.
888 * @param InterfaceName The Interface you wish to obtain the module
890 * @return A pointer to a deque of Module*, or NULL if the interface
893 modulelist* FindInterface(const std::string &InterfaceName);
895 /** Given a pointer to a Module, return its filename
896 * @param m The module pointer to identify
897 * @return The module name or an empty string
899 const std::string& GetModuleName(Module* m);
901 /** Return true if a nickname is valid
902 * @param n A nickname to verify
903 * @return True if the nick is valid
905 bool IsNick(const char* n);
907 /** Return true if an ident is valid
908 * @param An ident to verify
909 * @return True if the ident is valid
911 bool IsIdent(const char* n);
913 /** Find a username by their file descriptor.
914 * It is preferred to use this over directly accessing the fd_ref_table array.
915 * @param socket The file descriptor of a user
916 * @return A pointer to the user if the user exists locally on this descriptor
918 userrec* FindDescriptor(int socket);
920 /** Add a new mode to this server's mode parser
921 * @param mh The modehandler to add
922 * @param modechar The mode character this modehandler handles
923 * @return True if the mode handler was added
925 bool AddMode(ModeHandler* mh, const unsigned char modechar);
927 /** Add a new mode watcher to this server's mode parser
928 * @param mw The modewatcher to add
929 * @return True if the modewatcher was added
931 bool AddModeWatcher(ModeWatcher* mw);
933 /** Delete a mode watcher from this server's mode parser
934 * @param mw The modewatcher to delete
935 * @return True if the modewatcher was deleted
937 bool DelModeWatcher(ModeWatcher* mw);
939 /** Add a dns Resolver class to this server's active set
940 * @param r The resolver to add
941 * @param cached If this value is true, then the cache will
942 * be searched for the DNS result, immediately. If the value is
943 * false, then a request will be sent to the nameserver, and the
944 * result will not be immediately available. You should usually
945 * use the boolean value which you passed to the Resolver
946 * constructor, which Resolver will set appropriately depending
947 * on if cached results are available and haven't expired. It is
948 * however safe to force this value to false, forcing a remote DNS
949 * lookup, but not an update of the cache.
950 * @return True if the operation completed successfully. Note that
951 * if this method returns true, you should not attempt to access
952 * the resolver class you pass it after this call, as depending upon
953 * the request given, the object may be deleted!
955 bool AddResolver(Resolver* r, bool cached);
957 /** Add a command to this server's command parser
958 * @param f A command_t command handler object to add
959 * @throw ModuleException Will throw ModuleExcption if the command already exists
961 void AddCommand(command_t *f);
963 /** Send a modechange.
964 * The parameters provided are identical to that sent to the
965 * handler for class cmd_mode.
966 * @param parameters The mode parameters
967 * @param pcnt The number of items you have given in the first parameter
968 * @param user The user to send error messages to
970 void SendMode(const char **parameters, int pcnt, userrec *user);
972 /** Match two strings using pattern matching.
973 * This operates identically to the global function match(),
974 * except for that it takes std::string arguments rather than
976 * @param sliteral The literal string to match against
977 * @param spattern The pattern to match against. CIDR and globs are supported.
979 bool MatchText(const std::string &sliteral, const std::string &spattern);
981 /** Call the handler for a given command.
982 * @param commandname The command whos handler you wish to call
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 execute the command as
986 * @return True if the command handler was called successfully
988 bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
990 /** Return true if the command is a module-implemented command and the given parameters are valid for it
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 test-execute the command as
994 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
996 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
998 /** Add a gline 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 hostmask The hostmask to set the line against
1004 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1006 /** Add a qline 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 nickname The nickmask to set the line against
1012 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
1014 /** Add a zline 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 ipaddr The ip-mask to set the line against
1020 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
1022 /** Add a kline 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 hostmask The hostmask to set the line against
1028 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
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 AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1039 * @param hostmask The gline to delete
1040 * @return True if the item was removed
1042 bool DelGLine(const std::string &hostmask);
1045 * @param nickname The qline to delete
1046 * @return True if the item was removed
1048 bool DelQLine(const std::string &nickname);
1051 * @param ipaddr The zline to delete
1052 * @return True if the item was removed
1054 bool DelZLine(const std::string &ipaddr);
1057 * @param hostmask The kline to delete
1058 * @return True if the item was removed
1060 bool DelKLine(const std::string &hostmask);
1063 * @param hostmask The kline to delete
1064 * @return True if the item was removed
1066 bool DelELine(const std::string &hostmask);
1068 /** Return true if the given parameter is a valid nick!user\@host mask
1069 * @param mask A nick!user\@host masak to match against
1070 * @return True i the mask is valid
1072 bool IsValidMask(const std::string &mask);
1074 /** Rehash the local server
1076 void RehashServer();
1078 /** Return the channel whos index number matches that provided
1079 * @param The index number of the channel to fetch
1080 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1082 chanrec* GetChannelIndex(long index);
1084 /** Dump text to a user target, splitting it appropriately to fit
1085 * @param User the user to dump the text to
1086 * @param LinePrefix text to prefix each complete line with
1087 * @param TextStream the text to send to the user
1089 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1091 /** Check if the given nickmask matches too many users, send errors to the given user
1092 * @param nick A nickmask to match against
1093 * @param user A user to send error text to
1094 * @return True if the nick matches too many users
1096 bool NickMatchesEveryone(const std::string &nick, userrec* user);
1098 /** Check if the given IP mask matches too many users, send errors to the given user
1099 * @param ip An ipmask to match against
1100 * @param user A user to send error text to
1101 * @return True if the ip matches too many users
1103 bool IPMatchesEveryone(const std::string &ip, userrec* user);
1105 /** Check if the given hostmask matches too many users, send errors to the given user
1106 * @param mask A hostmask to match against
1107 * @param user A user to send error text to
1108 * @return True if the host matches too many users
1110 bool HostMatchesEveryone(const std::string &mask, userrec* user);
1112 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1113 * @param str A string containing a time in the form 1y2w3d4h6m5s
1114 * (one year, two weeks, three days, four hours, six minutes and five seconds)
1115 * @return The total number of seconds
1117 long Duration(const char* str);
1119 /** Attempt to compare an oper password to a string from the config file.
1120 * This will be passed to handling modules which will compare the data
1121 * against possible hashed equivalents in the input string.
1122 * @param data The data from the config file
1123 * @param input The data input by the oper
1124 * @param tagnum the tag number of the oper's tag in the config file
1125 * @return 0 if the strings match, 1 or -1 if they do not
1127 int OperPassCompare(const char* data,const char* input, int tagnum);
1129 /** Check if a given server is a uline.
1130 * An empty string returns true, this is by design.
1131 * @param server The server to check for uline status
1132 * @return True if the server is a uline OR the string is empty
1134 bool ULine(const char* server);
1136 /** Returns the subversion revision ID of this ircd
1137 * @return The revision ID or an empty string
1139 std::string GetRevision();
1141 /** Returns the full version string of this ircd
1142 * @return The version string
1144 std::string GetVersionString();
1146 /** Attempt to write the process id to a given file
1147 * @param filename The PID file to attempt to write to
1148 * @return This function may bail if the file cannot be written
1150 void WritePID(const std::string &filename);
1152 /** Returns text describing the last module error
1153 * @return The last error message to occur
1155 char* ModuleError();
1157 /** Load a given module file
1158 * @param filename The file to load
1159 * @return True if the module was found and loaded
1161 bool LoadModule(const char* filename);
1163 /** Unload a given module file
1164 * @param filename The file to unload
1165 * @return True if the module was unloaded
1167 bool UnloadModule(const char* filename);
1169 /** This constructor initialises all the subsystems and reads the config file.
1170 * @param argc The argument count passed to main()
1171 * @param argv The argument list passed to main()
1172 * @throw <anything> If anything is thrown from here and makes it to
1173 * you, you should probably just give up and go home. Yes, really.
1174 * It's that bad. Higher level classes should catch any non-fatal exceptions.
1176 InspIRCd(int argc, char** argv);
1178 /** Do one iteration of the mainloop
1179 * @param process_module_sockets True if module sockets are to be processed
1180 * this time around the event loop. The is the default.
1182 void DoOneIteration(bool process_module_sockets = true);
1184 /** Output a log message to the ircd.log file
1185 * The text will only be output if the current loglevel
1186 * is less than or equal to the level you provide
1187 * @param level A log level from the DebugLevel enum
1188 * @param text Format string of to write to the log
1189 * @param ... Format arguments of text to write to the log
1191 void Log(int level, const char* text, ...);
1193 /** Output a log message to the ircd.log file
1194 * The text will only be output if the current loglevel
1195 * is less than or equal to the level you provide
1196 * @param level A log level from the DebugLevel enum
1197 * @param text Text to write to the log
1199 void Log(int level, const std::string &text);
1201 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1203 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1205 /** Restart the server.
1206 * This function will not return. If an error occurs,
1207 * it will throw an instance of CoreException.
1208 * @param reason The restart reason to show to all clients
1209 * @throw CoreException An instance of CoreException indicating the error from execv().
1211 void Restart(const std::string &reason);
1213 /** Prepare the ircd for restart or shutdown.
1214 * This function unloads all modules which can be unloaded,
1215 * closes all open sockets, and closes the logfile.
1219 /** This copies the user and channel hash_maps into new hash maps.
1220 * This frees memory used by the hash_map allocator (which it neglects
1221 * to free, most of the time, using tons of ram)
1223 void RehashUsersAndChans();
1225 /** Resets the cached max bans value on all channels.
1228 void ResetMaxBans();
1230 /** Begin execution of the server.
1231 * NOTE: this function NEVER returns. Internally,
1232 * after performing some initialisation routines,
1233 * it will repeatedly call DoOneIteration in a loop.
1234 * @return The return value for this function is undefined.