1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/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__
17 #define _FILE_OFFSET_BITS 64
18 #ifndef _LARGEFILE_SOURCE
19 #define _LARGEFILE_SOURCE
25 #define printf_c printf
27 #include "inspircd_win32wrapper.h"
28 /** Windows defines these already */
34 #define CUSTOM_PRINTF(STRING, FIRST) __attribute__((format(printf, STRING, FIRST)))
36 #define CUSTOM_PRINTF(STRING, FIRST)
39 // Required system headers.
57 /** A list of failed port bindings, used for informational purposes on startup */
58 typedef std::vector<std::pair<std::string, std::string> > FailedPortList;
61 CoreExport extern InspIRCd* ServerInstance;
63 #include "inspircd_config.h"
64 #include "inspircd_version.h"
66 #include "cull_list.h"
67 #include "extensible.h"
76 #include "usermanager.h"
79 #include "command_parse.h"
81 #include "socketengine.h"
83 #include "filelogger.h"
86 #include "configreader.h"
87 #include "inspstring.h"
89 #include "threadengine.h"
93 #warning Potentially broken system, PATH_MAX undefined
98 * Used to define the maximum number of parameters a command may have.
100 #define MAXPARAMETERS 127
102 /** Returned by some functions to indicate failure.
106 /** Support for librodent -
107 * see http://www.chatspike.net/index.php?z=64
109 #define ETIREDHAMSTERS EAGAIN
111 /** Template function to convert any input type to std::string
113 template<typename T> inline std::string ConvNumeric(const T &in)
115 if (in == 0) return "0";
120 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
127 std::reverse(res,out);
131 /** Template function to convert any input type to std::string
133 inline std::string ConvToStr(const int in)
135 return ConvNumeric(in);
138 /** Template function to convert any input type to std::string
140 inline std::string ConvToStr(const long in)
142 return ConvNumeric(in);
145 /** Template function to convert any input type to std::string
147 inline std::string ConvToStr(const char* in)
152 /** Template function to convert any input type to std::string
154 inline std::string ConvToStr(const bool in)
156 return (in ? "1" : "0");
159 /** Template function to convert any input type to std::string
161 inline std::string ConvToStr(char in)
163 return std::string(in,1);
166 /** Template function to convert any input type to std::string
168 template <class T> inline std::string ConvToStr(const T &in)
170 std::stringstream tmp;
171 if (!(tmp << in)) return std::string();
175 /** Template function to convert any input type to any other type
176 * (usually an integer or numeric type)
178 template<typename T> inline long ConvToInt(const T &in)
180 std::stringstream tmp;
181 if (!(tmp << in)) return 0;
182 return atol(tmp.str().c_str());
185 /** This class contains various STATS counters
186 * It is used by the InspIRCd class, which internally
187 * has an instance of it.
192 /** Number of accepted connections
194 unsigned long statsAccept;
195 /** Number of failed accepts
197 unsigned long statsRefused;
198 /** Number of unknown commands seen
200 unsigned long statsUnknown;
201 /** Number of nickname collisions handled
203 unsigned long statsCollisions;
204 /** Number of DNS queries sent out
206 unsigned long statsDns;
207 /** Number of good DNS replies received
208 * NOTE: This may not tally to the number sent out,
209 * due to timeouts and other latency issues.
211 unsigned long statsDnsGood;
212 /** Number of bad (negative) DNS replies received
213 * NOTE: This may not tally to the number sent out,
214 * due to timeouts and other latency issues.
216 unsigned long statsDnsBad;
217 /** Number of inbound connections seen
219 unsigned long statsConnects;
220 /** Total bytes of data transmitted
223 /** Total bytes of data received
226 /** Cpu usage at last sample
229 /** Time last sample was read
232 /** The constructor initializes all the counts to zero
235 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
236 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
243 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
244 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
245 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
246 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
247 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
248 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
250 /* Forward declaration - required */
252 class BanCacheManager;
254 /** The background thread for config reading, so that reading from executable includes
257 class CoreExport ConfigReaderThread : public Thread
259 ServerConfig* Config;
262 std::string TheUserUID;
263 ConfigReaderThread(const std::string &useruid)
264 : Thread(), done(false), TheUserUID(useruid)
268 virtual ~ConfigReaderThread()
273 /** Run in the main thread to apply the configuration */
275 bool IsDone() { return done; }
278 /** The main class of the irc server.
279 * This class contains instances of all the other classes in this software.
280 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
281 * object, and a list of active Module objects, and facilities for Module
282 * objects to interact with the core system it implements.
284 class CoreExport InspIRCd
287 /** Holds the current UID. Used to generate the next one.
289 char current_uid[UUID_LENGTH];
291 /** Set up the signal handlers
295 /** Daemonize the ircd and close standard input/output streams
296 * @return True if the program daemonized succesfully
300 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
301 * @param TIME the current time
303 void DoSocketTimeouts(time_t TIME);
305 /** Increments the current UID by one.
307 void IncrementUID(int pos);
309 /** Perform background user events such as PING checks
311 void DoBackgroundUserStuff();
313 /** Returns true when all modules have done pre-registration checks on a user
314 * @param user The user to verify
315 * @return True if all modules have finished checking this user
317 bool AllModulesReportReady(User* user);
319 /** Logfile pathname specified on the commandline, or empty string
321 char LogFileName[MAXBUF];
323 /** The current time, updated in the mainloop
327 /** The time that was recorded last time around the mainloop
331 /** A 64k buffer used to read socket data into
332 * NOTE: update ValidateNetBufferSize if you change this
334 char ReadBuffer[65535];
342 /** Global cull list, will be processed on next iteration
344 CullList GlobalCulls;
345 /** Actions that must happen outside of the current call stack */
346 ActionList AtomicActions;
350 IsNickHandler HandleIsNick;
351 IsIdentHandler HandleIsIdent;
352 FloodQuitUserHandler HandleFloodQuitUser;
353 IsChannelHandler HandleIsChannel;
354 IsSIDHandler HandleIsSID;
355 RehashHandler HandleRehash;
357 /** Globally accessible fake user record. This is used to force mode changes etc across s2s, etc.. bit ugly, but.. better than how this was done in 1.1
360 * SendMode expects a User* to send the numeric replies
361 * back to, so we create it a fake user that isnt in the user
362 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
363 * falls into the abyss :p
365 FakeUser* FakeClient;
367 /** Returns the next available UID for this server.
369 std::string GetUID();
371 /** Find a user in the UUID hash
372 * @param nick The nickname to find
373 * @return A pointer to the user, or NULL if the user does not exist
375 User* FindUUID(const std::string &);
377 /** Find a user in the UUID hash
378 * @param nick The nickname to find
379 * @return A pointer to the user, or NULL if the user does not exist
381 User* FindUUID(const char *);
383 /** Build the ISUPPORT string by triggering all modules On005Numeric events
385 void BuildISupport();
387 /** Time this ircd was booted
391 /** Config file pathname specified on the commandline or via ./configure
393 std::string ConfigFileName;
395 ExtensionManager Extensions;
397 /** Mode handler, handles mode setting and removal
401 /** Command parser, handles client to server commands
403 CommandParser* Parser;
405 /** Socket engine, handles socket activity events
409 /** Thread engine, Handles threading where required
411 ThreadEngine* Threads;
413 /** The thread/class used to read config files in REHASH and on startup
415 ConfigReaderThread* ConfigThread;
417 /** LogManager handles logging.
421 /** ModuleManager contains everything related to loading/unloading
424 ModuleManager* Modules;
426 /** BanCacheManager is used to speed up checking of restrictions on connection
429 BanCacheManager *BanCache;
431 /** Stats class, holds miscellaneous stats counters
435 /** Server Config class, holds configuration file data
437 ServerConfig* Config;
439 /** Snomask manager - handles routing of snomask messages
444 /** DNS class, provides resolver facilities to the core and modules
448 /** Timer manager class, triggers Timer timer events
450 TimerManager* Timers;
452 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
454 XLineManager* XLines;
456 /** User manager. Various methods and data associated with users.
460 /** Channel list, a hash_map containing all channels XXX move to channel manager class
464 /** List of the open ports
466 std::vector<ListenSocketBase *> ports;
468 /** Set to the current signal recieved
472 /** Protocol interface, overridden by server protocol modules
474 ProtocolInterface* PI;
476 /** Holds extensible for user nickforced
478 LocalIntExt NICKForced;
480 /** Holds extensible for user operquit
482 LocalStringExt OperQuit;
484 /** Get the current time
485 * Because this only calls time() once every time around the mainloop,
486 * it is much faster than calling time() directly.
487 * @return The current time as an epoch value (time_t)
491 /** Bind all ports specified in the configuration file.
492 * @return The number of ports bound without error
494 int BindPorts(FailedPortList &failed_ports);
496 /** Binds a socket on an already open file descriptor
497 * @param sockfd A valid file descriptor of an open socket
498 * @param port The port number to bind to
499 * @param addr The address to bind to (IP only)
500 * @return True if the port was bound successfully
502 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
504 /** Gets the GECOS (description) field of the given server.
505 * If the servername is not that of the local server, the name
506 * is passed to handling modules which will attempt to determine
507 * the GECOS that bleongs to the given servername.
508 * @param servername The servername to find the description of
509 * @return The description of this server, or of the local server
511 std::string GetServerDescription(const std::string& servername);
513 /** Find a user in the nick hash.
514 * If the user cant be found in the nick hash check the uuid hash
515 * @param nick The nickname to find
516 * @return A pointer to the user, or NULL if the user does not exist
518 User* FindNick(const std::string &nick);
520 /** Find a user in the nick hash.
521 * If the user cant be found in the nick hash check the uuid hash
522 * @param nick The nickname to find
523 * @return A pointer to the user, or NULL if the user does not exist
525 User* FindNick(const char* nick);
527 /** Find a user in the nick hash ONLY
529 User* FindNickOnly(const char* nick);
531 /** Find a user in the nick hash ONLY
533 User* FindNickOnly(const std::string &nick);
535 /** Find a channel in the channels hash
536 * @param chan The channel to find
537 * @return A pointer to the channel, or NULL if the channel does not exist
539 Channel* FindChan(const std::string &chan);
541 /** Find a channel in the channels hash
542 * @param chan The channel to find
543 * @return A pointer to the channel, or NULL if the channel does not exist
545 Channel* FindChan(const char* chan);
547 /** Check we aren't running as root, and exit if we are
548 * @return Depending on the configuration, this function may never return
552 /** Determine the right path for, and open, the logfile
553 * @param argv The argv passed to main() initially, used to calculate program path
554 * @param argc The argc passed to main() initially, used to calculate program path
555 * @return True if the log could be opened, false if otherwise
557 bool OpenLog(char** argv, int argc);
559 /** Return true if a channel name is valid
560 * @param chname A channel name to verify
561 * @return True if the name is valid
563 caller2<bool, const char*, size_t> IsChannel;
565 /** Return true if str looks like a server ID
566 * @param string to check against
568 caller1<bool, const std::string&> IsSID;
570 /** Rehash the local server
572 caller1<void, const std::string&> Rehash;
574 /** Handles incoming signals after being set
575 * @param signal the signal recieved
577 void SignalHandler(int signal);
579 /** Sets the signal recieved
580 * @param signal the signal recieved
582 static void SetSignal(int signal);
584 /** Causes the server to exit after unloading modules and
585 * closing all open file descriptors.
587 * @param The exit code to give to the operating system
588 * (See the ExitStatus enum for valid values)
590 void Exit(int status);
592 /** Causes the server to exit immediately with exit code 0.
593 * The status code is required for signal handlers, and ignored.
595 static void QuickExit(int status);
597 /** Return a count of channels on the network
598 * @return The number of channels
602 /** Send an error notice to all local users, opered and unopered
603 * @param s The error string to send
605 void SendError(const std::string &s);
607 /** Return true if a nickname is valid
608 * @param n A nickname to verify
609 * @return True if the nick is valid
611 caller2<bool, const char*, size_t> IsNick;
613 /** Return true if an ident is valid
614 * @param An ident to verify
615 * @return True if the ident is valid
617 caller1<bool, const char*> IsIdent;
619 /** Add a dns Resolver class to this server's active set
620 * @param r The resolver to add
621 * @param cached If this value is true, then the cache will
622 * be searched for the DNS result, immediately. If the value is
623 * false, then a request will be sent to the nameserver, and the
624 * result will not be immediately available. You should usually
625 * use the boolean value which you passed to the Resolver
626 * constructor, which Resolver will set appropriately depending
627 * on if cached results are available and haven't expired. It is
628 * however safe to force this value to false, forcing a remote DNS
629 * lookup, but not an update of the cache.
630 * @return True if the operation completed successfully. Note that
631 * if this method returns true, you should not attempt to access
632 * the resolver class you pass it after this call, as depending upon
633 * the request given, the object may be deleted!
635 bool AddResolver(Resolver* r, bool cached);
637 /** Add a command to this server's command parser
638 * @param f A Command command handler object to add
639 * @throw ModuleException Will throw ModuleExcption if the command already exists
641 void AddCommand(Command *f);
643 /** Send a modechange.
644 * The parameters provided are identical to that sent to the
645 * handler for class cmd_mode.
646 * @param parameters The mode parameters
647 * @param user The user to send error messages to
649 void SendMode(const std::vector<std::string>& parameters, User *user);
651 /** Match two strings using pattern matching, optionally, with a map
652 * to check case against (may be NULL). If map is null, match will be case insensitive.
653 * @param str The literal string to match against
654 * @param mask The glob pattern to match against.
656 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
657 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
659 /** Match two strings using pattern matching, optionally, with a map
660 * to check case against (may be NULL). If map is null, match will be case insensitive.
661 * Supports CIDR patterns as well as globs.
662 * @param str The literal string to match against
663 * @param mask The glob or CIDR pattern to match against.
665 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
666 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
668 /** Call the handler for a given command.
669 * @param commandname The command whos handler you wish to call
670 * @param parameters The mode parameters
671 * @param pcnt The number of items you have given in the first parameter
672 * @param user The user to execute the command as
673 * @return True if the command handler was called successfully
675 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
677 /** Return true if the command is a module-implemented command and the given parameters are valid for it
678 * @param parameters The mode parameters
679 * @param pcnt The number of items you have given in the first parameter
680 * @param user The user to test-execute the command as
681 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
683 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
685 /** Return true if the given parameter is a valid nick!user\@host mask
686 * @param mask A nick!user\@host masak to match against
687 * @return True i the mask is valid
689 bool IsValidMask(const std::string &mask);
691 /** Rehash the local server
695 /** Check if the given nickmask matches too many users, send errors to the given user
696 * @param nick A nickmask to match against
697 * @param user A user to send error text to
698 * @return True if the nick matches too many users
700 bool NickMatchesEveryone(const std::string &nick, User* user);
702 /** Check if the given IP mask matches too many users, send errors to the given user
703 * @param ip An ipmask to match against
704 * @param user A user to send error text to
705 * @return True if the ip matches too many users
707 bool IPMatchesEveryone(const std::string &ip, User* user);
709 /** Check if the given hostmask matches too many users, send errors to the given user
710 * @param mask A hostmask to match against
711 * @param user A user to send error text to
712 * @return True if the host matches too many users
714 bool HostMatchesEveryone(const std::string &mask, User* user);
716 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
717 * @param str A string containing a time in the form 1y2w3d4h6m5s
718 * (one year, two weeks, three days, four hours, six minutes and five seconds)
719 * @return The total number of seconds
721 long Duration(const std::string &str);
723 /** Attempt to compare a password to a string from the config file.
724 * This will be passed to handling modules which will compare the data
725 * against possible hashed equivalents in the input string.
726 * @param ex The object (user, server, whatever) causing the comparison.
727 * @param data The data from the config file
728 * @param input The data input by the oper
729 * @param hashtype The hash from the config file
730 * @return 0 if the strings match, 1 or -1 if they do not
732 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
734 /** Check if a given server is a uline.
735 * An empty string returns true, this is by design.
736 * @param server The server to check for uline status
737 * @return True if the server is a uline OR the string is empty
739 bool ULine(const std::string& server);
741 /** Returns true if the uline is 'silent' (doesnt generate
742 * remote connect notices etc).
744 bool SilentULine(const std::string& server);
746 /** Returns the subversion revision ID of this ircd
747 * @return The revision ID or an empty string
749 std::string GetRevision();
751 /** Returns the full version string of this ircd
752 * @return The version string
754 std::string GetVersionString();
756 /** Attempt to write the process id to a given file
757 * @param filename The PID file to attempt to write to
758 * @return This function may bail if the file cannot be written
760 void WritePID(const std::string &filename);
762 /** This constructor initialises all the subsystems and reads the config file.
763 * @param argc The argument count passed to main()
764 * @param argv The argument list passed to main()
765 * @throw <anything> If anything is thrown from here and makes it to
766 * you, you should probably just give up and go home. Yes, really.
767 * It's that bad. Higher level classes should catch any non-fatal exceptions.
769 InspIRCd(int argc, char** argv);
771 /** Send a line of WHOIS data to a user.
772 * @param user user to send the line to
773 * @param dest user being WHOISed
774 * @param numeric Numeric to send
775 * @param text Text of the numeric
777 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
779 /** Send a line of WHOIS data to a user.
780 * @param user user to send the line to
781 * @param dest user being WHOISed
782 * @param numeric Numeric to send
783 * @param format Format string for the numeric
784 * @param ... Parameters for the format string
786 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
790 void DoStats(char statschar, User* user, string_list &results);
794 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
796 /** Quit a user for excess flood, and if they are not
797 * fully registered yet, temporarily zline their IP.
798 * @param current user to quit
800 caller1<void, User*> FloodQuitUser;
802 /** Restart the server.
803 * This function will not return. If an error occurs,
804 * it will throw an instance of CoreException.
805 * @param reason The restart reason to show to all clients
806 * @throw CoreException An instance of CoreException indicating the error from execv().
808 void Restart(const std::string &reason);
810 /** Prepare the ircd for restart or shutdown.
811 * This function unloads all modules which can be unloaded,
812 * closes all open sockets, and closes the logfile.
816 /** This copies the user and channel hash_maps into new hash maps.
817 * This frees memory used by the hash_map allocator (which it neglects
818 * to free, most of the time, using tons of ram)
820 void RehashUsersAndChans();
822 /** Resets the cached max bans value on all channels.
827 /** Return a time_t as a human-readable string.
829 std::string TimeString(time_t curtime);
831 /** Begin execution of the server.
832 * NOTE: this function NEVER returns. Internally,
833 * it will repeatedly loop.
834 * @return The return value for this function is undefined.
838 /** Adds an extban char to the 005 token.
840 void AddExtBanChar(char c);
842 char* GetReadBuffer()
844 return this->ReadBuffer;
851 class CommandModule : public Module
855 CommandModule() : cmd(this)
857 ServerInstance->AddCommand(&cmd);
862 return Version(cmd.command, VF_VENDOR|VF_CORE);