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"
71 #include "cull_list.h"
72 #include "extensible.h"
73 #include "fileutils.h"
83 #include "usermanager.h"
86 #include "command_parse.h"
88 #include "socketengine.h"
90 #include "filelogger.h"
92 #include "threadengine.h"
93 #include "configreader.h"
94 #include "inspstring.h"
97 #include "isupportmanager.h"
99 /** This class contains various STATS counters
100 * It is used by the InspIRCd class, which internally
101 * has an instance of it.
106 /** Number of accepted connections
108 unsigned long Accept;
109 /** Number of failed accepts
111 unsigned long Refused;
112 /** Number of unknown commands seen
114 unsigned long Unknown;
115 /** Number of nickname collisions handled
117 unsigned long Collisions;
118 /** Number of DNS queries sent out
121 /** Number of good DNS replies received
122 * NOTE: This may not tally to the number sent out,
123 * due to timeouts and other latency issues.
125 unsigned long DnsGood;
126 /** Number of bad (negative) DNS replies received
127 * NOTE: This may not tally to the number sent out,
128 * due to timeouts and other latency issues.
130 unsigned long DnsBad;
131 /** Number of inbound connections seen
133 unsigned long Connects;
134 /** Total bytes of data transmitted
137 /** Total bytes of data received
141 /** Cpu usage at last sample
144 /** Time QP sample was read
146 LARGE_INTEGER LastSampled;
149 LARGE_INTEGER QPFrequency;
151 /** Cpu usage at last sample
154 /** Time last sample was read
156 timespec LastSampled;
158 /** The constructor initializes all the counts to zero
161 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
162 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
167 /** The main class of the irc server.
168 * This class contains instances of all the other classes in this software.
169 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
170 * object, and a list of active Module objects, and facilities for Module
171 * objects to interact with the core system it implements.
173 class CoreExport InspIRCd
176 /** Set up the signal handlers
180 /** Daemonize the ircd and close standard input/output streams
181 * @return True if the program daemonized succesfully
185 /** The current time, updated in the mainloop
187 struct timespec TIME;
189 /** A 64k buffer used to read socket data into
190 * NOTE: update ValidateNetBufferSize if you change this
192 char ReadBuffer[65535];
194 /** Check we aren't running as root, and exit if we are
195 * with exit code EXIT_STATUS_ROOT.
203 /** Global cull list, will be processed on next iteration
205 CullList GlobalCulls;
206 /** Actions that must happen outside of the current call stack */
207 ActionList AtomicActions;
209 /** 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
212 * SendMode expects a User* to send the numeric replies
213 * back to, so we create it a fake user that isnt in the user
214 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
215 * falls into the abyss :p
217 FakeUser* FakeClient;
219 /** Find a user in the UUID hash
220 * @param uid The UUID to find
221 * @return A pointer to the user, or NULL if the user does not exist
223 User* FindUUID(const std::string &uid);
225 /** Time this ircd was booted
229 /** Config file pathname specified on the commandline or via ./configure
231 std::string ConfigFileName;
233 ExtensionManager Extensions;
235 /** Mode handler, handles mode setting and removal
239 /** Command parser, handles client to server commands
241 CommandParser Parser;
243 /** Thread engine, Handles threading where required
245 ThreadEngine Threads;
247 /** The thread/class used to read config files in REHASH and on startup
249 ConfigReaderThread* ConfigThread;
251 /** LogManager handles logging.
255 /** ModuleManager contains everything related to loading/unloading
258 ModuleManager Modules;
260 /** BanCacheManager is used to speed up checking of restrictions on connection
263 BanCacheManager BanCache;
265 /** Stats class, holds miscellaneous stats counters
269 /** Server Config class, holds configuration file data
271 ServerConfig* Config;
273 /** Snomask manager - handles routing of snomask messages
278 /** Timer manager class, triggers Timer timer events
282 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
284 XLineManager* XLines;
286 /** User manager. Various methods and data associated with users.
290 /** Channel list, a hash_map containing all channels XXX move to channel manager class
294 /** List of the open ports
296 std::vector<ListenSocket*> ports;
298 /** Set to the current signal recieved
300 static sig_atomic_t s_signal;
302 /** Protocol interface, overridden by server protocol modules
304 ProtocolInterface* PI;
306 /** Default implementation of the ProtocolInterface, does nothing
308 ProtocolInterface DefaultProtocolInterface;
310 /** Manages the generation and transmission of ISUPPORT. */
311 ISupportManager ISupport;
313 /** Get the current time
314 * Because this only calls time() once every time around the mainloop,
315 * it is much faster than calling time() directly.
316 * @return The current time as an epoch value (time_t)
318 inline time_t Time() { return TIME.tv_sec; }
319 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
320 inline long Time_ns() { return TIME.tv_nsec; }
321 /** Update the current time. Don't call this unless you have reason to do so. */
324 /** Generate a random string with the given length
325 * @param length The length in bytes
326 * @param printable if false, the string will use characters 0-255; otherwise,
327 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
329 std::string GenRandomStr(unsigned int length, bool printable = true);
330 /** Generate a random integer.
331 * This is generally more secure than rand()
333 unsigned long GenRandomInt(unsigned long max);
335 /** Fill a buffer with random bits */
336 TR1NS::function<void(char*, size_t)> GenRandom;
338 /** Fills the output buffer with the specified number of random characters.
339 * This is the default function for InspIRCd::GenRandom.
340 * @param output The output buffer to store random characters in.
341 * @param max The maximum number of random characters to put in the buffer.
343 static void DefaultGenRandom(char* output, size_t max);
345 /** Bind all ports specified in the configuration file.
346 * @return The number of ports bound without error
348 int BindPorts(FailedPortList &failed_ports);
350 /** Find a user in the nick hash.
351 * If the user cant be found in the nick hash check the uuid hash
352 * @param nick The nickname to find
353 * @return A pointer to the user, or NULL if the user does not exist
355 User* FindNick(const std::string &nick);
357 /** Find a user in the nick hash ONLY
359 User* FindNickOnly(const std::string &nick);
361 /** Find a channel in the channels hash
362 * @param chan The channel to find
363 * @return A pointer to the channel, or NULL if the channel does not exist
365 Channel* FindChan(const std::string &chan);
367 /** Get a hash map containing all channels, keyed by their name
368 * @return A hash map mapping channel names to Channel pointers
370 chan_hash& GetChans() { return chanlist; }
372 /** Determines whether an channel name is valid. */
373 TR1NS::function<bool(const std::string&)> IsChannel;
375 /** Determines whether a channel name is valid according to the RFC 1459 rules.
376 * This is the default function for InspIRCd::IsChannel.
377 * @param nick The channel name to validate.
378 * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
380 static bool DefaultIsChannel(const std::string& channel);
382 /** Return true if str looks like a server ID
383 * @param sid string to check against
385 static bool IsSID(const std::string& sid);
387 /** Handles incoming signals after being set
388 * @param signal the signal recieved
390 void SignalHandler(int signal);
392 /** Sets the signal recieved
393 * @param signal the signal recieved
395 static void SetSignal(int signal);
397 /** Causes the server to exit after unloading modules and
398 * closing all open file descriptors.
400 * @param status The exit code to give to the operating system
401 * (See the ExitStatus enum for valid values)
403 void Exit(int status);
405 /** Causes the server to exit immediately with exit code 0.
406 * The status code is required for signal handlers, and ignored.
408 static void QuickExit(int status);
410 /** Formats the input string with the specified arguments.
411 * @param formatString The string to format
412 * @param ... A variable number of format arguments.
413 * @return The formatted string
415 static const char* Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
416 static const char* Format(va_list &vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
418 /** Determines whether a nickname is valid. */
419 TR1NS::function<bool(const std::string&)> IsNick;
421 /** Determines whether a nickname is valid according to the RFC 1459 rules.
422 * This is the default function for InspIRCd::IsNick.
423 * @param nick The nickname to validate.
424 * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
426 static bool DefaultIsNick(const std::string& nick);
428 /** Determines whether an ident is valid. */
429 TR1NS::function<bool(const std::string&)> IsIdent;
431 /** Determines whether a ident is valid according to the RFC 1459 rules.
432 * This is the default function for InspIRCd::IsIdent.
433 * @param nick The ident to validate.
434 * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
436 static bool DefaultIsIdent(const std::string& ident);
438 /** Match two strings using pattern matching, optionally, with a map
439 * to check case against (may be NULL). If map is null, match will be case insensitive.
440 * @param str The literal string to match against
441 * @param mask The glob pattern to match against.
442 * @param map The character map to use when matching.
444 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
445 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
447 /** Match two strings using pattern matching, optionally, with a map
448 * to check case against (may be NULL). If map is null, match will be case insensitive.
449 * Supports CIDR patterns as well as globs.
450 * @param str The literal string to match against
451 * @param mask The glob or CIDR pattern to match against.
452 * @param map The character map to use when matching.
454 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
455 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
457 /** Matches a hostname and IP against a space delimited list of hostmasks.
458 * @param masks The space delimited masks to match against.
459 * @param hostname The hostname to try and match.
460 * @param ipaddr The IP address to try and match.
462 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
464 /** Return true if the given parameter is a valid nick!user\@host mask
465 * @param mask A nick!user\@host masak to match against
466 * @return True i the mask is valid
468 static bool IsValidMask(const std::string& mask);
470 /** Strips all color and control codes except 001 from the given string
471 * @param sentence The string to strip from
473 static void StripColor(std::string &sentence);
475 /** Parses color codes from string values to actual color codes
476 * @param input The data to process
478 static void ProcessColors(file_cache& input);
480 /** Rehash the local server
481 * @param uuid The uuid of the user who started the rehash, can be empty
483 void Rehash(const std::string& uuid = "");
485 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
486 * @param str A string containing a time in the form 1y2w3d4h6m5s
487 * (one year, two weeks, three days, four hours, six minutes and five seconds)
488 * @return The total number of seconds
490 static unsigned long Duration(const std::string& str);
492 /** Attempt to compare a password to a string from the config file.
493 * This will be passed to handling modules which will compare the data
494 * against possible hashed equivalents in the input string.
495 * @param ex The object (user, server, whatever) causing the comparison.
496 * @param data The data from the config file
497 * @param input The data input by the oper
498 * @param hashtype The hash from the config file
499 * @return True if the strings match, false if they do not
501 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
503 /** Returns the full version string of this ircd
504 * @return The version string
506 std::string GetVersionString(bool getFullVersion = false);
508 /** Attempt to write the process id to a given file
509 * @param filename The PID file to attempt to write to
510 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
511 * @return This function may bail if the file cannot be written
513 void WritePID(const std::string& filename, bool exitonfail = true);
515 /** This constructor initialises all the subsystems and reads the config file.
516 * @param argc The argument count passed to main()
517 * @param argv The argument list passed to main()
518 * @throw <anything> If anything is thrown from here and makes it to
519 * you, you should probably just give up and go home. Yes, really.
520 * It's that bad. Higher level classes should catch any non-fatal exceptions.
522 InspIRCd(int argc, char** argv);
524 /** Prepare the ircd for restart or shutdown.
525 * This function unloads all modules which can be unloaded,
526 * closes all open sockets, and closes the logfile.
530 /** Return a time_t as a human-readable string.
531 * @param format The format to retrieve the date/time in. See `man 3 strftime`
532 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
533 * @param curtime The timestamp to convert to a human-readable string.
534 * @param utc True to convert the time to string as-is, false to convert it to local time first.
535 * @return A string representing the given date/time.
537 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
539 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
540 * returns false immediately (leaking information about the length), otherwise it compares each
541 * character and only returns after all characters have been compared.
542 * @param one First string
543 * @param two Second string
544 * @return True if the strings match, false if they don't
546 static bool TimingSafeCompare(const std::string& one, const std::string& two);
548 /** Begin execution of the server.
549 * NOTE: this function NEVER returns. Internally,
550 * it will repeatedly loop.
554 char* GetReadBuffer()
556 return this->ReadBuffer;
563 class CommandModule : public Module
567 CommandModule() : cmd(this)
571 Version GetVersion() CXX11_OVERRIDE
573 return Version(cmd.name, VF_VENDOR|VF_CORE);
577 inline void stdalgo::culldeleter::operator()(classbase* item)
580 ServerInstance->GlobalCulls.AddItem(item);
583 #include "numericbuilder.h"
584 #include "modules/whois.h"
585 #include "modules/stats.h"