1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 #ifndef __INSPIRCD_H__
15 #define __INSPIRCD_H__
17 #define _FILE_OFFSET_BITS 64
18 #ifndef _LARGEFILE_SOURCE
19 #define _LARGEFILE_SOURCE
25 #define printf_c printf
27 #include "inspircd_win32wrapper.h"
28 /** Windows defines these already */
33 #define CUSTOM_PRINTF(STRING, FIRST) __attribute__((format(printf, STRING, FIRST)))
35 #define CUSTOM_PRINTF(STRING, FIRST)
38 // Required system headers.
55 #include "inspircd_config.h"
56 #include "inspircd_version.h"
59 CoreExport extern InspIRCd* ServerInstance;
62 #include "cull_list.h"
63 #include "extensible.h"
71 #include "usermanager.h"
74 #include "command_parse.h"
76 #include "socketengine.h"
78 #include "filelogger.h"
81 #include "threadengine.h"
82 #include "configreader.h"
83 #include "inspstring.h"
87 #warning Potentially broken system, PATH_MAX undefined
92 * Used to define the maximum number of parameters a command may have.
94 #define MAXPARAMETERS 127
96 /** Returned by some functions to indicate failure.
100 /** Support for librodent -
101 * see http://www.chatspike.net/index.php?z=64
103 #define ETIREDHAMSTERS EAGAIN
105 /** Template function to convert any input type to std::string
107 template<typename T> inline std::string ConvNumeric(const T &in)
109 if (in == 0) return "0";
114 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
121 std::reverse(res,out);
125 /** Template function to convert any input type to std::string
127 inline std::string ConvToStr(const int in)
129 return ConvNumeric(in);
132 /** Template function to convert any input type to std::string
134 inline std::string ConvToStr(const long in)
136 return ConvNumeric(in);
139 /** Template function to convert any input type to std::string
141 inline std::string ConvToStr(const char* in)
146 /** Template function to convert any input type to std::string
148 inline std::string ConvToStr(const bool in)
150 return (in ? "1" : "0");
153 /** Template function to convert any input type to std::string
155 inline std::string ConvToStr(char in)
157 return std::string(in,1);
160 /** Template function to convert any input type to std::string
162 template <class T> inline std::string ConvToStr(const T &in)
164 std::stringstream tmp;
165 if (!(tmp << in)) return std::string();
169 /** Template function to convert any input type to any other type
170 * (usually an integer or numeric type)
172 template<typename T> inline long ConvToInt(const T &in)
174 std::stringstream tmp;
175 if (!(tmp << in)) return 0;
176 return atol(tmp.str().c_str());
179 /** This class contains various STATS counters
180 * It is used by the InspIRCd class, which internally
181 * has an instance of it.
186 /** Number of accepted connections
188 unsigned long statsAccept;
189 /** Number of failed accepts
191 unsigned long statsRefused;
192 /** Number of unknown commands seen
194 unsigned long statsUnknown;
195 /** Number of nickname collisions handled
197 unsigned long statsCollisions;
198 /** Number of DNS queries sent out
200 unsigned long statsDns;
201 /** Number of good DNS replies received
202 * NOTE: This may not tally to the number sent out,
203 * due to timeouts and other latency issues.
205 unsigned long statsDnsGood;
206 /** Number of bad (negative) DNS replies received
207 * NOTE: This may not tally to the number sent out,
208 * due to timeouts and other latency issues.
210 unsigned long statsDnsBad;
211 /** Number of inbound connections seen
213 unsigned long statsConnects;
214 /** Total bytes of data transmitted
217 /** Total bytes of data received
220 /** Cpu usage at last sample
223 /** Time last sample was read
226 /** The constructor initializes all the counts to zero
229 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
230 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
235 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
236 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
237 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
238 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
239 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
240 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
242 /** The main class of the irc server.
243 * This class contains instances of all the other classes in this software.
244 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
245 * object, and a list of active Module objects, and facilities for Module
246 * objects to interact with the core system it implements.
248 class CoreExport InspIRCd
251 /** Holds the current UID. Used to generate the next one.
253 char current_uid[UUID_LENGTH];
255 /** Set up the signal handlers
259 /** Daemonize the ircd and close standard input/output streams
260 * @return True if the program daemonized succesfully
264 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
265 * @param TIME the current time
267 void DoSocketTimeouts(time_t TIME);
269 /** Increments the current UID by one.
271 void IncrementUID(int pos);
273 /** Perform background user events such as PING checks
275 void DoBackgroundUserStuff();
277 /** Returns true when all modules have done pre-registration checks on a user
278 * @param user The user to verify
279 * @return True if all modules have finished checking this user
281 bool AllModulesReportReady(LocalUser* user);
283 /** The current time, updated in the mainloop
287 /** The time that was recorded last time around the mainloop
291 /** A 64k buffer used to read socket data into
292 * NOTE: update ValidateNetBufferSize if you change this
294 char ReadBuffer[65535];
302 /** Global cull list, will be processed on next iteration
304 CullList GlobalCulls;
305 /** Actions that must happen outside of the current call stack */
306 ActionList AtomicActions;
310 IsNickHandler HandleIsNick;
311 IsIdentHandler HandleIsIdent;
312 FloodQuitUserHandler HandleFloodQuitUser;
313 IsChannelHandler HandleIsChannel;
314 IsSIDHandler HandleIsSID;
315 RehashHandler HandleRehash;
317 /** 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
320 * SendMode expects a User* to send the numeric replies
321 * back to, so we create it a fake user that isnt in the user
322 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
323 * falls into the abyss :p
325 FakeUser* FakeClient;
327 /** Returns the next available UID for this server.
329 std::string GetUID();
331 /** Find a user in the UUID hash
332 * @param nick The nickname to find
333 * @return A pointer to the user, or NULL if the user does not exist
335 User* FindUUID(const std::string &);
337 /** Find a user in the UUID hash
338 * @param nick The nickname to find
339 * @return A pointer to the user, or NULL if the user does not exist
341 User* FindUUID(const char *);
343 /** Build the ISUPPORT string by triggering all modules On005Numeric events
345 void BuildISupport();
347 /** Time this ircd was booted
351 /** Config file pathname specified on the commandline or via ./configure
353 std::string ConfigFileName;
355 ExtensionManager Extensions;
357 /** Mode handler, handles mode setting and removal
361 /** Command parser, handles client to server commands
363 CommandParser* Parser;
365 /** Socket engine, handles socket activity events
369 /** Thread engine, Handles threading where required
371 ThreadEngine* Threads;
373 /** The thread/class used to read config files in REHASH and on startup
375 ConfigReaderThread* ConfigThread;
377 /** LogManager handles logging.
381 /** ModuleManager contains everything related to loading/unloading
384 ModuleManager* Modules;
386 /** BanCacheManager is used to speed up checking of restrictions on connection
389 BanCacheManager *BanCache;
391 /** Stats class, holds miscellaneous stats counters
395 /** Server Config class, holds configuration file data
397 ServerConfig* Config;
399 /** Snomask manager - handles routing of snomask messages
404 /** DNS class, provides resolver facilities to the core and modules
408 /** Timer manager class, triggers Timer timer events
410 TimerManager* Timers;
412 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
414 XLineManager* XLines;
416 /** User manager. Various methods and data associated with users.
420 /** Channel list, a hash_map containing all channels XXX move to channel manager class
424 /** List of the open ports
426 std::vector<ListenSocket*> ports;
428 /** Set to the current signal recieved
432 /** Protocol interface, overridden by server protocol modules
434 ProtocolInterface* PI;
436 /** Holds extensible for user nickforced
438 LocalIntExt NICKForced;
440 /** Holds extensible for user operquit
442 LocalStringExt OperQuit;
444 /** Get the current time
445 * Because this only calls time() once every time around the mainloop,
446 * it is much faster than calling time() directly.
447 * @return The current time as an epoch value (time_t)
451 /** Bind all ports specified in the configuration file.
452 * @return The number of ports bound without error
454 int BindPorts(FailedPortList &failed_ports);
456 /** Binds a socket on an already open file descriptor
457 * @param sockfd A valid file descriptor of an open socket
458 * @param port The port number to bind to
459 * @param addr The address to bind to (IP only)
460 * @return True if the port was bound successfully
462 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
464 /** Gets the GECOS (description) field of the given server.
465 * If the servername is not that of the local server, the name
466 * is passed to handling modules which will attempt to determine
467 * the GECOS that bleongs to the given servername.
468 * @param servername The servername to find the description of
469 * @return The description of this server, or of the local server
471 std::string GetServerDescription(const std::string& servername);
473 /** Find a user in the nick hash.
474 * If the user cant be found in the nick hash check the uuid hash
475 * @param nick The nickname to find
476 * @return A pointer to the user, or NULL if the user does not exist
478 User* FindNick(const std::string &nick);
480 /** Find a user in the nick hash.
481 * If the user cant be found in the nick hash check the uuid hash
482 * @param nick The nickname to find
483 * @return A pointer to the user, or NULL if the user does not exist
485 User* FindNick(const char* nick);
487 /** Find a user in the nick hash ONLY
489 User* FindNickOnly(const char* nick);
491 /** Find a user in the nick hash ONLY
493 User* FindNickOnly(const std::string &nick);
495 /** Find a channel in the channels hash
496 * @param chan The channel to find
497 * @return A pointer to the channel, or NULL if the channel does not exist
499 Channel* FindChan(const std::string &chan);
501 /** Find a channel in the channels hash
502 * @param chan The channel to find
503 * @return A pointer to the channel, or NULL if the channel does not exist
505 Channel* FindChan(const char* chan);
507 /** Check we aren't running as root, and exit if we are
508 * @return Depending on the configuration, this function may never return
512 /** Determine the right path for, and open, the logfile
513 * @param argv The argv passed to main() initially, used to calculate program path
514 * @param argc The argc passed to main() initially, used to calculate program path
515 * @return True if the log could be opened, false if otherwise
517 bool OpenLog(char** argv, int argc);
519 /** Return true if a channel name is valid
520 * @param chname A channel name to verify
521 * @return True if the name is valid
523 caller2<bool, const char*, size_t> IsChannel;
525 /** Return true if str looks like a server ID
526 * @param string to check against
528 caller1<bool, const std::string&> IsSID;
530 /** Rehash the local server
532 caller1<void, const std::string&> Rehash;
534 /** Handles incoming signals after being set
535 * @param signal the signal recieved
537 void SignalHandler(int signal);
539 /** Sets the signal recieved
540 * @param signal the signal recieved
542 static void SetSignal(int signal);
544 /** Causes the server to exit after unloading modules and
545 * closing all open file descriptors.
547 * @param The exit code to give to the operating system
548 * (See the ExitStatus enum for valid values)
550 void Exit(int status);
552 /** Causes the server to exit immediately with exit code 0.
553 * The status code is required for signal handlers, and ignored.
555 static void QuickExit(int status);
557 /** Return a count of channels on the network
558 * @return The number of channels
562 /** Send an error notice to all local users, opered and unopered
563 * @param s The error string to send
565 void SendError(const std::string &s);
567 /** Return true if a nickname is valid
568 * @param n A nickname to verify
569 * @return True if the nick is valid
571 caller2<bool, const char*, size_t> IsNick;
573 /** Return true if an ident is valid
574 * @param An ident to verify
575 * @return True if the ident is valid
577 caller1<bool, const char*> IsIdent;
579 /** Add a dns Resolver class to this server's active set
580 * @param r The resolver to add
581 * @param cached If this value is true, then the cache will
582 * be searched for the DNS result, immediately. If the value is
583 * false, then a request will be sent to the nameserver, and the
584 * result will not be immediately available. You should usually
585 * use the boolean value which you passed to the Resolver
586 * constructor, which Resolver will set appropriately depending
587 * on if cached results are available and haven't expired. It is
588 * however safe to force this value to false, forcing a remote DNS
589 * lookup, but not an update of the cache.
590 * @return True if the operation completed successfully. Note that
591 * if this method returns true, you should not attempt to access
592 * the resolver class you pass it after this call, as depending upon
593 * the request given, the object may be deleted!
595 bool AddResolver(Resolver* r, bool cached);
597 /** Add a command to this server's command parser
598 * @param f A Command command handler object to add
599 * @throw ModuleException Will throw ModuleExcption if the command already exists
601 inline void AddCommand(Command *f)
603 Modules->AddService(*f);
606 /** Send a modechange.
607 * The parameters provided are identical to that sent to the
608 * handler for class cmd_mode.
609 * @param parameters The mode parameters
610 * @param user The user to send error messages to
612 void SendMode(const std::vector<std::string>& parameters, User *user);
614 /** Match two strings using pattern matching, optionally, with a map
615 * to check case against (may be NULL). If map is null, match will be case insensitive.
616 * @param str The literal string to match against
617 * @param mask The glob pattern to match against.
619 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
620 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
622 /** Match two strings using pattern matching, optionally, with a map
623 * to check case against (may be NULL). If map is null, match will be case insensitive.
624 * Supports CIDR patterns as well as globs.
625 * @param str The literal string to match against
626 * @param mask The glob or CIDR pattern to match against.
628 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
629 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
631 /** Call the handler for a given command.
632 * @param commandname The command whos handler you wish to call
633 * @param parameters The mode parameters
634 * @param pcnt The number of items you have given in the first parameter
635 * @param user The user to execute the command as
636 * @return True if the command handler was called successfully
638 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
640 /** Return true if the command is a module-implemented command and the given parameters are valid for it
641 * @param parameters The mode parameters
642 * @param pcnt The number of items you have given in the first parameter
643 * @param user The user to test-execute the command as
644 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
646 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
648 /** Return true if the given parameter is a valid nick!user\@host mask
649 * @param mask A nick!user\@host masak to match against
650 * @return True i the mask is valid
652 bool IsValidMask(const std::string &mask);
654 /** Rehash the local server
658 /** Check if the given nickmask matches too many users, send errors to the given user
659 * @param nick A nickmask to match against
660 * @param user A user to send error text to
661 * @return True if the nick matches too many users
663 bool NickMatchesEveryone(const std::string &nick, User* user);
665 /** Check if the given IP mask matches too many users, send errors to the given user
666 * @param ip An ipmask to match against
667 * @param user A user to send error text to
668 * @return True if the ip matches too many users
670 bool IPMatchesEveryone(const std::string &ip, User* user);
672 /** Check if the given hostmask matches too many users, send errors to the given user
673 * @param mask A hostmask to match against
674 * @param user A user to send error text to
675 * @return True if the host matches too many users
677 bool HostMatchesEveryone(const std::string &mask, User* user);
679 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
680 * @param str A string containing a time in the form 1y2w3d4h6m5s
681 * (one year, two weeks, three days, four hours, six minutes and five seconds)
682 * @return The total number of seconds
684 long Duration(const std::string &str);
686 /** Attempt to compare a password to a string from the config file.
687 * This will be passed to handling modules which will compare the data
688 * against possible hashed equivalents in the input string.
689 * @param ex The object (user, server, whatever) causing the comparison.
690 * @param data The data from the config file
691 * @param input The data input by the oper
692 * @param hashtype The hash from the config file
693 * @return 0 if the strings match, 1 or -1 if they do not
695 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
697 /** Check if a given server is a uline.
698 * An empty string returns true, this is by design.
699 * @param server The server to check for uline status
700 * @return True if the server is a uline OR the string is empty
702 bool ULine(const std::string& server);
704 /** Returns true if the uline is 'silent' (doesnt generate
705 * remote connect notices etc).
707 bool SilentULine(const std::string& server);
709 /** Returns the full version string of this ircd
710 * @return The version string
712 std::string GetVersionString();
714 /** Attempt to write the process id to a given file
715 * @param filename The PID file to attempt to write to
716 * @return This function may bail if the file cannot be written
718 void WritePID(const std::string &filename);
720 /** This constructor initialises all the subsystems and reads the config file.
721 * @param argc The argument count passed to main()
722 * @param argv The argument list passed to main()
723 * @throw <anything> If anything is thrown from here and makes it to
724 * you, you should probably just give up and go home. Yes, really.
725 * It's that bad. Higher level classes should catch any non-fatal exceptions.
727 InspIRCd(int argc, char** argv);
729 /** Send a line of WHOIS data to a user.
730 * @param user user to send the line to
731 * @param dest user being WHOISed
732 * @param numeric Numeric to send
733 * @param text Text of the numeric
735 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
737 /** Send a line of WHOIS data to a user.
738 * @param user user to send the line to
739 * @param dest user being WHOISed
740 * @param numeric Numeric to send
741 * @param format Format string for the numeric
742 * @param ... Parameters for the format string
744 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
748 void DoStats(char statschar, User* user, string_list &results);
752 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
754 /** Quit a user for excess flood, and if they are not
755 * fully registered yet, temporarily zline their IP.
756 * @param current user to quit
758 caller1<void, User*> FloodQuitUser;
760 /** Restart the server.
761 * This function will not return. If an error occurs,
762 * it will throw an instance of CoreException.
763 * @param reason The restart reason to show to all clients
764 * @throw CoreException An instance of CoreException indicating the error from execv().
766 void Restart(const std::string &reason);
768 /** Prepare the ircd for restart or shutdown.
769 * This function unloads all modules which can be unloaded,
770 * closes all open sockets, and closes the logfile.
774 /** This copies the user and channel hash_maps into new hash maps.
775 * This frees memory used by the hash_map allocator (which it neglects
776 * to free, most of the time, using tons of ram)
778 void RehashUsersAndChans();
780 /** Resets the cached max bans value on all channels.
785 /** Return a time_t as a human-readable string.
787 std::string TimeString(time_t curtime);
789 /** Begin execution of the server.
790 * NOTE: this function NEVER returns. Internally,
791 * it will repeatedly loop.
792 * @return The return value for this function is undefined.
796 /** Adds an extban char to the 005 token.
798 void AddExtBanChar(char c);
800 char* GetReadBuffer()
802 return this->ReadBuffer;
809 class CommandModule : public Module
813 CommandModule() : cmd(this)
815 ServerInstance->AddCommand(&cmd);
820 return Version(cmd.name, VF_VENDOR|VF_CORE);