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 // Required system headers.
71 #include "inspircd_config.h"
72 #include "inspircd_version.h"
74 #include "consolecolors.h"
76 CoreExport extern InspIRCd* ServerInstance;
79 #include "cull_list.h"
80 #include "extensible.h"
88 #include "usermanager.h"
91 #include "command_parse.h"
93 #include "socketengine.h"
95 #include "filelogger.h"
97 #include "threadengine.h"
98 #include "configreader.h"
99 #include "inspstring.h"
100 #include "protocol.h"
103 #warning Potentially broken system, PATH_MAX undefined
104 #define PATH_MAX 4096
108 * Used to define the maximum number of parameters a command may have.
110 #define MAXPARAMETERS 127
112 /** Returned by some functions to indicate failure.
116 /** Support for librodent -
117 * see http://www.chatspike.net/index.php?z=64
119 #define ETIREDHAMSTERS EAGAIN
121 /** Template function to convert any input type to std::string
123 template<typename T> inline std::string ConvNumeric(const T &in)
125 if (in == 0) return "0";
130 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
137 std::reverse(res,out);
141 /** Template function to convert any input type to std::string
143 inline std::string ConvToStr(const int in)
145 return ConvNumeric(in);
148 /** Template function to convert any input type to std::string
150 inline std::string ConvToStr(const long in)
152 return ConvNumeric(in);
155 /** Template function to convert any input type to std::string
157 inline std::string ConvToStr(const char* in)
162 /** Template function to convert any input type to std::string
164 inline std::string ConvToStr(const bool in)
166 return (in ? "1" : "0");
169 /** Template function to convert any input type to std::string
171 inline std::string ConvToStr(char in)
173 return std::string(1, in);
176 /** Template function to convert any input type to std::string
178 template <class T> inline std::string ConvToStr(const T &in)
180 std::stringstream tmp;
181 if (!(tmp << in)) return std::string();
185 /** Template function to convert any input type to any other type
186 * (usually an integer or numeric type)
188 template<typename T> inline long ConvToInt(const T &in)
190 std::stringstream tmp;
191 if (!(tmp << in)) return 0;
192 return atol(tmp.str().c_str());
195 /** This class contains various STATS counters
196 * It is used by the InspIRCd class, which internally
197 * has an instance of it.
202 /** Number of accepted connections
204 unsigned long statsAccept;
205 /** Number of failed accepts
207 unsigned long statsRefused;
208 /** Number of unknown commands seen
210 unsigned long statsUnknown;
211 /** Number of nickname collisions handled
213 unsigned long statsCollisions;
214 /** Number of DNS queries sent out
216 unsigned long statsDns;
217 /** Number of good DNS replies received
218 * NOTE: This may not tally to the number sent out,
219 * due to timeouts and other latency issues.
221 unsigned long statsDnsGood;
222 /** Number of bad (negative) DNS replies received
223 * NOTE: This may not tally to the number sent out,
224 * due to timeouts and other latency issues.
226 unsigned long statsDnsBad;
227 /** Number of inbound connections seen
229 unsigned long statsConnects;
230 /** Total bytes of data transmitted
232 unsigned long statsSent;
233 /** Total bytes of data received
235 unsigned long statsRecv;
237 /** Cpu usage at last sample
240 /** Time QP sample was read
242 LARGE_INTEGER LastSampled;
245 LARGE_INTEGER QPFrequency;
247 /** Cpu usage at last sample
250 /** Time last sample was read
252 timespec LastSampled;
254 /** The constructor initializes all the counts to zero
257 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
258 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0), statsRecv(0)
263 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
264 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
265 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
266 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
267 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
268 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
269 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
270 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
274 /** The main class of the irc server.
275 * This class contains instances of all the other classes in this software.
276 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
277 * object, and a list of active Module objects, and facilities for Module
278 * objects to interact with the core system it implements.
280 class CoreExport InspIRCd
283 /** Holds the current UID. Used to generate the next one.
285 char current_uid[UUID_LENGTH];
287 /** Set up the signal handlers
291 /** Daemonize the ircd and close standard input/output streams
292 * @return True if the program daemonized succesfully
296 /** Iterate the list of BufferedSocket objects, removing ones which have timed out
297 * @param TIME the current time
299 void DoSocketTimeouts(time_t TIME);
301 /** Increments the current UID by one.
303 void IncrementUID(int pos);
305 /** Perform background user events such as PING checks
307 void DoBackgroundUserStuff();
309 /** Returns true when all modules have done pre-registration checks on a user
310 * @param user The user to verify
311 * @return True if all modules have finished checking this user
313 bool AllModulesReportReady(LocalUser* user);
315 /** The current time, updated in the mainloop
317 struct timespec TIME;
319 /** A 64k buffer used to read socket data into
320 * NOTE: update ValidateNetBufferSize if you change this
322 char ReadBuffer[65535];
326 /** Global cull list, will be processed on next iteration
328 CullList GlobalCulls;
329 /** Actions that must happen outside of the current call stack */
330 ActionList AtomicActions;
334 IsNickHandler HandleIsNick;
335 IsIdentHandler HandleIsIdent;
336 FloodQuitUserHandler HandleFloodQuitUser;
337 OnCheckExemptionHandler HandleOnCheckExemption;
338 IsChannelHandler HandleIsChannel;
339 IsSIDHandler HandleIsSID;
340 RehashHandler HandleRehash;
341 GenRandomHandler HandleGenRandom;
343 /** 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
346 * SendMode expects a User* to send the numeric replies
347 * back to, so we create it a fake user that isnt in the user
348 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
349 * falls into the abyss :p
351 FakeUser* FakeClient;
353 /** Returns the next available UID for this server.
355 std::string GetUID();
357 static const char LogHeader[];
359 /** Find a user in the UUID hash
360 * @param uid The UUID to find
361 * @return A pointer to the user, or NULL if the user does not exist
363 User* FindUUID(const std::string &uid);
365 /** Find a user in the UUID hash
366 * @param uid The UUID to find
367 * @return A pointer to the user, or NULL if the user does not exist
369 User* FindUUID(const char *uid);
371 /** Build the ISUPPORT string by triggering all modules On005Numeric events
373 void BuildISupport();
375 /** Time this ircd was booted
379 /** Config file pathname specified on the commandline or via ./configure
381 std::string ConfigFileName;
383 ExtensionManager Extensions;
385 /** Mode handler, handles mode setting and removal
389 /** Command parser, handles client to server commands
391 CommandParser* Parser;
393 /** Socket engine, handles socket activity events
397 /** Thread engine, Handles threading where required
399 ThreadEngine* Threads;
401 /** The thread/class used to read config files in REHASH and on startup
403 ConfigReaderThread* ConfigThread;
405 /** LogManager handles logging.
409 /** ModuleManager contains everything related to loading/unloading
412 ModuleManager* Modules;
414 /** BanCacheManager is used to speed up checking of restrictions on connection
417 BanCacheManager *BanCache;
419 /** Stats class, holds miscellaneous stats counters
423 /** Server Config class, holds configuration file data
425 ServerConfig* Config;
427 /** Snomask manager - handles routing of snomask messages
432 /** DNS class, provides resolver facilities to the core and modules
436 /** Timer manager class, triggers Timer timer events
438 TimerManager* Timers;
440 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
442 XLineManager* XLines;
444 /** User manager. Various methods and data associated with users.
448 /** Channel list, a hash_map containing all channels XXX move to channel manager class
452 /** List of the open ports
454 std::vector<ListenSocket*> ports;
456 /** Set to the current signal recieved
458 static sig_atomic_t s_signal;
460 /** Protocol interface, overridden by server protocol modules
462 ProtocolInterface* PI;
464 /** Holds extensible for user nickforced
466 LocalIntExt NICKForced;
468 /** Holds extensible for user operquit
470 LocalStringExt OperQuit;
472 /** Get the current time
473 * Because this only calls time() once every time around the mainloop,
474 * it is much faster than calling time() directly.
475 * @return The current time as an epoch value (time_t)
477 inline time_t Time() { return TIME.tv_sec; }
478 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
479 inline long Time_ns() { return TIME.tv_nsec; }
480 /** Update the current time. Don't call this unless you have reason to do so. */
483 /** Generate a random string with the given length
484 * @param length The length in bytes
485 * @param printable if false, the string will use characters 0-255; otherwise,
486 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
488 std::string GenRandomStr(int length, bool printable = true);
489 /** Generate a random integer.
490 * This is generally more secure than rand()
492 unsigned long GenRandomInt(unsigned long max);
494 /** Fill a buffer with random bits */
495 caller2<void, char*, size_t> GenRandom;
497 /** Bind all ports specified in the configuration file.
498 * @return The number of ports bound without error
500 int BindPorts(FailedPortList &failed_ports);
502 /** Binds a socket on an already open file descriptor
503 * @param sockfd A valid file descriptor of an open socket
504 * @param port The port number to bind to
505 * @param addr The address to bind to (IP only)
506 * @param dolisten Should this port be listened on?
507 * @return True if the port was bound successfully
509 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
511 /** Gets the GECOS (description) field of the given server.
512 * If the servername is not that of the local server, the name
513 * is passed to handling modules which will attempt to determine
514 * the GECOS that bleongs to the given servername.
515 * @param servername The servername to find the description of
516 * @return The description of this server, or of the local server
518 std::string GetServerDescription(const std::string& servername);
520 /** Find a user in the nick hash.
521 * If the user cant be found in the nick hash check the uuid hash
522 * @param nick The nickname to find
523 * @return A pointer to the user, or NULL if the user does not exist
525 User* FindNick(const std::string &nick);
527 /** Find a user in the nick hash.
528 * If the user cant be found in the nick hash check the uuid hash
529 * @param nick The nickname to find
530 * @return A pointer to the user, or NULL if the user does not exist
532 User* FindNick(const char* nick);
534 /** Find a user in the nick hash ONLY
536 User* FindNickOnly(const char* nick);
538 /** Find a user in the nick hash ONLY
540 User* FindNickOnly(const std::string &nick);
542 /** Find a channel in the channels hash
543 * @param chan The channel to find
544 * @return A pointer to the channel, or NULL if the channel does not exist
546 Channel* FindChan(const std::string &chan);
548 /** Find a channel in the channels hash
549 * @param chan The channel to find
550 * @return A pointer to the channel, or NULL if the channel does not exist
552 Channel* FindChan(const char* chan);
554 /** Check we aren't running as root, and exit if we are
555 * @return Depending on the configuration, this function may never return
559 /** Determine the right path for, and open, the logfile
560 * @param argv The argv passed to main() initially, used to calculate program path
561 * @param argc The argc passed to main() initially, used to calculate program path
562 * @return True if the log could be opened, false if otherwise
564 bool OpenLog(char** argv, int argc);
566 /** Return true if a channel name is valid
567 * @param chname A channel name to verify
568 * @return True if the name is valid
570 caller2<bool, const char*, size_t> IsChannel;
572 /** Return true if str looks like a server ID
573 * @param string to check against
575 caller1<bool, const std::string&> IsSID;
577 /** Rehash the local server
579 caller1<void, const std::string&> Rehash;
581 /** Handles incoming signals after being set
582 * @param signal the signal recieved
584 void SignalHandler(int signal);
586 /** Sets the signal recieved
587 * @param signal the signal recieved
589 static void SetSignal(int signal);
591 /** Causes the server to exit after unloading modules and
592 * closing all open file descriptors.
594 * @param status The exit code to give to the operating system
595 * (See the ExitStatus enum for valid values)
597 void Exit(int status);
599 /** Causes the server to exit immediately with exit code 0.
600 * The status code is required for signal handlers, and ignored.
602 static void QuickExit(int status);
604 /** Return a count of channels on the network
605 * @return The number of channels
609 /** Send an error notice to all local users, opered and unopered
610 * @param s The error string to send
612 void SendError(const std::string &s);
614 /** Return true if a nickname is valid
615 * @param n A nickname to verify
616 * @return True if the nick is valid
618 caller2<bool, const char*, size_t> IsNick;
620 /** Return true if an ident is valid
621 * @param An ident to verify
622 * @return True if the ident is valid
624 caller1<bool, const char*> IsIdent;
626 /** Add a dns Resolver class to this server's active set
627 * @param r The resolver to add
628 * @param cached If this value is true, then the cache will
629 * be searched for the DNS result, immediately. If the value is
630 * false, then a request will be sent to the nameserver, and the
631 * result will not be immediately available. You should usually
632 * use the boolean value which you passed to the Resolver
633 * constructor, which Resolver will set appropriately depending
634 * on if cached results are available and haven't expired. It is
635 * however safe to force this value to false, forcing a remote DNS
636 * lookup, but not an update of the cache.
637 * @return True if the operation completed successfully. Note that
638 * if this method returns true, you should not attempt to access
639 * the resolver class you pass it after this call, as depending upon
640 * the request given, the object may be deleted!
642 bool AddResolver(Resolver* r, bool cached);
644 /** Add a command to this server's command parser
645 * @param f A Command command handler object to add
646 * @throw ModuleException Will throw ModuleExcption if the command already exists
648 inline void AddCommand(Command *f)
650 Modules->AddService(*f);
653 /** Send a modechange.
654 * The parameters provided are identical to that sent to the
655 * handler for class cmd_mode.
656 * @param parameters The mode parameters
657 * @param user The user to send error messages to
659 void SendMode(const std::vector<std::string>& parameters, User *user);
661 /** Send a modechange and route it to the network.
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 SendGlobalMode(const std::vector<std::string>& parameters, User *user);
669 /** Match two strings using pattern matching, optionally, with a map
670 * to check case against (may be NULL). If map is null, match will be case insensitive.
671 * @param str The literal string to match against
672 * @param mask The glob pattern to match against.
673 * @param map The character map to use when matching.
675 static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
676 static bool Match(const char *str, const char *mask, unsigned const char *map = NULL);
678 /** Match two strings using pattern matching, optionally, with a map
679 * to check case against (may be NULL). If map is null, match will be case insensitive.
680 * Supports CIDR patterns as well as globs.
681 * @param str The literal string to match against
682 * @param mask The glob or CIDR pattern to match against.
683 * @param map The character map to use when matching.
685 static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
686 static bool MatchCIDR(const char *str, const char *mask, unsigned const char *map = NULL);
688 /** Call the handler for a given command.
689 * @param commandname The command whos handler you wish to call
690 * @param parameters The mode parameters
691 * @param user The user to execute the command as
692 * @return True if the command handler was called successfully
694 CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
696 /** Return true if the command is a module-implemented command and the given parameters are valid for it
697 * @param commandname The command name to check
698 * @param pcnt The parameter count
699 * @param user The user to test-execute the command as
700 * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
702 bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
704 /** Return true if the given parameter is a valid nick!user\@host mask
705 * @param mask A nick!user\@host masak to match against
706 * @return True i the mask is valid
708 bool IsValidMask(const std::string &mask);
710 /** Strips all color codes from the given string
711 * @param sentence The string to strip from
713 static void StripColor(std::string &sentence);
715 /** Parses color codes from string values to actual color codes
716 * @param input The data to process
718 static void ProcessColors(file_cache& input);
720 /** Rehash the local server
724 /** Check if the given nickmask matches too many users, send errors to the given user
725 * @param nick A nickmask to match against
726 * @param user A user to send error text to
727 * @return True if the nick matches too many users
729 bool NickMatchesEveryone(const std::string &nick, User* user);
731 /** Check if the given IP mask matches too many users, send errors to the given user
732 * @param ip An ipmask to match against
733 * @param user A user to send error text to
734 * @return True if the ip matches too many users
736 bool IPMatchesEveryone(const std::string &ip, User* user);
738 /** Check if the given hostmask matches too many users, send errors to the given user
739 * @param mask A hostmask to match against
740 * @param user A user to send error text to
741 * @return True if the host matches too many users
743 bool HostMatchesEveryone(const std::string &mask, User* user);
745 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
746 * @param str A string containing a time in the form 1y2w3d4h6m5s
747 * (one year, two weeks, three days, four hours, six minutes and five seconds)
748 * @return The total number of seconds
750 long Duration(const std::string &str);
752 /** Attempt to compare a password to a string from the config file.
753 * This will be passed to handling modules which will compare the data
754 * against possible hashed equivalents in the input string.
755 * @param ex The object (user, server, whatever) causing the comparison.
756 * @param data The data from the config file
757 * @param input The data input by the oper
758 * @param hashtype The hash from the config file
759 * @return 0 if the strings match, 1 or -1 if they do not
761 int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
763 /** Check if a given server is a uline.
764 * An empty string returns true, this is by design.
765 * @param server The server to check for uline status
766 * @return True if the server is a uline OR the string is empty
768 bool ULine(const std::string& server);
770 /** Returns true if the uline is 'silent' (doesnt generate
771 * remote connect notices etc).
773 bool SilentULine(const std::string& server);
775 /** Returns the full version string of this ircd
776 * @return The version string
778 std::string GetVersionString(bool rawversion = false);
780 /** Attempt to write the process id to a given file
781 * @param filename The PID file to attempt to write to
782 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
783 * @return This function may bail if the file cannot be written
785 void WritePID(const std::string& filename, bool exitonfail = true);
787 /** This constructor initialises all the subsystems and reads the config file.
788 * @param argc The argument count passed to main()
789 * @param argv The argument list passed to main()
790 * @throw <anything> If anything is thrown from here and makes it to
791 * you, you should probably just give up and go home. Yes, really.
792 * It's that bad. Higher level classes should catch any non-fatal exceptions.
794 InspIRCd(int argc, char** argv);
796 /** Send a line of WHOIS data to a user.
797 * @param user user to send the line to
798 * @param dest user being WHOISed
799 * @param numeric Numeric to send
800 * @param text Text of the numeric
802 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
804 /** Send a line of WHOIS data to a user.
805 * @param user user to send the line to
806 * @param dest user being WHOISed
807 * @param numeric Numeric to send
808 * @param format Format string for the numeric
809 * @param ... Parameters for the format string
811 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
815 void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
817 /** Quit a user for excess flood, and if they are not
818 * fully registered yet, temporarily zline their IP.
819 * @param current user to quit
821 caller1<void, User*> FloodQuitUser;
823 /** Called to check whether a channel restriction mode applies to a user
824 * @param User that is attempting some action
825 * @param Channel that the action is being performed on
828 caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
830 /** Restart the server.
831 * This function will not return. If an error occurs,
832 * it will throw an instance of CoreException.
833 * @param reason The restart reason to show to all clients
834 * @throw CoreException An instance of CoreException indicating the error from execv().
836 void Restart(const std::string &reason);
838 /** Prepare the ircd for restart or shutdown.
839 * This function unloads all modules which can be unloaded,
840 * closes all open sockets, and closes the logfile.
844 /** This copies the user and channel hash_maps into new hash maps.
845 * This frees memory used by the hash_map allocator (which it neglects
846 * to free, most of the time, using tons of ram)
848 void RehashUsersAndChans();
850 /** Resets the cached max bans value on all channels.
855 /** Return a time_t as a human-readable string.
857 std::string TimeString(time_t curtime);
859 /** Begin execution of the server.
860 * NOTE: this function NEVER returns. Internally,
861 * it will repeatedly loop.
862 * @return The return value for this function is undefined.
866 /** Adds an extban char to the 005 token.
868 void AddExtBanChar(char c);
870 char* GetReadBuffer()
872 return this->ReadBuffer;
875 friend class TestSuite;
881 class CommandModule : public Module
885 CommandModule() : cmd(this)
891 ServerInstance->Modules->AddService(cmd);
896 return Version(cmd.name, VF_VENDOR|VF_CORE);