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.
56 #include "inspircd_config.h"
57 #include "inspircd_version.h"
60 CoreExport extern InspIRCd* ServerInstance;
63 #include "cull_list.h"
64 #include "extensible.h"
72 #include "usermanager.h"
75 #include "command_parse.h"
77 #include "socketengine.h"
79 #include "filelogger.h"
82 #include "threadengine.h"
83 #include "configreader.h"
84 #include "inspstring.h"
88 #warning Potentially broken system, PATH_MAX undefined
93 * Used to define the maximum number of parameters a command may have.
95 #define MAXPARAMETERS 127
97 /** Returned by some functions to indicate failure.
101 /** Support for librodent -
102 * see http://www.chatspike.net/index.php?z=64
104 #define ETIREDHAMSTERS EAGAIN
106 /** Template function to convert any input type to std::string
108 template<typename T> inline std::string ConvNumeric(const T &in)
110 if (in == 0) return "0";
115 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
122 std::reverse(res,out);
126 /** Template function to convert any input type to std::string
128 inline std::string ConvToStr(const int in)
130 return ConvNumeric(in);
133 /** Template function to convert any input type to std::string
135 inline std::string ConvToStr(const long in)
137 return ConvNumeric(in);
140 /** Template function to convert any input type to std::string
142 inline std::string ConvToStr(const char* in)
147 /** Template function to convert any input type to std::string
149 inline std::string ConvToStr(const bool in)
151 return (in ? "1" : "0");
154 /** Template function to convert any input type to std::string
156 inline std::string ConvToStr(char in)
158 return std::string(in,1);
161 /** Template function to convert any input type to std::string
163 template <class T> inline std::string ConvToStr(const T &in)
165 std::stringstream tmp;
166 if (!(tmp << in)) return std::string();
170 /** Template function to convert any input type to any other type
171 * (usually an integer or numeric type)
173 template<typename T> inline long ConvToInt(const T &in)
175 std::stringstream tmp;
176 if (!(tmp << in)) return 0;
177 return atol(tmp.str().c_str());
180 /** This class contains various STATS counters
181 * It is used by the InspIRCd class, which internally
182 * has an instance of it.
187 /** Number of accepted connections
189 unsigned long statsAccept;
190 /** Number of failed accepts
192 unsigned long statsRefused;
193 /** Number of unknown commands seen
195 unsigned long statsUnknown;
196 /** Number of nickname collisions handled
198 unsigned long statsCollisions;
199 /** Number of DNS queries sent out
201 unsigned long statsDns;
202 /** Number of good DNS replies received
203 * NOTE: This may not tally to the number sent out,
204 * due to timeouts and other latency issues.
206 unsigned long statsDnsGood;
207 /** Number of bad (negative) DNS replies received
208 * NOTE: This may not tally to the number sent out,
209 * due to timeouts and other latency issues.
211 unsigned long statsDnsBad;
212 /** Number of inbound connections seen
214 unsigned long statsConnects;
215 /** Total bytes of data transmitted
218 /** Total bytes of data received
221 /** Cpu usage at last sample
224 /** Time last sample was read
226 timespec LastSampled;
227 /** The constructor initializes all the counts to zero
230 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
231 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
236 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
237 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
238 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
239 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
240 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
241 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
243 /** The main class of the irc server.
244 * This class contains instances of all the other classes in this software.
245 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
246 * object, and a list of active Module objects, and facilities for Module
247 * objects to interact with the core system it implements.
249 class CoreExport InspIRCd
252 /** Holds the current UID. Used to generate the next one.
254 char current_uid[UUID_LENGTH];
256 /** Set up the signal handlers
260 /** Daemonize the ircd and close standard input/output streams
261 * @return True if the program daemonized succesfully
265 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
266 * @param TIME the current time
268 void DoSocketTimeouts(time_t TIME);
270 /** Increments the current UID by one.
272 void IncrementUID(int pos);
274 /** Perform background user events such as PING checks
276 void DoBackgroundUserStuff();
278 /** Returns true when all modules have done pre-registration checks on a user
279 * @param user The user to verify
280 * @return True if all modules have finished checking this user
282 bool AllModulesReportReady(LocalUser* user);
284 /** The current time, updated in the mainloop
286 struct timespec TIME;
288 /** A 64k buffer used to read socket data into
289 * NOTE: update ValidateNetBufferSize if you change this
291 char ReadBuffer[65535];
299 /** Global cull list, will be processed on next iteration
301 CullList GlobalCulls;
302 /** Actions that must happen outside of the current call stack */
303 ActionList AtomicActions;
307 IsNickHandler HandleIsNick;
308 IsIdentHandler HandleIsIdent;
309 FloodQuitUserHandler HandleFloodQuitUser;
310 IsChannelHandler HandleIsChannel;
311 IsSIDHandler HandleIsSID;
312 RehashHandler HandleRehash;
314 /** 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
317 * SendMode expects a User* to send the numeric replies
318 * back to, so we create it a fake user that isnt in the user
319 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
320 * falls into the abyss :p
322 FakeUser* FakeClient;
324 /** Returns the next available UID for this server.
326 std::string GetUID();
328 /** Find a user in the UUID hash
329 * @param nick The nickname to find
330 * @return A pointer to the user, or NULL if the user does not exist
332 User* FindUUID(const std::string &);
334 /** Find a user in the UUID hash
335 * @param nick The nickname to find
336 * @return A pointer to the user, or NULL if the user does not exist
338 User* FindUUID(const char *);
340 /** Build the ISUPPORT string by triggering all modules On005Numeric events
342 void BuildISupport();
344 /** Time this ircd was booted
348 /** Config file pathname specified on the commandline or via ./configure
350 std::string ConfigFileName;
352 ExtensionManager Extensions;
354 /** Mode handler, handles mode setting and removal
358 /** Command parser, handles client to server commands
360 CommandParser* Parser;
362 /** Socket engine, handles socket activity events
366 /** Thread engine, Handles threading where required
368 ThreadEngine* Threads;
370 /** The thread/class used to read config files in REHASH and on startup
372 ConfigReaderThread* ConfigThread;
374 /** LogManager handles logging.
378 /** ModuleManager contains everything related to loading/unloading
381 ModuleManager* Modules;
383 /** BanCacheManager is used to speed up checking of restrictions on connection
386 BanCacheManager *BanCache;
388 /** Stats class, holds miscellaneous stats counters
392 /** Server Config class, holds configuration file data
394 ServerConfig* Config;
396 /** Snomask manager - handles routing of snomask messages
401 /** DNS class, provides resolver facilities to the core and modules
405 /** Timer manager class, triggers Timer timer events
407 TimerManager* Timers;
409 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
411 XLineManager* XLines;
413 /** User manager. Various methods and data associated with users.
417 /** Channel list, a hash_map containing all channels XXX move to channel manager class
421 /** List of the open ports
423 std::vector<ListenSocket*> ports;
425 /** Set to the current signal recieved
429 /** Protocol interface, overridden by server protocol modules
431 ProtocolInterface* PI;
433 /** Holds extensible for user nickforced
435 LocalIntExt NICKForced;
437 /** Holds extensible for user operquit
439 LocalStringExt OperQuit;
441 /** Get the current time
442 * Because this only calls time() once every time around the mainloop,
443 * it is much faster than calling time() directly.
444 * @return The current time as an epoch value (time_t)
446 inline time_t Time() { return TIME.tv_sec; }
447 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
448 inline long Time_ns() { return TIME.tv_nsec; }
449 /** Update the current time. Don't call this unless you have reason to do so. */
452 /** Bind all ports specified in the configuration file.
453 * @return The number of ports bound without error
455 int BindPorts(FailedPortList &failed_ports);
457 /** Binds a socket on an already open file descriptor
458 * @param sockfd A valid file descriptor of an open socket
459 * @param port The port number to bind to
460 * @param addr The address to bind to (IP only)
461 * @return True if the port was bound successfully
463 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
465 /** Gets the GECOS (description) field of the given server.
466 * If the servername is not that of the local server, the name
467 * is passed to handling modules which will attempt to determine
468 * the GECOS that bleongs to the given servername.
469 * @param servername The servername to find the description of
470 * @return The description of this server, or of the local server
472 std::string GetServerDescription(const std::string& servername);
474 /** Find a user in the nick hash.
475 * If the user cant be found in the nick hash check the uuid hash
476 * @param nick The nickname to find
477 * @return A pointer to the user, or NULL if the user does not exist
479 User* FindNick(const std::string &nick);
481 /** Find a user in the nick hash.
482 * If the user cant be found in the nick hash check the uuid hash
483 * @param nick The nickname to find
484 * @return A pointer to the user, or NULL if the user does not exist
486 User* FindNick(const char* nick);
488 /** Find a user in the nick hash ONLY
490 User* FindNickOnly(const char* nick);
492 /** Find a user in the nick hash ONLY
494 User* FindNickOnly(const std::string &nick);
496 /** Find a channel in the channels hash
497 * @param chan The channel to find
498 * @return A pointer to the channel, or NULL if the channel does not exist
500 Channel* FindChan(const std::string &chan);
502 /** Find a channel in the channels hash
503 * @param chan The channel to find
504 * @return A pointer to the channel, or NULL if the channel does not exist
506 Channel* FindChan(const char* chan);
508 /** Check we aren't running as root, and exit if we are
509 * @return Depending on the configuration, this function may never return
513 /** Determine the right path for, and open, the logfile
514 * @param argv The argv passed to main() initially, used to calculate program path
515 * @param argc The argc passed to main() initially, used to calculate program path
516 * @return True if the log could be opened, false if otherwise
518 bool OpenLog(char** argv, int argc);
520 /** Return true if a channel name is valid
521 * @param chname A channel name to verify
522 * @return True if the name is valid
524 caller2<bool, const char*, size_t> IsChannel;
526 /** Return true if str looks like a server ID
527 * @param string to check against
529 caller1<bool, const std::string&> IsSID;
531 /** Rehash the local server
533 caller1<void, const std::string&> Rehash;
535 /** Handles incoming signals after being set
536 * @param signal the signal recieved
538 void SignalHandler(int signal);
540 /** Sets the signal recieved
541 * @param signal the signal recieved
543 static void SetSignal(int signal);
545 /** Causes the server to exit after unloading modules and
546 * closing all open file descriptors.
548 * @param The exit code to give to the operating system
549 * (See the ExitStatus enum for valid values)
551 void Exit(int status);
553 /** Causes the server to exit immediately with exit code 0.
554 * The status code is required for signal handlers, and ignored.
556 static void QuickExit(int status);
558 /** Return a count of channels on the network
559 * @return The number of channels
563 /** Send an error notice to all local users, opered and unopered
564 * @param s The error string to send
566 void SendError(const std::string &s);
568 /** Return true if a nickname is valid
569 * @param n A nickname to verify
570 * @return True if the nick is valid
572 caller2<bool, const char*, size_t> IsNick;
574 /** Return true if an ident is valid
575 * @param An ident to verify
576 * @return True if the ident is valid
578 caller1<bool, const char*> IsIdent;
580 /** Add a dns Resolver class to this server's active set
581 * @param r The resolver to add
582 * @param cached If this value is true, then the cache will
583 * be searched for the DNS result, immediately. If the value is
584 * false, then a request will be sent to the nameserver, and the
585 * result will not be immediately available. You should usually
586 * use the boolean value which you passed to the Resolver
587 * constructor, which Resolver will set appropriately depending
588 * on if cached results are available and haven't expired. It is
589 * however safe to force this value to false, forcing a remote DNS
590 * lookup, but not an update of the cache.
591 * @return True if the operation completed successfully. Note that
592 * if this method returns true, you should not attempt to access
593 * the resolver class you pass it after this call, as depending upon
594 * the request given, the object may be deleted!
596 bool AddResolver(Resolver* r, bool cached);
598 /** Add a command to this server's command parser
599 * @param f A Command command handler object to add
600 * @throw ModuleException Will throw ModuleExcption if the command already exists
602 inline void AddCommand(Command *f)
604 Modules->AddService(*f);
607 /** Send a modechange.
608 * The parameters provided are identical to that sent to the
609 * handler for class cmd_mode.
610 * @param parameters The mode parameters
611 * @param user The user to send error messages to
613 void SendMode(const std::vector<std::string>& parameters, User *user);
615 /** Send a modechange and route it to the network.
616 * The parameters provided are identical to that sent to the
617 * handler for class cmd_mode.
618 * @param parameters The mode parameters
619 * @param user The user to send error messages to
621 void SendGlobalMode(const std::vector<std::string>& parameters, User *user);
623 /** Match two strings using pattern matching, optionally, with a map
624 * to check case against (may be NULL). If map is null, match will be case insensitive.
625 * @param str The literal string to match against
626 * @param mask The glob pattern to match against.
628 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
629 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
631 /** Match two strings using pattern matching, optionally, with a map
632 * to check case against (may be NULL). If map is null, match will be case insensitive.
633 * Supports CIDR patterns as well as globs.
634 * @param str The literal string to match against
635 * @param mask The glob or CIDR pattern to match against.
637 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
638 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
640 /** Call the handler for a given command.
641 * @param commandname The command whos handler you wish to call
642 * @param parameters The mode parameters
643 * @param pcnt The number of items you have given in the first parameter
644 * @param user The user to execute the command as
645 * @return True if the command handler was called successfully
647 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
649 /** Return true if the command is a module-implemented command and the given parameters are valid for it
650 * @param parameters The mode parameters
651 * @param pcnt The number of items you have given in the first parameter
652 * @param user The user to test-execute the command as
653 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
655 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
657 /** Return true if the given parameter is a valid nick!user\@host mask
658 * @param mask A nick!user\@host masak to match against
659 * @return True i the mask is valid
661 bool IsValidMask(const std::string &mask);
663 /** Rehash the local server
667 /** Check if the given nickmask matches too many users, send errors to the given user
668 * @param nick A nickmask to match against
669 * @param user A user to send error text to
670 * @return True if the nick matches too many users
672 bool NickMatchesEveryone(const std::string &nick, User* user);
674 /** Check if the given IP mask matches too many users, send errors to the given user
675 * @param ip An ipmask to match against
676 * @param user A user to send error text to
677 * @return True if the ip matches too many users
679 bool IPMatchesEveryone(const std::string &ip, User* user);
681 /** Check if the given hostmask matches too many users, send errors to the given user
682 * @param mask A hostmask to match against
683 * @param user A user to send error text to
684 * @return True if the host matches too many users
686 bool HostMatchesEveryone(const std::string &mask, User* user);
688 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
689 * @param str A string containing a time in the form 1y2w3d4h6m5s
690 * (one year, two weeks, three days, four hours, six minutes and five seconds)
691 * @return The total number of seconds
693 long Duration(const std::string &str);
695 /** Attempt to compare a password to a string from the config file.
696 * This will be passed to handling modules which will compare the data
697 * against possible hashed equivalents in the input string.
698 * @param ex The object (user, server, whatever) causing the comparison.
699 * @param data The data from the config file
700 * @param input The data input by the oper
701 * @param hashtype The hash from the config file
702 * @return 0 if the strings match, 1 or -1 if they do not
704 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
706 /** Check if a given server is a uline.
707 * An empty string returns true, this is by design.
708 * @param server The server to check for uline status
709 * @return True if the server is a uline OR the string is empty
711 bool ULine(const std::string& server);
713 /** Returns true if the uline is 'silent' (doesnt generate
714 * remote connect notices etc).
716 bool SilentULine(const std::string& server);
718 /** Returns the full version string of this ircd
719 * @return The version string
721 std::string GetVersionString();
723 /** Attempt to write the process id to a given file
724 * @param filename The PID file to attempt to write to
725 * @return This function may bail if the file cannot be written
727 void WritePID(const std::string &filename);
729 /** This constructor initialises all the subsystems and reads the config file.
730 * @param argc The argument count passed to main()
731 * @param argv The argument list passed to main()
732 * @throw <anything> If anything is thrown from here and makes it to
733 * you, you should probably just give up and go home. Yes, really.
734 * It's that bad. Higher level classes should catch any non-fatal exceptions.
736 InspIRCd(int argc, char** argv);
738 /** Send a line of WHOIS data to a user.
739 * @param user user to send the line to
740 * @param dest user being WHOISed
741 * @param numeric Numeric to send
742 * @param text Text of the numeric
744 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
746 /** Send a line of WHOIS data to a user.
747 * @param user user to send the line to
748 * @param dest user being WHOISed
749 * @param numeric Numeric to send
750 * @param format Format string for the numeric
751 * @param ... Parameters for the format string
753 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
757 void DoStats(char statschar, User* user, string_list &results);
761 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
763 /** Quit a user for excess flood, and if they are not
764 * fully registered yet, temporarily zline their IP.
765 * @param current user to quit
767 caller1<void, User*> FloodQuitUser;
769 /** Restart the server.
770 * This function will not return. If an error occurs,
771 * it will throw an instance of CoreException.
772 * @param reason The restart reason to show to all clients
773 * @throw CoreException An instance of CoreException indicating the error from execv().
775 void Restart(const std::string &reason);
777 /** Prepare the ircd for restart or shutdown.
778 * This function unloads all modules which can be unloaded,
779 * closes all open sockets, and closes the logfile.
783 /** This copies the user and channel hash_maps into new hash maps.
784 * This frees memory used by the hash_map allocator (which it neglects
785 * to free, most of the time, using tons of ram)
787 void RehashUsersAndChans();
789 /** Resets the cached max bans value on all channels.
794 /** Return a time_t as a human-readable string.
796 std::string TimeString(time_t curtime);
798 /** Begin execution of the server.
799 * NOTE: this function NEVER returns. Internally,
800 * it will repeatedly loop.
801 * @return The return value for this function is undefined.
805 /** Adds an extban char to the 005 token.
807 void AddExtBanChar(char c);
809 char* GetReadBuffer()
811 return this->ReadBuffer;
818 class CommandModule : public Module
822 CommandModule() : cmd(this)
828 ServerInstance->Modules->AddService(cmd);
833 return Version(cmd.name, VF_VENDOR|VF_CORE);