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/>.
46 #include "intrusive_list.h"
51 CoreExport extern InspIRCd* ServerInstance;
55 #include "consolecolors.h"
57 #include "cull_list.h"
58 #include "extensible.h"
59 #include "fileutils.h"
68 #include "usermanager.h"
71 #include "command_parse.h"
73 #include "socketengine.h"
75 #include "filelogger.h"
77 #include "threadengine.h"
78 #include "configreader.h"
79 #include "inspstring.h"
82 /** Returned by some functions to indicate failure.
86 /** Template function to convert any input type to std::string
88 template<typename T> inline std::string ConvNumeric(const T &in)
96 out += "0123456789"[ std::abs( (long)quotient % 10 ) ];
101 std::reverse(out.begin(), out.end());
105 /** Template function to convert any input type to std::string
107 inline std::string ConvToStr(const int in)
109 return ConvNumeric(in);
112 /** Template function to convert any input type to std::string
114 inline std::string ConvToStr(const long in)
116 return ConvNumeric(in);
119 /** Template function to convert any input type to std::string
121 inline std::string ConvToStr(const char* in)
126 /** Template function to convert any input type to std::string
128 inline std::string ConvToStr(const bool in)
130 return (in ? "1" : "0");
133 /** Template function to convert any input type to std::string
135 inline std::string ConvToStr(char in)
137 return std::string(1, in);
140 /** Template function to convert any input type to std::string
142 template <class T> inline std::string ConvToStr(const T &in)
144 std::stringstream tmp;
145 if (!(tmp << in)) return std::string();
149 /** Template function to convert any input type to any other type
150 * (usually an integer or numeric type)
152 template<typename T> inline long ConvToInt(const T &in)
154 std::stringstream tmp;
155 if (!(tmp << in)) return 0;
156 return atol(tmp.str().c_str());
159 inline uint64_t ConvToUInt64(const std::string& in)
162 std::istringstream tmp(in);
168 /** This class contains various STATS counters
169 * It is used by the InspIRCd class, which internally
170 * has an instance of it.
175 /** Number of accepted connections
177 unsigned long Accept;
178 /** Number of failed accepts
180 unsigned long Refused;
181 /** Number of unknown commands seen
183 unsigned long Unknown;
184 /** Number of nickname collisions handled
186 unsigned long Collisions;
187 /** Number of DNS queries sent out
190 /** Number of good DNS replies received
191 * NOTE: This may not tally to the number sent out,
192 * due to timeouts and other latency issues.
194 unsigned long DnsGood;
195 /** Number of bad (negative) DNS replies received
196 * NOTE: This may not tally to the number sent out,
197 * due to timeouts and other latency issues.
199 unsigned long DnsBad;
200 /** Number of inbound connections seen
202 unsigned long Connects;
203 /** Total bytes of data transmitted
206 /** Total bytes of data received
210 /** Cpu usage at last sample
213 /** Time QP sample was read
215 LARGE_INTEGER LastSampled;
218 LARGE_INTEGER QPFrequency;
220 /** Cpu usage at last sample
223 /** Time last sample was read
225 timespec LastSampled;
227 /** The constructor initializes all the counts to zero
230 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
231 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
236 /** This class manages the generation and transmission of ISUPPORT. */
237 class CoreExport ISupportManager
240 /** The generated lines which are sent to clients. */
241 std::vector<std::string> Lines;
244 /** (Re)build the ISUPPORT vector. */
247 /** Returns the std::vector of ISUPPORT lines. */
248 const std::vector<std::string>& GetLines()
253 /** Send the 005 numerics (ISUPPORT) to a user. */
254 void SendTo(LocalUser* user);
257 DEFINE_HANDLER1(IsNickHandler, bool, const std::string&);
258 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
259 DEFINE_HANDLER1(IsIdentHandler, bool, const std::string&);
260 DEFINE_HANDLER1(IsChannelHandler, bool, const std::string&);
261 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
263 /** The main class of the irc server.
264 * This class contains instances of all the other classes in this software.
265 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
266 * object, and a list of active Module objects, and facilities for Module
267 * objects to interact with the core system it implements.
269 class CoreExport InspIRCd
272 /** Set up the signal handlers
276 /** Daemonize the ircd and close standard input/output streams
277 * @return True if the program daemonized succesfully
281 /** The current time, updated in the mainloop
283 struct timespec TIME;
285 /** A 64k buffer used to read socket data into
286 * NOTE: update ValidateNetBufferSize if you change this
288 char ReadBuffer[65535];
290 /** Check we aren't running as root, and exit if we are
291 * with exit code EXIT_STATUS_ROOT.
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 OnCheckExemptionHandler HandleOnCheckExemption;
310 IsChannelHandler HandleIsChannel;
311 GenRandomHandler HandleGenRandom;
313 /** 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
316 * SendMode expects a User* to send the numeric replies
317 * back to, so we create it a fake user that isnt in the user
318 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
319 * falls into the abyss :p
321 FakeUser* FakeClient;
323 /** Find a user in the UUID hash
324 * @param uid The UUID to find
325 * @return A pointer to the user, or NULL if the user does not exist
327 User* FindUUID(const std::string &uid);
329 /** Time this ircd was booted
333 /** Config file pathname specified on the commandline or via ./configure
335 std::string ConfigFileName;
337 ExtensionManager Extensions;
339 /** Mode handler, handles mode setting and removal
343 /** Command parser, handles client to server commands
345 CommandParser* Parser;
347 /** Thread engine, Handles threading where required
349 ThreadEngine* Threads;
351 /** The thread/class used to read config files in REHASH and on startup
353 ConfigReaderThread* ConfigThread;
355 /** LogManager handles logging.
359 /** ModuleManager contains everything related to loading/unloading
362 ModuleManager* Modules;
364 /** BanCacheManager is used to speed up checking of restrictions on connection
367 BanCacheManager *BanCache;
369 /** Stats class, holds miscellaneous stats counters
373 /** Server Config class, holds configuration file data
375 ServerConfig* Config;
377 /** Snomask manager - handles routing of snomask messages
382 /** Timer manager class, triggers Timer timer events
386 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
388 XLineManager* XLines;
390 /** User manager. Various methods and data associated with users.
394 /** Channel list, a hash_map containing all channels XXX move to channel manager class
398 /** List of the open ports
400 std::vector<ListenSocket*> ports;
402 /** Set to the current signal recieved
404 static sig_atomic_t s_signal;
406 /** Protocol interface, overridden by server protocol modules
408 ProtocolInterface* PI;
410 /** Holds extensible for user operquit
412 StringExtItem OperQuit;
414 /** Manages the generation and transmission of ISUPPORT. */
415 ISupportManager ISupport;
417 /** Get the current time
418 * Because this only calls time() once every time around the mainloop,
419 * it is much faster than calling time() directly.
420 * @return The current time as an epoch value (time_t)
422 inline time_t Time() { return TIME.tv_sec; }
423 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
424 inline long Time_ns() { return TIME.tv_nsec; }
425 /** Update the current time. Don't call this unless you have reason to do so. */
428 /** Generate a random string with the given length
429 * @param length The length in bytes
430 * @param printable if false, the string will use characters 0-255; otherwise,
431 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
433 std::string GenRandomStr(int length, bool printable = true);
434 /** Generate a random integer.
435 * This is generally more secure than rand()
437 unsigned long GenRandomInt(unsigned long max);
439 /** Fill a buffer with random bits */
440 caller2<void, char*, size_t> GenRandom;
442 /** Bind all ports specified in the configuration file.
443 * @return The number of ports bound without error
445 int BindPorts(FailedPortList &failed_ports);
447 /** Binds a socket on an already open file descriptor
448 * @param sockfd A valid file descriptor of an open socket
449 * @param port The port number to bind to
450 * @param addr The address to bind to (IP only)
451 * @param dolisten Should this port be listened on?
452 * @return True if the port was bound successfully
454 bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
456 /** Find a user in the nick hash.
457 * If the user cant be found in the nick hash check the uuid hash
458 * @param nick The nickname to find
459 * @return A pointer to the user, or NULL if the user does not exist
461 User* FindNick(const std::string &nick);
463 /** Find a user in the nick hash ONLY
465 User* FindNickOnly(const std::string &nick);
467 /** Find a channel in the channels hash
468 * @param chan The channel to find
469 * @return A pointer to the channel, or NULL if the channel does not exist
471 Channel* FindChan(const std::string &chan);
473 /** Get a hash map containing all channels, keyed by their name
474 * @return A hash map mapping channel names to Channel pointers
476 chan_hash& GetChans() { return chanlist; }
478 /** Return true if a channel name is valid
479 * @param chname A channel name to verify
480 * @return True if the name is valid
482 caller1<bool, const std::string&> IsChannel;
484 /** Return true if str looks like a server ID
485 * @param sid string to check against
487 static bool IsSID(const std::string& sid);
489 /** Handles incoming signals after being set
490 * @param signal the signal recieved
492 void SignalHandler(int signal);
494 /** Sets the signal recieved
495 * @param signal the signal recieved
497 static void SetSignal(int signal);
499 /** Causes the server to exit after unloading modules and
500 * closing all open file descriptors.
502 * @param status The exit code to give to the operating system
503 * (See the ExitStatus enum for valid values)
505 void Exit(int status);
507 /** Causes the server to exit immediately with exit code 0.
508 * The status code is required for signal handlers, and ignored.
510 static void QuickExit(int status);
512 /** Formats the input string with the specified arguments.
513 * @param formatString The string to format
514 * @param ... A variable number of format arguments.
515 * @return The formatted string
517 static const char* Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
518 static const char* Format(va_list &vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
520 /** Send an error notice to all local users, opered and unopered
521 * @param s The error string to send
523 void SendError(const std::string &s);
525 /** Return true if a nickname is valid
526 * @param n A nickname to verify
527 * @return True if the nick is valid
529 caller1<bool, const std::string&> IsNick;
531 /** Return true if an ident is valid
532 * @param An ident to verify
533 * @return True if the ident is valid
535 caller1<bool, const std::string&> IsIdent;
537 /** Match two strings using pattern matching, optionally, with a map
538 * to check case against (may be NULL). If map is null, match will be case insensitive.
539 * @param str The literal string to match against
540 * @param mask The glob pattern to match against.
541 * @param map The character map to use when matching.
543 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
544 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
546 /** Match two strings using pattern matching, optionally, with a map
547 * to check case against (may be NULL). If map is null, match will be case insensitive.
548 * Supports CIDR patterns as well as globs.
549 * @param str The literal string to match against
550 * @param mask The glob or CIDR pattern to match against.
551 * @param map The character map to use when matching.
553 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
554 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
556 /** Matches a hostname and IP against a space delimited list of hostmasks.
557 * @param masks The space delimited masks to match against.
558 * @param hostname The hostname to try and match.
559 * @param ipaddr The IP address to try and match.
561 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
563 /** Return true if the given parameter is a valid nick!user\@host mask
564 * @param mask A nick!user\@host masak to match against
565 * @return True i the mask is valid
567 static bool IsValidMask(const std::string& mask);
569 /** Strips all color codes from the given string
570 * @param sentence The string to strip from
572 static void StripColor(std::string &sentence);
574 /** Parses color codes from string values to actual color codes
575 * @param input The data to process
577 static void ProcessColors(file_cache& input);
579 /** Rehash the local server
580 * @param uuid The uuid of the user who started the rehash, can be empty
582 void Rehash(const std::string& uuid = "");
584 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
585 * @param str A string containing a time in the form 1y2w3d4h6m5s
586 * (one year, two weeks, three days, four hours, six minutes and five seconds)
587 * @return The total number of seconds
589 static unsigned long Duration(const std::string& str);
591 /** Attempt to compare a password to a string from the config file.
592 * This will be passed to handling modules which will compare the data
593 * against possible hashed equivalents in the input string.
594 * @param ex The object (user, server, whatever) causing the comparison.
595 * @param data The data from the config file
596 * @param input The data input by the oper
597 * @param hashtype The hash from the config file
598 * @return True if the strings match, false if they do not
600 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
602 /** Returns the full version string of this ircd
603 * @return The version string
605 std::string GetVersionString(bool getFullVersion = false);
607 /** Attempt to write the process id to a given file
608 * @param filename The PID file to attempt to write to
609 * @return This function may bail if the file cannot be written
611 void WritePID(const std::string &filename);
613 /** This constructor initialises all the subsystems and reads the config file.
614 * @param argc The argument count passed to main()
615 * @param argv The argument list passed to main()
616 * @throw <anything> If anything is thrown from here and makes it to
617 * you, you should probably just give up and go home. Yes, really.
618 * It's that bad. Higher level classes should catch any non-fatal exceptions.
620 InspIRCd(int argc, char** argv);
622 /** Send a line of WHOIS data to a user.
623 * @param user user to send the line to
624 * @param dest user being WHOISed
625 * @param numeric Numeric to send
626 * @param text Text of the numeric
628 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
630 /** Send a line of WHOIS data to a user.
631 * @param user user to send the line to
632 * @param dest user being WHOISed
633 * @param numeric Numeric to send
634 * @param format Format string for the numeric
635 * @param ... Parameters for the format string
637 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
639 /** Called to check whether a channel restriction mode applies to a user
640 * @param User that is attempting some action
641 * @param Channel that the action is being performed on
644 caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
646 /** Prepare the ircd for restart or shutdown.
647 * This function unloads all modules which can be unloaded,
648 * closes all open sockets, and closes the logfile.
652 /** Return a time_t as a human-readable string.
654 static std::string TimeString(time_t curtime);
656 /** Begin execution of the server.
657 * NOTE: this function NEVER returns. Internally,
658 * it will repeatedly loop.
662 char* GetReadBuffer()
664 return this->ReadBuffer;
671 class CommandModule : public Module
675 CommandModule() : cmd(this)
681 return Version(cmd.name, VF_VENDOR|VF_CORE);
685 inline void stdalgo::culldeleter::operator()(classbase* item)
688 ServerInstance->GlobalCulls.AddItem(item);