2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
7 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10 * Copyright (C) 2003 randomdan <???@???>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 #define _FILE_OFFSET_BITS 64
30 #ifndef _LARGEFILE_SOURCE
31 #define _LARGEFILE_SOURCE
38 #include "inspircd_win32wrapper.h"
39 /** Windows defines these already */
44 #define CUSTOM_PRINTF(STRING, FIRST) __attribute__((format(printf, STRING, FIRST)))
46 #define CUSTOM_PRINTF(STRING, FIRST)
49 #if defined __clang__ || defined __GNUC__
50 # define DEPRECATED_METHOD(function) function __attribute__((deprecated))
51 #elif defined _MSC_VER
52 # define DEPRECATED_METHOD(function) __declspec(deprecated) function
54 # pragma message ("Warning! DEPRECATED_METHOD() does not work on your compiler!")
55 # define DEPRECATED_METHOD(function) function
58 // Required system headers.
79 #include "inspircd_config.h"
80 #include "inspircd_version.h"
82 #include "consolecolors.h"
84 CoreExport extern InspIRCd* ServerInstance;
87 #include "cull_list.h"
88 #include "extensible.h"
96 #include "usermanager.h"
99 #include "command_parse.h"
101 #include "socketengine.h"
102 #include "snomasks.h"
103 #include "filelogger.h"
105 #include "threadengine.h"
106 #include "configreader.h"
107 #include "inspstring.h"
108 #include "protocol.h"
111 #warning Potentially broken system, PATH_MAX undefined
112 #define PATH_MAX 4096
116 * Used to define the maximum number of parameters a command may have.
118 #define MAXPARAMETERS 127
120 /** Returned by some functions to indicate failure.
124 /** Support for librodent -
125 * see http://www.chatspike.net/index.php?z=64
127 #define ETIREDHAMSTERS EAGAIN
129 /** Template function to convert any input type to std::string
131 template<typename T> inline std::string ConvNumeric(const T &in)
133 if (in == 0) return "0";
138 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
145 std::reverse(res,out);
149 /** Template function to convert any input type to std::string
151 inline std::string ConvToStr(const int in)
153 return ConvNumeric(in);
156 /** Template function to convert any input type to std::string
158 inline std::string ConvToStr(const long in)
160 return ConvNumeric(in);
163 /** Template function to convert any input type to std::string
165 inline std::string ConvToStr(const char* in)
170 /** Template function to convert any input type to std::string
172 inline std::string ConvToStr(const bool in)
174 return (in ? "1" : "0");
177 /** Template function to convert any input type to std::string
179 inline std::string ConvToStr(char in)
181 return std::string(in,1);
184 /** Template function to convert any input type to std::string
186 template <class T> inline std::string ConvToStr(const T &in)
188 std::stringstream tmp;
189 if (!(tmp << in)) return std::string();
193 /** Template function to convert any input type to any other type
194 * (usually an integer or numeric type)
196 template<typename T> inline long ConvToInt(const T &in)
198 std::stringstream tmp;
199 if (!(tmp << in)) return 0;
200 return atol(tmp.str().c_str());
203 /** This class contains various STATS counters
204 * It is used by the InspIRCd class, which internally
205 * has an instance of it.
210 /** Number of accepted connections
212 unsigned long statsAccept;
213 /** Number of failed accepts
215 unsigned long statsRefused;
216 /** Number of unknown commands seen
218 unsigned long statsUnknown;
219 /** Number of nickname collisions handled
221 unsigned long statsCollisions;
222 /** Number of DNS queries sent out
224 unsigned long statsDns;
225 /** Number of good DNS replies received
226 * NOTE: This may not tally to the number sent out,
227 * due to timeouts and other latency issues.
229 unsigned long statsDnsGood;
230 /** Number of bad (negative) DNS replies received
231 * NOTE: This may not tally to the number sent out,
232 * due to timeouts and other latency issues.
234 unsigned long statsDnsBad;
235 /** Number of inbound connections seen
237 unsigned long statsConnects;
238 /** Total bytes of data transmitted
240 unsigned long statsSent;
241 /** Total bytes of data received
243 unsigned long statsRecv;
245 /** Cpu usage at last sample
248 /** Time QP sample was read
250 LARGE_INTEGER LastSampled;
253 LARGE_INTEGER QPFrequency;
255 /** Cpu usage at last sample
258 /** Time last sample was read
260 timespec LastSampled;
262 /** The constructor initializes all the counts to zero
265 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
266 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0), statsRecv(0)
271 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
272 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
273 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
274 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
275 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
276 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
277 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
278 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
282 /** The main class of the irc server.
283 * This class contains instances of all the other classes in this software.
284 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
285 * object, and a list of active Module objects, and facilities for Module
286 * objects to interact with the core system it implements.
288 class CoreExport InspIRCd
291 /** Holds the current UID. Used to generate the next one.
293 char current_uid[UUID_LENGTH];
295 /** Set up the signal handlers
299 /** Daemonize the ircd and close standard input/output streams
300 * @return True if the program daemonized succesfully
304 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
305 * @param TIME the current time
307 void DoSocketTimeouts(time_t TIME);
309 /** Increments the current UID by one.
311 void IncrementUID(int pos);
313 /** Perform background user events such as PING checks
315 void DoBackgroundUserStuff();
317 /** Returns true when all modules have done pre-registration checks on a user
318 * @param user The user to verify
319 * @return True if all modules have finished checking this user
321 bool AllModulesReportReady(LocalUser* user);
323 /** The current time, updated in the mainloop
325 struct timespec TIME;
327 /** A 64k buffer used to read socket data into
328 * NOTE: update ValidateNetBufferSize if you change this
330 char ReadBuffer[65535];
334 /** Global cull list, will be processed on next iteration
336 CullList GlobalCulls;
337 /** Actions that must happen outside of the current call stack */
338 ActionList AtomicActions;
342 IsNickHandler HandleIsNick;
343 IsIdentHandler HandleIsIdent;
344 FloodQuitUserHandler HandleFloodQuitUser;
345 OnCheckExemptionHandler HandleOnCheckExemption;
346 IsChannelHandler HandleIsChannel;
347 IsSIDHandler HandleIsSID;
348 RehashHandler HandleRehash;
349 GenRandomHandler HandleGenRandom;
351 /** 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
354 * SendMode expects a User* to send the numeric replies
355 * back to, so we create it a fake user that isnt in the user
356 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
357 * falls into the abyss :p
359 FakeUser* FakeClient;
361 /** Returns the next available UID for this server.
363 std::string GetUID();
365 static const char LogHeader[];
367 /** Find a user in the UUID hash
368 * @param uid The UUID to find
369 * @return A pointer to the user, or NULL if the user does not exist
371 User* FindUUID(const std::string &uid);
373 /** Find a user in the UUID hash
374 * @param uid The UUID to find
375 * @return A pointer to the user, or NULL if the user does not exist
377 User* FindUUID(const char *uid);
379 /** Build the ISUPPORT string by triggering all modules On005Numeric events
381 void BuildISupport();
383 /** Time this ircd was booted
387 /** Config file pathname specified on the commandline or via ./configure
389 std::string ConfigFileName;
391 ExtensionManager Extensions;
393 /** Mode handler, handles mode setting and removal
397 /** Command parser, handles client to server commands
399 CommandParser* Parser;
401 /** Socket engine, handles socket activity events
405 /** Thread engine, Handles threading where required
407 ThreadEngine* Threads;
409 /** The thread/class used to read config files in REHASH and on startup
411 ConfigReaderThread* ConfigThread;
413 /** LogManager handles logging.
417 /** ModuleManager contains everything related to loading/unloading
420 ModuleManager* Modules;
422 /** BanCacheManager is used to speed up checking of restrictions on connection
425 BanCacheManager *BanCache;
427 /** Stats class, holds miscellaneous stats counters
431 /** Server Config class, holds configuration file data
433 ServerConfig* Config;
435 /** Snomask manager - handles routing of snomask messages
440 /** DNS class, provides resolver facilities to the core and modules
444 /** Timer manager class, triggers Timer timer events
446 TimerManager* Timers;
448 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
450 XLineManager* XLines;
452 /** User manager. Various methods and data associated with users.
456 /** Channel list, a hash_map containing all channels XXX move to channel manager class
460 /** List of the open ports
462 std::vector<ListenSocket*> ports;
464 /** Set to the current signal recieved
468 /** Protocol interface, overridden by server protocol modules
470 ProtocolInterface* PI;
472 /** Holds extensible for user nickforced
474 LocalIntExt NICKForced;
476 /** Holds extensible for user operquit
478 LocalStringExt OperQuit;
480 /** Get the current time
481 * Because this only calls time() once every time around the mainloop,
482 * it is much faster than calling time() directly.
483 * @return The current time as an epoch value (time_t)
485 inline time_t Time() { return TIME.tv_sec; }
486 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
487 inline long Time_ns() { return TIME.tv_nsec; }
488 /** Update the current time. Don't call this unless you have reason to do so. */
491 /** Generate a random string with the given length
492 * @param length The length in bytes
493 * @param printable if false, the string will use characters 0-255; otherwise,
494 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
496 std::string GenRandomStr(int length, bool printable = true);
497 /** Generate a random integer.
498 * This is generally more secure than rand()
500 unsigned long GenRandomInt(unsigned long max);
502 /** Fill a buffer with random bits */
503 caller2<void, char*, size_t> GenRandom;
505 /** Bind all ports specified in the configuration file.
506 * @return The number of ports bound without error
508 int BindPorts(FailedPortList &failed_ports);
510 /** Binds a socket on an already open file descriptor
511 * @param sockfd A valid file descriptor of an open socket
512 * @param port The port number to bind to
513 * @param addr The address to bind to (IP only)
514 * @param dolisten Should this port be listened on?
515 * @return True if the port was bound successfully
517 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
519 /** Gets the GECOS (description) field of the given server.
520 * If the servername is not that of the local server, the name
521 * is passed to handling modules which will attempt to determine
522 * the GECOS that bleongs to the given servername.
523 * @param servername The servername to find the description of
524 * @return The description of this server, or of the local server
526 std::string GetServerDescription(const std::string& servername);
528 /** Find a user in the nick hash.
529 * If the user cant be found in the nick hash check the uuid hash
530 * @param nick The nickname to find
531 * @return A pointer to the user, or NULL if the user does not exist
533 User* FindNick(const std::string &nick);
535 /** Find a user in the nick hash.
536 * If the user cant be found in the nick hash check the uuid hash
537 * @param nick The nickname to find
538 * @return A pointer to the user, or NULL if the user does not exist
540 User* FindNick(const char* nick);
542 /** Find a user in the nick hash ONLY
544 User* FindNickOnly(const char* nick);
546 /** Find a user in the nick hash ONLY
548 User* FindNickOnly(const std::string &nick);
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 std::string &chan);
556 /** Find a channel in the channels hash
557 * @param chan The channel to find
558 * @return A pointer to the channel, or NULL if the channel does not exist
560 Channel* FindChan(const char* chan);
562 /** Check we aren't running as root, and exit if we are
563 * @return Depending on the configuration, this function may never return
567 /** Determine the right path for, and open, the logfile
568 * @param argv The argv passed to main() initially, used to calculate program path
569 * @param argc The argc passed to main() initially, used to calculate program path
570 * @return True if the log could be opened, false if otherwise
572 bool OpenLog(char** argv, int argc);
574 /** Return true if a channel name is valid
575 * @param chname A channel name to verify
576 * @return True if the name is valid
578 caller2<bool, const char*, size_t> IsChannel;
580 /** Return true if str looks like a server ID
581 * @param string to check against
583 caller1<bool, const std::string&> IsSID;
585 /** Rehash the local server
587 caller1<void, const std::string&> Rehash;
589 /** Handles incoming signals after being set
590 * @param signal the signal recieved
592 void SignalHandler(int signal);
594 /** Sets the signal recieved
595 * @param signal the signal recieved
597 static void SetSignal(int signal);
599 /** Causes the server to exit after unloading modules and
600 * closing all open file descriptors.
602 * @param status The exit code to give to the operating system
603 * (See the ExitStatus enum for valid values)
605 void Exit(int status);
607 /** Causes the server to exit immediately with exit code 0.
608 * The status code is required for signal handlers, and ignored.
610 static void QuickExit(int status);
612 /** Return a count of channels on the network
613 * @return The number of channels
617 /** Send an error notice to all local users, opered and unopered
618 * @param s The error string to send
620 void SendError(const std::string &s);
622 /** Return true if a nickname is valid
623 * @param n A nickname to verify
624 * @return True if the nick is valid
626 caller2<bool, const char*, size_t> IsNick;
628 /** Return true if an ident is valid
629 * @param An ident to verify
630 * @return True if the ident is valid
632 caller1<bool, const char*> IsIdent;
634 /** Add a dns Resolver class to this server's active set
635 * @param r The resolver to add
636 * @param cached If this value is true, then the cache will
637 * be searched for the DNS result, immediately. If the value is
638 * false, then a request will be sent to the nameserver, and the
639 * result will not be immediately available. You should usually
640 * use the boolean value which you passed to the Resolver
641 * constructor, which Resolver will set appropriately depending
642 * on if cached results are available and haven't expired. It is
643 * however safe to force this value to false, forcing a remote DNS
644 * lookup, but not an update of the cache.
645 * @return True if the operation completed successfully. Note that
646 * if this method returns true, you should not attempt to access
647 * the resolver class you pass it after this call, as depending upon
648 * the request given, the object may be deleted!
650 bool AddResolver(Resolver* r, bool cached);
652 /** Add a command to this server's command parser
653 * @param f A Command command handler object to add
654 * @throw ModuleException Will throw ModuleExcption if the command already exists
656 inline void AddCommand(Command *f)
658 Modules->AddService(*f);
661 /** Send a modechange.
662 * The parameters provided are identical to that sent to the
663 * handler for class cmd_mode.
664 * @param parameters The mode parameters
665 * @param user The user to send error messages to
667 void SendMode(const std::vector<std::string>& parameters, User *user);
669 /** Send a modechange and route it to the network.
670 * The parameters provided are identical to that sent to the
671 * handler for class cmd_mode.
672 * @param parameters The mode parameters
673 * @param user The user to send error messages to
675 void SendGlobalMode(const std::vector<std::string>& parameters, User *user);
677 /** Match two strings using pattern matching, optionally, with a map
678 * to check case against (may be NULL). If map is null, match will be case insensitive.
679 * @param str The literal string to match against
680 * @param mask The glob pattern to match against.
681 * @param map The character map to use when matching.
683 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
684 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
686 /** Match two strings using pattern matching, optionally, with a map
687 * to check case against (may be NULL). If map is null, match will be case insensitive.
688 * Supports CIDR patterns as well as globs.
689 * @param str The literal string to match against
690 * @param mask The glob or CIDR pattern to match against.
691 * @param map The character map to use when matching.
693 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
694 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
696 /** Call the handler for a given command.
697 * @param commandname The command whos handler you wish to call
698 * @param parameters The mode parameters
699 * @param user The user to execute the command as
700 * @return True if the command handler was called successfully
702 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
704 /** Return true if the command is a module-implemented command and the given parameters are valid for it
705 * @param commandname The command name to check
706 * @param pcnt The parameter count
707 * @param user The user to test-execute the command as
708 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
710 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
712 /** Return true if the given parameter is a valid nick!user\@host mask
713 * @param mask A nick!user\@host masak to match against
714 * @return True i the mask is valid
716 bool IsValidMask(const std::string &mask);
718 /** Strips all color codes from the given string
719 * @param sentence The string to strip from
721 static void StripColor(std::string &sentence);
723 /** Parses color codes from string values to actual color codes
724 * @param input The data to process
726 static void ProcessColors(file_cache& input);
728 /** Rehash the local server
732 /** Check if the given nickmask matches too many users, send errors to the given user
733 * @param nick A nickmask to match against
734 * @param user A user to send error text to
735 * @return True if the nick matches too many users
737 bool NickMatchesEveryone(const std::string &nick, User* user);
739 /** Check if the given IP mask matches too many users, send errors to the given user
740 * @param ip An ipmask to match against
741 * @param user A user to send error text to
742 * @return True if the ip matches too many users
744 bool IPMatchesEveryone(const std::string &ip, User* user);
746 /** Check if the given hostmask matches too many users, send errors to the given user
747 * @param mask A hostmask to match against
748 * @param user A user to send error text to
749 * @return True if the host matches too many users
751 bool HostMatchesEveryone(const std::string &mask, User* user);
753 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
754 * @param str A string containing a time in the form 1y2w3d4h6m5s
755 * (one year, two weeks, three days, four hours, six minutes and five seconds)
756 * @return The total number of seconds
758 long Duration(const std::string &str);
760 /** Attempt to compare a password to a string from the config file.
761 * This will be passed to handling modules which will compare the data
762 * against possible hashed equivalents in the input string.
763 * @param ex The object (user, server, whatever) causing the comparison.
764 * @param data The data from the config file
765 * @param input The data input by the oper
766 * @param hashtype The hash from the config file
767 * @return 0 if the strings match, 1 or -1 if they do not
769 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
771 /** Check if a given server is a uline.
772 * An empty string returns true, this is by design.
773 * @param server The server to check for uline status
774 * @return True if the server is a uline OR the string is empty
776 bool ULine(const std::string& server);
778 /** Returns true if the uline is 'silent' (doesnt generate
779 * remote connect notices etc).
781 bool SilentULine(const std::string& server);
783 /** Returns the full version string of this ircd
784 * @return The version string
786 std::string GetVersionString(bool rawversion = false);
788 /** Attempt to write the process id to a given file
789 * @param filename The PID file to attempt to write to
790 * @return This function may bail if the file cannot be written
792 void WritePID(const std::string &filename);
794 /** This constructor initialises all the subsystems and reads the config file.
795 * @param argc The argument count passed to main()
796 * @param argv The argument list passed to main()
797 * @throw <anything> If anything is thrown from here and makes it to
798 * you, you should probably just give up and go home. Yes, really.
799 * It's that bad. Higher level classes should catch any non-fatal exceptions.
801 InspIRCd(int argc, char** argv);
803 /** Send a line of WHOIS data to a user.
804 * @param user user to send the line to
805 * @param dest user being WHOISed
806 * @param numeric Numeric to send
807 * @param text Text of the numeric
809 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
811 /** Send a line of WHOIS data to a user.
812 * @param user user to send the line to
813 * @param dest user being WHOISed
814 * @param numeric Numeric to send
815 * @param format Format string for the numeric
816 * @param ... Parameters for the format string
818 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
822 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
824 /** Quit a user for excess flood, and if they are not
825 * fully registered yet, temporarily zline their IP.
826 * @param current user to quit
828 caller1<void, User*> FloodQuitUser;
830 /** Called to check whether a channel restriction mode applies to a user
831 * @param User that is attempting some action
832 * @param Channel that the action is being performed on
835 caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
837 /** Restart the server.
838 * This function will not return. If an error occurs,
839 * it will throw an instance of CoreException.
840 * @param reason The restart reason to show to all clients
841 * @throw CoreException An instance of CoreException indicating the error from execv().
843 void Restart(const std::string &reason);
845 /** Prepare the ircd for restart or shutdown.
846 * This function unloads all modules which can be unloaded,
847 * closes all open sockets, and closes the logfile.
851 /** This copies the user and channel hash_maps into new hash maps.
852 * This frees memory used by the hash_map allocator (which it neglects
853 * to free, most of the time, using tons of ram)
855 void RehashUsersAndChans();
857 /** Resets the cached max bans value on all channels.
862 /** Return a time_t as a human-readable string.
864 std::string TimeString(time_t curtime);
866 /** Begin execution of the server.
867 * NOTE: this function NEVER returns. Internally,
868 * it will repeatedly loop.
869 * @return The return value for this function is undefined.
873 /** Adds an extban char to the 005 token.
875 void AddExtBanChar(char c);
877 char* GetReadBuffer()
879 return this->ReadBuffer;
882 friend class TestSuite;
888 class CommandModule : public Module
892 CommandModule() : cmd(this)
898 ServerInstance->Modules->AddService(cmd);
903 return Version(cmd.name, VF_VENDOR|VF_CORE);