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/>.
47 #include "intrusive_list.h"
50 #include "aligned_storage.h"
54 CoreExport extern InspIRCd* ServerInstance;
56 /** Base class for manager classes that are still accessed using -> but are no longer pointers
63 return static_cast<T*>(this);
70 #include "consolecolors.h"
72 #include "cull_list.h"
73 #include "extensible.h"
74 #include "fileutils.h"
84 #include "usermanager.h"
87 #include "command_parse.h"
89 #include "socketengine.h"
91 #include "filelogger.h"
93 #include "threadengine.h"
94 #include "configreader.h"
95 #include "inspstring.h"
98 #include "isupportmanager.h"
100 /** This class contains various STATS counters
101 * It is used by the InspIRCd class, which internally
102 * has an instance of it.
107 /** Number of accepted connections
109 unsigned long Accept;
110 /** Number of failed accepts
112 unsigned long Refused;
113 /** Number of unknown commands seen
115 unsigned long Unknown;
116 /** Number of nickname collisions handled
118 unsigned long Collisions;
119 /** Number of DNS queries sent out
122 /** Number of good DNS replies received
123 * NOTE: This may not tally to the number sent out,
124 * due to timeouts and other latency issues.
126 unsigned long DnsGood;
127 /** Number of bad (negative) DNS replies received
128 * NOTE: This may not tally to the number sent out,
129 * due to timeouts and other latency issues.
131 unsigned long DnsBad;
132 /** Number of inbound connections seen
134 unsigned long Connects;
135 /** Total bytes of data transmitted
138 /** Total bytes of data received
142 /** Cpu usage at last sample
145 /** Time QP sample was read
147 LARGE_INTEGER LastSampled;
150 LARGE_INTEGER QPFrequency;
152 /** Cpu usage at last sample
155 /** Time last sample was read
157 timespec LastSampled;
159 /** The constructor initializes all the counts to zero
162 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
163 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
168 /** The main class of the irc server.
169 * This class contains instances of all the other classes in this software.
170 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
171 * object, and a list of active Module objects, and facilities for Module
172 * objects to interact with the core system it implements.
174 class CoreExport InspIRCd
177 /** Set up the signal handlers
181 /** Daemonize the ircd and close standard input/output streams
182 * @return True if the program daemonized succesfully
186 /** The current time, updated in the mainloop
188 struct timespec TIME;
190 /** A 64k buffer used to read socket data into
191 * NOTE: update ValidateNetBufferSize if you change this
193 char ReadBuffer[65535];
195 /** Check we aren't running as root, and exit if we are
196 * with exit code EXIT_STATUS_ROOT.
204 /** Global cull list, will be processed on next iteration
206 CullList GlobalCulls;
207 /** Actions that must happen outside of the current call stack */
208 ActionList AtomicActions;
210 /** 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
213 * SendMode expects a User* to send the numeric replies
214 * back to, so we create it a fake user that isnt in the user
215 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
216 * falls into the abyss :p
218 FakeUser* FakeClient;
220 /** Find a user in the UUID hash
221 * @param uid The UUID to find
222 * @return A pointer to the user, or NULL if the user does not exist
224 User* FindUUID(const std::string &uid);
226 /** Time this ircd was booted
230 /** Config file pathname specified on the commandline or via ./configure
232 std::string ConfigFileName;
234 ExtensionManager Extensions;
236 /** Mode handler, handles mode setting and removal
240 /** Command parser, handles client to server commands
242 CommandParser Parser;
244 /** Thread engine, Handles threading where required
246 ThreadEngine Threads;
248 /** The thread/class used to read config files in REHASH and on startup
250 ConfigReaderThread* ConfigThread;
252 /** LogManager handles logging.
256 /** ModuleManager contains everything related to loading/unloading
259 ModuleManager Modules;
261 /** BanCacheManager is used to speed up checking of restrictions on connection
264 BanCacheManager BanCache;
266 /** Stats class, holds miscellaneous stats counters
270 /** Server Config class, holds configuration file data
272 ServerConfig* Config;
274 /** Snomask manager - handles routing of snomask messages
279 /** Timer manager class, triggers Timer timer events
283 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
285 XLineManager* XLines;
287 /** User manager. Various methods and data associated with users.
291 /** Channel list, a hash_map containing all channels XXX move to channel manager class
295 /** List of the open ports
297 std::vector<ListenSocket*> ports;
299 /** Set to the current signal recieved
301 static sig_atomic_t s_signal;
303 /** Protocol interface, overridden by server protocol modules
305 ProtocolInterface* PI;
307 /** Default implementation of the ProtocolInterface, does nothing
309 ProtocolInterface DefaultProtocolInterface;
311 /** Manages the generation and transmission of ISUPPORT. */
312 ISupportManager ISupport;
314 /** Get the current time
315 * Because this only calls time() once every time around the mainloop,
316 * it is much faster than calling time() directly.
317 * @return The current time as an epoch value (time_t)
319 inline time_t Time() { return TIME.tv_sec; }
320 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
321 inline long Time_ns() { return TIME.tv_nsec; }
322 /** Update the current time. Don't call this unless you have reason to do so. */
325 /** Generate a random string with the given length
326 * @param length The length in bytes
327 * @param printable if false, the string will use characters 0-255; otherwise,
328 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
330 std::string GenRandomStr(unsigned int length, bool printable = true);
331 /** Generate a random integer.
332 * This is generally more secure than rand()
334 unsigned long GenRandomInt(unsigned long max);
336 /** Fill a buffer with random bits */
337 TR1NS::function<void(char*, size_t)> GenRandom;
339 /** Fills the output buffer with the specified number of random characters.
340 * This is the default function for InspIRCd::GenRandom.
341 * @param output The output buffer to store random characters in.
342 * @param max The maximum number of random characters to put in the buffer.
344 static void DefaultGenRandom(char* output, size_t max);
346 /** Bind all ports specified in the configuration file.
347 * @return The number of ports bound without error
349 int BindPorts(FailedPortList &failed_ports);
351 /** Find a user in the nick hash.
352 * If the user cant be found in the nick hash check the uuid hash
353 * @param nick The nickname to find
354 * @return A pointer to the user, or NULL if the user does not exist
356 User* FindNick(const std::string &nick);
358 /** Find a user in the nick hash ONLY
360 User* FindNickOnly(const std::string &nick);
362 /** Find a channel in the channels hash
363 * @param chan The channel to find
364 * @return A pointer to the channel, or NULL if the channel does not exist
366 Channel* FindChan(const std::string &chan);
368 /** Get a hash map containing all channels, keyed by their name
369 * @return A hash map mapping channel names to Channel pointers
371 chan_hash& GetChans() { return chanlist; }
373 /** Determines whether an channel name is valid. */
374 TR1NS::function<bool(const std::string&)> IsChannel;
376 /** Determines whether a channel name is valid according to the RFC 1459 rules.
377 * This is the default function for InspIRCd::IsChannel.
378 * @param nick The channel name to validate.
379 * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
381 static bool DefaultIsChannel(const std::string& channel);
383 /** Return true if str looks like a server ID
384 * @param sid string to check against
386 static bool IsSID(const std::string& sid);
388 /** Handles incoming signals after being set
389 * @param signal the signal recieved
391 void SignalHandler(int signal);
393 /** Sets the signal recieved
394 * @param signal the signal recieved
396 static void SetSignal(int signal);
398 /** Causes the server to exit after unloading modules and
399 * closing all open file descriptors.
401 * @param status The exit code to give to the operating system
402 * (See the ExitStatus enum for valid values)
404 void Exit(int status);
406 /** Causes the server to exit immediately with exit code 0.
407 * The status code is required for signal handlers, and ignored.
409 static void QuickExit(int status);
411 /** Formats the input string with the specified arguments.
412 * @param formatString The string to format
413 * @param ... A variable number of format arguments.
414 * @return The formatted string
416 static const char* Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
417 static const char* Format(va_list &vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
419 /** Determines whether a nickname is valid. */
420 TR1NS::function<bool(const std::string&)> IsNick;
422 /** Determines whether a nickname is valid according to the RFC 1459 rules.
423 * This is the default function for InspIRCd::IsNick.
424 * @param nick The nickname to validate.
425 * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
427 static bool DefaultIsNick(const std::string& nick);
429 /** Determines whether an ident is valid. */
430 TR1NS::function<bool(const std::string&)> IsIdent;
432 /** Determines whether a ident is valid according to the RFC 1459 rules.
433 * This is the default function for InspIRCd::IsIdent.
434 * @param nick The ident to validate.
435 * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
437 static bool DefaultIsIdent(const std::string& ident);
439 /** Match two strings using pattern matching, optionally, with a map
440 * to check case against (may be NULL). If map is null, match will be case insensitive.
441 * @param str The literal string to match against
442 * @param mask The glob pattern to match against.
443 * @param map The character map to use when matching.
445 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
446 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
448 /** Match two strings using pattern matching, optionally, with a map
449 * to check case against (may be NULL). If map is null, match will be case insensitive.
450 * Supports CIDR patterns as well as globs.
451 * @param str The literal string to match against
452 * @param mask The glob or CIDR pattern to match against.
453 * @param map The character map to use when matching.
455 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
456 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
458 /** Matches a hostname and IP against a space delimited list of hostmasks.
459 * @param masks The space delimited masks to match against.
460 * @param hostname The hostname to try and match.
461 * @param ipaddr The IP address to try and match.
463 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
465 /** Return true if the given parameter is a valid nick!user\@host mask
466 * @param mask A nick!user\@host masak to match against
467 * @return True i the mask is valid
469 static bool IsValidMask(const std::string& mask);
471 /** Strips all color and control codes except 001 from the given string
472 * @param sentence The string to strip from
474 static void StripColor(std::string &sentence);
476 /** Parses color codes from string values to actual color codes
477 * @param input The data to process
479 static void ProcessColors(file_cache& input);
481 /** Rehash the local server
482 * @param uuid The uuid of the user who started the rehash, can be empty
484 void Rehash(const std::string& uuid = "");
486 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
487 * @param str A string containing a time in the form 1y2w3d4h6m5s
488 * (one year, two weeks, three days, four hours, six minutes and five seconds)
489 * @return The total number of seconds
491 static unsigned long Duration(const std::string& str);
493 /** Attempt to compare a password to a string from the config file.
494 * This will be passed to handling modules which will compare the data
495 * against possible hashed equivalents in the input string.
496 * @param ex The object (user, server, whatever) causing the comparison.
497 * @param data The data from the config file
498 * @param input The data input by the oper
499 * @param hashtype The hash from the config file
500 * @return True if the strings match, false if they do not
502 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
504 /** Returns the full version string of this ircd
505 * @return The version string
507 std::string GetVersionString(bool getFullVersion = false);
509 /** Attempt to write the process id to a given file
510 * @param filename The PID file to attempt to write to
511 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
512 * @return This function may bail if the file cannot be written
514 void WritePID(const std::string& filename, bool exitonfail = true);
516 /** This constructor initialises all the subsystems and reads the config file.
517 * @param argc The argument count passed to main()
518 * @param argv The argument list passed to main()
519 * @throw <anything> If anything is thrown from here and makes it to
520 * you, you should probably just give up and go home. Yes, really.
521 * It's that bad. Higher level classes should catch any non-fatal exceptions.
523 InspIRCd(int argc, char** argv);
525 /** Prepare the ircd for restart or shutdown.
526 * This function unloads all modules which can be unloaded,
527 * closes all open sockets, and closes the logfile.
531 /** Return a time_t as a human-readable string.
532 * @param format The format to retrieve the date/time in. See `man 3 strftime`
533 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
534 * @param curtime The timestamp to convert to a human-readable string.
535 * @param utc True to convert the time to string as-is, false to convert it to local time first.
536 * @return A string representing the given date/time.
538 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
540 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
541 * returns false immediately (leaking information about the length), otherwise it compares each
542 * character and only returns after all characters have been compared.
543 * @param one First string
544 * @param two Second string
545 * @return True if the strings match, false if they don't
547 static bool TimingSafeCompare(const std::string& one, const std::string& two);
549 /** Begin execution of the server.
550 * NOTE: this function NEVER returns. Internally,
551 * it will repeatedly loop.
555 char* GetReadBuffer()
557 return this->ReadBuffer;
564 class CommandModule : public Module
568 CommandModule() : cmd(this)
572 Version GetVersion() CXX11_OVERRIDE
574 return Version(cmd.name, VF_VENDOR|VF_CORE);
578 inline void stdalgo::culldeleter::operator()(classbase* item)
581 ServerInstance->GlobalCulls.AddItem(item);
584 #include "numericbuilder.h"
585 #include "modules/whois.h"
586 #include "modules/stats.h"