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"
61 * Used to define the maximum number of parameters a command may have.
63 #define MAXPARAMETERS 127
65 /** Returned by some functions to indicate failure.
69 /** Support for librodent -
70 * see http://www.chatspike.net/index.php?z=64
72 #define ETIREDHAMSTERS EAGAIN
74 /** Template function to convert any input type to std::string
76 template<typename T> inline std::string ConvNumeric(const T &in)
78 if (in == 0) return "0";
83 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
90 std::reverse(res,out);
94 /** Template function to convert any input type to std::string
96 inline std::string ConvToStr(const int in)
98 return ConvNumeric(in);
101 /** Template function to convert any input type to std::string
103 inline std::string ConvToStr(const long in)
105 return ConvNumeric(in);
108 /** Template function to convert any input type to std::string
110 inline std::string ConvToStr(const char* in)
115 /** Template function to convert any input type to std::string
117 inline std::string ConvToStr(const bool in)
119 return (in ? "1" : "0");
122 /** Template function to convert any input type to std::string
124 inline std::string ConvToStr(char in)
126 return std::string(in,1);
129 /** Template function to convert any input type to std::string
131 template <class T> inline std::string ConvToStr(const T &in)
133 std::stringstream tmp;
134 if (!(tmp << in)) return std::string();
138 /** Template function to convert any input type to any other type
139 * (usually an integer or numeric type)
141 template<typename T> inline long ConvToInt(const T &in)
143 std::stringstream tmp;
144 if (!(tmp << in)) return 0;
145 return atoi(tmp.str().c_str());
148 /** Template function to convert integer to char, storing result in *res and
149 * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
150 * @param T input value
151 * @param V result value
152 * @param R base to convert to
154 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
156 if (base < 2 || base > 16) { *res = 0; return res; }
160 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
164 if ( in < 0 && base == 10) *out++ = '-';
165 std::reverse( res, out );
170 /** This class contains various STATS counters
171 * It is used by the InspIRCd class, which internally
172 * has an instance of it.
174 class serverstats : public classbase
177 /** Number of accepted connections
179 unsigned long statsAccept;
180 /** Number of failed accepts
182 unsigned long statsRefused;
183 /** Number of unknown commands seen
185 unsigned long statsUnknown;
186 /** Number of nickname collisions handled
188 unsigned long statsCollisions;
189 /** Number of DNS queries sent out
191 unsigned long statsDns;
192 /** Number of good DNS replies received
193 * NOTE: This may not tally to the number sent out,
194 * due to timeouts and other latency issues.
196 unsigned long statsDnsGood;
197 /** Number of bad (negative) DNS replies received
198 * NOTE: This may not tally to the number sent out,
199 * due to timeouts and other latency issues.
201 unsigned long statsDnsBad;
202 /** Number of inbound connections seen
204 unsigned long statsConnects;
205 /** Total bytes of data transmitted
208 /** Total bytes of data received
211 /** Cpu usage at last sample
214 /** Time last sample was read
217 /** The constructor initializes all the counts to zero
220 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
221 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
226 /** A list of failed port bindings, used for informational purposes on startup */
227 typedef std::vector<std::pair<std::string, long> > FailedPortList;
231 DEFINE_HANDLER1(ProcessUserHandler, void, User*);
232 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
233 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
234 DEFINE_HANDLER1(FindDescriptorHandler, User*, int);
235 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
237 /* Forward declaration - required */
239 class BanCacheManager;
241 class CoreExport ConfigReaderThread : public Thread
243 InspIRCd* ServerInstance;
247 ConfigReaderThread(InspIRCd* Instance, bool bail, User* user) : Thread(), ServerInstance(Instance), do_bail(bail), TheUser(user)
251 virtual ~ConfigReaderThread()
258 /** The main class of the irc server.
259 * This class contains instances of all the other classes
260 * in this software, with the exception of the base class,
261 * classbase. Amongst other things, it contains a ModeParser,
262 * a DNS object, a CommandParser object, and a list of active
263 * Module objects, and facilities for Module objects to
264 * interact with the core system it implements. You should
265 * NEVER attempt to instantiate a class of type InspIRCd
266 * yourself. If you do, this is equivalent to spawning a second
267 * IRC server, and could have catastrophic consequences for the
268 * program in terms of ram usage (basically, you could create
269 * an obese forkbomb built from recursively spawning irc servers!)
271 class CoreExport InspIRCd : public classbase
274 /** Holds the current UID. Used to generate the next one.
276 char current_uid[UUID_LENGTH];
278 /** Set up the signal handlers
282 /** Daemonize the ircd and close standard input/output streams
283 * @return True if the program daemonized succesfully
287 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
288 * @param TIME the current time
290 void DoSocketTimeouts(time_t TIME);
292 /** Increments the current UID by one.
294 void IncrementUID(int pos);
296 /** Perform background user events such as PING checks
298 void DoBackgroundUserStuff();
300 /** Returns true when all modules have done pre-registration checks on a user
301 * @param user The user to verify
302 * @return True if all modules have finished checking this user
304 bool AllModulesReportReady(User* user);
306 /** Logfile pathname specified on the commandline, or empty string
308 char LogFileName[MAXBUF];
310 /** The current time, updated in the mainloop
314 /** The time that was recorded last time around the mainloop
318 /** A 64k buffer used to read client lines into
320 char ReadBuffer[65535];
322 /** Used when connecting clients
324 irc::sockets::insp_sockaddr client, server;
326 /** Used when connecting clients
336 /** Global cull list, will be processed on next iteration
338 CullList GlobalCulls;
342 ProcessUserHandler HandleProcessUser;
343 IsNickHandler HandleIsNick;
344 IsIdentHandler HandleIsIdent;
345 FindDescriptorHandler HandleFindDescriptor;
346 FloodQuitUserHandler HandleFloodQuitUser;
348 /** BufferedSocket classes pending deletion after being closed.
349 * We don't delete these immediately as this may cause a segmentation fault.
351 std::map<BufferedSocket*,BufferedSocket*> SocketCull;
353 /** 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
356 * SendMode expects a User* to send the numeric replies
357 * back to, so we create it a fake user that isnt in the user
358 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
359 * falls into the abyss :p
363 /** Returns the next available UID for this server.
365 std::string GetUID();
367 /** Find a user in the UUID hash
368 * @param nick The nickname to find
369 * @return A pointer to the user, or NULL if the user does not exist
371 User *FindUUID(const std::string &);
373 /** Find a user in the UUID hash
374 * @param nick The nickname to find
375 * @return A pointer to the user, or NULL if the user does not exist
377 User *FindUUID(const char *);
379 /** Build the ISUPPORT string by triggering all modules On005Numeric events
381 void BuildISupport();
383 /** List of server names we've seen.
385 servernamelist servernames;
387 /** Time this ircd was booted
391 /** Config file pathname specified on the commandline or via ./configure
393 char ConfigFileName[MAXBUF];
395 /** Mode handler, handles mode setting and removal
399 /** Command parser, handles client to server commands
401 CommandParser* Parser;
403 /** Socket engine, handles socket activity events
407 /** Thread engine, Handles threading where required
409 ThreadEngine* Threads;
411 /** The thread/class used to read config files in REHASH and on startup
413 ConfigReaderThread* ConfigThread;
415 /** LogManager handles logging.
419 /** ModuleManager contains everything related to loading/unloading
422 ModuleManager* Modules;
424 /** BanCacheManager is used to speed up checking of restrictions on connection
427 BanCacheManager *BanCache;
429 /** Stats class, holds miscellaneous stats counters
433 /** Server Config class, holds configuration file data
435 ServerConfig* Config;
437 /** Snomask manager - handles routing of snomask messages
442 /** DNS class, provides resolver facilities to the core and modules
446 /** Timer manager class, triggers Timer timer events
448 TimerManager* Timers;
450 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
452 XLineManager* XLines;
454 /** User manager. Various methods and data associated with users.
458 /** Channel list, a hash_map containing all channels XXX move to channel manager class
462 /** Set to the current signal recieved
466 /** Get the current time
467 * Because this only calls time() once every time around the mainloop,
468 * it is much faster than calling time() directly.
469 * @return The current time as an epoch value (time_t)
473 /** Process a user whos socket has been flagged as active
474 * @param cu The user to process
475 * @return There is no actual return value, however upon exit, the user 'cu' may have been
476 * marked for deletion in the global CullList.
478 caller1<void, User*> ProcessUser;
480 /** Bind all ports specified in the configuration file.
481 * @param bail True if the function should bail back to the shell on failure
482 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
483 * @return The number of ports actually bound without error
485 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
487 /** Binds a socket on an already open file descriptor
488 * @param sockfd A valid file descriptor of an open socket
489 * @param port The port number to bind to
490 * @param addr The address to bind to (IP only)
491 * @return True if the port was bound successfully
493 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
495 /** Adds a server name to the list of servers we've seen
496 * @param The servername to add
498 void AddServerName(const std::string &servername);
500 /** Finds a cached char* pointer of a server name,
501 * This is used to optimize User by storing only the pointer to the name
502 * @param The servername to find
503 * @return A pointer to this name, gauranteed to never become invalid
505 const char* FindServerNamePtr(const std::string &servername);
507 /** Returns true if we've seen the given server name before
508 * @param The servername to find
509 * @return True if we've seen this server name before
511 bool FindServerName(const std::string &servername);
513 /** Gets the GECOS (description) field of the given server.
514 * If the servername is not that of the local server, the name
515 * is passed to handling modules which will attempt to determine
516 * the GECOS that bleongs to the given servername.
517 * @param servername The servername to find the description of
518 * @return The description of this server, or of the local server
520 std::string GetServerDescription(const char* servername);
522 /** Find a user in the nick hash.
523 * If the user cant be found in the nick hash check the uuid hash
524 * @param nick The nickname to find
525 * @return A pointer to the user, or NULL if the user does not exist
527 User* FindNick(const std::string &nick);
529 /** Find a user in the nick hash.
530 * If the user cant be found in the nick hash check the uuid hash
531 * @param nick The nickname to find
532 * @return A pointer to the user, or NULL if the user does not exist
534 User* FindNick(const char* nick);
536 /** Find a user in the nick hash ONLY
538 User* FindNickOnly(const char* nick);
540 /** Find a user in the nick hash ONLY
542 User* FindNickOnly(const std::string &nick);
544 /** Find a channel in the channels hash
545 * @param chan The channel to find
546 * @return A pointer to the channel, or NULL if the channel does not exist
548 Channel* FindChan(const std::string &chan);
550 /** Find a channel in the channels hash
551 * @param chan The channel to find
552 * @return A pointer to the channel, or NULL if the channel does not exist
554 Channel* FindChan(const char* chan);
556 /** Check for a 'die' tag in the config file, and abort if found
557 * @return Depending on the configuration, this function may never return
561 /** Check we aren't running as root, and exit if we are
562 * @return Depending on the configuration, this function may never return
566 /** Determine the right path for, and open, the logfile
567 * @param argv The argv passed to main() initially, used to calculate program path
568 * @param argc The argc passed to main() initially, used to calculate program path
569 * @return True if the log could be opened, false if otherwise
571 bool OpenLog(char** argv, int argc);
573 /** Return true if a channel name is valid
574 * @param chname A channel name to verify
575 * @return True if the name is valid
577 bool IsChannel(const char *chname);
579 /** Return true if str looks like a server ID
580 * @param string to check against
582 bool IsSID(const std::string &str);
584 /** Rehash the local server
588 /** Handles incoming signals after being set
589 * @param signal the signal recieved
591 void SignalHandler(int signal);
593 /** Sets the signal recieved
594 * @param signal the signal recieved
596 static void SetSignal(int signal);
598 /** Causes the server to exit after unloading modules and
599 * closing all open file descriptors.
601 * @param The exit code to give to the operating system
602 * (See the ExitStatus enum for valid values)
604 void Exit(int status);
606 /** Causes the server to exit immediately with exit code 0.
607 * The status code is required for signal handlers, and ignored.
609 static void QuickExit(int status);
611 /** Return a count of channels on the network
612 * @return The number of channels
616 /** Send an error notice to all local users, opered and unopered
617 * @param s The error string to send
619 void SendError(const std::string &s);
621 /** Return true if a nickname is valid
622 * @param n A nickname to verify
623 * @return True if the nick is valid
625 caller1<bool, const char*> IsNick;
627 /** Return true if an ident is valid
628 * @param An ident to verify
629 * @return True if the ident is valid
631 caller1<bool, const char*> IsIdent;
633 /** Find a username by their file descriptor.
634 * It is preferred to use this over directly accessing the fd_ref_table array.
635 * @param socket The file descriptor of a user
636 * @return A pointer to the user if the user exists locally on this descriptor
638 caller1<User*, int> FindDescriptor;
640 /** Add a dns Resolver class to this server's active set
641 * @param r The resolver to add
642 * @param cached If this value is true, then the cache will
643 * be searched for the DNS result, immediately. If the value is
644 * false, then a request will be sent to the nameserver, and the
645 * result will not be immediately available. You should usually
646 * use the boolean value which you passed to the Resolver
647 * constructor, which Resolver will set appropriately depending
648 * on if cached results are available and haven't expired. It is
649 * however safe to force this value to false, forcing a remote DNS
650 * lookup, but not an update of the cache.
651 * @return True if the operation completed successfully. Note that
652 * if this method returns true, you should not attempt to access
653 * the resolver class you pass it after this call, as depending upon
654 * the request given, the object may be deleted!
656 bool AddResolver(Resolver* r, bool cached);
658 /** Add a command to this server's command parser
659 * @param f A Command command handler object to add
660 * @throw ModuleException Will throw ModuleExcption if the command already exists
662 void AddCommand(Command *f);
664 /** Send a modechange.
665 * The parameters provided are identical to that sent to the
666 * handler for class cmd_mode.
667 * @param parameters The mode parameters
668 * @param pcnt The number of items you have given in the first parameter
669 * @param user The user to send error messages to
671 void SendMode(const char* const* parameters, int pcnt, User *user);
673 /** Match two strings using pattern matching.
674 * This operates identically to the global function match(),
675 * except for that it takes std::string arguments rather than
677 * @param sliteral The literal string to match against
678 * @param spattern The pattern to match against. CIDR and globs are supported.
680 bool MatchText(const std::string &sliteral, const std::string &spattern);
682 /** Call the handler for a given command.
683 * @param commandname The command whos handler you wish to call
684 * @param parameters The mode parameters
685 * @param pcnt The number of items you have given in the first parameter
686 * @param user The user to execute the command as
687 * @return True if the command handler was called successfully
689 CmdResult CallCommandHandler(const std::string &commandname, const char* const* parameters, int pcnt, User* user);
691 /** Return true if the command is a module-implemented command and the given parameters are valid for it
692 * @param parameters The mode parameters
693 * @param pcnt The number of items you have given in the first parameter
694 * @param user The user to test-execute the command as
695 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
697 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
699 /** Return true if the given parameter is a valid nick!user\@host mask
700 * @param mask A nick!user\@host masak to match against
701 * @return True i the mask is valid
703 bool IsValidMask(const std::string &mask);
705 /** Rehash the local server
709 /** Return the channel whos index number matches that provided
710 * @param The index number of the channel to fetch
711 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
713 Channel* GetChannelIndex(long index);
715 /** Dump text to a user target, splitting it appropriately to fit
716 * @param User the user to dump the text to
717 * @param LinePrefix text to prefix each complete line with
718 * @param TextStream the text to send to the user
720 void DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream);
722 /** Check if the given nickmask matches too many users, send errors to the given user
723 * @param nick A nickmask to match against
724 * @param user A user to send error text to
725 * @return True if the nick matches too many users
727 bool NickMatchesEveryone(const std::string &nick, User* user);
729 /** Check if the given IP mask matches too many users, send errors to the given user
730 * @param ip An ipmask to match against
731 * @param user A user to send error text to
732 * @return True if the ip matches too many users
734 bool IPMatchesEveryone(const std::string &ip, User* user);
736 /** Check if the given hostmask matches too many users, send errors to the given user
737 * @param mask A hostmask to match against
738 * @param user A user to send error text to
739 * @return True if the host matches too many users
741 bool HostMatchesEveryone(const std::string &mask, User* user);
743 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
744 * @param str A string containing a time in the form 1y2w3d4h6m5s
745 * (one year, two weeks, three days, four hours, six minutes and five seconds)
746 * @return The total number of seconds
748 long Duration(const std::string &str);
750 /** Attempt to compare a password to a string from the config file.
751 * This will be passed to handling modules which will compare the data
752 * against possible hashed equivalents in the input string.
753 * @param ex The object (user, server, whatever) causing the comparison.
754 * @param data The data from the config file
755 * @param input The data input by the oper
756 * @param hashtype The hash from the config file
757 * @return 0 if the strings match, 1 or -1 if they do not
759 int PassCompare(Extensible* ex, const char* data,const char* input, const char* hashtype);
761 /** Check if a given server is a uline.
762 * An empty string returns true, this is by design.
763 * @param server The server to check for uline status
764 * @return True if the server is a uline OR the string is empty
766 bool ULine(const char* server);
768 /** Returns true if the uline is 'silent' (doesnt generate
769 * remote connect notices etc).
771 bool SilentULine(const char* server);
773 /** Returns the subversion revision ID of this ircd
774 * @return The revision ID or an empty string
776 std::string GetRevision();
778 /** Returns the full version string of this ircd
779 * @return The version string
781 std::string GetVersionString();
783 /** Attempt to write the process id to a given file
784 * @param filename The PID file to attempt to write to
785 * @return This function may bail if the file cannot be written
787 void WritePID(const std::string &filename);
789 /** This constructor initialises all the subsystems and reads the config file.
790 * @param argc The argument count passed to main()
791 * @param argv The argument list passed to main()
792 * @throw <anything> If anything is thrown from here and makes it to
793 * you, you should probably just give up and go home. Yes, really.
794 * It's that bad. Higher level classes should catch any non-fatal exceptions.
796 InspIRCd(int argc, char** argv);
798 /** Output a log message to the ircd.log file
799 * The text will only be output if the current loglevel
800 * is less than or equal to the level you provide
801 * @param level A log level from the DebugLevel enum
802 * @param text Format string of to write to the log
803 * @param ... Format arguments of text to write to the log
805 void Log(int level, const char* text, ...) CUSTOM_PRINTF(3, 4);
807 /** Output a log message to the ircd.log file
808 * The text will only be output if the current loglevel
809 * is less than or equal to the level you provide
810 * @param level A log level from the DebugLevel enum
811 * @param text Text to write to the log
813 void Log(int level, const std::string &text);
815 /** Send a line of WHOIS data to a user.
816 * @param user user to send the line to
817 * @param dest user being WHOISed
818 * @param numeric Numeric to send
819 * @param text Text of the numeric
821 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
823 /** Send a line of WHOIS data to a user.
824 * @param user user to send the line to
825 * @param dest user being WHOISed
826 * @param numeric Numeric to send
827 * @param format Format string for the numeric
828 * @param ... Parameters for the format string
830 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
832 /** Quit a user for excess flood, and if they are not
833 * fully registered yet, temporarily zline their IP.
834 * @param current user to quit
836 caller1<void, User*> FloodQuitUser;
838 /** Restart the server.
839 * This function will not return. If an error occurs,
840 * it will throw an instance of CoreException.
841 * @param reason The restart reason to show to all clients
842 * @throw CoreException An instance of CoreException indicating the error from execv().
844 void Restart(const std::string &reason);
846 /** Prepare the ircd for restart or shutdown.
847 * This function unloads all modules which can be unloaded,
848 * closes all open sockets, and closes the logfile.
852 /** This copies the user and channel hash_maps into new hash maps.
853 * This frees memory used by the hash_map allocator (which it neglects
854 * to free, most of the time, using tons of ram)
856 void RehashUsersAndChans();
858 /** Resets the cached max bans value on all channels.
863 /** Return a time_t as a human-readable string.
865 std::string TimeString(time_t curtime);
867 /** Begin execution of the server.
868 * NOTE: this function NEVER returns. Internally,
869 * it will repeatedly loop.
870 * @return The return value for this function is undefined.
874 /** Force all BufferedSockets to be removed which are due to
877 void BufferedSocketCull();
879 char* GetReadBuffer()
881 return this->ReadBuffer;