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;
60 /** A cached text file stored with its contents as lines
62 typedef std::deque< std::string > file_cache;
64 /** A configuration key and value pair
66 typedef std::pair< std::string, std::string > KeyVal;
68 /** A list of related configuration keys and values
70 typedef std::vector< KeyVal > KeyValList;
72 /** An entire config file, built up of KeyValLists
74 typedef std::multimap< std::string, KeyValList > ConfigDataHash;
77 CoreExport extern InspIRCd* ServerInstance;
79 #include "inspircd_config.h"
80 #include "inspircd_version.h"
82 #include "cull_list.h"
83 #include "extensible.h"
92 #include "usermanager.h"
95 #include "command_parse.h"
97 #include "socketengine.h"
99 #include "filelogger.h"
102 #include "configreader.h"
103 #include "inspstring.h"
104 #include "protocol.h"
105 #include "threadengine.h"
106 #include "fakeuser.h"
109 #warning Potentially broken system, PATH_MAX undefined
110 #define PATH_MAX 4096
114 * Used to define the maximum number of parameters a command may have.
116 #define MAXPARAMETERS 127
118 /** Returned by some functions to indicate failure.
122 /** Support for librodent -
123 * see http://www.chatspike.net/index.php?z=64
125 #define ETIREDHAMSTERS EAGAIN
127 /** Template function to convert any input type to std::string
129 template<typename T> inline std::string ConvNumeric(const T &in)
131 if (in == 0) return "0";
136 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
143 std::reverse(res,out);
147 /** Template function to convert any input type to std::string
149 inline std::string ConvToStr(const int in)
151 return ConvNumeric(in);
154 /** Template function to convert any input type to std::string
156 inline std::string ConvToStr(const long in)
158 return ConvNumeric(in);
161 /** Template function to convert any input type to std::string
163 inline std::string ConvToStr(const char* in)
168 /** Template function to convert any input type to std::string
170 inline std::string ConvToStr(const bool in)
172 return (in ? "1" : "0");
175 /** Template function to convert any input type to std::string
177 inline std::string ConvToStr(char in)
179 return std::string(in,1);
182 /** Template function to convert any input type to std::string
184 template <class T> inline std::string ConvToStr(const T &in)
186 std::stringstream tmp;
187 if (!(tmp << in)) return std::string();
191 /** Template function to convert any input type to any other type
192 * (usually an integer or numeric type)
194 template<typename T> inline long ConvToInt(const T &in)
196 std::stringstream tmp;
197 if (!(tmp << in)) return 0;
198 return atoi(tmp.str().c_str());
201 /** Template function to convert integer to char, storing result in *res and
202 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
203 * @param T input value
204 * @param V result value
205 * @param R base to convert to
207 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
209 if (base < 2 || base > 16) { *res = 0; return res; }
213 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
217 if ( in < 0 && base == 10) *out++ = '-';
218 std::reverse( res, out );
223 /** This class contains various STATS counters
224 * It is used by the InspIRCd class, which internally
225 * has an instance of it.
227 class serverstats : public classbase
230 /** Number of accepted connections
232 unsigned long statsAccept;
233 /** Number of failed accepts
235 unsigned long statsRefused;
236 /** Number of unknown commands seen
238 unsigned long statsUnknown;
239 /** Number of nickname collisions handled
241 unsigned long statsCollisions;
242 /** Number of DNS queries sent out
244 unsigned long statsDns;
245 /** Number of good DNS replies received
246 * NOTE: This may not tally to the number sent out,
247 * due to timeouts and other latency issues.
249 unsigned long statsDnsGood;
250 /** Number of bad (negative) DNS replies received
251 * NOTE: This may not tally to the number sent out,
252 * due to timeouts and other latency issues.
254 unsigned long statsDnsBad;
255 /** Number of inbound connections seen
257 unsigned long statsConnects;
258 /** Total bytes of data transmitted
261 /** Total bytes of data received
264 /** Cpu usage at last sample
267 /** Time last sample was read
270 /** The constructor initializes all the counts to zero
273 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
274 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
281 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
282 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
283 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
284 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
285 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
286 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
288 /* Forward declaration - required */
290 class BanCacheManager;
292 /** The background thread for config reading, so that reading from executable includes
295 class CoreExport ConfigReaderThread : public Thread
297 ServerConfig* Config;
300 std::string TheUserUID;
301 ConfigReaderThread(const std::string &useruid)
302 : Thread(), done(false), TheUserUID(useruid)
306 virtual ~ConfigReaderThread()
311 /** Run in the main thread to apply the configuration */
313 bool IsDone() { return done; }
316 /** The main class of the irc server.
317 * This class contains instances of all the other classes
318 * in this software, with the exception of the base class,
319 * classbase. Amongst other things, it contains a ModeParser,
320 * a DNS object, a CommandParser object, and a list of active
321 * Module objects, and facilities for Module objects to
322 * interact with the core system it implements.
324 class CoreExport InspIRCd : public classbase
327 /** Holds the current UID. Used to generate the next one.
329 char current_uid[UUID_LENGTH];
331 /** Set up the signal handlers
335 /** Daemonize the ircd and close standard input/output streams
336 * @return True if the program daemonized succesfully
340 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
341 * @param TIME the current time
343 void DoSocketTimeouts(time_t TIME);
345 /** Increments the current UID by one.
347 void IncrementUID(int pos);
349 /** Perform background user events such as PING checks
351 void DoBackgroundUserStuff();
353 /** Returns true when all modules have done pre-registration checks on a user
354 * @param user The user to verify
355 * @return True if all modules have finished checking this user
357 bool AllModulesReportReady(User* user);
359 /** Logfile pathname specified on the commandline, or empty string
361 char LogFileName[MAXBUF];
363 /** The current time, updated in the mainloop
367 /** The time that was recorded last time around the mainloop
371 /** A 64k buffer used to read socket data into
372 * NOTE: update ValidateNetBufferSize if you change this
374 char ReadBuffer[65535];
382 /** Global cull list, will be processed on next iteration
384 CullList GlobalCulls;
385 /** Actions that must happen outside of the current call stack */
386 ActionList AtomicActions;
390 IsNickHandler HandleIsNick;
391 IsIdentHandler HandleIsIdent;
392 FloodQuitUserHandler HandleFloodQuitUser;
393 IsChannelHandler HandleIsChannel;
394 IsSIDHandler HandleIsSID;
395 RehashHandler HandleRehash;
397 /** 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
400 * SendMode expects a User* to send the numeric replies
401 * back to, so we create it a fake user that isnt in the user
402 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
403 * falls into the abyss :p
405 FakeUser* FakeClient;
407 /** Returns the next available UID for this server.
409 std::string GetUID();
411 /** Find a user in the UUID hash
412 * @param nick The nickname to find
413 * @return A pointer to the user, or NULL if the user does not exist
415 User* FindUUID(const std::string &);
417 /** Find a user in the UUID hash
418 * @param nick The nickname to find
419 * @return A pointer to the user, or NULL if the user does not exist
421 User* FindUUID(const char *);
423 /** Build the ISUPPORT string by triggering all modules On005Numeric events
425 void BuildISupport();
427 /** Time this ircd was booted
431 /** Config file pathname specified on the commandline or via ./configure
433 std::string ConfigFileName;
435 ExtensionManager Extensions;
437 /** Mode handler, handles mode setting and removal
441 /** Command parser, handles client to server commands
443 CommandParser* Parser;
445 /** Socket engine, handles socket activity events
449 /** Thread engine, Handles threading where required
451 ThreadEngine* Threads;
453 /** The thread/class used to read config files in REHASH and on startup
455 ConfigReaderThread* ConfigThread;
457 /** LogManager handles logging.
461 /** ModuleManager contains everything related to loading/unloading
464 ModuleManager* Modules;
466 /** BanCacheManager is used to speed up checking of restrictions on connection
469 BanCacheManager *BanCache;
471 /** Stats class, holds miscellaneous stats counters
475 /** Server Config class, holds configuration file data
477 ServerConfig* Config;
479 /** Snomask manager - handles routing of snomask messages
484 /** DNS class, provides resolver facilities to the core and modules
488 /** Timer manager class, triggers Timer timer events
490 TimerManager* Timers;
492 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
494 XLineManager* XLines;
496 /** User manager. Various methods and data associated with users.
500 /** Channel list, a hash_map containing all channels XXX move to channel manager class
504 /** List of the open ports
506 std::vector<ListenSocketBase *> ports;
508 /** Set to the current signal recieved
512 /** Protocol interface, overridden by server protocol modules
514 ProtocolInterface* PI;
516 /** Holds extensible for user nickforced
518 LocalIntExt NICKForced;
520 /** Holds extensible for user operquit
522 LocalStringExt OperQuit;
524 /** Get the current time
525 * Because this only calls time() once every time around the mainloop,
526 * it is much faster than calling time() directly.
527 * @return The current time as an epoch value (time_t)
531 /** Bind all ports specified in the configuration file.
532 * @return The number of ports bound without error
534 int BindPorts(FailedPortList &failed_ports);
536 /** Binds a socket on an already open file descriptor
537 * @param sockfd A valid file descriptor of an open socket
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, int port, const char* addr, bool dolisten = true);
544 /** Gets the GECOS (description) field of the given server.
545 * If the servername is not that of the local server, the name
546 * is passed to handling modules which will attempt to determine
547 * the GECOS that bleongs to the given servername.
548 * @param servername The servername to find the description of
549 * @return The description of this server, or of the local server
551 std::string GetServerDescription(const std::string& servername);
553 /** Find a user in the nick hash.
554 * If the user cant be found in the nick hash check the uuid hash
555 * @param nick The nickname to find
556 * @return A pointer to the user, or NULL if the user does not exist
558 User* FindNick(const std::string &nick);
560 /** Find a user in the nick hash.
561 * If the user cant be found in the nick hash check the uuid hash
562 * @param nick The nickname to find
563 * @return A pointer to the user, or NULL if the user does not exist
565 User* FindNick(const char* nick);
567 /** Find a user in the nick hash ONLY
569 User* FindNickOnly(const char* nick);
571 /** Find a user in the nick hash ONLY
573 User* FindNickOnly(const std::string &nick);
575 /** Find a channel in the channels hash
576 * @param chan The channel to find
577 * @return A pointer to the channel, or NULL if the channel does not exist
579 Channel* FindChan(const std::string &chan);
581 /** Find a channel in the channels hash
582 * @param chan The channel to find
583 * @return A pointer to the channel, or NULL if the channel does not exist
585 Channel* FindChan(const char* chan);
587 /** Check we aren't running as root, and exit if we are
588 * @return Depending on the configuration, this function may never return
592 /** Determine the right path for, and open, the logfile
593 * @param argv The argv passed to main() initially, used to calculate program path
594 * @param argc The argc passed to main() initially, used to calculate program path
595 * @return True if the log could be opened, false if otherwise
597 bool OpenLog(char** argv, int argc);
599 /** Return true if a channel name is valid
600 * @param chname A channel name to verify
601 * @return True if the name is valid
603 caller2<bool, const char*, size_t> IsChannel;
605 /** Return true if str looks like a server ID
606 * @param string to check against
608 caller1<bool, const std::string&> IsSID;
610 /** Rehash the local server
612 caller1<void, const std::string&> Rehash;
614 /** Handles incoming signals after being set
615 * @param signal the signal recieved
617 void SignalHandler(int signal);
619 /** Sets the signal recieved
620 * @param signal the signal recieved
622 static void SetSignal(int signal);
624 /** Causes the server to exit after unloading modules and
625 * closing all open file descriptors.
627 * @param The exit code to give to the operating system
628 * (See the ExitStatus enum for valid values)
630 void Exit(int status);
632 /** Causes the server to exit immediately with exit code 0.
633 * The status code is required for signal handlers, and ignored.
635 static void QuickExit(int status);
637 /** Return a count of channels on the network
638 * @return The number of channels
642 /** Send an error notice to all local users, opered and unopered
643 * @param s The error string to send
645 void SendError(const std::string &s);
647 /** Return true if a nickname is valid
648 * @param n A nickname to verify
649 * @return True if the nick is valid
651 caller2<bool, const char*, size_t> IsNick;
653 /** Return true if an ident is valid
654 * @param An ident to verify
655 * @return True if the ident is valid
657 caller1<bool, const char*> IsIdent;
659 /** Add a dns Resolver class to this server's active set
660 * @param r The resolver to add
661 * @param cached If this value is true, then the cache will
662 * be searched for the DNS result, immediately. If the value is
663 * false, then a request will be sent to the nameserver, and the
664 * result will not be immediately available. You should usually
665 * use the boolean value which you passed to the Resolver
666 * constructor, which Resolver will set appropriately depending
667 * on if cached results are available and haven't expired. It is
668 * however safe to force this value to false, forcing a remote DNS
669 * lookup, but not an update of the cache.
670 * @return True if the operation completed successfully. Note that
671 * if this method returns true, you should not attempt to access
672 * the resolver class you pass it after this call, as depending upon
673 * the request given, the object may be deleted!
675 bool AddResolver(Resolver* r, bool cached);
677 /** Add a command to this server's command parser
678 * @param f A Command command handler object to add
679 * @throw ModuleException Will throw ModuleExcption if the command already exists
681 void AddCommand(Command *f);
683 /** Send a modechange.
684 * The parameters provided are identical to that sent to the
685 * handler for class cmd_mode.
686 * @param parameters The mode parameters
687 * @param user The user to send error messages to
689 void SendMode(const std::vector<std::string>& parameters, User *user);
691 /** Match two strings using pattern matching, optionally, with a map
692 * to check case against (may be NULL). If map is null, match will be case insensitive.
693 * @param str The literal string to match against
694 * @param mask The glob pattern to match against.
696 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
697 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
699 /** Match two strings using pattern matching, optionally, with a map
700 * to check case against (may be NULL). If map is null, match will be case insensitive.
701 * Supports CIDR patterns as well as globs.
702 * @param str The literal string to match against
703 * @param mask The glob or CIDR pattern to match against.
705 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
706 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
708 /** Call the handler for a given command.
709 * @param commandname The command whos handler you wish to call
710 * @param parameters The mode parameters
711 * @param pcnt The number of items you have given in the first parameter
712 * @param user The user to execute the command as
713 * @return True if the command handler was called successfully
715 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
717 /** Return true if the command is a module-implemented command and the given parameters are valid for it
718 * @param parameters The mode parameters
719 * @param pcnt The number of items you have given in the first parameter
720 * @param user The user to test-execute the command as
721 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
723 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
725 /** Return true if the given parameter is a valid nick!user\@host mask
726 * @param mask A nick!user\@host masak to match against
727 * @return True i the mask is valid
729 bool IsValidMask(const std::string &mask);
731 /** Rehash the local server
735 /** Dump text to a user target, splitting it appropriately to fit
736 * @param User the user to dump the text to
737 * @param LinePrefix text to prefix each complete line with
738 * @param TextStream the text to send to the user
740 void DumpText(User* user, const std::string &LinePrefix, std::stringstream &TextStream);
742 /** Dump text to a user target (local or remote)
743 * @param user the user to dump the text to
744 * @param text the full line of text
746 void DumpText(User* user, const std::string &text);
748 /** Dump text to a user target (local or remote)
749 * @param user the user to dump the text to
750 * @param format the printf format string for the text to send
752 void DumpText(User* user, const char* format, ...) CUSTOM_PRINTF(3, 4);
754 /** Check if the given nickmask matches too many users, send errors to the given user
755 * @param nick A nickmask to match against
756 * @param user A user to send error text to
757 * @return True if the nick matches too many users
759 bool NickMatchesEveryone(const std::string &nick, User* user);
761 /** Check if the given IP mask matches too many users, send errors to the given user
762 * @param ip An ipmask to match against
763 * @param user A user to send error text to
764 * @return True if the ip matches too many users
766 bool IPMatchesEveryone(const std::string &ip, User* user);
768 /** Check if the given hostmask matches too many users, send errors to the given user
769 * @param mask A hostmask to match against
770 * @param user A user to send error text to
771 * @return True if the host matches too many users
773 bool HostMatchesEveryone(const std::string &mask, User* user);
775 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
776 * @param str A string containing a time in the form 1y2w3d4h6m5s
777 * (one year, two weeks, three days, four hours, six minutes and five seconds)
778 * @return The total number of seconds
780 long Duration(const std::string &str);
782 /** Attempt to compare a password to a string from the config file.
783 * This will be passed to handling modules which will compare the data
784 * against possible hashed equivalents in the input string.
785 * @param ex The object (user, server, whatever) causing the comparison.
786 * @param data The data from the config file
787 * @param input The data input by the oper
788 * @param hashtype The hash from the config file
789 * @return 0 if the strings match, 1 or -1 if they do not
791 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
793 /** Check if a given server is a uline.
794 * An empty string returns true, this is by design.
795 * @param server The server to check for uline status
796 * @return True if the server is a uline OR the string is empty
798 bool ULine(const std::string& server);
800 /** Returns true if the uline is 'silent' (doesnt generate
801 * remote connect notices etc).
803 bool SilentULine(const std::string& server);
805 /** Returns the subversion revision ID of this ircd
806 * @return The revision ID or an empty string
808 std::string GetRevision();
810 /** Returns the full version string of this ircd
811 * @return The version string
813 std::string GetVersionString();
815 /** Attempt to write the process id to a given file
816 * @param filename The PID file to attempt to write to
817 * @return This function may bail if the file cannot be written
819 void WritePID(const std::string &filename);
821 /** This constructor initialises all the subsystems and reads the config file.
822 * @param argc The argument count passed to main()
823 * @param argv The argument list passed to main()
824 * @throw <anything> If anything is thrown from here and makes it to
825 * you, you should probably just give up and go home. Yes, really.
826 * It's that bad. Higher level classes should catch any non-fatal exceptions.
828 InspIRCd(int argc, char** argv);
830 /** Send a line of WHOIS data to a user.
831 * @param user user to send the line to
832 * @param dest user being WHOISed
833 * @param numeric Numeric to send
834 * @param text Text of the numeric
836 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
838 /** Send a line of WHOIS data to a user.
839 * @param user user to send the line to
840 * @param dest user being WHOISed
841 * @param numeric Numeric to send
842 * @param format Format string for the numeric
843 * @param ... Parameters for the format string
845 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
849 void DoStats(char statschar, User* user, string_list &results);
853 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
855 /** Quit a user for excess flood, and if they are not
856 * fully registered yet, temporarily zline their IP.
857 * @param current user to quit
859 caller1<void, User*> FloodQuitUser;
861 /** Restart the server.
862 * This function will not return. If an error occurs,
863 * it will throw an instance of CoreException.
864 * @param reason The restart reason to show to all clients
865 * @throw CoreException An instance of CoreException indicating the error from execv().
867 void Restart(const std::string &reason);
869 /** Prepare the ircd for restart or shutdown.
870 * This function unloads all modules which can be unloaded,
871 * closes all open sockets, and closes the logfile.
875 /** This copies the user and channel hash_maps into new hash maps.
876 * This frees memory used by the hash_map allocator (which it neglects
877 * to free, most of the time, using tons of ram)
879 void RehashUsersAndChans();
881 /** Resets the cached max bans value on all channels.
886 /** Return a time_t as a human-readable string.
888 std::string TimeString(time_t curtime);
890 /** Begin execution of the server.
891 * NOTE: this function NEVER returns. Internally,
892 * it will repeatedly loop.
893 * @return The return value for this function is undefined.
897 /** Adds an extban char to the 005 token.
899 void AddExtBanChar(char c);
901 char* GetReadBuffer()
903 return this->ReadBuffer;
910 class CommandModule : public Module
914 CommandModule() : cmd(this)
916 ServerInstance->AddCommand(&cmd);
921 return Version(cmd.command, VF_VENDOR|VF_CORE);