1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 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 */
29 #define CUSTOM_PRINTF(STRING, FIRST) __attribute__((format(printf, STRING, FIRST)))
31 #define CUSTOM_PRINTF(STRING, FIRST)
34 // Required system headers.
41 #include "inspircd_config.h"
49 #include "usermanager.h"
52 #include "command_parse.h"
54 #include "socketengine.h"
56 #include "cull_list.h"
57 #include "filelogger.h"
60 #include "configreader.h"
61 #include "inspstring.h"
65 * Used to define the maximum number of parameters a command may have.
67 #define MAXPARAMETERS 127
69 /** Returned by some functions to indicate failure.
73 /** Support for librodent -
74 * see http://www.chatspike.net/index.php?z=64
76 #define ETIREDHAMSTERS EAGAIN
78 /** Template function to convert any input type to std::string
80 template<typename T> inline std::string ConvNumeric(const T &in)
82 if (in == 0) return "0";
87 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
94 std::reverse(res,out);
98 /** Template function to convert any input type to std::string
100 inline std::string ConvToStr(const int in)
102 return ConvNumeric(in);
105 /** Template function to convert any input type to std::string
107 inline std::string ConvToStr(const long in)
109 return ConvNumeric(in);
112 /** Template function to convert any input type to std::string
114 inline std::string ConvToStr(const char* in)
119 /** Template function to convert any input type to std::string
121 inline std::string ConvToStr(const bool in)
123 return (in ? "1" : "0");
126 /** Template function to convert any input type to std::string
128 inline std::string ConvToStr(char in)
130 return std::string(in,1);
133 /** Template function to convert any input type to std::string
135 template <class T> inline std::string ConvToStr(const T &in)
137 std::stringstream tmp;
138 if (!(tmp << in)) return std::string();
142 /** Template function to convert any input type to any other type
143 * (usually an integer or numeric type)
145 template<typename T> inline long ConvToInt(const T &in)
147 std::stringstream tmp;
148 if (!(tmp << in)) return 0;
149 return atoi(tmp.str().c_str());
152 template<typename CharT, typename TraitsT, std::size_t N>
153 static inline bool operator == (std::basic_string<CharT, TraitsT> const &lhs, char const (&rhs)[N])
155 return lhs.length() == N - 1 && !std::memcmp(lhs.data(), rhs, N - 1);
158 template<typename CharT, typename TraitsT, std::size_t N>
159 static inline bool operator != (std::basic_string<CharT, TraitsT> const &lhs, char const (&rhs)[N])
161 return !(lhs == rhs);
164 /** Template function to convert integer to char, storing result in *res and
165 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
166 * @param T input value
167 * @param V result value
168 * @param R base to convert to
170 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
172 if (base < 2 || base > 16) { *res = 0; return res; }
176 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
180 if ( in < 0 && base == 10) *out++ = '-';
181 std::reverse( res, out );
186 /** This class contains various STATS counters
187 * It is used by the InspIRCd class, which internally
188 * has an instance of it.
190 class serverstats : public classbase
193 /** Number of accepted connections
195 unsigned long statsAccept;
196 /** Number of failed accepts
198 unsigned long statsRefused;
199 /** Number of unknown commands seen
201 unsigned long statsUnknown;
202 /** Number of nickname collisions handled
204 unsigned long statsCollisions;
205 /** Number of DNS queries sent out
207 unsigned long statsDns;
208 /** Number of good DNS replies received
209 * NOTE: This may not tally to the number sent out,
210 * due to timeouts and other latency issues.
212 unsigned long statsDnsGood;
213 /** Number of bad (negative) DNS replies received
214 * NOTE: This may not tally to the number sent out,
215 * due to timeouts and other latency issues.
217 unsigned long statsDnsBad;
218 /** Number of inbound connections seen
220 unsigned long statsConnects;
221 /** Total bytes of data transmitted
224 /** Total bytes of data received
227 /** Cpu usage at last sample
230 /** Time last sample was read
233 /** The constructor initializes all the counts to zero
236 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
237 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
242 /** A list of failed port bindings, used for informational purposes on startup */
243 typedef std::vector<std::pair<std::string, long> > FailedPortList;
247 DEFINE_HANDLER1(ProcessUserHandler, void, User*);
248 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
249 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
250 DEFINE_HANDLER1(FindDescriptorHandler, User*, int);
251 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
252 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
253 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
254 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
256 /* Forward declaration - required */
258 class BanCacheManager;
260 class CoreExport ConfigReaderThread : public Thread
262 InspIRCd* ServerInstance;
266 ConfigReaderThread(InspIRCd* Instance, bool bail, User* user) : Thread(), ServerInstance(Instance), do_bail(bail), TheUser(user)
270 virtual ~ConfigReaderThread()
277 /** The main class of the irc server.
278 * This class contains instances of all the other classes
279 * in this software, with the exception of the base class,
280 * classbase. Amongst other things, it contains a ModeParser,
281 * a DNS object, a CommandParser object, and a list of active
282 * Module objects, and facilities for Module objects to
283 * interact with the core system it implements. You should
284 * NEVER attempt to instantiate a class of type InspIRCd
285 * yourself. If you do, this is equivalent to spawning a second
286 * IRC server, and could have catastrophic consequences for the
287 * program in terms of ram usage (basically, you could create
288 * an obese forkbomb built from recursively spawning irc servers!)
290 class CoreExport InspIRCd : public classbase
293 /** Holds the current UID. Used to generate the next one.
295 char current_uid[UUID_LENGTH];
297 /** Set up the signal handlers
301 /** Daemonize the ircd and close standard input/output streams
302 * @return True if the program daemonized succesfully
306 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
307 * @param TIME the current time
309 void DoSocketTimeouts(time_t TIME);
311 /** Increments the current UID by one.
313 void IncrementUID(int pos);
315 /** Perform background user events such as PING checks
317 void DoBackgroundUserStuff();
319 /** Returns true when all modules have done pre-registration checks on a user
320 * @param user The user to verify
321 * @return True if all modules have finished checking this user
323 bool AllModulesReportReady(User* user);
325 /** Logfile pathname specified on the commandline, or empty string
327 char LogFileName[MAXBUF];
329 /** The current time, updated in the mainloop
333 /** The time that was recorded last time around the mainloop
337 /** A 64k buffer used to read client lines into
339 char ReadBuffer[65535];
341 /** Used when connecting clients
343 irc::sockets::insp_sockaddr client, server;
345 /** Used when connecting clients
355 /** Global cull list, will be processed on next iteration
357 CullList GlobalCulls;
361 ProcessUserHandler HandleProcessUser;
362 IsNickHandler HandleIsNick;
363 IsIdentHandler HandleIsIdent;
364 FindDescriptorHandler HandleFindDescriptor;
365 FloodQuitUserHandler HandleFloodQuitUser;
366 IsChannelHandler HandleIsChannel;
367 IsSIDHandler HandleIsSID;
368 RehashHandler HandleRehash;
370 /** BufferedSocket classes pending deletion after being closed.
371 * We don't delete these immediately as this may cause a segmentation fault.
373 std::map<BufferedSocket*,BufferedSocket*> SocketCull;
375 /** 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
378 * SendMode expects a User* to send the numeric replies
379 * back to, so we create it a fake user that isnt in the user
380 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
381 * falls into the abyss :p
385 /** Returns the next available UID for this server.
387 std::string GetUID();
389 /** Find a user in the UUID hash
390 * @param nick The nickname to find
391 * @return A pointer to the user, or NULL if the user does not exist
393 User *FindUUID(const std::string &);
395 /** Find a user in the UUID hash
396 * @param nick The nickname to find
397 * @return A pointer to the user, or NULL if the user does not exist
399 User *FindUUID(const char *);
401 /** Build the ISUPPORT string by triggering all modules On005Numeric events
403 void BuildISupport();
405 /** List of server names we've seen.
407 servernamelist servernames;
409 /** Time this ircd was booted
413 /** Config file pathname specified on the commandline or via ./configure
415 char ConfigFileName[MAXBUF];
417 /** Mode handler, handles mode setting and removal
421 /** Command parser, handles client to server commands
423 CommandParser* Parser;
425 /** Socket engine, handles socket activity events
429 /** Thread engine, Handles threading where required
431 ThreadEngine* Threads;
433 /** The thread/class used to read config files in REHASH and on startup
435 ConfigReaderThread* ConfigThread;
437 /** LogManager handles logging.
441 /** ModuleManager contains everything related to loading/unloading
444 ModuleManager* Modules;
446 /** BanCacheManager is used to speed up checking of restrictions on connection
449 BanCacheManager *BanCache;
451 /** Stats class, holds miscellaneous stats counters
455 /** Server Config class, holds configuration file data
457 ServerConfig* Config;
459 /** Snomask manager - handles routing of snomask messages
464 /** DNS class, provides resolver facilities to the core and modules
468 /** Timer manager class, triggers Timer timer events
470 TimerManager* Timers;
472 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
474 XLineManager* XLines;
476 /** User manager. Various methods and data associated with users.
480 /** Channel list, a hash_map containing all channels XXX move to channel manager class
484 /** Set to the current signal recieved
488 /** Protocol interface, overridden by server protocol modules
490 ProtocolInterface* PI;
492 /** Get the current time
493 * Because this only calls time() once every time around the mainloop,
494 * it is much faster than calling time() directly.
495 * @return The current time as an epoch value (time_t)
499 /** Process a user whos socket has been flagged as active
500 * @param cu The user to process
501 * @return There is no actual return value, however upon exit, the user 'cu' may have been
502 * marked for deletion in the global CullList.
504 caller1<void, User*> ProcessUser;
506 /** Bind all ports specified in the configuration file.
507 * @param bail True if the function should bail back to the shell on failure
508 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
509 * @return The number of ports actually bound without error
511 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
513 /** Binds a socket on an already open file descriptor
514 * @param sockfd A valid file descriptor of an open socket
515 * @param port The port number to bind to
516 * @param addr The address to bind to (IP only)
517 * @return True if the port was bound successfully
519 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
521 /** Adds a server name to the list of servers we've seen
522 * @param The servername to add
524 void AddServerName(const std::string &servername);
526 /** Finds a cached char* pointer of a server name,
527 * This is used to optimize User by storing only the pointer to the name
528 * @param The servername to find
529 * @return A pointer to this name, gauranteed to never become invalid
531 const char* FindServerNamePtr(const std::string &servername);
533 /** Returns true if we've seen the given server name before
534 * @param The servername to find
535 * @return True if we've seen this server name before
537 bool FindServerName(const std::string &servername);
539 /** Gets the GECOS (description) field of the given server.
540 * If the servername is not that of the local server, the name
541 * is passed to handling modules which will attempt to determine
542 * the GECOS that bleongs to the given servername.
543 * @param servername The servername to find the description of
544 * @return The description of this server, or of the local server
546 std::string GetServerDescription(const char* servername);
548 /** Find a user in the nick hash.
549 * If the user cant be found in the nick hash check the uuid hash
550 * @param nick The nickname to find
551 * @return A pointer to the user, or NULL if the user does not exist
553 User* FindNick(const std::string &nick);
555 /** Find a user in the nick hash.
556 * If the user cant be found in the nick hash check the uuid hash
557 * @param nick The nickname to find
558 * @return A pointer to the user, or NULL if the user does not exist
560 User* FindNick(const char* nick);
562 /** Find a user in the nick hash ONLY
564 User* FindNickOnly(const char* nick);
566 /** Find a user in the nick hash ONLY
568 User* FindNickOnly(const std::string &nick);
570 /** Find a channel in the channels hash
571 * @param chan The channel to find
572 * @return A pointer to the channel, or NULL if the channel does not exist
574 Channel* FindChan(const std::string &chan);
576 /** Find a channel in the channels hash
577 * @param chan The channel to find
578 * @return A pointer to the channel, or NULL if the channel does not exist
580 Channel* FindChan(const char* chan);
582 /** Check for a 'die' tag in the config file, and abort if found
583 * @return Depending on the configuration, this function may never return
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 /** Find a username by their file descriptor.
660 * It is preferred to use this over directly accessing the fd_ref_table array.
661 * @param socket The file descriptor of a user
662 * @return A pointer to the user if the user exists locally on this descriptor
664 caller1<User*, int> FindDescriptor;
666 /** Add a dns Resolver class to this server's active set
667 * @param r The resolver to add
668 * @param cached If this value is true, then the cache will
669 * be searched for the DNS result, immediately. If the value is
670 * false, then a request will be sent to the nameserver, and the
671 * result will not be immediately available. You should usually
672 * use the boolean value which you passed to the Resolver
673 * constructor, which Resolver will set appropriately depending
674 * on if cached results are available and haven't expired. It is
675 * however safe to force this value to false, forcing a remote DNS
676 * lookup, but not an update of the cache.
677 * @return True if the operation completed successfully. Note that
678 * if this method returns true, you should not attempt to access
679 * the resolver class you pass it after this call, as depending upon
680 * the request given, the object may be deleted!
682 bool AddResolver(Resolver* r, bool cached);
684 /** Add a command to this server's command parser
685 * @param f A Command command handler object to add
686 * @throw ModuleException Will throw ModuleExcption if the command already exists
688 void AddCommand(Command *f);
690 /** Send a modechange.
691 * The parameters provided are identical to that sent to the
692 * handler for class cmd_mode.
693 * @param parameters The mode parameters
694 * @param pcnt The number of items you have given in the first parameter
695 * @param user The user to send error messages to
697 void SendMode(const std::vector<std::string>& parameters, User *user);
699 /** Match two strings using pattern matching.
700 * This operates identically to the global function match(),
701 * except for that it takes std::string arguments rather than
703 * @param sliteral The literal string to match against
704 * @param spattern The pattern to match against. CIDR and globs are supported.
706 bool MatchText(const std::string &sliteral, const std::string &spattern);
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 /** Return the channel whos index number matches that provided
736 * @param The index number of the channel to fetch
737 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
739 Channel* GetChannelIndex(long index);
741 /** Dump text to a user target, splitting it appropriately to fit
742 * @param User the user to dump the text to
743 * @param LinePrefix text to prefix each complete line with
744 * @param TextStream the text to send to the user
746 void DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream);
748 /** Check if the given nickmask matches too many users, send errors to the given user
749 * @param nick A nickmask to match against
750 * @param user A user to send error text to
751 * @return True if the nick matches too many users
753 bool NickMatchesEveryone(const std::string &nick, User* user);
755 /** Check if the given IP mask matches too many users, send errors to the given user
756 * @param ip An ipmask to match against
757 * @param user A user to send error text to
758 * @return True if the ip matches too many users
760 bool IPMatchesEveryone(const std::string &ip, User* user);
762 /** Check if the given hostmask matches too many users, send errors to the given user
763 * @param mask A hostmask to match against
764 * @param user A user to send error text to
765 * @return True if the host matches too many users
767 bool HostMatchesEveryone(const std::string &mask, User* user);
769 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
770 * @param str A string containing a time in the form 1y2w3d4h6m5s
771 * (one year, two weeks, three days, four hours, six minutes and five seconds)
772 * @return The total number of seconds
774 long Duration(const std::string &str);
776 /** Attempt to compare a password to a string from the config file.
777 * This will be passed to handling modules which will compare the data
778 * against possible hashed equivalents in the input string.
779 * @param ex The object (user, server, whatever) causing the comparison.
780 * @param data The data from the config file
781 * @param input The data input by the oper
782 * @param hashtype The hash from the config file
783 * @return 0 if the strings match, 1 or -1 if they do not
785 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
787 /** Check if a given server is a uline.
788 * An empty string returns true, this is by design.
789 * @param server The server to check for uline status
790 * @return True if the server is a uline OR the string is empty
792 bool ULine(const char* server);
794 /** Returns true if the uline is 'silent' (doesnt generate
795 * remote connect notices etc).
797 bool SilentULine(const char* server);
799 /** Returns the subversion revision ID of this ircd
800 * @return The revision ID or an empty string
802 std::string GetRevision();
804 /** Returns the full version string of this ircd
805 * @return The version string
807 std::string GetVersionString();
809 /** Attempt to write the process id to a given file
810 * @param filename The PID file to attempt to write to
811 * @return This function may bail if the file cannot be written
813 void WritePID(const std::string &filename);
815 /** This constructor initialises all the subsystems and reads the config file.
816 * @param argc The argument count passed to main()
817 * @param argv The argument list passed to main()
818 * @throw <anything> If anything is thrown from here and makes it to
819 * you, you should probably just give up and go home. Yes, really.
820 * It's that bad. Higher level classes should catch any non-fatal exceptions.
822 InspIRCd(int argc, char** argv);
824 /** Send a line of WHOIS data to a user.
825 * @param user user to send the line to
826 * @param dest user being WHOISed
827 * @param numeric Numeric to send
828 * @param text Text of the numeric
830 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
832 /** Send a line of WHOIS data to a user.
833 * @param user user to send the line to
834 * @param dest user being WHOISed
835 * @param numeric Numeric to send
836 * @param format Format string for the numeric
837 * @param ... Parameters for the format string
839 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
841 /** Quit a user for excess flood, and if they are not
842 * fully registered yet, temporarily zline their IP.
843 * @param current user to quit
845 caller1<void, User*> FloodQuitUser;
847 /** Restart the server.
848 * This function will not return. If an error occurs,
849 * it will throw an instance of CoreException.
850 * @param reason The restart reason to show to all clients
851 * @throw CoreException An instance of CoreException indicating the error from execv().
853 void Restart(const std::string &reason);
855 /** Prepare the ircd for restart or shutdown.
856 * This function unloads all modules which can be unloaded,
857 * closes all open sockets, and closes the logfile.
861 /** This copies the user and channel hash_maps into new hash maps.
862 * This frees memory used by the hash_map allocator (which it neglects
863 * to free, most of the time, using tons of ram)
865 void RehashUsersAndChans();
867 /** Resets the cached max bans value on all channels.
872 /** Return a time_t as a human-readable string.
874 std::string TimeString(time_t curtime);
876 /** Begin execution of the server.
877 * NOTE: this function NEVER returns. Internally,
878 * it will repeatedly loop.
879 * @return The return value for this function is undefined.
883 /** Force all BufferedSockets to be removed which are due to
886 void BufferedSocketCull();
888 char* GetReadBuffer()
890 return this->ReadBuffer;