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 /** Template function to convert any input type to std::string
126 template<typename T> inline std::string ConvNumeric(const T &in)
128 if (in == 0) return "0";
133 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
140 std::reverse(res,out);
144 /** Template function to convert any input type to std::string
146 inline std::string ConvToStr(const int in)
148 return ConvNumeric(in);
151 /** Template function to convert any input type to std::string
153 inline std::string ConvToStr(const long in)
155 return ConvNumeric(in);
158 /** Template function to convert any input type to std::string
160 inline std::string ConvToStr(const char* in)
165 /** Template function to convert any input type to std::string
167 inline std::string ConvToStr(const bool in)
169 return (in ? "1" : "0");
172 /** Template function to convert any input type to std::string
174 inline std::string ConvToStr(char in)
176 return std::string(in,1);
179 /** Template function to convert any input type to std::string
181 template <class T> inline std::string ConvToStr(const T &in)
183 std::stringstream tmp;
184 if (!(tmp << in)) return std::string();
188 /** Template function to convert any input type to any other type
189 * (usually an integer or numeric type)
191 template<typename T> inline long ConvToInt(const T &in)
193 std::stringstream tmp;
194 if (!(tmp << in)) return 0;
195 return atol(tmp.str().c_str());
198 /** This class contains various STATS counters
199 * It is used by the InspIRCd class, which internally
200 * has an instance of it.
205 /** Number of accepted connections
207 unsigned long statsAccept;
208 /** Number of failed accepts
210 unsigned long statsRefused;
211 /** Number of unknown commands seen
213 unsigned long statsUnknown;
214 /** Number of nickname collisions handled
216 unsigned long statsCollisions;
217 /** Number of DNS queries sent out
219 unsigned long statsDns;
220 /** Number of good DNS replies received
221 * NOTE: This may not tally to the number sent out,
222 * due to timeouts and other latency issues.
224 unsigned long statsDnsGood;
225 /** Number of bad (negative) 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 statsDnsBad;
230 /** Number of inbound connections seen
232 unsigned long statsConnects;
233 /** Total bytes of data transmitted
235 unsigned long statsSent;
236 /** Total bytes of data received
238 unsigned long statsRecv;
240 /** Cpu usage at last sample
243 /** Time QP sample was read
245 LARGE_INTEGER LastSampled;
248 LARGE_INTEGER QPFrequency;
250 /** Cpu usage at last sample
253 /** Time last sample was read
255 timespec LastSampled;
257 /** The constructor initializes all the counts to zero
260 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
261 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0), statsRecv(0)
266 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
267 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
268 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
269 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
270 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
271 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
272 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
276 /** The main class of the irc server.
277 * This class contains instances of all the other classes in this software.
278 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
279 * object, and a list of active Module objects, and facilities for Module
280 * objects to interact with the core system it implements.
282 class CoreExport InspIRCd
285 /** Holds the current UID. Used to generate the next one.
287 char current_uid[UUID_LENGTH];
289 /** Set up the signal handlers
293 /** Daemonize the ircd and close standard input/output streams
294 * @return True if the program daemonized succesfully
298 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
299 * @param TIME the current time
301 void DoSocketTimeouts(time_t TIME);
303 /** Increments the current UID by one.
305 void IncrementUID(int pos);
307 /** Perform background user events such as PING checks
309 void DoBackgroundUserStuff();
311 /** Returns true when all modules have done pre-registration checks on a user
312 * @param user The user to verify
313 * @return True if all modules have finished checking this user
315 bool AllModulesReportReady(LocalUser* user);
317 /** The current time, updated in the mainloop
319 struct timespec TIME;
321 /** A 64k buffer used to read socket data into
322 * NOTE: update ValidateNetBufferSize if you change this
324 char ReadBuffer[65535];
328 /** Global cull list, will be processed on next iteration
330 CullList GlobalCulls;
331 /** Actions that must happen outside of the current call stack */
332 ActionList AtomicActions;
336 IsNickHandler HandleIsNick;
337 IsIdentHandler HandleIsIdent;
338 OnCheckExemptionHandler HandleOnCheckExemption;
339 IsChannelHandler HandleIsChannel;
340 IsSIDHandler HandleIsSID;
341 RehashHandler HandleRehash;
342 GenRandomHandler HandleGenRandom;
344 /** 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
347 * SendMode expects a User* to send the numeric replies
348 * back to, so we create it a fake user that isnt in the user
349 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
350 * falls into the abyss :p
352 FakeUser* FakeClient;
354 /** Returns the next available UID for this server.
356 std::string GetUID();
358 static const char LogHeader[];
360 /** Find a user in the UUID hash
361 * @param uid The UUID to find
362 * @return A pointer to the user, or NULL if the user does not exist
364 User* FindUUID(const std::string &uid);
366 /** Find a user in the UUID hash
367 * @param uid The UUID to find
368 * @return A pointer to the user, or NULL if the user does not exist
370 User* FindUUID(const char *uid);
372 /** Build the ISUPPORT string by triggering all modules On005Numeric events
374 void BuildISupport();
376 /** Time this ircd was booted
380 /** Config file pathname specified on the commandline or via ./configure
382 std::string ConfigFileName;
384 ExtensionManager Extensions;
386 /** Mode handler, handles mode setting and removal
390 /** Command parser, handles client to server commands
392 CommandParser* Parser;
394 /** Socket engine, handles socket activity events
398 /** Thread engine, Handles threading where required
400 ThreadEngine* Threads;
402 /** The thread/class used to read config files in REHASH and on startup
404 ConfigReaderThread* ConfigThread;
406 /** LogManager handles logging.
410 /** ModuleManager contains everything related to loading/unloading
413 ModuleManager* Modules;
415 /** BanCacheManager is used to speed up checking of restrictions on connection
418 BanCacheManager *BanCache;
420 /** Stats class, holds miscellaneous stats counters
424 /** Server Config class, holds configuration file data
426 ServerConfig* Config;
428 /** Snomask manager - handles routing of snomask messages
433 /** DNS class, provides resolver facilities to the core and modules
437 /** Timer manager class, triggers Timer timer events
439 TimerManager* Timers;
441 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
443 XLineManager* XLines;
445 /** User manager. Various methods and data associated with users.
449 /** Channel list, a hash_map containing all channels XXX move to channel manager class
453 /** List of the open ports
455 std::vector<ListenSocket*> ports;
457 /** Set to the current signal recieved
461 /** Protocol interface, overridden by server protocol modules
463 ProtocolInterface* PI;
465 /** Holds extensible for user nickforced
467 LocalIntExt NICKForced;
469 /** Holds extensible for user operquit
471 LocalStringExt OperQuit;
473 /** Get the current time
474 * Because this only calls time() once every time around the mainloop,
475 * it is much faster than calling time() directly.
476 * @return The current time as an epoch value (time_t)
478 inline time_t Time() { return TIME.tv_sec; }
479 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
480 inline long Time_ns() { return TIME.tv_nsec; }
481 /** Update the current time. Don't call this unless you have reason to do so. */
484 /** Generate a random string with the given length
485 * @param length The length in bytes
486 * @param printable if false, the string will use characters 0-255; otherwise,
487 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
489 std::string GenRandomStr(int length, bool printable = true);
490 /** Generate a random integer.
491 * This is generally more secure than rand()
493 unsigned long GenRandomInt(unsigned long max);
495 /** Fill a buffer with random bits */
496 caller2<void, char*, size_t> GenRandom;
498 /** Bind all ports specified in the configuration file.
499 * @return The number of ports bound without error
501 int BindPorts(FailedPortList &failed_ports);
503 /** Binds a socket on an already open file descriptor
504 * @param sockfd A valid file descriptor of an open socket
505 * @param port The port number to bind to
506 * @param addr The address to bind to (IP only)
507 * @param dolisten Should this port be listened on?
508 * @return True if the port was bound successfully
510 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
512 /** Gets the GECOS (description) field of the given server.
513 * If the servername is not that of the local server, the name
514 * is passed to handling modules which will attempt to determine
515 * the GECOS that bleongs to the given servername.
516 * @param servername The servername to find the description of
517 * @return The description of this server, or of the local server
519 std::string GetServerDescription(const std::string& servername);
521 /** Find a user in the nick hash.
522 * If the user cant be found in the nick hash check the uuid hash
523 * @param nick The nickname to find
524 * @return A pointer to the user, or NULL if the user does not exist
526 User* FindNick(const std::string &nick);
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 char* nick);
535 /** Find a user in the nick hash ONLY
537 User* FindNickOnly(const char* nick);
539 /** Find a user in the nick hash ONLY
541 User* FindNickOnly(const std::string &nick);
543 /** Find a channel in the channels hash
544 * @param chan The channel to find
545 * @return A pointer to the channel, or NULL if the channel does not exist
547 Channel* FindChan(const std::string &chan);
549 /** Find a channel in the channels hash
550 * @param chan The channel to find
551 * @return A pointer to the channel, or NULL if the channel does not exist
553 Channel* FindChan(const char* chan);
555 /** Check we aren't running as root, and exit if we are
556 * @return Depending on the configuration, this function may never return
560 /** Determine the right path for, and open, the logfile
561 * @param argv The argv passed to main() initially, used to calculate program path
562 * @param argc The argc passed to main() initially, used to calculate program path
563 * @return True if the log could be opened, false if otherwise
565 bool OpenLog(char** argv, int argc);
567 /** Return true if a channel name is valid
568 * @param chname A channel name to verify
569 * @return True if the name is valid
571 caller2<bool, const char*, size_t> IsChannel;
573 /** Return true if str looks like a server ID
574 * @param string to check against
576 caller1<bool, const std::string&> IsSID;
578 /** Rehash the local server
580 caller1<void, const std::string&> Rehash;
582 /** Handles incoming signals after being set
583 * @param signal the signal recieved
585 void SignalHandler(int signal);
587 /** Sets the signal recieved
588 * @param signal the signal recieved
590 static void SetSignal(int signal);
592 /** Causes the server to exit after unloading modules and
593 * closing all open file descriptors.
595 * @param status The exit code to give to the operating system
596 * (See the ExitStatus enum for valid values)
598 void Exit(int status);
600 /** Causes the server to exit immediately with exit code 0.
601 * The status code is required for signal handlers, and ignored.
603 static void QuickExit(int status);
605 /** Return a count of channels on the network
606 * @return The number of channels
610 /** Send an error notice to all local users, opered and unopered
611 * @param s The error string to send
613 void SendError(const std::string &s);
615 /** Return true if a nickname is valid
616 * @param n A nickname to verify
617 * @return True if the nick is valid
619 caller2<bool, const char*, size_t> IsNick;
621 /** Return true if an ident is valid
622 * @param An ident to verify
623 * @return True if the ident is valid
625 caller1<bool, const char*> IsIdent;
627 /** Add a dns Resolver class to this server's active set
628 * @param r The resolver to add
629 * @param cached If this value is true, then the cache will
630 * be searched for the DNS result, immediately. If the value is
631 * false, then a request will be sent to the nameserver, and the
632 * result will not be immediately available. You should usually
633 * use the boolean value which you passed to the Resolver
634 * constructor, which Resolver will set appropriately depending
635 * on if cached results are available and haven't expired. It is
636 * however safe to force this value to false, forcing a remote DNS
637 * lookup, but not an update of the cache.
638 * @return True if the operation completed successfully. Note that
639 * if this method returns true, you should not attempt to access
640 * the resolver class you pass it after this call, as depending upon
641 * the request given, the object may be deleted!
643 bool AddResolver(Resolver* r, bool cached);
645 /** Add a command to this server's command parser
646 * @param f A Command command handler object to add
647 * @throw ModuleException Will throw ModuleExcption if the command already exists
649 inline void AddCommand(Command *f)
651 Modules->AddService(*f);
654 /** Send a modechange.
655 * The parameters provided are identical to that sent to the
656 * handler for class cmd_mode.
657 * @param parameters The mode parameters
658 * @param user The user to send error messages to
660 void SendMode(const std::vector<std::string>& parameters, User *user);
662 /** Send a modechange and route it to the network.
663 * The parameters provided are identical to that sent to the
664 * handler for class cmd_mode.
665 * @param parameters The mode parameters
666 * @param user The user to send error messages to
668 void SendGlobalMode(const std::vector<std::string>& parameters, User *user);
670 /** Match two strings using pattern matching, optionally, with a map
671 * to check case against (may be NULL). If map is null, match will be case insensitive.
672 * @param str The literal string to match against
673 * @param mask The glob pattern to match against.
674 * @param map The character map to use when matching.
676 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
677 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
679 /** Match two strings using pattern matching, optionally, with a map
680 * to check case against (may be NULL). If map is null, match will be case insensitive.
681 * Supports CIDR patterns as well as globs.
682 * @param str The literal string to match against
683 * @param mask The glob or CIDR pattern to match against.
684 * @param map The character map to use when matching.
686 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
687 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
689 /** Return true if the given parameter is a valid nick!user\@host mask
690 * @param mask A nick!user\@host masak to match against
691 * @return True i the mask is valid
693 bool IsValidMask(const std::string &mask);
695 /** Strips all color codes from the given string
696 * @param sentence The string to strip from
698 static void StripColor(std::string &sentence);
700 /** Parses color codes from string values to actual color codes
701 * @param input The data to process
703 static void ProcessColors(file_cache& input);
705 /** Rehash the local server
709 /** Check if the given nickmask matches too many users, send errors to the given user
710 * @param nick A nickmask to match against
711 * @param user A user to send error text to
712 * @return True if the nick matches too many users
714 bool NickMatchesEveryone(const std::string &nick, User* user);
716 /** Check if the given IP mask matches too many users, send errors to the given user
717 * @param ip An ipmask to match against
718 * @param user A user to send error text to
719 * @return True if the ip matches too many users
721 bool IPMatchesEveryone(const std::string &ip, User* user);
723 /** Check if the given hostmask matches too many users, send errors to the given user
724 * @param mask A hostmask to match against
725 * @param user A user to send error text to
726 * @return True if the host matches too many users
728 bool HostMatchesEveryone(const std::string &mask, User* user);
730 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
731 * @param str A string containing a time in the form 1y2w3d4h6m5s
732 * (one year, two weeks, three days, four hours, six minutes and five seconds)
733 * @return The total number of seconds
735 long Duration(const std::string &str);
737 /** Attempt to compare a password to a string from the config file.
738 * This will be passed to handling modules which will compare the data
739 * against possible hashed equivalents in the input string.
740 * @param ex The object (user, server, whatever) causing the comparison.
741 * @param data The data from the config file
742 * @param input The data input by the oper
743 * @param hashtype The hash from the config file
744 * @return 0 if the strings match, 1 or -1 if they do not
746 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
748 /** Check if a given server is a uline.
749 * An empty string returns true, this is by design.
750 * @param server The server to check for uline status
751 * @return True if the server is a uline OR the string is empty
753 bool ULine(const std::string& server);
755 /** Returns true if the uline is 'silent' (doesnt generate
756 * remote connect notices etc).
758 bool SilentULine(const std::string& server);
760 /** Returns the full version string of this ircd
761 * @return The version string
763 std::string GetVersionString(bool rawversion = false);
765 /** Attempt to write the process id to a given file
766 * @param filename The PID file to attempt to write to
767 * @return This function may bail if the file cannot be written
769 void WritePID(const std::string &filename);
771 /** This constructor initialises all the subsystems and reads the config file.
772 * @param argc The argument count passed to main()
773 * @param argv The argument list passed to main()
774 * @throw <anything> If anything is thrown from here and makes it to
775 * you, you should probably just give up and go home. Yes, really.
776 * It's that bad. Higher level classes should catch any non-fatal exceptions.
778 InspIRCd(int argc, char** argv);
780 /** Send a line of WHOIS data to a user.
781 * @param user user to send the line to
782 * @param dest user being WHOISed
783 * @param numeric Numeric to send
784 * @param text Text of the numeric
786 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
788 /** Send a line of WHOIS data to a user.
789 * @param user user to send the line to
790 * @param dest user being WHOISed
791 * @param numeric Numeric to send
792 * @param format Format string for the numeric
793 * @param ... Parameters for the format string
795 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
799 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
801 /** Called to check whether a channel restriction mode applies to a user
802 * @param User that is attempting some action
803 * @param Channel that the action is being performed on
806 caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
808 /** Restart the server.
809 * This function will not return. If an error occurs,
810 * it will throw an instance of CoreException.
811 * @param reason The restart reason to show to all clients
812 * @throw CoreException An instance of CoreException indicating the error from execv().
814 void Restart(const std::string &reason);
816 /** Prepare the ircd for restart or shutdown.
817 * This function unloads all modules which can be unloaded,
818 * closes all open sockets, and closes the logfile.
822 /** This copies the user and channel hash_maps into new hash maps.
823 * This frees memory used by the hash_map allocator (which it neglects
824 * to free, most of the time, using tons of ram)
826 void RehashUsersAndChans();
828 /** Resets the cached max bans value on all channels.
833 /** Return a time_t as a human-readable string.
835 std::string TimeString(time_t curtime);
837 /** Begin execution of the server.
838 * NOTE: this function NEVER returns. Internally,
839 * it will repeatedly loop.
840 * @return The return value for this function is undefined.
844 /** Adds an extban char to the 005 token.
846 void AddExtBanChar(char c);
848 char* GetReadBuffer()
850 return this->ReadBuffer;
853 friend class TestSuite;
859 class CommandModule : public Module
863 CommandModule() : cmd(this)
869 ServerInstance->Modules->AddService(cmd);
874 return Version(cmd.name, VF_VENDOR|VF_CORE);