1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #ifndef __INSPIRCD_H__
15 #define __INSPIRCD_H__
20 #define printf_c printf
22 #include "inspircd_win32wrapper.h"
23 /** Windows defines these already */
31 #include "inspircd_config.h"
36 #include "socketengine.h"
37 #include "command_parse.h"
39 #include "cull_list.h"
40 #include "filelogger.h"
44 * Used to define the maximum number of parameters a command may have.
46 #define MAXPARAMETERS 127
48 /** Returned by some functions to indicate failure.
52 /** Support for librodent -
53 * see http://www.chatspike.net/index.php?z=64
55 #define ETIREDHAMSTERS EAGAIN
58 * This define is used in place of strcmp when we
59 * want to check if a char* string contains only one
60 * letter. Pretty fast, its just two compares and an
63 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
67 /** Delete a pointer, and NULL its value
69 template<typename T> inline void DELETE(T* x)
75 /** Template function to convert any input type to std::string
77 template<typename T> inline std::string ConvNumeric(const T &in)
79 if (in == 0) return "0";
84 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
91 std::reverse(res,out);
95 /** Template function to convert any input type to std::string
97 inline std::string ConvToStr(const int in)
99 return ConvNumeric(in);
102 /** Template function to convert any input type to std::string
104 inline std::string ConvToStr(const long in)
106 return ConvNumeric(in);
109 /** Template function to convert any input type to std::string
111 inline std::string ConvToStr(const unsigned long in)
113 return ConvNumeric(in);
116 /** Template function to convert any input type to std::string
118 inline std::string ConvToStr(const char* in)
123 /** Template function to convert any input type to std::string
125 inline std::string ConvToStr(const bool in)
127 return (in ? "1" : "0");
130 /** Template function to convert any input type to std::string
132 inline std::string ConvToStr(char in)
134 return std::string(in,1);
137 /** Template function to convert any input type to std::string
139 template <class T> inline std::string ConvToStr(const T &in)
141 std::stringstream tmp;
142 if (!(tmp << in)) return std::string();
146 /** Template function to convert any input type to any other type
147 * (usually an integer or numeric type)
149 template<typename T> inline long ConvToInt(const T &in)
151 std::stringstream tmp;
152 if (!(tmp << in)) return 0;
153 return atoi(tmp.str().c_str());
156 /** Template function to convert integer to char, storing result in *res and
157 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
158 * @param T input value
159 * @param V result value
160 * @param R base to convert to
162 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
164 if (base < 2 || base > 16) { *res = 0; return res; }
168 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
172 if ( in < 0 && base == 10) *out++ = '-';
173 std::reverse( res, out );
178 /** This class contains various STATS counters
179 * It is used by the InspIRCd class, which internally
180 * has an instance of it.
182 class serverstats : public classbase
185 /** Number of accepted connections
187 unsigned long statsAccept;
188 /** Number of failed accepts
190 unsigned long statsRefused;
191 /** Number of unknown commands seen
193 unsigned long statsUnknown;
194 /** Number of nickname collisions handled
196 unsigned long statsCollisions;
197 /** Number of DNS queries sent out
199 unsigned long statsDns;
200 /** Number of good DNS replies received
201 * NOTE: This may not tally to the number sent out,
202 * due to timeouts and other latency issues.
204 unsigned long statsDnsGood;
205 /** Number of bad (negative) DNS replies received
206 * NOTE: This may not tally to the number sent out,
207 * due to timeouts and other latency issues.
209 unsigned long statsDnsBad;
210 /** Number of inbound connections seen
212 unsigned long statsConnects;
213 /** Total bytes of data transmitted
216 /** Total bytes of data received
219 /** Cpu usage at last sample
222 /** Time last sample was read
225 /** The constructor initializes all the counts to zero
228 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
229 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
234 /** A list of failed port bindings, used for informational purposes on startup */
235 typedef std::vector<std::pair<std::string, long> > FailedPortList;
237 /** A list of ip addresses cross referenced against clone counts */
238 typedef std::map<irc::string, unsigned int> clonemap;
242 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
243 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
244 DEFINE_HANDLER1(FindDescriptorHandler, userrec*, int);
246 /* Forward declaration - required */
249 /** The main class of the irc server.
250 * This class contains instances of all the other classes
251 * in this software, with the exception of the base class,
252 * classbase. Amongst other things, it contains a ModeParser,
253 * a DNS object, a CommandParser object, and a list of active
254 * Module objects, and facilities for Module objects to
255 * interact with the core system it implements. You should
256 * NEVER attempt to instantiate a class of type InspIRCd
257 * yourself. If you do, this is equivalent to spawning a second
258 * IRC server, and could have catastrophic consequences for the
259 * program in terms of ram usage (basically, you could create
260 * an obese forkbomb built from recursively spawning irc servers!)
262 class CoreExport InspIRCd : public classbase
265 /** Holds a string describing the last module error to occur
269 /** Remove a ModuleFactory pointer
270 * @param j Index number of the ModuleFactory to remove
272 void EraseFactory(int j);
274 /** Remove a Module pointer
275 * @param j Index number of the Module to remove
277 void EraseModule(int j);
279 /** Move a given module to a specific slot in the list
280 * @param modulename The module name to relocate
281 * @param slot The slot to move the module into
283 void MoveTo(std::string modulename,int slot);
285 /** Set up the signal handlers
289 /** Daemonize the ircd and close standard input/output streams
290 * @return True if the program daemonized succesfully
294 /** Moves the given module to the last slot in the list
295 * @param modulename The module name to relocate
297 void MoveToLast(std::string modulename);
299 /** Moves the given module to the first slot in the list
300 * @param modulename The module name to relocate
302 void MoveToFirst(std::string modulename);
304 /** Moves one module to be placed after another in the list
305 * @param modulename The module name to relocate
306 * @param after The module name to place the module after
308 void MoveAfter(std::string modulename, std::string after);
310 /** Moves one module to be placed before another in the list
311 * @param modulename The module name to relocate
312 * @param after The module name to place the module before
314 void MoveBefore(std::string modulename, std::string before);
316 /** Iterate the list of InspSocket objects, removing ones which have timed out
317 * @param TIME the current time
319 void DoSocketTimeouts(time_t TIME);
321 /** Perform background user events such as PING checks
322 * @param TIME the current time
324 void DoBackgroundUserStuff(time_t TIME);
326 /** Returns true when all modules have done pre-registration checks on a user
327 * @param user The user to verify
328 * @return True if all modules have finished checking this user
330 bool AllModulesReportReady(userrec* user);
332 /** Total number of modules loaded into the ircd, minus one
336 /** Logfile pathname specified on the commandline, or empty string
338 char LogFileName[MAXBUF];
340 /** The feature names published by various modules
342 featurelist Features;
344 /** The interface names published by various modules
346 interfacelist Interfaces;
348 /** The current time, updated in the mainloop
352 /** The time that was recorded last time around the mainloop
356 /** A 64k buffer used to read client lines into
358 char ReadBuffer[65535];
360 /** Used when connecting clients
362 insp_sockaddr client, server;
364 /** Used when connecting clients
368 /** Nonblocking file writer
372 /** Time offset in seconds
373 * This offset is added to all calls to Time(). Use SetTimeDelta() to update
379 /** Global cull list, will be processed on next iteration
381 CullList GlobalCulls;
386 IsNickHandler HandleIsNick;
387 IsIdentHandler HandleIsIdent;
388 FindDescriptorHandler HandleFindDescriptor;
390 /** InspSocket classes pending deletion after being closed.
391 * We don't delete these immediately as this may cause a segmentation fault.
393 std::map<InspSocket*,InspSocket*> SocketCull;
395 /** Build the ISUPPORT string by triggering all modules On005Numeric events
397 void BuildISupport();
399 /** Number of unregistered users online right now.
400 * (Unregistered means before USER/NICK/dns)
402 int unregistered_count;
404 /** List of server names we've seen.
406 servernamelist servernames;
408 /** Time this ircd was booted
412 /** Config file pathname specified on the commandline or via ./configure
414 char ConfigFileName[MAXBUF];
416 /** Mode handler, handles mode setting and removal
420 /** Command parser, handles client to server commands
422 CommandParser* Parser;
424 /** Socket engine, handles socket activity events
428 /** Stats class, holds miscellaneous stats counters
432 /** Server Config class, holds configuration file data
434 ServerConfig* Config;
436 /** Snomask manager - handles routing of snomask messages
441 /** Client list, a hash_map containing all clients, local and remote
443 user_hash* clientlist;
445 /** Channel list, a hash_map containing all channels
449 /** Local client list, a vector containing only local clients
451 std::vector<userrec*> local_users;
453 /** Oper list, a vector containing all local and remote opered users
455 std::vector<userrec*> all_opers;
457 /** Map of local ip addresses for clone counting
459 clonemap local_clones;
461 /** Map of global ip addresses for clone counting
463 clonemap global_clones;
465 /** DNS class, provides resolver facilities to the core and modules
469 /** Timer manager class, triggers InspTimer timer events
471 TimerManager* Timers;
473 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
475 XLineManager* XLines;
477 /** A list of Module* module classes
478 * Note that this list is always exactly 255 in size.
479 * The actual number of loaded modules is available from GetModuleCount()
483 /** A list of ModuleFactory* module factories
484 * Note that this list is always exactly 255 in size.
485 * The actual number of loaded modules is available from GetModuleCount()
489 /** The time we next call our ping timeout and reg timeout checks
493 /** Get the current time
494 * Because this only calls time() once every time around the mainloop,
495 * it is much faster than calling time() directly.
496 * @param delta True to use the delta as an offset, false otherwise
497 * @return The current time as an epoch value (time_t)
499 time_t Time(bool delta = false);
501 /** Set the time offset in seconds
502 * This offset is added to Time() to offset the system time by the specified
504 * @param delta The number of seconds to offset
505 * @return The old time delta
507 int SetTimeDelta(int delta);
509 /** Add a user to the local clone map
510 * @param user The user to add
512 void AddLocalClone(userrec* user);
514 /** Add a user to the global clone map
515 * @param user The user to add
517 void AddGlobalClone(userrec* user);
519 /** Number of users with a certain mode set on them
521 int ModeCount(const char mode);
523 /** Get the time offset in seconds
524 * @return The current time delta (in seconds)
528 /** Process a user whos socket has been flagged as active
529 * @param cu The user to process
530 * @return There is no actual return value, however upon exit, the user 'cu' may have been
531 * marked for deletion in the global CullList.
533 void ProcessUser(userrec* cu);
535 /** Get the total number of currently loaded modules
536 * @return The number of loaded modules
538 int GetModuleCount();
540 /** Find a module by name, and return a Module* to it.
541 * This is preferred over iterating the module lists yourself.
542 * @param name The module name to look up
543 * @return A pointer to the module, or NULL if the module cannot be found
545 Module* FindModule(const std::string &name);
547 /** Bind all ports specified in the configuration file.
548 * @param bail True if the function should bail back to the shell on failure
549 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
550 * @return The number of ports actually bound without error
552 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
554 /** Binds a socket on an already open file descriptor
555 * @param sockfd A valid file descriptor of an open socket
556 * @param port The port number to bind to
557 * @param addr The address to bind to (IP only)
558 * @return True if the port was bound successfully
560 bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
562 /** Adds a server name to the list of servers we've seen
563 * @param The servername to add
565 void AddServerName(const std::string &servername);
567 /** Finds a cached char* pointer of a server name,
568 * This is used to optimize userrec by storing only the pointer to the name
569 * @param The servername to find
570 * @return A pointer to this name, gauranteed to never become invalid
572 const char* FindServerNamePtr(const std::string &servername);
574 /** Returns true if we've seen the given server name before
575 * @param The servername to find
576 * @return True if we've seen this server name before
578 bool FindServerName(const std::string &servername);
580 /** Gets the GECOS (description) field of the given server.
581 * If the servername is not that of the local server, the name
582 * is passed to handling modules which will attempt to determine
583 * the GECOS that bleongs to the given servername.
584 * @param servername The servername to find the description of
585 * @return The description of this server, or of the local server
587 std::string GetServerDescription(const char* servername);
589 /** Write text to all opers connected to this server
590 * @param text The text format string
591 * @param ... Format args
593 void WriteOpers(const char* text, ...);
595 /** Write text to all opers connected to this server
596 * @param text The text to send
598 void WriteOpers(const std::string &text);
600 /** Find a nickname in the nick hash
601 * @param nick The nickname to find
602 * @return A pointer to the user, or NULL if the user does not exist
604 userrec* FindNick(const std::string &nick);
606 /** Find a nickname in the nick hash
607 * @param nick The nickname to find
608 * @return A pointer to the user, or NULL if the user does not exist
610 userrec* FindNick(const char* nick);
612 /** Find a channel in the channels hash
613 * @param chan The channel to find
614 * @return A pointer to the channel, or NULL if the channel does not exist
616 chanrec* FindChan(const std::string &chan);
618 /** Find a channel in the channels hash
619 * @param chan The channel to find
620 * @return A pointer to the channel, or NULL if the channel does not exist
622 chanrec* FindChan(const char* chan);
624 /** Called by the constructor to load all modules from the config file.
626 void LoadAllModules();
628 /** Check for a 'die' tag in the config file, and abort if found
629 * @return Depending on the configuration, this function may never return
633 /** Check we aren't running as root, and exit if we are
634 * @return Depending on the configuration, this function may never return
638 /** Determine the right path for, and open, the logfile
639 * @param argv The argv passed to main() initially, used to calculate program path
640 * @param argc The argc passed to main() initially, used to calculate program path
642 void OpenLog(char** argv, int argc);
644 /** Close the currently open log file
648 /** Send a server notice to all local users
649 * @param text The text format string to send
650 * @param ... The format arguments
652 void ServerNoticeAll(char* text, ...);
654 /** Send a server message (PRIVMSG) to all local users
655 * @param text The text format string to send
656 * @param ... The format arguments
658 void ServerPrivmsgAll(char* text, ...);
660 /** Send text to all users with a specific set of modes
661 * @param modes The modes to check against, without a +, e.g. 'og'
662 * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
663 * mode characters in the first parameter causes receipt of the message, and
664 * if you specify WM_OR, all the modes must be present.
665 * @param text The text format string to send
666 * @param ... The format arguments
668 void WriteMode(const char* modes, int flags, const char* text, ...);
670 /** Return true if a channel name is valid
671 * @param chname A channel name to verify
672 * @return True if the name is valid
674 bool IsChannel(const char *chname);
676 /** Rehash the local server
677 * @param status This value is unused, and required for signal handler functions
679 static void Rehash(int status);
681 /** Causes the server to exit after unloading modules and
682 * closing all open file descriptors.
684 * @param The exit code to give to the operating system
685 * (See the ExitStatus enum for valid values)
687 static void Exit(int status);
689 /** Causes the server to exit immediately with exit code 0.
690 * The status code is required for signal handlers, and ignored.
692 static void QuickExit(int status);
694 /** Return a count of users, unknown and known connections
695 * @return The number of users
699 /** Return a count of fully registered connections only
700 * @return The number of registered users
702 int RegisteredUserCount();
704 /** Return a count of invisible (umode +i) users only
705 * @return The number of invisible users
707 int InvisibleUserCount();
709 /** Return a count of opered (umode +o) users only
710 * @return The number of opers
714 /** Return a count of unregistered (before NICK/USER) users only
715 * @return The number of unregistered (unknown) connections
717 int UnregisteredUserCount();
719 /** Return a count of channels on the network
720 * @return The number of channels
724 /** Return a count of local users on this server only
725 * @return The number of local users
727 long LocalUserCount();
729 /** Send an error notice to all local users, opered and unopered
730 * @param s The error string to send
732 void SendError(const std::string &s);
734 /** For use with Module::Prioritize().
735 * When the return value of this function is returned from
736 * Module::Prioritize(), this specifies that the module wishes
737 * to be ordered exactly BEFORE 'modulename'. For more information
738 * please see Module::Prioritize().
739 * @param modulename The module your module wants to be before in the call list
740 * @returns a priority ID which the core uses to relocate the module in the list
742 long PriorityBefore(const std::string &modulename);
744 /** For use with Module::Prioritize().
745 * When the return value of this function is returned from
746 * Module::Prioritize(), this specifies that the module wishes
747 * to be ordered exactly AFTER 'modulename'. For more information please
748 * see Module::Prioritize().
749 * @param modulename The module your module wants to be after in the call list
750 * @returns a priority ID which the core uses to relocate the module in the list
752 long PriorityAfter(const std::string &modulename);
754 /** Publish a 'feature'.
755 * There are two ways for a module to find another module it depends on.
756 * Either by name, using InspIRCd::FindModule, or by feature, using this
757 * function. A feature is an arbitary string which identifies something this
758 * module can do. For example, if your module provides SSL support, but other
759 * modules provide SSL support too, all the modules supporting SSL should
760 * publish an identical 'SSL' feature. This way, any module requiring use
761 * of SSL functions can just look up the 'SSL' feature using FindFeature,
762 * then use the module pointer they are given.
763 * @param FeatureName The case sensitive feature name to make available
764 * @param Mod a pointer to your module class
765 * @returns True on success, false if the feature is already published by
768 bool PublishFeature(const std::string &FeatureName, Module* Mod);
770 /** Publish a module to an 'interface'.
771 * Modules which implement the same interface (the same way of communicating
772 * with other modules) can publish themselves to an interface, using this
773 * method. When they do so, they become part of a list of related or
774 * compatible modules, and a third module may then query for that list
775 * and know that all modules within that list offer the same API.
776 * A prime example of this is the hashing modules, which all accept the
777 * same types of Request class. Consider this to be similar to PublishFeature,
778 * except for that multiple modules may publish the same 'feature'.
779 * @param InterfaceName The case sensitive interface name to make available
780 * @param Mod a pointer to your module class
781 * @returns True on success, false on failure (there are currently no failure
784 bool PublishInterface(const std::string &InterfaceName, Module* Mod);
786 /** Return a pair saying how many other modules are currently using the
787 * interfaces provided by module m.
788 * @param m The module to count usage for
789 * @return A pair, where the first value is the number of uses of the interface,
790 * and the second value is the interface name being used.
792 std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
794 /** Mark your module as using an interface.
795 * If you mark your module as using an interface, then that interface
796 * module may not unload until your module has unloaded first.
797 * This can be used to prevent crashes by ensuring code you depend on
798 * is always in memory while your module is active.
799 * @param InterfaceName The interface to use
801 void UseInterface(const std::string &InterfaceName);
803 /** Mark your module as finished with an interface.
804 * If you used UseInterface() above, you should use this method when
805 * your module is finished with the interface (usually in its destructor)
806 * to allow the modules which implement the given interface to be unloaded.
807 * @param InterfaceName The interface you are finished with using.
809 void DoneWithInterface(const std::string &InterfaceName);
811 /** Unpublish a 'feature'.
812 * When your module exits, it must call this method for every feature it
813 * is providing so that the feature table is cleaned up.
814 * @param FeatureName the feature to remove
816 bool UnpublishFeature(const std::string &FeatureName);
818 /** Unpublish your module from an interface
819 * When your module exits, it must call this method for every interface
820 * it is part of so that the interfaces table is cleaned up. Only when
821 * the last item is deleted from an interface does the interface get
823 * @param InterfaceName the interface to be removed from
824 * @param Mod The module to remove from the interface list
826 bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
828 /** Find a 'feature'.
829 * There are two ways for a module to find another module it depends on.
830 * Either by name, using InspIRCd::FindModule, or by feature, using the
831 * InspIRCd::PublishFeature method. A feature is an arbitary string which
832 * identifies something this module can do. For example, if your module
833 * provides SSL support, but other modules provide SSL support too, all
834 * the modules supporting SSL should publish an identical 'SSL' feature.
835 * To find a module capable of providing the feature you want, simply
836 * call this method with the feature name you are looking for.
837 * @param FeatureName The feature name you wish to obtain the module for
838 * @returns A pointer to a valid module class on success, NULL on failure.
840 Module* FindFeature(const std::string &FeatureName);
842 /** Find an 'interface'.
843 * An interface is a list of modules which all implement the same API.
844 * @param InterfaceName The Interface you wish to obtain the module
846 * @return A pointer to a deque of Module*, or NULL if the interface
849 modulelist* FindInterface(const std::string &InterfaceName);
851 /** Given a pointer to a Module, return its filename
852 * @param m The module pointer to identify
853 * @return The module name or an empty string
855 const std::string& GetModuleName(Module* m);
857 /** Return true if a nickname is valid
858 * @param n A nickname to verify
859 * @return True if the nick is valid
861 caller1<bool, const char*> IsNick;
863 /** Return true if an ident is valid
864 * @param An ident to verify
865 * @return True if the ident is valid
867 caller1<bool, const char*> IsIdent;
869 /** Find a username by their file descriptor.
870 * It is preferred to use this over directly accessing the fd_ref_table array.
871 * @param socket The file descriptor of a user
872 * @return A pointer to the user if the user exists locally on this descriptor
874 caller1<userrec*, int> FindDescriptor;
876 /** Add a new mode to this server's mode parser
877 * @param mh The modehandler to add
878 * @param modechar The mode character this modehandler handles
879 * @return True if the mode handler was added
881 bool AddMode(ModeHandler* mh, const unsigned char modechar);
883 /** Add a new mode watcher to this server's mode parser
884 * @param mw The modewatcher to add
885 * @return True if the modewatcher was added
887 bool AddModeWatcher(ModeWatcher* mw);
889 /** Delete a mode watcher from this server's mode parser
890 * @param mw The modewatcher to delete
891 * @return True if the modewatcher was deleted
893 bool DelModeWatcher(ModeWatcher* mw);
895 /** Add a dns Resolver class to this server's active set
896 * @param r The resolver to add
897 * @param cached If this value is true, then the cache will
898 * be searched for the DNS result, immediately. If the value is
899 * false, then a request will be sent to the nameserver, and the
900 * result will not be immediately available. You should usually
901 * use the boolean value which you passed to the Resolver
902 * constructor, which Resolver will set appropriately depending
903 * on if cached results are available and haven't expired. It is
904 * however safe to force this value to false, forcing a remote DNS
905 * lookup, but not an update of the cache.
906 * @return True if the operation completed successfully. Note that
907 * if this method returns true, you should not attempt to access
908 * the resolver class you pass it after this call, as depending upon
909 * the request given, the object may be deleted!
911 bool AddResolver(Resolver* r, bool cached);
913 /** Add a command to this server's command parser
914 * @param f A command_t command handler object to add
915 * @throw ModuleException Will throw ModuleExcption if the command already exists
917 void AddCommand(command_t *f);
919 /** Send a modechange.
920 * The parameters provided are identical to that sent to the
921 * handler for class cmd_mode.
922 * @param parameters The mode parameters
923 * @param pcnt The number of items you have given in the first parameter
924 * @param user The user to send error messages to
926 void SendMode(const char **parameters, int pcnt, userrec *user);
928 /** Match two strings using pattern matching.
929 * This operates identically to the global function match(),
930 * except for that it takes std::string arguments rather than
932 * @param sliteral The literal string to match against
933 * @param spattern The pattern to match against. CIDR and globs are supported.
935 bool MatchText(const std::string &sliteral, const std::string &spattern);
937 /** Call the handler for a given command.
938 * @param commandname The command whos handler you wish to call
939 * @param parameters The mode parameters
940 * @param pcnt The number of items you have given in the first parameter
941 * @param user The user to execute the command as
942 * @return True if the command handler was called successfully
944 CmdResult CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
946 /** Return true if the command is a module-implemented command and the given parameters are valid for it
947 * @param parameters The mode parameters
948 * @param pcnt The number of items you have given in the first parameter
949 * @param user The user to test-execute the command as
950 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
952 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
954 /** Add a gline 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 AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
962 /** Add a qline and apply it
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 nickname The nickmask to set the line against
968 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
970 /** Add a zline and apply it
971 * @param duration How long the line should last
972 * @param source Who set the line
973 * @param reason The reason for the line
974 * @param ipaddr The ip-mask to set the line against
976 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
978 /** Add a kline and apply it
979 * @param duration How long the line should last
980 * @param source Who set the line
981 * @param reason The reason for the line
982 * @param hostmask The hostmask to set the line against
984 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
987 * @param duration How long the line should last
988 * @param source Who set the line
989 * @param reason The reason for the line
990 * @param hostmask The hostmask to set the line against
992 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
995 * @param hostmask The gline to delete
996 * @return True if the item was removed
998 bool DelGLine(const std::string &hostmask);
1001 * @param nickname The qline to delete
1002 * @return True if the item was removed
1004 bool DelQLine(const std::string &nickname);
1007 * @param ipaddr The zline to delete
1008 * @return True if the item was removed
1010 bool DelZLine(const std::string &ipaddr);
1013 * @param hostmask The kline to delete
1014 * @return True if the item was removed
1016 bool DelKLine(const std::string &hostmask);
1019 * @param hostmask The kline to delete
1020 * @return True if the item was removed
1022 bool DelELine(const std::string &hostmask);
1024 /** Return true if the given parameter is a valid nick!user\@host mask
1025 * @param mask A nick!user\@host masak to match against
1026 * @return True i the mask is valid
1028 bool IsValidMask(const std::string &mask);
1030 /** Rehash the local server
1032 void RehashServer();
1034 /** Return the channel whos index number matches that provided
1035 * @param The index number of the channel to fetch
1036 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1038 chanrec* GetChannelIndex(long index);
1040 /** Dump text to a user target, splitting it appropriately to fit
1041 * @param User the user to dump the text to
1042 * @param LinePrefix text to prefix each complete line with
1043 * @param TextStream the text to send to the user
1045 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1047 /** Check if the given nickmask matches too many users, send errors to the given user
1048 * @param nick A nickmask to match against
1049 * @param user A user to send error text to
1050 * @return True if the nick matches too many users
1052 bool NickMatchesEveryone(const std::string &nick, userrec* user);
1054 /** Check if the given IP mask matches too many users, send errors to the given user
1055 * @param ip An ipmask to match against
1056 * @param user A user to send error text to
1057 * @return True if the ip matches too many users
1059 bool IPMatchesEveryone(const std::string &ip, userrec* user);
1061 /** Check if the given hostmask matches too many users, send errors to the given user
1062 * @param mask A hostmask to match against
1063 * @param user A user to send error text to
1064 * @return True if the host matches too many users
1066 bool HostMatchesEveryone(const std::string &mask, userrec* user);
1068 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1069 * @param str A string containing a time in the form 1y2w3d4h6m5s
1070 * (one year, two weeks, three days, four hours, six minutes and five seconds)
1071 * @return The total number of seconds
1073 long Duration(const std::string &str);
1075 /** Attempt to compare an oper password to a string from the config file.
1076 * This will be passed to handling modules which will compare the data
1077 * against possible hashed equivalents in the input string.
1078 * @param data The data from the config file
1079 * @param input The data input by the oper
1080 * @param tagnum the tag number of the oper's tag in the config file
1081 * @return 0 if the strings match, 1 or -1 if they do not
1083 int OperPassCompare(const char* data,const char* input, int tagnum);
1085 /** Check if a given server is a uline.
1086 * An empty string returns true, this is by design.
1087 * @param server The server to check for uline status
1088 * @return True if the server is a uline OR the string is empty
1090 bool ULine(const char* server);
1092 /** Returns true if the uline is 'silent' (doesnt generate
1093 * remote connect notices etc).
1095 bool SilentULine(const char* server);
1097 /** Returns the subversion revision ID of this ircd
1098 * @return The revision ID or an empty string
1100 std::string GetRevision();
1102 /** Returns the full version string of this ircd
1103 * @return The version string
1105 std::string GetVersionString();
1107 /** Attempt to write the process id to a given file
1108 * @param filename The PID file to attempt to write to
1109 * @return This function may bail if the file cannot be written
1111 void WritePID(const std::string &filename);
1113 /** Returns text describing the last module error
1114 * @return The last error message to occur
1116 char* ModuleError();
1118 /** Load a given module file
1119 * @param filename The file to load
1120 * @return True if the module was found and loaded
1122 bool LoadModule(const char* filename);
1124 /** Unload a given module file
1125 * @param filename The file to unload
1126 * @return True if the module was unloaded
1128 bool UnloadModule(const char* filename);
1130 /** This constructor initialises all the subsystems and reads the config file.
1131 * @param argc The argument count passed to main()
1132 * @param argv The argument list passed to main()
1133 * @throw <anything> If anything is thrown from here and makes it to
1134 * you, you should probably just give up and go home. Yes, really.
1135 * It's that bad. Higher level classes should catch any non-fatal exceptions.
1137 InspIRCd(int argc, char** argv);
1139 /** Do one iteration of the mainloop
1140 * @param process_module_sockets True if module sockets are to be processed
1141 * this time around the event loop. The is the default.
1143 void DoOneIteration(bool process_module_sockets = true);
1145 /** Output a log message to the ircd.log file
1146 * The text will only be output if the current loglevel
1147 * is less than or equal to the level you provide
1148 * @param level A log level from the DebugLevel enum
1149 * @param text Format string of to write to the log
1150 * @param ... Format arguments of text to write to the log
1152 void Log(int level, const char* text, ...);
1154 /** Output a log message to the ircd.log file
1155 * The text will only be output if the current loglevel
1156 * is less than or equal to the level you provide
1157 * @param level A log level from the DebugLevel enum
1158 * @param text Text to write to the log
1160 void Log(int level, const std::string &text);
1162 /** Send a line of WHOIS data to a user.
1163 * @param user user to send the line to
1164 * @param dest user being WHOISed
1165 * @param numeric Numeric to send
1166 * @param text Text of the numeric
1168 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1170 /** Send a line of WHOIS data to a user.
1171 * @param user user to send the line to
1172 * @param dest user being WHOISed
1173 * @param numeric Numeric to send
1174 * @param format Format string for the numeric
1175 * @param ... Parameters for the format string
1177 void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1179 /** Quit a user for excess flood, and if they are not
1180 * fully registered yet, temporarily zline their IP.
1181 * @param current user to quit
1183 void FloodQuitUser(userrec* current);
1185 /** Restart the server.
1186 * This function will not return. If an error occurs,
1187 * it will throw an instance of CoreException.
1188 * @param reason The restart reason to show to all clients
1189 * @throw CoreException An instance of CoreException indicating the error from execv().
1191 void Restart(const std::string &reason);
1193 /** Prepare the ircd for restart or shutdown.
1194 * This function unloads all modules which can be unloaded,
1195 * closes all open sockets, and closes the logfile.
1199 /** This copies the user and channel hash_maps into new hash maps.
1200 * This frees memory used by the hash_map allocator (which it neglects
1201 * to free, most of the time, using tons of ram)
1203 void RehashUsersAndChans();
1205 /** Resets the cached max bans value on all channels.
1208 void ResetMaxBans();
1210 /** Return a time_t as a human-readable string.
1212 std::string TimeString(time_t curtime);
1214 /** Begin execution of the server.
1215 * NOTE: this function NEVER returns. Internally,
1216 * after performing some initialisation routines,
1217 * it will repeatedly call DoOneIteration in a loop.
1218 * @return The return value for this function is undefined.
1222 /** Force all InspSockets to be removed which are due to
1225 void InspSocketCull();