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"
29 /** Returned by some functions to indicate failure.
35 #define ETIREDGERBILS EAGAIN
37 /** Debug levels for use with InspIRCd::Log()
49 * This define is used in place of strcmp when we
50 * want to check if a char* string contains only one
51 * letter. Pretty fast, its just two compares and an
54 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
56 /** Delete a pointer, and NULL its value
58 template<typename T> inline void DELETE(T* x)
64 /** Template function to convert any input type to std::string
66 template<typename T> inline std::string ConvToStr(const T &in)
68 std::stringstream tmp;
69 if (!(tmp << in)) return std::string();
73 template<typename T> inline long ConvToInt(const T &in)
75 std::stringstream tmp;
76 if (!(tmp << in)) return 0;
77 return atoi(tmp.str().c_str());
80 /** Template function to convert integer to char, storing result in *res and
81 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
83 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
85 if (base < 2 || base > 16) { *res = 0; return res; }
89 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
93 if ( in < 0 && base == 10) *out++ = '-';
94 std::reverse( res, out );
99 /** This class contains various STATS counters
100 * It is used by the InspIRCd class, which internally
101 * has an instance of it.
103 class serverstats : public classbase
106 /** Number of accepted connections
108 unsigned long statsAccept;
109 /** Number of failed accepts
111 unsigned long statsRefused;
112 /** Number of unknown commands seen
114 unsigned long statsUnknown;
115 /** Number of nickname collisions handled
117 unsigned long statsCollisions;
118 /** Number of DNS queries sent out
120 unsigned long statsDns;
121 /** Number of good DNS replies received
122 * NOTE: This may not tally to the number sent out,
123 * due to timeouts and other latency issues.
125 unsigned long statsDnsGood;
126 /** Number of bad (negative) DNS replies received
127 * NOTE: This may not tally to the number sent out,
128 * due to timeouts and other latency issues.
130 unsigned long statsDnsBad;
131 /** Number of inbound connections seen
133 unsigned long statsConnects;
134 /** Total bytes of data transmitted
137 /** Total bytes of data received
140 /** Number of bound listening ports
142 unsigned long BoundPortCount;
144 /** Cpu usage at last sample
148 /** Time last sample was read
152 /** The constructor initializes all the counts to zero
155 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
156 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0),
164 /** This class implements a nonblocking log-writer.
165 * Most people writing an ircd give little thought to their disk
166 * i/o. On a congested system, disk writes can block for long
167 * periods of time (e.g. if the system is busy and/or swapping
168 * a lot). If we just use a blocking fprintf() call, this could
169 * block for undesirable amounts of time (half of a second through
170 * to whole seconds). We DO NOT want this, so we make our logfile
171 * nonblocking and hook it into the SocketEngine.
172 * NB: If the operating system does not support nonblocking file
173 * I/O (linux seems to, as does freebsd) this will default to
174 * blocking behaviour.
176 class FileLogger : public EventHandler
179 /** The creator/owner of this object
181 InspIRCd* ServerInstance;
182 /** The log file (fd is inside this somewhere,
183 * we get it out with fileno())
186 /** Buffer of pending log lines to be written
189 /** Number of write operations that have occured
193 /** The constructor takes an already opened logfile.
195 FileLogger(InspIRCd* Instance, FILE* logfile);
196 /** This returns false, logfiles are writeable.
198 virtual bool Readable();
199 /** Handle pending write events.
200 * This will flush any waiting data to disk.
201 * If any data remains after the fprintf call,
202 * another write event is scheduled to write
203 * the rest of the data when possible.
205 virtual void HandleEvent(EventType et, int errornum = 0);
206 /** Write one or more preformatted log lines.
207 * If the data cannot be written immediately,
208 * this class will insert itself into the
209 * SocketEngine, and register a write event,
210 * and when the write event occurs it will
211 * attempt again to write the data.
213 void WriteLogLine(const std::string &line);
214 /** Close the log file and cancel any events.
216 virtual void Close();
217 /** Close the log file and cancel any events.
218 * (indirectly call Close()
220 virtual ~FileLogger();
223 /** A list of failed port bindings, used for informational purposes on startup */
224 typedef std::vector<std::pair<std::string, long> > FailedPortList;
226 /** A list of ip addresses cross referenced against clone counts */
227 typedef std::map<irc::string, unsigned int> clonemap;
231 /** The main class of the irc server.
232 * This class contains instances of all the other classes
233 * in this software, with the exception of the base class,
234 * classbase. Amongst other things, it contains a ModeParser,
235 * a DNS object, a CommandParser object, and a list of active
236 * Module objects, and facilities for Module objects to
237 * interact with the core system it implements. You should
238 * NEVER attempt to instantiate a class of type InspIRCd
239 * yourself. If you do, this is equivalent to spawning a second
240 * IRC server, and could have catastrophic consequences for the
241 * program in terms of ram usage (basically, you could create
242 * an obese forkbomb built from recursively spawning irc servers!)
244 class InspIRCd : public classbase
247 /** Holds a string describing the last module error to occur
251 /** Remove a ModuleFactory pointer
252 * @param j Index number of the ModuleFactory to remove
254 void EraseFactory(int j);
256 /** Remove a Module pointer
257 * @param j Index number of the Module to remove
259 void EraseModule(int j);
261 /** Build the ISUPPORT string by triggering all modules On005Numeric events
263 void BuildISupport();
265 /** Move a given module to a specific slot in the list
266 * @param modulename The module name to relocate
267 * @param slot The slot to move the module into
269 void MoveTo(std::string modulename,int slot);
271 /** Display the startup banner
275 /** Set up the signal handlers
279 /** Daemonize the ircd and close standard input/output streams
280 * @return True if the program daemonized succesfully
284 /** Moves the given module to the last slot in the list
285 * @param modulename The module name to relocate
287 void MoveToLast(std::string modulename);
289 /** Moves the given module to the first slot in the list
290 * @param modulename The module name to relocate
292 void MoveToFirst(std::string modulename);
294 /** Moves one module to be placed after another in the list
295 * @param modulename The module name to relocate
296 * @param after The module name to place the module after
298 void MoveAfter(std::string modulename, std::string after);
300 /** Moves one module to be placed before another in the list
301 * @param modulename The module name to relocate
302 * @param after The module name to place the module before
304 void MoveBefore(std::string modulename, std::string before);
306 /** Iterate the list of InspSocket objects, removing ones which have timed out
307 * @param TIME the current time
309 void DoSocketTimeouts(time_t TIME);
311 /** Perform background user events such as PING checks
312 * @param TIME the current time
314 void DoBackgroundUserStuff(time_t TIME);
316 /** Returns true when all modules have done pre-registration checks on a user
317 * @param user The user to verify
318 * @return True if all modules have finished checking this user
320 bool AllModulesReportReady(userrec* user);
322 /** Total number of modules loaded into the ircd, minus one
326 /** Logfile pathname specified on the commandline, or empty string
328 char LogFileName[MAXBUF];
330 /** The feature names published by various modules
332 featurelist Features;
334 /** The interface names published by various modules
336 interfacelist Interfaces;
338 /** The current time, updated in the mainloop
342 /** The time that was recorded last time around the mainloop
346 /** A 64k buffer used to read client lines into
348 char ReadBuffer[65535];
350 /** Number of seconds in a minute
352 const long duration_m;
354 /** Number of seconds in an hour
356 const long duration_h;
358 /** Number of seconds in a day
360 const long duration_d;
362 /** Number of seconds in a week
364 const long duration_w;
366 /** Number of seconds in a year
368 const long duration_y;
370 /** Used when connecting clients
372 insp_sockaddr client, server;
374 /** Used when connecting clients
378 /** Nonblocking file writer
382 /** Time offset in seconds
383 * This offset is added to all calls to Time(). Use SetTimeDelta() to update
388 /** List of server names we've seen.
390 servernamelist servernames;
392 /** Time this ircd was booted
396 /** Mode handler, handles mode setting and removal
400 /** Command parser, handles client to server commands
402 CommandParser* Parser;
404 /** Socket engine, handles socket activity events
408 /** Stats class, holds miscellaneous stats counters
412 /** Server Config class, holds configuration file data
414 ServerConfig* Config;
416 /** Snomask manager - handles routing of snomask messages
421 /** Client list, a hash_map containing all clients, local and remote
423 user_hash* clientlist;
425 /** Channel list, a hash_map containing all channels
429 /** Local client list, a vector containing only local clients
431 std::vector<userrec*> local_users;
433 /** Oper list, a vector containing all local and remote opered users
435 std::vector<userrec*> all_opers;
437 clonemap local_clones;
439 clonemap global_clones;
441 /** Whowas container, contains a map of vectors of users tracked by WHOWAS
443 irc::whowas::whowas_users whowas;
445 /** Whowas container, contains a map of time_t to users tracked by WHOWAS
447 irc::whowas::whowas_users_fifo whowas_fifo;
449 /** DNS class, provides resolver facilities to the core and modules
453 /** Timer manager class, triggers InspTimer timer events
455 TimerManager* Timers;
457 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
459 XLineManager* XLines;
461 /** A list of Module* module classes
462 * Note that this list is always exactly 255 in size.
463 * The actual number of loaded modules is available from GetModuleCount()
467 /** A list of ModuleFactory* module factories
468 * Note that this list is always exactly 255 in size.
469 * The actual number of loaded modules is available from GetModuleCount()
473 /** The time we next call our ping timeout and reg timeout checks
477 /** Get the current time
478 * Because this only calls time() once every time around the mainloop,
479 * it is much faster than calling time() directly.
480 * @param delta True to use the delta as an offset, false otherwise
481 * @return The current time as an epoch value (time_t)
483 time_t Time(bool delta = false);
485 /** Set the time offset in seconds
486 * This offset is added to Time() to offset the system time by the specified
488 * @param delta The number of seconds to offset
489 * @return The old time delta
491 int SetTimeDelta(int delta);
493 void AddLocalClone(userrec* user);
495 void AddGlobalClone(userrec* user);
497 /** Get the time offset in seconds
498 * @return The current time delta (in seconds)
502 /** Process a user whos socket has been flagged as active
503 * @param cu The user to process
504 * @return There is no actual return value, however upon exit, the user 'cu' may have been deleted
506 void ProcessUser(userrec* cu);
508 /** Get the total number of currently loaded modules
509 * @return The number of loaded modules
511 int GetModuleCount();
513 /** Find a module by name, and return a Module* to it.
514 * This is preferred over iterating the module lists yourself.
515 * @param name The module name to look up
516 * @return A pointer to the module, or NULL if the module cannot be found
518 Module* FindModule(const std::string &name);
520 /** Bind all ports specified in the configuration file.
521 * @param bail True if the function should bail back to the shell on failure
522 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
523 * @return The number of ports actually bound without error
525 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
527 /** Returns true if this server has the given port bound to the given address
528 * @param port The port number
529 * @param addr The address
530 * @return True if we have a port listening on this address
532 bool HasPort(int port, char* addr);
534 /** Binds a socket on an already open file descriptor
535 * @param sockfd A valid file descriptor of an open socket
536 * @param client A sockaddr to use as temporary storage
537 * @param server A sockaddr to use as temporary storage
538 * @param port The port number to bind to
539 * @param addr The address to bind to (IP only)
540 * @return True if the port was bound successfully
542 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
544 /** Adds a server name to the list of servers we've seen
545 * @param The servername to add
547 void AddServerName(const std::string &servername);
549 /** Finds a cached char* pointer of a server name,
550 * This is used to optimize userrec by storing only the pointer to the name
551 * @param The servername to find
552 * @return A pointer to this name, gauranteed to never become invalid
554 const char* FindServerNamePtr(const std::string &servername);
556 /** Returns true if we've seen the given server name before
557 * @param The servername to find
558 * @return True if we've seen this server name before
560 bool FindServerName(const std::string &servername);
562 /** Gets the GECOS (description) field of the given server.
563 * If the servername is not that of the local server, the name
564 * is passed to handling modules which will attempt to determine
565 * the GECOS that bleongs to the given servername.
566 * @param servername The servername to find the description of
567 * @return The description of this server, or of the local server
569 std::string GetServerDescription(const char* servername);
571 /** Write text to all opers connected to this server
572 * @param text The text format string
573 * @param ... Format args
575 void WriteOpers(const char* text, ...);
577 /** Write text to all opers connected to this server
578 * @param text The text to send
580 void WriteOpers(const std::string &text);
582 /** Find a nickname in the nick hash
583 * @param nick The nickname to find
584 * @return A pointer to the user, or NULL if the user does not exist
586 userrec* FindNick(const std::string &nick);
588 /** Find a nickname in the nick hash
589 * @param nick The nickname to find
590 * @return A pointer to the user, or NULL if the user does not exist
592 userrec* FindNick(const char* nick);
594 /** Find a channel in the channels hash
595 * @param chan The channel to find
596 * @return A pointer to the channel, or NULL if the channel does not exist
598 chanrec* FindChan(const std::string &chan);
600 /** Find a channel in the channels hash
601 * @param chan The channel to find
602 * @return A pointer to the channel, or NULL if the channel does not exist
604 chanrec* FindChan(const char* chan);
606 /** Called by the constructor to load all modules from the config file.
608 void LoadAllModules();
610 /** Check for a 'die' tag in the config file, and abort if found
611 * @return Depending on the configuration, this function may never return
615 /** Check we aren't running as root, and exit if we are
616 * @return Depending on the configuration, this function may never return
620 /** Determine the right path for, and open, the logfile
621 * @param argv The argv passed to main() initially, used to calculate program path
622 * @param argc The argc passed to main() initially, used to calculate program path
624 void OpenLog(char** argv, int argc);
628 /** Convert a user to a pseudoclient, disconnecting the real user
629 * @param user The user to convert
630 * @param message The quit message to display when exiting the user
631 * @return True if the operation succeeded
633 bool UserToPseudo(userrec* user, const std::string &message);
635 /** Convert a pseudoclient to a real user, discarding the pseudoclient
636 * @param alive A live client
637 * @param zombie A pseudoclient
638 * @param message The message to display when quitting the pseudoclient
639 * @return True if the operation succeeded
641 bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
643 /** Send a server notice to all local users
644 * @param text The text format string to send
645 * @param ... The format arguments
647 void ServerNoticeAll(char* text, ...);
649 /** Send a server message (PRIVMSG) to all local users
650 * @param text The text format string to send
651 * @param ... The format arguments
653 void ServerPrivmsgAll(char* text, ...);
655 /** Send text to all users with a specific set of modes
656 * @param modes The modes to check against, without a +, e.g. 'og'
657 * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
658 * mode characters in the first parameter causes receipt of the message, and
659 * if you specify WM_OR, all the modes must be present.
660 * @param text The text format string to send
661 * @param ... The format arguments
663 void WriteMode(const char* modes, int flags, const char* text, ...);
665 /** Return true if a channel name is valid
666 * @param chname A channel name to verify
667 * @return True if the name is valid
669 bool IsChannel(const char *chname);
671 /** Rehash the local server
672 * @param status This value is unused, and required for signal handler functions
674 static void Rehash(int status);
676 /** Causes the server to exit immediately
677 * @param The exit code to give to the operating system
678 * (See the ExitStatus enum for valid values)
680 static void Exit(int status);
682 /** Return a count of users, unknown and known connections
683 * @return The number of users
687 /** Return a count of fully registered connections only
688 * @return The number of registered users
690 int RegisteredUserCount();
692 /** Return a count of invisible (umode +i) users only
693 * @return The number of invisible users
695 int InvisibleUserCount();
697 /** Return a count of opered (umode +o) users only
698 * @return The number of opers
702 /** Return a count of unregistered (before NICK/USER) users only
703 * @return The number of unregistered (unknown) connections
705 int UnregisteredUserCount();
707 /** Return a count of channels on the network
708 * @return The number of channels
712 /** Return a count of local users on this server only
713 * @return The number of local users
715 long LocalUserCount();
717 /** Send an error notice to all local users, opered and unopered
718 * @param s The error string to send
720 void SendError(const std::string &s);
722 /** For use with Module::Prioritize().
723 * When the return value of this function is returned from
724 * Module::Prioritize(), this specifies that the module wishes
725 * to be ordered exactly BEFORE 'modulename'. For more information
726 * please see Module::Prioritize().
727 * @param modulename The module your module wants to be before in the call list
728 * @returns a priority ID which the core uses to relocate the module in the list
730 long PriorityBefore(const std::string &modulename);
732 /** For use with Module::Prioritize().
733 * When the return value of this function is returned from
734 * Module::Prioritize(), this specifies that the module wishes
735 * to be ordered exactly AFTER 'modulename'. For more information please
736 * see Module::Prioritize().
737 * @param modulename The module your module wants to be after in the call list
738 * @returns a priority ID which the core uses to relocate the module in the list
740 long PriorityAfter(const std::string &modulename);
742 /** Publish a 'feature'.
743 * There are two ways for a module to find another module it depends on.
744 * Either by name, using InspIRCd::FindModule, or by feature, using this
745 * function. A feature is an arbitary string which identifies something this
746 * module can do. For example, if your module provides SSL support, but other
747 * modules provide SSL support too, all the modules supporting SSL should
748 * publish an identical 'SSL' feature. This way, any module requiring use
749 * of SSL functions can just look up the 'SSL' feature using FindFeature,
750 * then use the module pointer they are given.
751 * @param FeatureName The case sensitive feature name to make available
752 * @param Mod a pointer to your module class
753 * @returns True on success, false if the feature is already published by
756 bool PublishFeature(const std::string &FeatureName, Module* Mod);
758 /** Publish a module to an 'interface'.
759 * Modules which implement the same interface (the same way of communicating
760 * with other modules) can publish themselves to an interface, using this
761 * method. When they do so, they become part of a list of related or
762 * compatible modules, and a third module may then query for that list
763 * and know that all modules within that list offer the same API.
764 * A prime example of this is the hashing modules, which all accept the
765 * same types of Request class. Consider this to be similar to PublishFeature,
766 * except for that multiple modules may publish the same 'feature'.
767 * @param InterfaceName The case sensitive interface name to make available
768 * @param Mod a pointer to your module class
769 * @returns True on success, false on failure (there are currently no failure
772 bool PublishInterface(const std::string &InterfaceName, Module* Mod);
774 /** Return a pair saying how many other modules are currently using the
775 * interfaces provided by module m.
776 * @param m The module to count usage for
777 * @return A pair, where the first value is the number of uses of the interface,
778 * and the second value is the interface name being used.
780 std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
782 /** Mark your module as using an interface.
783 * If you mark your module as using an interface, then that interface
784 * module may not unload until your module has unloaded first.
785 * This can be used to prevent crashes by ensuring code you depend on
786 * is always in memory while your module is active.
787 * @param InterfaceName The interface to use
789 void UseInterface(const std::string &InterfaceName);
791 /** Mark your module as finished with an interface.
792 * If you used UseInterface() above, you should use this method when
793 * your module is finished with the interface (usually in its destructor)
794 * to allow the modules which implement the given interface to be unloaded.
795 * @param InterfaceName The interface you are finished with using.
797 void DoneWithInterface(const std::string &InterfaceName);
799 /** Unpublish a 'feature'.
800 * When your module exits, it must call this method for every feature it
801 * is providing so that the feature table is cleaned up.
802 * @param FeatureName the feature to remove
804 bool UnpublishFeature(const std::string &FeatureName);
806 /** Unpublish your module from an interface
807 * When your module exits, it must call this method for every interface
808 * it is part of so that the interfaces table is cleaned up. Only when
809 * the last item is deleted from an interface does the interface get
811 * @param InterfaceName the interface to be removed from
812 * @param Mod The module to remove from the interface list
814 bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
816 /** Find a 'feature'.
817 * There are two ways for a module to find another module it depends on.
818 * Either by name, using InspIRCd::FindModule, or by feature, using the
819 * InspIRCd::PublishFeature method. A feature is an arbitary string which
820 * identifies something this module can do. For example, if your module
821 * provides SSL support, but other modules provide SSL support too, all
822 * the modules supporting SSL should publish an identical 'SSL' feature.
823 * To find a module capable of providing the feature you want, simply
824 * call this method with the feature name you are looking for.
825 * @param FeatureName The feature name you wish to obtain the module for
826 * @returns A pointer to a valid module class on success, NULL on failure.
828 Module* FindFeature(const std::string &FeatureName);
830 /** Find an 'interface'.
831 * An interface is a list of modules which all implement the same API.
832 * @param InterfaceName The Interface you wish to obtain the module
834 * @return A pointer to a deque of Module*, or NULL if the interface
837 modulelist* FindInterface(const std::string &InterfaceName);
839 /** Given a pointer to a Module, return its filename
840 * @param m The module pointer to identify
841 * @return The module name or an empty string
843 const std::string& GetModuleName(Module* m);
845 /** Return true if a nickname is valid
846 * @param n A nickname to verify
847 * @return True if the nick is valid
849 bool IsNick(const char* n);
851 /** Return true if an ident is valid
852 * @param An ident to verify
853 * @return True if the ident is valid
855 bool IsIdent(const char* n);
857 /** Find a username by their file descriptor.
858 * It is preferred to use this over directly accessing the fd_ref_table array.
859 * @param socket The file descriptor of a user
860 * @return A pointer to the user if the user exists locally on this descriptor
862 userrec* FindDescriptor(int socket);
864 /** Add a new mode to this server's mode parser
865 * @param mh The modehandler to add
866 * @param modechar The mode character this modehandler handles
867 * @return True if the mode handler was added
869 bool AddMode(ModeHandler* mh, const unsigned char modechar);
871 /** Add a new mode watcher to this server's mode parser
872 * @param mw The modewatcher to add
873 * @return True if the modewatcher was added
875 bool AddModeWatcher(ModeWatcher* mw);
877 /** Delete a mode watcher from this server's mode parser
878 * @param mw The modewatcher to delete
879 * @return True if the modewatcher was deleted
881 bool DelModeWatcher(ModeWatcher* mw);
883 /** Add a dns Resolver class to this server's active set
884 * @param r The resolver to add
885 * @return True if the resolver was added
887 bool AddResolver(Resolver* r);
889 /** Add a command to this server's command parser
890 * @param f A command_t command handler object to add
891 * @throw ModuleException Will throw ModuleExcption if the command already exists
893 void AddCommand(command_t *f);
895 /** Send a modechange.
896 * The parameters provided are identical to that sent to the
897 * handler for class cmd_mode.
898 * @param parameters The mode parameters
899 * @param pcnt The number of items you have given in the first parameter
900 * @param user The user to send error messages to
902 void SendMode(const char **parameters, int pcnt, userrec *user);
904 /** Match two strings using pattern matching.
905 * This operates identically to the global function match(),
906 * except for that it takes std::string arguments rather than
908 * @param sliteral The literal string to match against
909 * @param spattern The pattern to match against. CIDR and globs are supported.
911 bool MatchText(const std::string &sliteral, const std::string &spattern);
913 /** Call the handler for a given command.
914 * @param commandname The command whos handler you wish to call
915 * @param parameters The mode parameters
916 * @param pcnt The number of items you have given in the first parameter
917 * @param user The user to execute the command as
918 * @return True if the command handler was called successfully
920 bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
922 /** Return true if the command is a module-implemented command and the given parameters are valid for it
923 * @param parameters The mode parameters
924 * @param pcnt The number of items you have given in the first parameter
925 * @param user The user to test-execute the command as
926 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
928 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
930 /** Add a gline and apply it
931 * @param duration How long the line should last
932 * @param source Who set the line
933 * @param reason The reason for the line
934 * @param hostmask The hostmask to set the line against
936 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
938 /** Add a qline and apply it
939 * @param duration How long the line should last
940 * @param source Who set the line
941 * @param reason The reason for the line
942 * @param nickname The nickmask to set the line against
944 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
946 /** Add a zline and apply it
947 * @param duration How long the line should last
948 * @param source Who set the line
949 * @param reason The reason for the line
950 * @param ipaddr The ip-mask to set the line against
952 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
954 /** Add a kline and apply it
955 * @param duration How long the line should last
956 * @param source Who set the line
957 * @param reason The reason for the line
958 * @param hostmask The hostmask to set the line against
960 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
963 * @param duration How long the line should last
964 * @param source Who set the line
965 * @param reason The reason for the line
966 * @param hostmask The hostmask to set the line against
968 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
971 * @param hostmask The gline to delete
972 * @return True if the item was removed
974 bool DelGLine(const std::string &hostmask);
977 * @param nickname The qline to delete
978 * @return True if the item was removed
980 bool DelQLine(const std::string &nickname);
983 * @param ipaddr The zline to delete
984 * @return True if the item was removed
986 bool DelZLine(const std::string &ipaddr);
989 * @param hostmask The kline to delete
990 * @return True if the item was removed
992 bool DelKLine(const std::string &hostmask);
995 * @param hostmask The kline to delete
996 * @return True if the item was removed
998 bool DelELine(const std::string &hostmask);
1000 /** Return true if the given parameter is a valid nick!user\@host mask
1001 * @param mask A nick!user\@host masak to match against
1002 * @return True i the mask is valid
1004 bool IsValidMask(const std::string &mask);
1006 /** Rehash the local server
1008 void RehashServer();
1010 /** Return the channel whos index number matches that provided
1011 * @param The index number of the channel to fetch
1012 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1014 chanrec* GetChannelIndex(long index);
1016 /** Dump text to a user target, splitting it appropriately to fit
1017 * @param User the user to dump the text to
1018 * @param LinePrefix text to prefix each complete line with
1019 * @param TextStream the text to send to the user
1021 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1023 /** Check if the given nickmask matches too many users, send errors to the given user
1024 * @param nick A nickmask to match against
1025 * @param user A user to send error text to
1026 * @return True if the nick matches too many users
1028 bool NickMatchesEveryone(const std::string &nick, userrec* user);
1030 /** Check if the given IP mask matches too many users, send errors to the given user
1031 * @param ip An ipmask to match against
1032 * @param user A user to send error text to
1033 * @return True if the ip matches too many users
1035 bool IPMatchesEveryone(const std::string &ip, userrec* user);
1037 /** Check if the given hostmask matches too many users, send errors to the given user
1038 * @param mask A hostmask to match against
1039 * @param user A user to send error text to
1040 * @return True if the host matches too many users
1042 bool HostMatchesEveryone(const std::string &mask, userrec* user);
1044 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1045 * @param str A string containing a time in the form 1y2w3d4h6m5s
1046 * (one year, two weeks, three days, four hours, six minutes and five seconds)
1047 * @return The total number of seconds
1049 long Duration(const char* str);
1051 /** Attempt to compare an oper password to a string from the config file.
1052 * This will be passed to handling modules which will compare the data
1053 * against possible hashed equivalents in the input string.
1054 * @param data The data from the config file
1055 * @param input The data input by the oper
1056 * @param tagnum the tag number of the oper's tag in the config file
1057 * @return 0 if the strings match, 1 or -1 if they do not
1059 int OperPassCompare(const char* data,const char* input, int tagnum);
1061 /** Check if a given server is a uline.
1062 * An empty string returns true, this is by design.
1063 * @param server The server to check for uline status
1064 * @return True if the server is a uline OR the string is empty
1066 bool ULine(const char* server);
1068 /** Returns the subversion revision ID of this ircd
1069 * @return The revision ID or an empty string
1071 std::string GetRevision();
1073 /** Returns the full version string of this ircd
1074 * @return The version string
1076 std::string GetVersionString();
1078 /** Attempt to write the process id to a given file
1079 * @param filename The PID file to attempt to write to
1080 * @return This function may bail if the file cannot be written
1082 void WritePID(const std::string &filename);
1084 /** Returns text describing the last module error
1085 * @return The last error message to occur
1087 char* ModuleError();
1089 /** Load a given module file
1090 * @param filename The file to load
1091 * @return True if the module was found and loaded
1093 bool LoadModule(const char* filename);
1095 /** Unload a given module file
1096 * @param filename The file to unload
1097 * @return True if the module was unloaded
1099 bool UnloadModule(const char* filename);
1101 /** This constructor initialises all the subsystems and reads the config file.
1102 * @param argc The argument count passed to main()
1103 * @param argv The argument list passed to main()
1104 * @throw <anything> If anything is thrown from here and makes it to
1105 * you, you should probably just give up and go home. Yes, really.
1106 * It's that bad. Higher level classes should catch any non-fatal exceptions.
1108 InspIRCd(int argc, char** argv);
1110 /** Do one iteration of the mainloop
1111 * @param process_module_sockets True if module sockets are to be processed
1112 * this time around the event loop. The is the default.
1114 void DoOneIteration(bool process_module_sockets = true);
1116 /** Output a log message to the ircd.log file
1117 * The text will only be output if the current loglevel
1118 * is less than or equal to the level you provide
1119 * @param level A log level from the DebugLevel enum
1120 * @param text Format string of to write to the log
1121 * @param ... Format arguments of text to write to the log
1123 void Log(int level, const char* text, ...);
1125 /** Output a log message to the ircd.log file
1126 * The text will only be output if the current loglevel
1127 * is less than or equal to the level you provide
1128 * @param level A log level from the DebugLevel enum
1129 * @param text Text to write to the log
1131 void Log(int level, const std::string &text);
1133 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1135 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1137 /** Restart the server.
1138 * This function will not return. If an error occurs,
1139 * it will throw an instance of CoreException.
1140 * @param reason The restart reason to show to all clients
1141 * @throw CoreException An instance of CoreException indicating the error from execv().
1143 void Restart(const std::string &reason);
1145 /** Prepare the ircd for restart or shutdown.
1146 * This function unloads all modules which can be unloaded,
1147 * closes all open sockets, and closes the logfile.
1151 /** This copies the user and channel hash_maps into new hash maps.
1152 * This frees memory used by the hash_map allocator (which it neglects
1153 * to free, most of the time, using tons of ram)
1155 void RehashUsersAndChans();
1157 /** Begin execution of the server.
1158 * NOTE: this function NEVER returns. Internally,
1159 * after performing some initialisation routines,
1160 * it will repeatedly call DoOneIteration in a loop.
1161 * @return The return value for this function is undefined.