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.
38 #include "inspircd_config.h"
46 #include "usermanager.h"
49 #include "command_parse.h"
51 #include "socketengine.h"
53 #include "cull_list.h"
54 #include "filelogger.h"
57 #include "configreader.h"
58 #include "inspstring.h"
62 * Used to define the maximum number of parameters a command may have.
64 #define MAXPARAMETERS 127
66 /** Returned by some functions to indicate failure.
70 /** Support for librodent -
71 * see http://www.chatspike.net/index.php?z=64
73 #define ETIREDHAMSTERS EAGAIN
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 char* in)
116 /** Template function to convert any input type to std::string
118 inline std::string ConvToStr(const bool in)
120 return (in ? "1" : "0");
123 /** Template function to convert any input type to std::string
125 inline std::string ConvToStr(char in)
127 return std::string(in,1);
130 /** Template function to convert any input type to std::string
132 template <class T> inline std::string ConvToStr(const T &in)
134 std::stringstream tmp;
135 if (!(tmp << in)) return std::string();
139 /** Template function to convert any input type to any other type
140 * (usually an integer or numeric type)
142 template<typename T> inline long ConvToInt(const T &in)
144 std::stringstream tmp;
145 if (!(tmp << in)) return 0;
146 return atoi(tmp.str().c_str());
149 /** Template function to convert integer to char, storing result in *res and
150 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
151 * @param T input value
152 * @param V result value
153 * @param R base to convert to
155 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
157 if (base < 2 || base > 16) { *res = 0; return res; }
161 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
165 if ( in < 0 && base == 10) *out++ = '-';
166 std::reverse( res, out );
171 /** This class contains various STATS counters
172 * It is used by the InspIRCd class, which internally
173 * has an instance of it.
175 class serverstats : public classbase
178 /** Number of accepted connections
180 unsigned long statsAccept;
181 /** Number of failed accepts
183 unsigned long statsRefused;
184 /** Number of unknown commands seen
186 unsigned long statsUnknown;
187 /** Number of nickname collisions handled
189 unsigned long statsCollisions;
190 /** Number of DNS queries sent out
192 unsigned long statsDns;
193 /** Number of good DNS replies received
194 * NOTE: This may not tally to the number sent out,
195 * due to timeouts and other latency issues.
197 unsigned long statsDnsGood;
198 /** Number of bad (negative) DNS replies received
199 * NOTE: This may not tally to the number sent out,
200 * due to timeouts and other latency issues.
202 unsigned long statsDnsBad;
203 /** Number of inbound connections seen
205 unsigned long statsConnects;
206 /** Total bytes of data transmitted
209 /** Total bytes of data received
212 /** Cpu usage at last sample
215 /** Time last sample was read
218 /** The constructor initializes all the counts to zero
221 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
222 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
227 /** A list of failed port bindings, used for informational purposes on startup */
228 typedef std::vector<std::pair<std::string, long> > FailedPortList;
232 DEFINE_HANDLER1(ProcessUserHandler, void, User*);
233 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
234 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
235 DEFINE_HANDLER1(FindDescriptorHandler, User*, int);
236 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
238 /* Forward declaration - required */
240 class BanCacheManager;
242 class CoreExport ConfigReaderThread : public Thread
244 InspIRCd* ServerInstance;
248 ConfigReaderThread(InspIRCd* Instance, bool bail, User* user) : Thread(), ServerInstance(Instance), do_bail(bail), TheUser(user)
252 virtual ~ConfigReaderThread()
259 /** The main class of the irc server.
260 * This class contains instances of all the other classes
261 * in this software, with the exception of the base class,
262 * classbase. Amongst other things, it contains a ModeParser,
263 * a DNS object, a CommandParser object, and a list of active
264 * Module objects, and facilities for Module objects to
265 * interact with the core system it implements. You should
266 * NEVER attempt to instantiate a class of type InspIRCd
267 * yourself. If you do, this is equivalent to spawning a second
268 * IRC server, and could have catastrophic consequences for the
269 * program in terms of ram usage (basically, you could create
270 * an obese forkbomb built from recursively spawning irc servers!)
272 class CoreExport InspIRCd : public classbase
275 /** Holds the current UID. Used to generate the next one.
277 char current_uid[UUID_LENGTH];
279 /** Set up the signal handlers
283 /** Daemonize the ircd and close standard input/output streams
284 * @return True if the program daemonized succesfully
288 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
289 * @param TIME the current time
291 void DoSocketTimeouts(time_t TIME);
293 /** Increments the current UID by one.
295 void IncrementUID(int pos);
297 /** Perform background user events such as PING checks
299 void DoBackgroundUserStuff();
301 /** Returns true when all modules have done pre-registration checks on a user
302 * @param user The user to verify
303 * @return True if all modules have finished checking this user
305 bool AllModulesReportReady(User* user);
307 /** Logfile pathname specified on the commandline, or empty string
309 char LogFileName[MAXBUF];
311 /** The current time, updated in the mainloop
315 /** The time that was recorded last time around the mainloop
319 /** A 64k buffer used to read client lines into
321 char ReadBuffer[65535];
323 /** Used when connecting clients
325 irc::sockets::insp_sockaddr client, server;
327 /** Used when connecting clients
337 /** Global cull list, will be processed on next iteration
339 CullList GlobalCulls;
343 ProcessUserHandler HandleProcessUser;
344 IsNickHandler HandleIsNick;
345 IsIdentHandler HandleIsIdent;
346 FindDescriptorHandler HandleFindDescriptor;
347 FloodQuitUserHandler HandleFloodQuitUser;
349 /** BufferedSocket classes pending deletion after being closed.
350 * We don't delete these immediately as this may cause a segmentation fault.
352 std::map<BufferedSocket*,BufferedSocket*> SocketCull;
354 /** 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
357 * SendMode expects a User* to send the numeric replies
358 * back to, so we create it a fake user that isnt in the user
359 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
360 * falls into the abyss :p
364 /** Returns the next available UID for this server.
366 std::string GetUID();
368 /** Find a user in the UUID hash
369 * @param nick The nickname to find
370 * @return A pointer to the user, or NULL if the user does not exist
372 User *FindUUID(const std::string &);
374 /** Find a user in the UUID hash
375 * @param nick The nickname to find
376 * @return A pointer to the user, or NULL if the user does not exist
378 User *FindUUID(const char *);
380 /** Build the ISUPPORT string by triggering all modules On005Numeric events
382 void BuildISupport();
384 /** List of server names we've seen.
386 servernamelist servernames;
388 /** Time this ircd was booted
392 /** Config file pathname specified on the commandline or via ./configure
394 char ConfigFileName[MAXBUF];
396 /** Mode handler, handles mode setting and removal
400 /** Command parser, handles client to server commands
402 CommandParser* Parser;
404 /** Socket engine, handles socket activity events
408 /** Thread engine, Handles threading where required
410 ThreadEngine* Threads;
412 /** The thread/class used to read config files in REHASH and on startup
414 ConfigReaderThread* ConfigThread;
416 /** LogManager handles logging.
420 /** ModuleManager contains everything related to loading/unloading
423 ModuleManager* Modules;
425 /** BanCacheManager is used to speed up checking of restrictions on connection
428 BanCacheManager *BanCache;
430 /** Stats class, holds miscellaneous stats counters
434 /** Server Config class, holds configuration file data
436 ServerConfig* Config;
438 /** Snomask manager - handles routing of snomask messages
443 /** DNS class, provides resolver facilities to the core and modules
447 /** Timer manager class, triggers Timer timer events
449 TimerManager* Timers;
451 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
453 XLineManager* XLines;
455 /** User manager. Various methods and data associated with users.
459 /** Channel list, a hash_map containing all channels XXX move to channel manager class
463 /** Set to the current signal recieved
467 /** Protocol interface, overridden by server protocol modules
469 ProtocolInterface* PI;
471 /** Get the current time
472 * Because this only calls time() once every time around the mainloop,
473 * it is much faster than calling time() directly.
474 * @return The current time as an epoch value (time_t)
478 /** Process a user whos socket has been flagged as active
479 * @param cu The user to process
480 * @return There is no actual return value, however upon exit, the user 'cu' may have been
481 * marked for deletion in the global CullList.
483 caller1<void, User*> ProcessUser;
485 /** Bind all ports specified in the configuration file.
486 * @param bail True if the function should bail back to the shell on failure
487 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
488 * @return The number of ports actually bound without error
490 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
492 /** Binds a socket on an already open file descriptor
493 * @param sockfd A valid file descriptor of an open socket
494 * @param port The port number to bind to
495 * @param addr The address to bind to (IP only)
496 * @return True if the port was bound successfully
498 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
500 /** Adds a server name to the list of servers we've seen
501 * @param The servername to add
503 void AddServerName(const std::string &servername);
505 /** Finds a cached char* pointer of a server name,
506 * This is used to optimize User by storing only the pointer to the name
507 * @param The servername to find
508 * @return A pointer to this name, gauranteed to never become invalid
510 const char* FindServerNamePtr(const std::string &servername);
512 /** Returns true if we've seen the given server name before
513 * @param The servername to find
514 * @return True if we've seen this server name before
516 bool FindServerName(const std::string &servername);
518 /** Gets the GECOS (description) field of the given server.
519 * If the servername is not that of the local server, the name
520 * is passed to handling modules which will attempt to determine
521 * the GECOS that bleongs to the given servername.
522 * @param servername The servername to find the description of
523 * @return The description of this server, or of the local server
525 std::string GetServerDescription(const char* servername);
527 /** Find a user in the nick hash.
528 * If the user cant be found in the nick hash check the uuid hash
529 * @param nick The nickname to find
530 * @return A pointer to the user, or NULL if the user does not exist
532 User* FindNick(const std::string &nick);
534 /** Find a user in the nick hash.
535 * If the user cant be found in the nick hash check the uuid hash
536 * @param nick The nickname to find
537 * @return A pointer to the user, or NULL if the user does not exist
539 User* FindNick(const char* nick);
541 /** Find a user in the nick hash ONLY
543 User* FindNickOnly(const char* nick);
545 /** Find a user in the nick hash ONLY
547 User* FindNickOnly(const std::string &nick);
549 /** Find a channel in the channels hash
550 * @param chan The channel to find
551 * @return A pointer to the channel, or NULL if the channel does not exist
553 Channel* FindChan(const std::string &chan);
555 /** Find a channel in the channels hash
556 * @param chan The channel to find
557 * @return A pointer to the channel, or NULL if the channel does not exist
559 Channel* FindChan(const char* chan);
561 /** Check for a 'die' tag in the config file, and abort if found
562 * @return Depending on the configuration, this function may never return
566 /** Check we aren't running as root, and exit if we are
567 * @return Depending on the configuration, this function may never return
571 /** Determine the right path for, and open, the logfile
572 * @param argv The argv passed to main() initially, used to calculate program path
573 * @param argc The argc passed to main() initially, used to calculate program path
574 * @return True if the log could be opened, false if otherwise
576 bool OpenLog(char** argv, int argc);
578 /** Return true if a channel name is valid
579 * @param chname A channel name to verify
580 * @return True if the name is valid
582 bool IsChannel(const char *chname);
584 /** Return true if str looks like a server ID
585 * @param string to check against
587 bool IsSID(const std::string &str);
589 /** Rehash the local server
593 /** Handles incoming signals after being set
594 * @param signal the signal recieved
596 void SignalHandler(int signal);
598 /** Sets the signal recieved
599 * @param signal the signal recieved
601 static void SetSignal(int signal);
603 /** Causes the server to exit after unloading modules and
604 * closing all open file descriptors.
606 * @param The exit code to give to the operating system
607 * (See the ExitStatus enum for valid values)
609 void Exit(int status);
611 /** Causes the server to exit immediately with exit code 0.
612 * The status code is required for signal handlers, and ignored.
614 static void QuickExit(int status);
616 /** Return a count of channels on the network
617 * @return The number of channels
621 /** Send an error notice to all local users, opered and unopered
622 * @param s The error string to send
624 void SendError(const std::string &s);
626 /** Return true if a nickname is valid
627 * @param n A nickname to verify
628 * @return True if the nick is valid
630 caller1<bool, const char*> IsNick;
632 /** Return true if an ident is valid
633 * @param An ident to verify
634 * @return True if the ident is valid
636 caller1<bool, const char*> IsIdent;
638 /** Find a username by their file descriptor.
639 * It is preferred to use this over directly accessing the fd_ref_table array.
640 * @param socket The file descriptor of a user
641 * @return A pointer to the user if the user exists locally on this descriptor
643 caller1<User*, int> FindDescriptor;
645 /** Add a dns Resolver class to this server's active set
646 * @param r The resolver to add
647 * @param cached If this value is true, then the cache will
648 * be searched for the DNS result, immediately. If the value is
649 * false, then a request will be sent to the nameserver, and the
650 * result will not be immediately available. You should usually
651 * use the boolean value which you passed to the Resolver
652 * constructor, which Resolver will set appropriately depending
653 * on if cached results are available and haven't expired. It is
654 * however safe to force this value to false, forcing a remote DNS
655 * lookup, but not an update of the cache.
656 * @return True if the operation completed successfully. Note that
657 * if this method returns true, you should not attempt to access
658 * the resolver class you pass it after this call, as depending upon
659 * the request given, the object may be deleted!
661 bool AddResolver(Resolver* r, bool cached);
663 /** Add a command to this server's command parser
664 * @param f A Command command handler object to add
665 * @throw ModuleException Will throw ModuleExcption if the command already exists
667 void AddCommand(Command *f);
669 /** Send a modechange.
670 * The parameters provided are identical to that sent to the
671 * handler for class cmd_mode.
672 * @param parameters The mode parameters
673 * @param pcnt The number of items you have given in the first parameter
674 * @param user The user to send error messages to
676 void SendMode(const char* const* parameters, int pcnt, User *user);
678 /** Match two strings using pattern matching.
679 * This operates identically to the global function match(),
680 * except for that it takes std::string arguments rather than
682 * @param sliteral The literal string to match against
683 * @param spattern The pattern to match against. CIDR and globs are supported.
685 bool MatchText(const std::string &sliteral, const std::string &spattern);
687 /** Call the handler for a given command.
688 * @param commandname The command whos handler you wish to call
689 * @param parameters The mode parameters
690 * @param pcnt The number of items you have given in the first parameter
691 * @param user The user to execute the command as
692 * @return True if the command handler was called successfully
694 CmdResult CallCommandHandler(const std::string &commandname, const char* const* parameters, int pcnt, User* user);
696 /** Return true if the command is a module-implemented command and the given parameters are valid for it
697 * @param parameters The mode parameters
698 * @param pcnt The number of items you have given in the first parameter
699 * @param user The user to test-execute the command as
700 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
702 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
704 /** Return true if the given parameter is a valid nick!user\@host mask
705 * @param mask A nick!user\@host masak to match against
706 * @return True i the mask is valid
708 bool IsValidMask(const std::string &mask);
710 /** Rehash the local server
714 /** Return the channel whos index number matches that provided
715 * @param The index number of the channel to fetch
716 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
718 Channel* GetChannelIndex(long index);
720 /** Dump text to a user target, splitting it appropriately to fit
721 * @param User the user to dump the text to
722 * @param LinePrefix text to prefix each complete line with
723 * @param TextStream the text to send to the user
725 void DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream);
727 /** Check if the given nickmask matches too many users, send errors to the given user
728 * @param nick A nickmask to match against
729 * @param user A user to send error text to
730 * @return True if the nick matches too many users
732 bool NickMatchesEveryone(const std::string &nick, User* user);
734 /** Check if the given IP mask matches too many users, send errors to the given user
735 * @param ip An ipmask to match against
736 * @param user A user to send error text to
737 * @return True if the ip matches too many users
739 bool IPMatchesEveryone(const std::string &ip, User* user);
741 /** Check if the given hostmask matches too many users, send errors to the given user
742 * @param mask A hostmask to match against
743 * @param user A user to send error text to
744 * @return True if the host matches too many users
746 bool HostMatchesEveryone(const std::string &mask, User* user);
748 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
749 * @param str A string containing a time in the form 1y2w3d4h6m5s
750 * (one year, two weeks, three days, four hours, six minutes and five seconds)
751 * @return The total number of seconds
753 long Duration(const std::string &str);
755 /** Attempt to compare a password to a string from the config file.
756 * This will be passed to handling modules which will compare the data
757 * against possible hashed equivalents in the input string.
758 * @param ex The object (user, server, whatever) causing the comparison.
759 * @param data The data from the config file
760 * @param input The data input by the oper
761 * @param hashtype The hash from the config file
762 * @return 0 if the strings match, 1 or -1 if they do not
764 int PassCompare(Extensible* ex, const char* data,const char* input, const char* hashtype);
766 /** Check if a given server is a uline.
767 * An empty string returns true, this is by design.
768 * @param server The server to check for uline status
769 * @return True if the server is a uline OR the string is empty
771 bool ULine(const char* server);
773 /** Returns true if the uline is 'silent' (doesnt generate
774 * remote connect notices etc).
776 bool SilentULine(const char* server);
778 /** Returns the subversion revision ID of this ircd
779 * @return The revision ID or an empty string
781 std::string GetRevision();
783 /** Returns the full version string of this ircd
784 * @return The version string
786 std::string GetVersionString();
788 /** Attempt to write the process id to a given file
789 * @param filename The PID file to attempt to write to
790 * @return This function may bail if the file cannot be written
792 void WritePID(const std::string &filename);
794 /** This constructor initialises all the subsystems and reads the config file.
795 * @param argc The argument count passed to main()
796 * @param argv The argument list passed to main()
797 * @throw <anything> If anything is thrown from here and makes it to
798 * you, you should probably just give up and go home. Yes, really.
799 * It's that bad. Higher level classes should catch any non-fatal exceptions.
801 InspIRCd(int argc, char** argv);
803 /** Send a line of WHOIS data to a user.
804 * @param user user to send the line to
805 * @param dest user being WHOISed
806 * @param numeric Numeric to send
807 * @param text Text of the numeric
809 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
811 /** Send a line of WHOIS data to a user.
812 * @param user user to send the line to
813 * @param dest user being WHOISed
814 * @param numeric Numeric to send
815 * @param format Format string for the numeric
816 * @param ... Parameters for the format string
818 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
820 /** Quit a user for excess flood, and if they are not
821 * fully registered yet, temporarily zline their IP.
822 * @param current user to quit
824 caller1<void, User*> FloodQuitUser;
826 /** Restart the server.
827 * This function will not return. If an error occurs,
828 * it will throw an instance of CoreException.
829 * @param reason The restart reason to show to all clients
830 * @throw CoreException An instance of CoreException indicating the error from execv().
832 void Restart(const std::string &reason);
834 /** Prepare the ircd for restart or shutdown.
835 * This function unloads all modules which can be unloaded,
836 * closes all open sockets, and closes the logfile.
840 /** This copies the user and channel hash_maps into new hash maps.
841 * This frees memory used by the hash_map allocator (which it neglects
842 * to free, most of the time, using tons of ram)
844 void RehashUsersAndChans();
846 /** Resets the cached max bans value on all channels.
851 /** Return a time_t as a human-readable string.
853 std::string TimeString(time_t curtime);
855 /** Begin execution of the server.
856 * NOTE: this function NEVER returns. Internally,
857 * it will repeatedly loop.
858 * @return The return value for this function is undefined.
862 /** Force all BufferedSockets to be removed which are due to
865 void BufferedSocketCull();
867 char* GetReadBuffer()
869 return this->ReadBuffer;