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/>.
28 // If the system has a pre-C11 stdint header this must be defined in
29 // order to use the numeric limit macros.
30 #define __STDC_LIMIT_MACROS
52 #include "intrusive_list.h"
55 #include "aligned_storage.h"
60 CoreExport extern InspIRCd* ServerInstance;
62 /** Base class for manager classes that are still accessed using -> but are no longer pointers
69 return static_cast<T*>(this);
75 #include "consolecolors.h"
76 #include "cull_list.h"
77 #include "extensible.h"
78 #include "fileutils.h"
89 #include "usermanager.h"
91 #include "command_parse.h"
93 #include "socketengine.h"
95 #include "filelogger.h"
98 #include "clientprotocol.h"
99 #include "threadengine.h"
100 #include "configreader.h"
101 #include "inspstring.h"
102 #include "protocol.h"
103 #include "bancache.h"
104 #include "isupportmanager.h"
106 /** This class contains various STATS counters
107 * It is used by the InspIRCd class, which internally
108 * has an instance of it.
113 /** Number of accepted connections
115 unsigned long Accept;
116 /** Number of failed accepts
118 unsigned long Refused;
119 /** Number of unknown commands seen
121 unsigned long Unknown;
122 /** Number of nickname collisions handled
124 unsigned long Collisions;
125 /** Number of DNS queries sent out
128 /** Number of good 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 DnsGood;
133 /** Number of bad (negative) DNS replies received
134 * NOTE: This may not tally to the number sent out,
135 * due to timeouts and other latency issues.
137 unsigned long DnsBad;
138 /** Number of inbound connections seen
140 unsigned long Connects;
141 /** Total bytes of data transmitted
144 /** Total bytes of data received
148 /** Cpu usage at last sample
151 /** Time QP sample was read
153 LARGE_INTEGER LastSampled;
156 LARGE_INTEGER QPFrequency;
158 /** Cpu usage at last sample
161 /** Time last sample was read
163 timespec LastSampled;
165 /** The constructor initializes all the counts to zero
168 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
169 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
174 /** The main class of the irc server.
175 * This class contains instances of all the other classes in this software.
176 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
177 * object, and a list of active Module objects, and facilities for Module
178 * objects to interact with the core system it implements.
180 class CoreExport InspIRCd
183 /** Set up the signal handlers
187 /** Daemonize the ircd and close standard input/output streams
188 * @return True if the program daemonized succesfully
192 /** The current time, updated in the mainloop
194 struct timespec TIME;
196 /** A 64k buffer used to read socket data into
197 * NOTE: update ValidateNetBufferSize if you change this
199 char ReadBuffer[65535];
201 ClientProtocol::RFCEvents rfcevents;
203 /** Check we aren't running as root, and exit if we are
204 * with exit code EXIT_STATUS_ROOT.
212 /** Global cull list, will be processed on next iteration
214 CullList GlobalCulls;
215 /** Actions that must happen outside of the current call stack */
216 ActionList AtomicActions;
218 /** 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
221 * SendMode expects a User* to send the numeric replies
222 * back to, so we create it a fake user that isnt in the user
223 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
224 * falls into the abyss :p
226 FakeUser* FakeClient;
228 /** Find a user in the UUID hash
229 * @param uid The UUID to find
230 * @return A pointer to the user, or NULL if the user does not exist
232 User* FindUUID(const std::string &uid);
234 /** Time this ircd was booted
238 /** Config file pathname specified on the commandline or via ./configure
240 std::string ConfigFileName;
242 ExtensionManager Extensions;
244 /** Mode handler, handles mode setting and removal
248 /** Command parser, handles client to server commands
250 CommandParser Parser;
252 /** Thread engine, Handles threading where required
254 ThreadEngine Threads;
256 /** The thread/class used to read config files in REHASH and on startup
258 ConfigReaderThread* ConfigThread;
260 /** LogManager handles logging.
264 /** ModuleManager contains everything related to loading/unloading
267 ModuleManager Modules;
269 /** BanCacheManager is used to speed up checking of restrictions on connection
272 BanCacheManager BanCache;
274 /** Stats class, holds miscellaneous stats counters
278 /** Server Config class, holds configuration file data
280 ServerConfig* Config;
282 /** Snomask manager - handles routing of snomask messages
287 /** Timer manager class, triggers Timer timer events
291 /** X-line manager. Handles G/K/Q/E-line setting, removal and matching
293 XLineManager* XLines;
295 /** User manager. Various methods and data associated with users.
299 /** Channel list, a hash_map containing all channels XXX move to channel manager class
303 /** List of the open ports
305 std::vector<ListenSocket*> ports;
307 /** Set to the current signal received
309 static sig_atomic_t s_signal;
311 /** Protocol interface, overridden by server protocol modules
313 ProtocolInterface* PI;
315 /** Default implementation of the ProtocolInterface, does nothing
317 ProtocolInterface DefaultProtocolInterface;
319 /** Manages the generation and transmission of ISUPPORT. */
320 ISupportManager ISupport;
322 /** Get the current time
323 * Because this only calls time() once every time around the mainloop,
324 * it is much faster than calling time() directly.
325 * @return The current time as an epoch value (time_t)
327 inline time_t Time() { return TIME.tv_sec; }
328 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
329 inline long Time_ns() { return TIME.tv_nsec; }
330 /** Update the current time. Don't call this unless you have reason to do so. */
333 /** Generate a random string with the given length
334 * @param length The length in bytes
335 * @param printable if false, the string will use characters 0-255; otherwise,
336 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
338 std::string GenRandomStr(unsigned int length, bool printable = true);
339 /** Generate a random integer.
340 * This is generally more secure than rand()
342 unsigned long GenRandomInt(unsigned long max);
344 /** Fill a buffer with random bits */
345 TR1NS::function<void(char*, size_t)> GenRandom;
347 /** Fills the output buffer with the specified number of random characters.
348 * This is the default function for InspIRCd::GenRandom.
349 * @param output The output buffer to store random characters in.
350 * @param max The maximum number of random characters to put in the buffer.
352 static void DefaultGenRandom(char* output, size_t max);
354 /** Bind to a specific port from a config tag.
355 * @param tag the tag that contains bind information.
356 * @param sa The endpoint to listen on.
357 * @param old_ports Previously listening ports that may be on the same endpoint.
359 bool BindPort(ConfigTag* tag, const irc::sockets::sockaddrs& sa, std::vector<ListenSocket*>& old_ports);
361 /** Bind all ports specified in the configuration file.
362 * @return The number of ports bound without error
364 int BindPorts(FailedPortList &failed_ports);
366 /** Find a user in the nick hash.
367 * If the user cant be found in the nick hash check the uuid hash
368 * @param nick The nickname to find
369 * @return A pointer to the user, or NULL if the user does not exist
371 User* FindNick(const std::string &nick);
373 /** Find a user in the nick hash ONLY
375 User* FindNickOnly(const std::string &nick);
377 /** Find a channel in the channels hash
378 * @param chan The channel to find
379 * @return A pointer to the channel, or NULL if the channel does not exist
381 Channel* FindChan(const std::string &chan);
383 /** Get a hash map containing all channels, keyed by their name
384 * @return A hash map mapping channel names to Channel pointers
386 chan_hash& GetChans() { return chanlist; }
388 /** Determines whether an channel name is valid. */
389 TR1NS::function<bool(const std::string&)> IsChannel;
391 /** Determines whether a channel name is valid according to the RFC 1459 rules.
392 * This is the default function for InspIRCd::IsChannel.
393 * @param channel The channel name to validate.
394 * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
396 static bool DefaultIsChannel(const std::string& channel);
398 /** Determines whether a hostname is valid according to RFC 5891 rules.
399 * @param host The hostname to validate.
400 * @return True if the hostname is valid; otherwise, false.
402 static bool IsHost(const std::string& host);
404 /** Return true if str looks like a server ID
405 * @param sid string to check against
407 static bool IsSID(const std::string& sid);
409 /** Handles incoming signals after being set
410 * @param signal the signal received
412 void SignalHandler(int signal);
414 /** Sets the signal received
415 * @param signal the signal received
417 static void SetSignal(int signal);
419 /** Causes the server to exit after unloading modules and
420 * closing all open file descriptors.
422 * @param status The exit code to give to the operating system
423 * (See the ExitStatus enum for valid values)
425 void Exit(int status);
427 /** Formats the input string with the specified arguments.
428 * @param formatString The string to format
429 * @param ... A variable number of format arguments.
430 * @return The formatted string
432 static std::string Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
433 static std::string Format(va_list& vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
435 /** Determines whether a nickname is valid. */
436 TR1NS::function<bool(const std::string&)> IsNick;
438 /** Determines whether a nickname is valid according to the RFC 1459 rules.
439 * This is the default function for InspIRCd::IsNick.
440 * @param nick The nickname to validate.
441 * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
443 static bool DefaultIsNick(const std::string& nick);
445 /** Determines whether an ident is valid. */
446 TR1NS::function<bool(const std::string&)> IsIdent;
448 /** Determines whether a ident is valid according to the RFC 1459 rules.
449 * This is the default function for InspIRCd::IsIdent.
450 * @param ident The ident to validate.
451 * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
453 static bool DefaultIsIdent(const std::string& ident);
455 /** Match two strings using pattern matching, optionally, with a map
456 * to check case against (may be NULL). If map is null, match will be case insensitive.
457 * @param str The literal string to match against
458 * @param mask The glob pattern to match against.
459 * @param map The character map to use when matching.
461 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
462 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
464 /** Match two strings using pattern matching, optionally, with a map
465 * to check case against (may be NULL). If map is null, match will be case insensitive.
466 * Supports CIDR patterns as well as globs.
467 * @param str The literal string to match against
468 * @param mask The glob or CIDR pattern to match against.
469 * @param map The character map to use when matching.
471 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
472 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
474 /** Matches a hostname and IP against a space delimited list of hostmasks.
475 * @param masks The space delimited masks to match against.
476 * @param hostname The hostname to try and match.
477 * @param ipaddr The IP address to try and match.
479 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
481 /** Return true if the given parameter is a valid nick!user\@host mask
482 * @param mask A nick!user\@host masak to match against
483 * @return True i the mask is valid
485 static bool IsValidMask(const std::string& mask);
487 /** Strips all color and control codes except 001 from the given string
488 * @param sentence The string to strip from
490 static void StripColor(std::string &sentence);
492 /** Parses color codes from string values to actual color codes
493 * @param input The data to process
495 static void ProcessColors(file_cache& input);
497 /** Rehash the local server
498 * @param uuid The uuid of the user who started the rehash, can be empty
500 void Rehash(const std::string& uuid = "");
502 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
503 * @param str A string containing a time in the form 1y2w3d4h6m5s
504 * (one year, two weeks, three days, four hours, six minutes and five seconds)
505 * @return The total number of seconds
507 static unsigned long Duration(const std::string& str);
509 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
510 * @param str A string containing a time in the form 1y2w3d4h6m5s
511 * (one year, two weeks, three days, four hours, six minutes and five seconds)
512 * @param duration The location to place the parsed duration valur
513 * @return Whether the duration was a valid format or not
515 static bool Duration(const std::string& str, unsigned long& duration);
517 /** Determines whether a string contains a valid duration.
518 * @param str A string containing a time in the form 1y2w3d4h6m5s
519 * @return True if the string is a valid duration; otherwise, false.
521 static bool IsValidDuration(const std::string& str);
523 /** Return a duration in seconds as a human-readable string.
524 * @param duration The duration in seconds to convert to a human-readable string.
525 * @return A string representing the given duration.
527 static std::string DurationString(time_t duration);
529 /** Attempt to compare a password to a string from the config file.
530 * This will be passed to handling modules which will compare the data
531 * against possible hashed equivalents in the input string.
532 * @param ex The object (user, server, whatever) causing the comparison.
533 * @param data The data from the config file
534 * @param input The data input by the oper
535 * @param hashtype The hash from the config file
536 * @return True if the strings match, false if they do not
538 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
540 /** Returns the full version string of this ircd
541 * @return The version string
543 std::string GetVersionString(bool getFullVersion = false);
545 /** Attempt to write the process id to a given file
546 * @param filename The PID file to attempt to write to
547 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
548 * @return This function may bail if the file cannot be written
550 void WritePID(const std::string& filename, bool exitonfail = true);
552 /** This constructor initialises all the subsystems and reads the config file.
553 * @param argc The argument count passed to main()
554 * @param argv The argument list passed to main()
555 * @throw <anything> If anything is thrown from here and makes it to
556 * you, you should probably just give up and go home. Yes, really.
557 * It's that bad. Higher level classes should catch any non-fatal exceptions.
559 InspIRCd(int argc, char** argv);
561 /** Prepare the ircd for restart or shutdown.
562 * This function unloads all modules which can be unloaded,
563 * closes all open sockets, and closes the logfile.
567 /** Return a time_t as a human-readable string.
568 * @param format The format to retrieve the date/time in. See `man 3 strftime`
569 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
570 * @param curtime The timestamp to convert to a human-readable string.
571 * @param utc True to convert the time to string as-is, false to convert it to local time first.
572 * @return A string representing the given date/time.
574 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
576 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
577 * returns false immediately (leaking information about the length), otherwise it compares each
578 * character and only returns after all characters have been compared.
579 * @param one First string
580 * @param two Second string
581 * @return True if the strings match, false if they don't
583 static bool TimingSafeCompare(const std::string& one, const std::string& two);
585 /** Begin execution of the server.
586 * NOTE: this function NEVER returns. Internally,
587 * it will repeatedly loop.
591 char* GetReadBuffer()
593 return this->ReadBuffer;
596 ClientProtocol::RFCEvents& GetRFCEvents() { return rfcevents; }
601 inline void stdalgo::culldeleter::operator()(classbase* item)
604 ServerInstance->GlobalCulls.AddItem(item);
607 inline void Channel::Write(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg, char status, const CUList& except_list)
609 ClientProtocol::Event event(protoevprov, msg);
610 Write(event, status, except_list);
613 inline void LocalUser::Send(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg)
615 ClientProtocol::Event event(protoevprov, msg);
619 #include "numericbuilder.h"
620 #include "clientprotocolmsg.h"
621 #include "clientprotocolevent.h"