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"
48 #include "aligned_storage.h"
52 CoreExport extern InspIRCd* ServerInstance;
54 /** Base class for manager classes that are still accessed using -> but are no longer pointers
61 return static_cast<T*>(this);
67 #include "consolecolors.h"
69 #include "cull_list.h"
70 #include "extensible.h"
71 #include "fileutils.h"
80 #include "usermanager.h"
83 #include "command_parse.h"
85 #include "socketengine.h"
87 #include "filelogger.h"
89 #include "threadengine.h"
90 #include "configreader.h"
91 #include "inspstring.h"
94 #include "isupportmanager.h"
96 /** Template function to convert any input type to std::string
98 template<typename T> inline std::string ConvNumeric(const T &in)
106 out += "0123456789"[ std::abs( (long)quotient % 10 ) ];
111 std::reverse(out.begin(), out.end());
115 /** Template function to convert any input type to std::string
117 inline std::string ConvToStr(const int in)
119 return ConvNumeric(in);
122 /** Template function to convert any input type to std::string
124 inline std::string ConvToStr(const long in)
126 return ConvNumeric(in);
129 /** Template function to convert any input type to std::string
131 inline std::string ConvToStr(const char* in)
136 /** Template function to convert any input type to std::string
138 inline std::string ConvToStr(const bool in)
140 return (in ? "1" : "0");
143 /** Template function to convert any input type to std::string
145 inline std::string ConvToStr(char in)
147 return std::string(1, in);
150 /** Template function to convert any input type to std::string
152 template <class T> inline std::string ConvToStr(const T &in)
154 std::stringstream tmp;
155 if (!(tmp << in)) return std::string();
159 /** Template function to convert any input type to any other type
160 * (usually an integer or numeric type)
162 template<typename T> inline long ConvToInt(const T &in)
164 std::stringstream tmp;
165 if (!(tmp << in)) return 0;
166 return atol(tmp.str().c_str());
169 inline uint64_t ConvToUInt64(const std::string& in)
172 std::istringstream tmp(in);
178 /** This class contains various STATS counters
179 * It is used by the InspIRCd class, which internally
180 * has an instance of it.
185 /** Number of accepted connections
187 unsigned long Accept;
188 /** Number of failed accepts
190 unsigned long Refused;
191 /** Number of unknown commands seen
193 unsigned long Unknown;
194 /** Number of nickname collisions handled
196 unsigned long Collisions;
197 /** Number of DNS queries sent out
200 /** Number of good DNS replies received
201 * NOTE: This may not tally to the number sent out,
202 * due to timeouts and other latency issues.
204 unsigned long DnsGood;
205 /** Number of bad (negative) DNS replies received
206 * NOTE: This may not tally to the number sent out,
207 * due to timeouts and other latency issues.
209 unsigned long DnsBad;
210 /** Number of inbound connections seen
212 unsigned long Connects;
213 /** Total bytes of data transmitted
216 /** Total bytes of data received
220 /** Cpu usage at last sample
223 /** Time QP sample was read
225 LARGE_INTEGER LastSampled;
228 LARGE_INTEGER QPFrequency;
230 /** Cpu usage at last sample
233 /** Time last sample was read
235 timespec LastSampled;
237 /** The constructor initializes all the counts to zero
240 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
241 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
246 DEFINE_HANDLER1(IsNickHandler, bool, const std::string&);
247 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
248 DEFINE_HANDLER1(IsIdentHandler, bool, const std::string&);
249 DEFINE_HANDLER1(IsChannelHandler, bool, const std::string&);
250 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
252 /** The main class of the irc server.
253 * This class contains instances of all the other classes in this software.
254 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
255 * object, and a list of active Module objects, and facilities for Module
256 * objects to interact with the core system it implements.
258 class CoreExport InspIRCd
261 /** Set up the signal handlers
265 /** Daemonize the ircd and close standard input/output streams
266 * @return True if the program daemonized succesfully
270 /** The current time, updated in the mainloop
272 struct timespec TIME;
274 /** A 64k buffer used to read socket data into
275 * NOTE: update ValidateNetBufferSize if you change this
277 char ReadBuffer[65535];
279 /** Check we aren't running as root, and exit if we are
280 * with exit code EXIT_STATUS_ROOT.
288 /** Global cull list, will be processed on next iteration
290 CullList GlobalCulls;
291 /** Actions that must happen outside of the current call stack */
292 ActionList AtomicActions;
296 IsNickHandler HandleIsNick;
297 IsIdentHandler HandleIsIdent;
298 OnCheckExemptionHandler HandleOnCheckExemption;
299 IsChannelHandler HandleIsChannel;
300 GenRandomHandler HandleGenRandom;
302 /** 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
305 * SendMode expects a User* to send the numeric replies
306 * back to, so we create it a fake user that isnt in the user
307 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
308 * falls into the abyss :p
310 FakeUser* FakeClient;
312 /** Find a user in the UUID hash
313 * @param uid The UUID to find
314 * @return A pointer to the user, or NULL if the user does not exist
316 User* FindUUID(const std::string &uid);
318 /** Time this ircd was booted
322 /** Config file pathname specified on the commandline or via ./configure
324 std::string ConfigFileName;
326 ExtensionManager Extensions;
328 /** Mode handler, handles mode setting and removal
332 /** Command parser, handles client to server commands
334 CommandParser Parser;
336 /** Thread engine, Handles threading where required
338 ThreadEngine Threads;
340 /** The thread/class used to read config files in REHASH and on startup
342 ConfigReaderThread* ConfigThread;
344 /** LogManager handles logging.
348 /** ModuleManager contains everything related to loading/unloading
351 ModuleManager Modules;
353 /** BanCacheManager is used to speed up checking of restrictions on connection
356 BanCacheManager BanCache;
358 /** Stats class, holds miscellaneous stats counters
362 /** Server Config class, holds configuration file data
364 ServerConfig* Config;
366 /** Snomask manager - handles routing of snomask messages
371 /** Timer manager class, triggers Timer timer events
375 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
377 XLineManager* XLines;
379 /** User manager. Various methods and data associated with users.
383 /** Channel list, a hash_map containing all channels XXX move to channel manager class
387 /** List of the open ports
389 std::vector<ListenSocket*> ports;
391 /** Set to the current signal recieved
393 static sig_atomic_t s_signal;
395 /** Protocol interface, overridden by server protocol modules
397 ProtocolInterface* PI;
399 /** Default implementation of the ProtocolInterface, does nothing
401 ProtocolInterface DefaultProtocolInterface;
403 /** Holds extensible for user operquit
405 StringExtItem OperQuit;
407 /** Manages the generation and transmission of ISUPPORT. */
408 ISupportManager ISupport;
410 /** Get the current time
411 * Because this only calls time() once every time around the mainloop,
412 * it is much faster than calling time() directly.
413 * @return The current time as an epoch value (time_t)
415 inline time_t Time() { return TIME.tv_sec; }
416 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
417 inline long Time_ns() { return TIME.tv_nsec; }
418 /** Update the current time. Don't call this unless you have reason to do so. */
421 /** Generate a random string with the given length
422 * @param length The length in bytes
423 * @param printable if false, the string will use characters 0-255; otherwise,
424 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
426 std::string GenRandomStr(int length, bool printable = true);
427 /** Generate a random integer.
428 * This is generally more secure than rand()
430 unsigned long GenRandomInt(unsigned long max);
432 /** Fill a buffer with random bits */
433 caller2<void, char*, size_t> GenRandom;
435 /** Bind all ports specified in the configuration file.
436 * @return The number of ports bound without error
438 int BindPorts(FailedPortList &failed_ports);
440 /** Find a user in the nick hash.
441 * If the user cant be found in the nick hash check the uuid hash
442 * @param nick The nickname to find
443 * @return A pointer to the user, or NULL if the user does not exist
445 User* FindNick(const std::string &nick);
447 /** Find a user in the nick hash ONLY
449 User* FindNickOnly(const std::string &nick);
451 /** Find a channel in the channels hash
452 * @param chan The channel to find
453 * @return A pointer to the channel, or NULL if the channel does not exist
455 Channel* FindChan(const std::string &chan);
457 /** Get a hash map containing all channels, keyed by their name
458 * @return A hash map mapping channel names to Channel pointers
460 chan_hash& GetChans() { return chanlist; }
462 /** Return true if a channel name is valid
463 * @param chname A channel name to verify
464 * @return True if the name is valid
466 caller1<bool, const std::string&> IsChannel;
468 /** Return true if str looks like a server ID
469 * @param sid string to check against
471 static bool IsSID(const std::string& sid);
473 /** Handles incoming signals after being set
474 * @param signal the signal recieved
476 void SignalHandler(int signal);
478 /** Sets the signal recieved
479 * @param signal the signal recieved
481 static void SetSignal(int signal);
483 /** Causes the server to exit after unloading modules and
484 * closing all open file descriptors.
486 * @param status The exit code to give to the operating system
487 * (See the ExitStatus enum for valid values)
489 void Exit(int status);
491 /** Causes the server to exit immediately with exit code 0.
492 * The status code is required for signal handlers, and ignored.
494 static void QuickExit(int status);
496 /** Formats the input string with the specified arguments.
497 * @param formatString The string to format
498 * @param ... A variable number of format arguments.
499 * @return The formatted string
501 static const char* Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
502 static const char* Format(va_list &vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
504 /** Send an error notice to all local users, opered and unopered
505 * @param s The error string to send
507 void SendError(const std::string &s);
509 /** Return true if a nickname is valid
510 * @param n A nickname to verify
511 * @return True if the nick is valid
513 caller1<bool, const std::string&> IsNick;
515 /** Return true if an ident is valid
516 * @param An ident to verify
517 * @return True if the ident is valid
519 caller1<bool, const std::string&> IsIdent;
521 /** Match two strings using pattern matching, optionally, with a map
522 * to check case against (may be NULL). If map is null, match will be case insensitive.
523 * @param str The literal string to match against
524 * @param mask The glob pattern to match against.
525 * @param map The character map to use when matching.
527 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
528 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
530 /** Match two strings using pattern matching, optionally, with a map
531 * to check case against (may be NULL). If map is null, match will be case insensitive.
532 * Supports CIDR patterns as well as globs.
533 * @param str The literal string to match against
534 * @param mask The glob or CIDR pattern to match against.
535 * @param map The character map to use when matching.
537 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
538 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
540 /** Matches a hostname and IP against a space delimited list of hostmasks.
541 * @param masks The space delimited masks to match against.
542 * @param hostname The hostname to try and match.
543 * @param ipaddr The IP address to try and match.
545 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
547 /** Return true if the given parameter is a valid nick!user\@host mask
548 * @param mask A nick!user\@host masak to match against
549 * @return True i the mask is valid
551 static bool IsValidMask(const std::string& mask);
553 /** Strips all color codes from the given string
554 * @param sentence The string to strip from
556 static void StripColor(std::string &sentence);
558 /** Parses color codes from string values to actual color codes
559 * @param input The data to process
561 static void ProcessColors(file_cache& input);
563 /** Rehash the local server
564 * @param uuid The uuid of the user who started the rehash, can be empty
566 void Rehash(const std::string& uuid = "");
568 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
569 * @param str A string containing a time in the form 1y2w3d4h6m5s
570 * (one year, two weeks, three days, four hours, six minutes and five seconds)
571 * @return The total number of seconds
573 static unsigned long Duration(const std::string& str);
575 /** Attempt to compare a password to a string from the config file.
576 * This will be passed to handling modules which will compare the data
577 * against possible hashed equivalents in the input string.
578 * @param ex The object (user, server, whatever) causing the comparison.
579 * @param data The data from the config file
580 * @param input The data input by the oper
581 * @param hashtype The hash from the config file
582 * @return True if the strings match, false if they do not
584 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
586 /** Returns the full version string of this ircd
587 * @return The version string
589 std::string GetVersionString(bool getFullVersion = false);
591 /** Attempt to write the process id to a given file
592 * @param filename The PID file to attempt to write to
593 * @return This function may bail if the file cannot be written
595 void WritePID(const std::string &filename);
597 /** This constructor initialises all the subsystems and reads the config file.
598 * @param argc The argument count passed to main()
599 * @param argv The argument list passed to main()
600 * @throw <anything> If anything is thrown from here and makes it to
601 * you, you should probably just give up and go home. Yes, really.
602 * It's that bad. Higher level classes should catch any non-fatal exceptions.
604 InspIRCd(int argc, char** argv);
606 /** Send a line of WHOIS data to a user.
607 * @param user user to send the line to
608 * @param dest user being WHOISed
609 * @param numeric Numeric to send
610 * @param text Text of the numeric
612 void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
614 /** Send a line of WHOIS data to a user.
615 * @param user user to send the line to
616 * @param dest user being WHOISed
617 * @param numeric Numeric to send
618 * @param format Format string for the numeric
619 * @param ... Parameters for the format string
621 void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
623 /** Called to check whether a channel restriction mode applies to a user
624 * @param User that is attempting some action
625 * @param Channel that the action is being performed on
628 caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
630 /** Prepare the ircd for restart or shutdown.
631 * This function unloads all modules which can be unloaded,
632 * closes all open sockets, and closes the logfile.
636 /** Return a time_t as a human-readable string.
637 * @param format The format to retrieve the date/time in. See `man 3 strftime`
638 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
639 * @param utc True to convert the time to string as-is, false to convert it to local time first.
640 * @return A string representing the given date/time.
642 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
644 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
645 * returns false immediately (leaking information about the length), otherwise it compares each
646 * character and only returns after all characters have been compared.
647 * @param one First string
648 * @param two Second string
649 * @return True if the strings match, false if they don't
651 static bool TimingSafeCompare(const std::string& one, const std::string& two);
653 /** Begin execution of the server.
654 * NOTE: this function NEVER returns. Internally,
655 * it will repeatedly loop.
659 char* GetReadBuffer()
661 return this->ReadBuffer;
668 class CommandModule : public Module
672 CommandModule() : cmd(this)
678 return Version(cmd.name, VF_VENDOR|VF_CORE);
682 inline void stdalgo::culldeleter::operator()(classbase* item)
685 ServerInstance->GlobalCulls.AddItem(item);