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/>.
48 #include "intrusive_list.h"
51 #include "aligned_storage.h"
55 CoreExport extern InspIRCd* ServerInstance;
57 /** Base class for manager classes that are still accessed using -> but are no longer pointers
64 return static_cast<T*>(this);
71 #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"
94 #include "threadengine.h"
95 #include "configreader.h"
96 #include "inspstring.h"
99 #include "isupportmanager.h"
101 /** This class contains various STATS counters
102 * It is used by the InspIRCd class, which internally
103 * has an instance of it.
108 /** Number of accepted connections
110 unsigned long Accept;
111 /** Number of failed accepts
113 unsigned long Refused;
114 /** Number of unknown commands seen
116 unsigned long Unknown;
117 /** Number of nickname collisions handled
119 unsigned long Collisions;
120 /** Number of DNS queries sent out
123 /** Number of good DNS replies received
124 * NOTE: This may not tally to the number sent out,
125 * due to timeouts and other latency issues.
127 unsigned long DnsGood;
128 /** Number of bad (negative) DNS replies received
129 * NOTE: This may not tally to the number sent out,
130 * due to timeouts and other latency issues.
132 unsigned long DnsBad;
133 /** Number of inbound connections seen
135 unsigned long Connects;
136 /** Total bytes of data transmitted
139 /** Total bytes of data received
143 /** Cpu usage at last sample
146 /** Time QP sample was read
148 LARGE_INTEGER LastSampled;
151 LARGE_INTEGER QPFrequency;
153 /** Cpu usage at last sample
156 /** Time last sample was read
158 timespec LastSampled;
160 /** The constructor initializes all the counts to zero
163 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
164 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
169 /** The main class of the irc server.
170 * This class contains instances of all the other classes in this software.
171 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
172 * object, and a list of active Module objects, and facilities for Module
173 * objects to interact with the core system it implements.
175 class CoreExport InspIRCd
178 /** Set up the signal handlers
182 /** Daemonize the ircd and close standard input/output streams
183 * @return True if the program daemonized succesfully
187 /** The current time, updated in the mainloop
189 struct timespec TIME;
191 /** A 64k buffer used to read socket data into
192 * NOTE: update ValidateNetBufferSize if you change this
194 char ReadBuffer[65535];
196 /** Check we aren't running as root, and exit if we are
197 * with exit code EXIT_STATUS_ROOT.
205 /** Global cull list, will be processed on next iteration
207 CullList GlobalCulls;
208 /** Actions that must happen outside of the current call stack */
209 ActionList AtomicActions;
211 /** 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
214 * SendMode expects a User* to send the numeric replies
215 * back to, so we create it a fake user that isnt in the user
216 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
217 * falls into the abyss :p
219 FakeUser* FakeClient;
221 /** Find a user in the UUID hash
222 * @param uid The UUID to find
223 * @return A pointer to the user, or NULL if the user does not exist
225 User* FindUUID(const std::string &uid);
227 /** Time this ircd was booted
231 /** Config file pathname specified on the commandline or via ./configure
233 std::string ConfigFileName;
235 ExtensionManager Extensions;
237 /** Mode handler, handles mode setting and removal
241 /** Command parser, handles client to server commands
243 CommandParser Parser;
245 /** Thread engine, Handles threading where required
247 ThreadEngine Threads;
249 /** The thread/class used to read config files in REHASH and on startup
251 ConfigReaderThread* ConfigThread;
253 /** LogManager handles logging.
257 /** ModuleManager contains everything related to loading/unloading
260 ModuleManager Modules;
262 /** BanCacheManager is used to speed up checking of restrictions on connection
265 BanCacheManager BanCache;
267 /** Stats class, holds miscellaneous stats counters
271 /** Server Config class, holds configuration file data
273 ServerConfig* Config;
275 /** Snomask manager - handles routing of snomask messages
280 /** Timer manager class, triggers Timer timer events
284 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
286 XLineManager* XLines;
288 /** User manager. Various methods and data associated with users.
292 /** Channel list, a hash_map containing all channels XXX move to channel manager class
296 /** List of the open ports
298 std::vector<ListenSocket*> ports;
300 /** Set to the current signal recieved
302 static sig_atomic_t s_signal;
304 /** Protocol interface, overridden by server protocol modules
306 ProtocolInterface* PI;
308 /** Default implementation of the ProtocolInterface, does nothing
310 ProtocolInterface DefaultProtocolInterface;
312 /** Manages the generation and transmission of ISUPPORT. */
313 ISupportManager ISupport;
315 /** Get the current time
316 * Because this only calls time() once every time around the mainloop,
317 * it is much faster than calling time() directly.
318 * @return The current time as an epoch value (time_t)
320 inline time_t Time() { return TIME.tv_sec; }
321 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
322 inline long Time_ns() { return TIME.tv_nsec; }
323 /** Update the current time. Don't call this unless you have reason to do so. */
326 /** Generate a random string with the given length
327 * @param length The length in bytes
328 * @param printable if false, the string will use characters 0-255; otherwise,
329 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
331 std::string GenRandomStr(unsigned int length, bool printable = true);
332 /** Generate a random integer.
333 * This is generally more secure than rand()
335 unsigned long GenRandomInt(unsigned long max);
337 /** Fill a buffer with random bits */
338 TR1NS::function<void(char*, size_t)> GenRandom;
340 /** Fills the output buffer with the specified number of random characters.
341 * This is the default function for InspIRCd::GenRandom.
342 * @param output The output buffer to store random characters in.
343 * @param max The maximum number of random characters to put in the buffer.
345 static void DefaultGenRandom(char* output, size_t max);
347 /** Bind all ports specified in the configuration file.
348 * @return The number of ports bound without error
350 int BindPorts(FailedPortList &failed_ports);
352 /** Find a user in the nick hash.
353 * If the user cant be found in the nick hash check the uuid hash
354 * @param nick The nickname to find
355 * @return A pointer to the user, or NULL if the user does not exist
357 User* FindNick(const std::string &nick);
359 /** Find a user in the nick hash ONLY
361 User* FindNickOnly(const std::string &nick);
363 /** Find a channel in the channels hash
364 * @param chan The channel to find
365 * @return A pointer to the channel, or NULL if the channel does not exist
367 Channel* FindChan(const std::string &chan);
369 /** Get a hash map containing all channels, keyed by their name
370 * @return A hash map mapping channel names to Channel pointers
372 chan_hash& GetChans() { return chanlist; }
374 /** Determines whether an channel name is valid. */
375 TR1NS::function<bool(const std::string&)> IsChannel;
377 /** Determines whether a channel name is valid according to the RFC 1459 rules.
378 * This is the default function for InspIRCd::IsChannel.
379 * @param channel The channel name to validate.
380 * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
382 static bool DefaultIsChannel(const std::string& channel);
384 /** Return true if str looks like a server ID
385 * @param sid string to check against
387 static bool IsSID(const std::string& sid);
389 /** Handles incoming signals after being set
390 * @param signal the signal recieved
392 void SignalHandler(int signal);
394 /** Sets the signal recieved
395 * @param signal the signal recieved
397 static void SetSignal(int signal);
399 /** Causes the server to exit after unloading modules and
400 * closing all open file descriptors.
402 * @param status The exit code to give to the operating system
403 * (See the ExitStatus enum for valid values)
405 void Exit(int status);
407 /** Formats the input string with the specified arguments.
408 * @param formatString The string to format
409 * @param ... A variable number of format arguments.
410 * @return The formatted string
412 static std::string Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
413 static std::string Format(va_list& vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
415 /** Determines whether a nickname is valid. */
416 TR1NS::function<bool(const std::string&)> IsNick;
418 /** Determines whether a nickname is valid according to the RFC 1459 rules.
419 * This is the default function for InspIRCd::IsNick.
420 * @param nick The nickname to validate.
421 * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
423 static bool DefaultIsNick(const std::string& nick);
425 /** Determines whether an ident is valid. */
426 TR1NS::function<bool(const std::string&)> IsIdent;
428 /** Determines whether a ident is valid according to the RFC 1459 rules.
429 * This is the default function for InspIRCd::IsIdent.
430 * @param ident The ident to validate.
431 * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
433 static bool DefaultIsIdent(const std::string& ident);
435 /** Match two strings using pattern matching, optionally, with a map
436 * to check case against (may be NULL). If map is null, match will be case insensitive.
437 * @param str The literal string to match against
438 * @param mask The glob pattern to match against.
439 * @param map The character map to use when matching.
441 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
442 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
444 /** Match two strings using pattern matching, optionally, with a map
445 * to check case against (may be NULL). If map is null, match will be case insensitive.
446 * Supports CIDR patterns as well as globs.
447 * @param str The literal string to match against
448 * @param mask The glob or CIDR pattern to match against.
449 * @param map The character map to use when matching.
451 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
452 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
454 /** Matches a hostname and IP against a space delimited list of hostmasks.
455 * @param masks The space delimited masks to match against.
456 * @param hostname The hostname to try and match.
457 * @param ipaddr The IP address to try and match.
459 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
461 /** Return true if the given parameter is a valid nick!user\@host mask
462 * @param mask A nick!user\@host masak to match against
463 * @return True i the mask is valid
465 static bool IsValidMask(const std::string& mask);
467 /** Strips all color and control codes except 001 from the given string
468 * @param sentence The string to strip from
470 static void StripColor(std::string &sentence);
472 /** Parses color codes from string values to actual color codes
473 * @param input The data to process
475 static void ProcessColors(file_cache& input);
477 /** Rehash the local server
478 * @param uuid The uuid of the user who started the rehash, can be empty
480 void Rehash(const std::string& uuid = "");
482 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
483 * @param str A string containing a time in the form 1y2w3d4h6m5s
484 * (one year, two weeks, three days, four hours, six minutes and five seconds)
485 * @return The total number of seconds
487 static unsigned long Duration(const std::string& str);
489 /** Attempt to compare a password to a string from the config file.
490 * This will be passed to handling modules which will compare the data
491 * against possible hashed equivalents in the input string.
492 * @param ex The object (user, server, whatever) causing the comparison.
493 * @param data The data from the config file
494 * @param input The data input by the oper
495 * @param hashtype The hash from the config file
496 * @return True if the strings match, false if they do not
498 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
500 /** Returns the full version string of this ircd
501 * @return The version string
503 std::string GetVersionString(bool getFullVersion = false);
505 /** Attempt to write the process id to a given file
506 * @param filename The PID file to attempt to write to
507 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
508 * @return This function may bail if the file cannot be written
510 void WritePID(const std::string& filename, bool exitonfail = true);
512 /** This constructor initialises all the subsystems and reads the config file.
513 * @param argc The argument count passed to main()
514 * @param argv The argument list passed to main()
515 * @throw <anything> If anything is thrown from here and makes it to
516 * you, you should probably just give up and go home. Yes, really.
517 * It's that bad. Higher level classes should catch any non-fatal exceptions.
519 InspIRCd(int argc, char** argv);
521 /** Prepare the ircd for restart or shutdown.
522 * This function unloads all modules which can be unloaded,
523 * closes all open sockets, and closes the logfile.
527 /** Return a time_t as a human-readable string.
528 * @param format The format to retrieve the date/time in. See `man 3 strftime`
529 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
530 * @param curtime The timestamp to convert to a human-readable string.
531 * @param utc True to convert the time to string as-is, false to convert it to local time first.
532 * @return A string representing the given date/time.
534 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
536 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
537 * returns false immediately (leaking information about the length), otherwise it compares each
538 * character and only returns after all characters have been compared.
539 * @param one First string
540 * @param two Second string
541 * @return True if the strings match, false if they don't
543 static bool TimingSafeCompare(const std::string& one, const std::string& two);
545 /** Begin execution of the server.
546 * NOTE: this function NEVER returns. Internally,
547 * it will repeatedly loop.
551 char* GetReadBuffer()
553 return this->ReadBuffer;
560 class CommandModule : public Module
564 CommandModule() : cmd(this)
568 Version GetVersion() CXX11_OVERRIDE
570 return Version(cmd.name, VF_VENDOR|VF_CORE);
574 inline void stdalgo::culldeleter::operator()(classbase* item)
577 ServerInstance->GlobalCulls.AddItem(item);
580 #include "numericbuilder.h"