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*);
237 DEFINE_HANDLER1(IsChannelHandler, bool, const char*);
238 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
239 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
241 /* Forward declaration - required */
243 class BanCacheManager;
245 class CoreExport ConfigReaderThread : public Thread
247 InspIRCd* ServerInstance;
251 ConfigReaderThread(InspIRCd* Instance, bool bail, User* user) : Thread(), ServerInstance(Instance), do_bail(bail), TheUser(user)
255 virtual ~ConfigReaderThread()
262 /** The main class of the irc server.
263 * This class contains instances of all the other classes
264 * in this software, with the exception of the base class,
265 * classbase. Amongst other things, it contains a ModeParser,
266 * a DNS object, a CommandParser object, and a list of active
267 * Module objects, and facilities for Module objects to
268 * interact with the core system it implements. You should
269 * NEVER attempt to instantiate a class of type InspIRCd
270 * yourself. If you do, this is equivalent to spawning a second
271 * IRC server, and could have catastrophic consequences for the
272 * program in terms of ram usage (basically, you could create
273 * an obese forkbomb built from recursively spawning irc servers!)
275 class CoreExport InspIRCd : public classbase
278 /** Holds the current UID. Used to generate the next one.
280 char current_uid[UUID_LENGTH];
282 /** Set up the signal handlers
286 /** Daemonize the ircd and close standard input/output streams
287 * @return True if the program daemonized succesfully
291 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
292 * @param TIME the current time
294 void DoSocketTimeouts(time_t TIME);
296 /** Increments the current UID by one.
298 void IncrementUID(int pos);
300 /** Perform background user events such as PING checks
302 void DoBackgroundUserStuff();
304 /** Returns true when all modules have done pre-registration checks on a user
305 * @param user The user to verify
306 * @return True if all modules have finished checking this user
308 bool AllModulesReportReady(User* user);
310 /** Logfile pathname specified on the commandline, or empty string
312 char LogFileName[MAXBUF];
314 /** The current time, updated in the mainloop
318 /** The time that was recorded last time around the mainloop
322 /** A 64k buffer used to read client lines into
324 char ReadBuffer[65535];
326 /** Used when connecting clients
328 irc::sockets::insp_sockaddr client, server;
330 /** Used when connecting clients
340 /** Global cull list, will be processed on next iteration
342 CullList GlobalCulls;
346 ProcessUserHandler HandleProcessUser;
347 IsNickHandler HandleIsNick;
348 IsIdentHandler HandleIsIdent;
349 FindDescriptorHandler HandleFindDescriptor;
350 FloodQuitUserHandler HandleFloodQuitUser;
351 IsChannelHandler HandleIsChannel;
352 IsSIDHandler HandleIsSID;
353 RehashHandler HandleRehash;
355 /** BufferedSocket classes pending deletion after being closed.
356 * We don't delete these immediately as this may cause a segmentation fault.
358 std::map<BufferedSocket*,BufferedSocket*> SocketCull;
360 /** 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
363 * SendMode expects a User* to send the numeric replies
364 * back to, so we create it a fake user that isnt in the user
365 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
366 * falls into the abyss :p
370 /** Returns the next available UID for this server.
372 std::string GetUID();
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 std::string &);
380 /** Find a user in the UUID hash
381 * @param nick The nickname to find
382 * @return A pointer to the user, or NULL if the user does not exist
384 User *FindUUID(const char *);
386 /** Build the ISUPPORT string by triggering all modules On005Numeric events
388 void BuildISupport();
390 /** List of server names we've seen.
392 servernamelist servernames;
394 /** Time this ircd was booted
398 /** Config file pathname specified on the commandline or via ./configure
400 char ConfigFileName[MAXBUF];
402 /** Mode handler, handles mode setting and removal
406 /** Command parser, handles client to server commands
408 CommandParser* Parser;
410 /** Socket engine, handles socket activity events
414 /** Thread engine, Handles threading where required
416 ThreadEngine* Threads;
418 /** The thread/class used to read config files in REHASH and on startup
420 ConfigReaderThread* ConfigThread;
422 /** LogManager handles logging.
426 /** ModuleManager contains everything related to loading/unloading
429 ModuleManager* Modules;
431 /** BanCacheManager is used to speed up checking of restrictions on connection
434 BanCacheManager *BanCache;
436 /** Stats class, holds miscellaneous stats counters
440 /** Server Config class, holds configuration file data
442 ServerConfig* Config;
444 /** Snomask manager - handles routing of snomask messages
449 /** DNS class, provides resolver facilities to the core and modules
453 /** Timer manager class, triggers Timer timer events
455 TimerManager* Timers;
457 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
459 XLineManager* XLines;
461 /** User manager. Various methods and data associated with users.
465 /** Channel list, a hash_map containing all channels XXX move to channel manager class
469 /** Set to the current signal recieved
473 /** Protocol interface, overridden by server protocol modules
475 ProtocolInterface* PI;
477 /** Get the current time
478 * Because this only calls time() once every time around the mainloop,
479 * it is much faster than calling time() directly.
480 * @return The current time as an epoch value (time_t)
484 /** Process a user whos socket has been flagged as active
485 * @param cu The user to process
486 * @return There is no actual return value, however upon exit, the user 'cu' may have been
487 * marked for deletion in the global CullList.
489 caller1<void, User*> ProcessUser;
491 /** Bind all ports specified in the configuration file.
492 * @param bail True if the function should bail back to the shell on failure
493 * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
494 * @return The number of ports actually bound without error
496 int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
498 /** Binds a socket on an already open file descriptor
499 * @param sockfd A valid file descriptor of an open socket
500 * @param port The port number to bind to
501 * @param addr The address to bind to (IP only)
502 * @return True if the port was bound successfully
504 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
506 /** Adds a server name to the list of servers we've seen
507 * @param The servername to add
509 void AddServerName(const std::string &servername);
511 /** Finds a cached char* pointer of a server name,
512 * This is used to optimize User by storing only the pointer to the name
513 * @param The servername to find
514 * @return A pointer to this name, gauranteed to never become invalid
516 const char* FindServerNamePtr(const std::string &servername);
518 /** Returns true if we've seen the given server name before
519 * @param The servername to find
520 * @return True if we've seen this server name before
522 bool FindServerName(const std::string &servername);
524 /** Gets the GECOS (description) field of the given server.
525 * If the servername is not that of the local server, the name
526 * is passed to handling modules which will attempt to determine
527 * the GECOS that bleongs to the given servername.
528 * @param servername The servername to find the description of
529 * @return The description of this server, or of the local server
531 std::string GetServerDescription(const char* servername);
533 /** Find a user in the nick hash.
534 * If the user cant be found in the nick hash check the uuid hash
535 * @param nick The nickname to find
536 * @return A pointer to the user, or NULL if the user does not exist
538 User* FindNick(const std::string &nick);
540 /** Find a user in the nick hash.
541 * If the user cant be found in the nick hash check the uuid hash
542 * @param nick The nickname to find
543 * @return A pointer to the user, or NULL if the user does not exist
545 User* FindNick(const char* nick);
547 /** Find a user in the nick hash ONLY
549 User* FindNickOnly(const char* nick);
551 /** Find a user in the nick hash ONLY
553 User* FindNickOnly(const std::string &nick);
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 std::string &chan);
561 /** Find a channel in the channels hash
562 * @param chan The channel to find
563 * @return A pointer to the channel, or NULL if the channel does not exist
565 Channel* FindChan(const char* chan);
567 /** Check for a 'die' tag in the config file, and abort if found
568 * @return Depending on the configuration, this function may never return
572 /** Check we aren't running as root, and exit if we are
573 * @return Depending on the configuration, this function may never return
577 /** Determine the right path for, and open, the logfile
578 * @param argv The argv passed to main() initially, used to calculate program path
579 * @param argc The argc passed to main() initially, used to calculate program path
580 * @return True if the log could be opened, false if otherwise
582 bool OpenLog(char** argv, int argc);
584 /** Return true if a channel name is valid
585 * @param chname A channel name to verify
586 * @return True if the name is valid
588 caller1<bool, const char*> IsChannel;
590 /** Return true if str looks like a server ID
591 * @param string to check against
593 caller1<bool, const std::string&> IsSID;
595 /** Rehash the local server
597 caller1<void, const std::string&> Rehash;
599 /** Handles incoming signals after being set
600 * @param signal the signal recieved
602 void SignalHandler(int signal);
604 /** Sets the signal recieved
605 * @param signal the signal recieved
607 static void SetSignal(int signal);
609 /** Causes the server to exit after unloading modules and
610 * closing all open file descriptors.
612 * @param The exit code to give to the operating system
613 * (See the ExitStatus enum for valid values)
615 void Exit(int status);
617 /** Causes the server to exit immediately with exit code 0.
618 * The status code is required for signal handlers, and ignored.
620 static void QuickExit(int status);
622 /** Return a count of channels on the network
623 * @return The number of channels
627 /** Send an error notice to all local users, opered and unopered
628 * @param s The error string to send
630 void SendError(const std::string &s);
632 /** Return true if a nickname is valid
633 * @param n A nickname to verify
634 * @return True if the nick is valid
636 caller1<bool, const char*> IsNick;
638 /** Return true if an ident is valid
639 * @param An ident to verify
640 * @return True if the ident is valid
642 caller1<bool, const char*> IsIdent;
644 /** Find a username by their file descriptor.
645 * It is preferred to use this over directly accessing the fd_ref_table array.
646 * @param socket The file descriptor of a user
647 * @return A pointer to the user if the user exists locally on this descriptor
649 caller1<User*, int> FindDescriptor;
651 /** Add a dns Resolver class to this server's active set
652 * @param r The resolver to add
653 * @param cached If this value is true, then the cache will
654 * be searched for the DNS result, immediately. If the value is
655 * false, then a request will be sent to the nameserver, and the
656 * result will not be immediately available. You should usually
657 * use the boolean value which you passed to the Resolver
658 * constructor, which Resolver will set appropriately depending
659 * on if cached results are available and haven't expired. It is
660 * however safe to force this value to false, forcing a remote DNS
661 * lookup, but not an update of the cache.
662 * @return True if the operation completed successfully. Note that
663 * if this method returns true, you should not attempt to access
664 * the resolver class you pass it after this call, as depending upon
665 * the request given, the object may be deleted!
667 bool AddResolver(Resolver* r, bool cached);
669 /** Add a command to this server's command parser
670 * @param f A Command command handler object to add
671 * @throw ModuleException Will throw ModuleExcption if the command already exists
673 void AddCommand(Command *f);
675 /** Send a modechange.
676 * The parameters provided are identical to that sent to the
677 * handler for class cmd_mode.
678 * @param parameters The mode parameters
679 * @param pcnt The number of items you have given in the first parameter
680 * @param user The user to send error messages to
682 void SendMode(const char* const* parameters, int pcnt, User *user);
684 /** Match two strings using pattern matching.
685 * This operates identically to the global function match(),
686 * except for that it takes std::string arguments rather than
688 * @param sliteral The literal string to match against
689 * @param spattern The pattern to match against. CIDR and globs are supported.
691 bool MatchText(const std::string &sliteral, const std::string &spattern);
693 /** Call the handler for a given command.
694 * @param commandname The command whos handler you wish to call
695 * @param parameters The mode parameters
696 * @param pcnt The number of items you have given in the first parameter
697 * @param user The user to execute the command as
698 * @return True if the command handler was called successfully
700 CmdResult CallCommandHandler(const std::string &commandname, const char* const* parameters, int pcnt, User* user);
702 /** Return true if the command is a module-implemented command and the given parameters are valid for it
703 * @param parameters The mode parameters
704 * @param pcnt The number of items you have given in the first parameter
705 * @param user The user to test-execute the command as
706 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
708 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
710 /** Return true if the given parameter is a valid nick!user\@host mask
711 * @param mask A nick!user\@host masak to match against
712 * @return True i the mask is valid
714 bool IsValidMask(const std::string &mask);
716 /** Rehash the local server
720 /** Return the channel whos index number matches that provided
721 * @param The index number of the channel to fetch
722 * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
724 Channel* GetChannelIndex(long index);
726 /** Dump text to a user target, splitting it appropriately to fit
727 * @param User the user to dump the text to
728 * @param LinePrefix text to prefix each complete line with
729 * @param TextStream the text to send to the user
731 void DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream);
733 /** Check if the given nickmask matches too many users, send errors to the given user
734 * @param nick A nickmask to match against
735 * @param user A user to send error text to
736 * @return True if the nick matches too many users
738 bool NickMatchesEveryone(const std::string &nick, User* user);
740 /** Check if the given IP mask matches too many users, send errors to the given user
741 * @param ip An ipmask to match against
742 * @param user A user to send error text to
743 * @return True if the ip matches too many users
745 bool IPMatchesEveryone(const std::string &ip, User* user);
747 /** Check if the given hostmask matches too many users, send errors to the given user
748 * @param mask A hostmask to match against
749 * @param user A user to send error text to
750 * @return True if the host matches too many users
752 bool HostMatchesEveryone(const std::string &mask, User* user);
754 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
755 * @param str A string containing a time in the form 1y2w3d4h6m5s
756 * (one year, two weeks, three days, four hours, six minutes and five seconds)
757 * @return The total number of seconds
759 long Duration(const std::string &str);
761 /** Attempt to compare a password to a string from the config file.
762 * This will be passed to handling modules which will compare the data
763 * against possible hashed equivalents in the input string.
764 * @param ex The object (user, server, whatever) causing the comparison.
765 * @param data The data from the config file
766 * @param input The data input by the oper
767 * @param hashtype The hash from the config file
768 * @return 0 if the strings match, 1 or -1 if they do not
770 int PassCompare(Extensible* ex, const char* data,const char* input, const char* hashtype);
772 /** Check if a given server is a uline.
773 * An empty string returns true, this is by design.
774 * @param server The server to check for uline status
775 * @return True if the server is a uline OR the string is empty
777 bool ULine(const char* server);
779 /** Returns true if the uline is 'silent' (doesnt generate
780 * remote connect notices etc).
782 bool SilentULine(const char* server);
784 /** Returns the subversion revision ID of this ircd
785 * @return The revision ID or an empty string
787 std::string GetRevision();
789 /** Returns the full version string of this ircd
790 * @return The version string
792 std::string GetVersionString();
794 /** Attempt to write the process id to a given file
795 * @param filename The PID file to attempt to write to
796 * @return This function may bail if the file cannot be written
798 void WritePID(const std::string &filename);
800 /** This constructor initialises all the subsystems and reads the config file.
801 * @param argc The argument count passed to main()
802 * @param argv The argument list passed to main()
803 * @throw <anything> If anything is thrown from here and makes it to
804 * you, you should probably just give up and go home. Yes, really.
805 * It's that bad. Higher level classes should catch any non-fatal exceptions.
807 InspIRCd(int argc, char** argv);
809 /** Send a line of WHOIS data to a user.
810 * @param user user to send the line to
811 * @param dest user being WHOISed
812 * @param numeric Numeric to send
813 * @param text Text of the numeric
815 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
817 /** Send a line of WHOIS data to a user.
818 * @param user user to send the line to
819 * @param dest user being WHOISed
820 * @param numeric Numeric to send
821 * @param format Format string for the numeric
822 * @param ... Parameters for the format string
824 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
826 /** Quit a user for excess flood, and if they are not
827 * fully registered yet, temporarily zline their IP.
828 * @param current user to quit
830 caller1<void, User*> FloodQuitUser;
832 /** Restart the server.
833 * This function will not return. If an error occurs,
834 * it will throw an instance of CoreException.
835 * @param reason The restart reason to show to all clients
836 * @throw CoreException An instance of CoreException indicating the error from execv().
838 void Restart(const std::string &reason);
840 /** Prepare the ircd for restart or shutdown.
841 * This function unloads all modules which can be unloaded,
842 * closes all open sockets, and closes the logfile.
846 /** This copies the user and channel hash_maps into new hash maps.
847 * This frees memory used by the hash_map allocator (which it neglects
848 * to free, most of the time, using tons of ram)
850 void RehashUsersAndChans();
852 /** Resets the cached max bans value on all channels.
857 /** Return a time_t as a human-readable string.
859 std::string TimeString(time_t curtime);
861 /** Begin execution of the server.
862 * NOTE: this function NEVER returns. Internally,
863 * it will repeatedly loop.
864 * @return The return value for this function is undefined.
868 /** Force all BufferedSockets to be removed which are due to
871 void BufferedSocketCull();
873 char* GetReadBuffer()
875 return this->ReadBuffer;