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 "serialize.h"
78 #include "extensible.h"
79 #include "fileutils.h"
90 #include "usermanager.h"
92 #include "command_parse.h"
94 #include "socketengine.h"
96 #include "filelogger.h"
99 #include "clientprotocol.h"
100 #include "threadengine.h"
101 #include "configreader.h"
102 #include "inspstring.h"
103 #include "protocol.h"
104 #include "bancache.h"
105 #include "isupportmanager.h"
107 /** This class contains various STATS counters
108 * It is used by the InspIRCd class, which internally
109 * has an instance of it.
114 /** Number of accepted connections
116 unsigned long Accept;
117 /** Number of failed accepts
119 unsigned long Refused;
120 /** Number of unknown commands seen
122 unsigned long Unknown;
123 /** Number of nickname collisions handled
125 unsigned long Collisions;
126 /** Number of DNS queries sent out
129 /** Number of good DNS replies received
130 * NOTE: This may not tally to the number sent out,
131 * due to timeouts and other latency issues.
133 unsigned long DnsGood;
134 /** Number of bad (negative) DNS replies received
135 * NOTE: This may not tally to the number sent out,
136 * due to timeouts and other latency issues.
138 unsigned long DnsBad;
139 /** Number of inbound connections seen
141 unsigned long Connects;
142 /** Total bytes of data transmitted
145 /** Total bytes of data received
149 /** Cpu usage at last sample
152 /** Time QP sample was read
154 LARGE_INTEGER LastSampled;
157 LARGE_INTEGER QPFrequency;
159 /** Cpu usage at last sample
162 /** Time last sample was read
164 timespec LastSampled;
166 /** The constructor initializes all the counts to zero
169 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
170 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
175 /** The main class of the irc server.
176 * This class contains instances of all the other classes in this software.
177 * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
178 * object, and a list of active Module objects, and facilities for Module
179 * objects to interact with the core system it implements.
181 class CoreExport InspIRCd
184 /** The current time, updated in the mainloop
186 struct timespec TIME;
188 /** A 64k buffer used to read socket data into
189 * NOTE: update ValidateNetBufferSize if you change this
191 char ReadBuffer[65535];
193 ClientProtocol::RFCEvents rfcevents;
199 /** Global cull list, will be processed on next iteration
201 CullList GlobalCulls;
202 /** Actions that must happen outside of the current call stack */
203 ActionList AtomicActions;
205 /** 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
208 * SendMode expects a User* to send the numeric replies
209 * back to, so we create it a fake user that isnt in the user
210 * hash and set its descriptor to FD_MAGIC_NUMBER so the data
211 * falls into the abyss :p
213 FakeUser* FakeClient;
215 /** Find a user in the UUID hash
216 * @param uid The UUID to find
217 * @return A pointer to the user, or NULL if the user does not exist
219 User* FindUUID(const std::string &uid);
221 /** Time this ircd was booted
225 /** Config file pathname specified on the commandline or via ./configure
227 std::string ConfigFileName;
229 ExtensionManager Extensions;
231 /** Mode handler, handles mode setting and removal
235 /** Command parser, handles client to server commands
237 CommandParser Parser;
239 /** Thread engine, Handles threading where required
241 ThreadEngine Threads;
243 /** The thread/class used to read config files in REHASH and on startup
245 ConfigReaderThread* ConfigThread;
247 /** LogManager handles logging.
251 /** ModuleManager contains everything related to loading/unloading
254 ModuleManager Modules;
256 /** BanCacheManager is used to speed up checking of restrictions on connection
259 BanCacheManager BanCache;
261 /** Stats class, holds miscellaneous stats counters
265 /** Server Config class, holds configuration file data
267 ServerConfig* Config;
269 /** Snomask manager - handles routing of snomask messages
274 /** Timer manager class, triggers Timer timer events
278 /** X-line manager. Handles G/K/Q/E-line setting, removal and matching
280 XLineManager* XLines;
282 /** User manager. Various methods and data associated with users.
286 /** Channel list, a hash_map containing all channels XXX move to channel manager class
290 /** List of the open ports
292 std::vector<ListenSocket*> ports;
294 /** Set to the current signal received
296 static sig_atomic_t s_signal;
298 /** Protocol interface, overridden by server protocol modules
300 ProtocolInterface* PI;
302 /** Default implementation of the ProtocolInterface, does nothing
304 ProtocolInterface DefaultProtocolInterface;
306 /** Manages the generation and transmission of ISUPPORT. */
307 ISupportManager ISupport;
309 /** Get the current time
310 * Because this only calls time() once every time around the mainloop,
311 * it is much faster than calling time() directly.
312 * @return The current time as an epoch value (time_t)
314 inline time_t Time() { return TIME.tv_sec; }
315 /** The fractional time at the start of this mainloop iteration (nanoseconds) */
316 inline long Time_ns() { return TIME.tv_nsec; }
317 /** Update the current time. Don't call this unless you have reason to do so. */
320 /** Generate a random string with the given length
321 * @param length The length in bytes
322 * @param printable if false, the string will use characters 0-255; otherwise,
323 * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
325 std::string GenRandomStr(unsigned int length, bool printable = true);
326 /** Generate a random integer.
327 * This is generally more secure than rand()
329 unsigned long GenRandomInt(unsigned long max);
331 /** Fill a buffer with random bits */
332 TR1NS::function<void(char*, size_t)> GenRandom;
334 /** Fills the output buffer with the specified number of random characters.
335 * This is the default function for InspIRCd::GenRandom.
336 * @param output The output buffer to store random characters in.
337 * @param max The maximum number of random characters to put in the buffer.
339 static void DefaultGenRandom(char* output, size_t max);
341 /** Bind to a specific port from a config tag.
342 * @param tag the tag that contains bind information.
343 * @param sa The endpoint to listen on.
344 * @param old_ports Previously listening ports that may be on the same endpoint.
346 bool BindPort(ConfigTag* tag, const irc::sockets::sockaddrs& sa, std::vector<ListenSocket*>& old_ports);
348 /** Bind all ports specified in the configuration file.
349 * @return The number of ports bound without error
351 size_t BindPorts(FailedPortList &failed_ports);
353 /** Find a user in the nick hash.
354 * If the user cant be found in the nick hash check the uuid hash
355 * @param nick The nickname to find
356 * @return A pointer to the user, or NULL if the user does not exist
358 User* FindNick(const std::string &nick);
360 /** Find a user in the nick hash ONLY
362 User* FindNickOnly(const std::string &nick);
364 /** Find a channel in the channels hash
365 * @param chan The channel to find
366 * @return A pointer to the channel, or NULL if the channel does not exist
368 Channel* FindChan(const std::string &chan);
370 /** Get a hash map containing all channels, keyed by their name
371 * @return A hash map mapping channel names to Channel pointers
373 chan_hash& GetChans() { return chanlist; }
375 /** Determines whether an channel name is valid. */
376 TR1NS::function<bool(const std::string&)> IsChannel;
378 /** Determines whether a channel name is valid according to the RFC 1459 rules.
379 * This is the default function for InspIRCd::IsChannel.
380 * @param channel The channel name to validate.
381 * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
383 static bool DefaultIsChannel(const std::string& channel);
385 /** Determines whether a hostname is valid according to RFC 5891 rules.
386 * @param host The hostname to validate.
387 * @return True if the hostname is valid; otherwise, false.
389 static bool IsHost(const std::string& host);
391 /** Return true if str looks like a server ID
392 * @param sid string to check against
394 static bool IsSID(const std::string& sid);
396 /** Handles incoming signals after being set
397 * @param signal the signal received
399 void SignalHandler(int signal);
401 /** Sets the signal received
402 * @param signal the signal received
404 static void SetSignal(int signal);
406 /** Causes the server to exit after unloading modules and
407 * closing all open file descriptors.
409 * @param status The exit code to give to the operating system
410 * (See the ExitStatus enum for valid values)
412 void Exit(int status);
414 /** Formats the input string with the specified arguments.
415 * @param formatString The string to format
416 * @param ... A variable number of format arguments.
417 * @return The formatted string
419 static std::string Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
420 static std::string Format(va_list& vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
422 /** Determines whether a nickname is valid. */
423 TR1NS::function<bool(const std::string&)> IsNick;
425 /** Determines whether a nickname is valid according to the RFC 1459 rules.
426 * This is the default function for InspIRCd::IsNick.
427 * @param nick The nickname to validate.
428 * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
430 static bool DefaultIsNick(const std::string& nick);
432 /** Determines whether an ident is valid. */
433 TR1NS::function<bool(const std::string&)> IsIdent;
435 /** Determines whether a ident is valid according to the RFC 1459 rules.
436 * This is the default function for InspIRCd::IsIdent.
437 * @param ident The ident to validate.
438 * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
440 static bool DefaultIsIdent(const std::string& ident);
442 /** Match two strings using pattern matching, optionally, with a map
443 * to check case against (may be NULL). If map is null, match will be case insensitive.
444 * @param str The literal string to match against
445 * @param mask The glob pattern to match against.
446 * @param map The character map to use when matching.
448 static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
449 static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
451 /** Match two strings using pattern matching, optionally, with a map
452 * to check case against (may be NULL). If map is null, match will be case insensitive.
453 * Supports CIDR patterns as well as globs.
454 * @param str The literal string to match against
455 * @param mask The glob or CIDR pattern to match against.
456 * @param map The character map to use when matching.
458 static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
459 static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
461 /** Matches a hostname and IP against a space delimited list of hostmasks.
462 * @param masks The space delimited masks to match against.
463 * @param hostname The hostname to try and match.
464 * @param ipaddr The IP address to try and match.
466 static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
468 /** Return true if the given parameter is a valid nick!user\@host mask
469 * @param mask A nick!user\@host masak to match against
470 * @return True i the mask is valid
472 static bool IsValidMask(const std::string& mask);
474 /** Strips all color and control codes except 001 from the given string
475 * @param sentence The string to strip from
477 static void StripColor(std::string &sentence);
479 /** Parses color codes from string values to actual color codes
480 * @param input The data to process
482 static void ProcessColors(file_cache& input);
484 /** Rehash the local server
485 * @param uuid The uuid of the user who started the rehash, can be empty
487 void Rehash(const std::string& uuid = "");
489 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
490 * @param str A string containing a time in the form 1y2w3d4h6m5s
491 * (one year, two weeks, three days, four hours, six minutes and five seconds)
492 * @return The total number of seconds
494 static unsigned long Duration(const std::string& str);
496 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
497 * @param str A string containing a time in the form 1y2w3d4h6m5s
498 * (one year, two weeks, three days, four hours, six minutes and five seconds)
499 * @param duration The location to place the parsed duration valur
500 * @return Whether the duration was a valid format or not
502 static bool Duration(const std::string& str, unsigned long& duration);
504 /** Determines whether a string contains a valid duration.
505 * @param str A string containing a time in the form 1y2w3d4h6m5s
506 * @return True if the string is a valid duration; otherwise, false.
508 static bool IsValidDuration(const std::string& str);
510 /** Return a duration in seconds as a human-readable string.
511 * @param duration The duration in seconds to convert to a human-readable string.
512 * @return A string representing the given duration.
514 static std::string DurationString(time_t duration);
516 /** Attempt to compare a password to a string from the config file.
517 * This will be passed to handling modules which will compare the data
518 * against possible hashed equivalents in the input string.
519 * @param ex The object (user, server, whatever) causing the comparison.
520 * @param data The data from the config file
521 * @param input The data input by the oper
522 * @param hashtype The hash from the config file
523 * @return True if the strings match, false if they do not
525 bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
527 /** Returns the full version string of this ircd
528 * @return The version string
530 std::string GetVersionString(bool getFullVersion = false);
532 /** Attempt to write the process id to a given file
533 * @param filename The PID file to attempt to write to
534 * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
535 * @return This function may bail if the file cannot be written
537 void WritePID(const std::string& filename, bool exitonfail = true);
539 /** This constructor initialises all the subsystems and reads the config file.
540 * @param argc The argument count passed to main()
541 * @param argv The argument list passed to main()
542 * @throw <anything> If anything is thrown from here and makes it to
543 * you, you should probably just give up and go home. Yes, really.
544 * It's that bad. Higher level classes should catch any non-fatal exceptions.
546 InspIRCd(int argc, char** argv);
548 /** Prepare the ircd for restart or shutdown.
549 * This function unloads all modules which can be unloaded,
550 * closes all open sockets, and closes the logfile.
554 /** Return a time_t as a human-readable string.
555 * @param format The format to retrieve the date/time in. See `man 3 strftime`
556 * for more information. If NULL, "%a %b %d %T %Y" is assumed.
557 * @param curtime The timestamp to convert to a human-readable string.
558 * @param utc True to convert the time to string as-is, false to convert it to local time first.
559 * @return A string representing the given date/time.
561 static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
563 /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
564 * returns false immediately (leaking information about the length), otherwise it compares each
565 * character and only returns after all characters have been compared.
566 * @param one First string
567 * @param two Second string
568 * @return True if the strings match, false if they don't
570 static bool TimingSafeCompare(const std::string& one, const std::string& two);
572 /** Begin execution of the server.
573 * NOTE: this function NEVER returns. Internally,
574 * it will repeatedly loop.
578 char* GetReadBuffer()
580 return this->ReadBuffer;
583 ClientProtocol::RFCEvents& GetRFCEvents() { return rfcevents; }
588 inline void stdalgo::culldeleter::operator()(classbase* item)
591 ServerInstance->GlobalCulls.AddItem(item);
594 inline void Channel::Write(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg, char status, const CUList& except_list)
596 ClientProtocol::Event event(protoevprov, msg);
597 Write(event, status, except_list);
600 inline void LocalUser::Send(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg)
602 ClientProtocol::Event event(protoevprov, msg);
606 #include "numericbuilder.h"
607 #include "clientprotocolmsg.h"
608 #include "clientprotocolevent.h"