]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
a55d52c0b0e5dff8a0b2e250e0e9b4ef72d3a13c
[user/henk/code/inspircd.git] / include / inspircd.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2018 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
7  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012-2014, 2017-2019 Sadie Powell <sadie@witchery.services>
9  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
13  *   Copyright (C) 2007-2009 Dennis Friis <peavey@inspircd.org>
14  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
15  *   Copyright (C) 2007 Oliver Lupton <om@inspircd.org>
16  *   Copyright (C) 2005-2008, 2010 Craig Edwards <brain@inspircd.org>
17  *
18  * This file is part of InspIRCd.  InspIRCd is free software: you can
19  * redistribute it and/or modify it under the terms of the GNU General Public
20  * License as published by the Free Software Foundation, version 2.
21  *
22  * This program is distributed in the hope that it will be useful, but WITHOUT
23  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
24  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
25  * details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31
32 #pragma once
33
34 // If the system has a pre-C11 stdint header this must be defined in
35 // order to use the numeric limit macros.
36 #define __STDC_LIMIT_MACROS
37
38 #include <cfloat>
39 #include <climits>
40 #include <cmath>
41 #include <csignal>
42 #include <cstdarg>
43 #include <cstdio>
44 #include <cstring>
45 #include <ctime>
46 #include <stdint.h>
47
48 #include <algorithm>
49 #include <bitset>
50 #include <deque>
51 #include <list>
52 #include <map>
53 #include <set>
54 #include <sstream>
55 #include <string>
56 #include <vector>
57
58 #include "intrusive_list.h"
59 #include "flat_map.h"
60 #include "compat.h"
61 #include "aligned_storage.h"
62 #include "typedefs.h"
63 #include "convto.h"
64 #include "stdalgo.h"
65
66 CoreExport extern InspIRCd* ServerInstance;
67
68 /** Base class for manager classes that are still accessed using -> but are no longer pointers
69  */
70 template <typename T>
71 struct fakederef
72 {
73         T* operator->()
74         {
75                 return static_cast<T*>(this);
76         }
77 };
78
79 #include "config.h"
80 #include "dynref.h"
81 #include "consolecolors.h"
82 #include "cull_list.h"
83 #include "serialize.h"
84 #include "extensible.h"
85 #include "fileutils.h"
86 #include "ctables.h"
87 #include "numerics.h"
88 #include "numeric.h"
89 #include "uid.h"
90 #include "server.h"
91 #include "users.h"
92 #include "channels.h"
93 #include "timer.h"
94 #include "hashcomp.h"
95 #include "logger.h"
96 #include "usermanager.h"
97 #include "socket.h"
98 #include "command_parse.h"
99 #include "mode.h"
100 #include "socketengine.h"
101 #include "snomasks.h"
102 #include "filelogger.h"
103 #include "message.h"
104 #include "modules.h"
105 #include "clientprotocol.h"
106 #include "threadengine.h"
107 #include "configreader.h"
108 #include "inspstring.h"
109 #include "protocol.h"
110 #include "bancache.h"
111 #include "isupportmanager.h"
112
113 /** This class contains various STATS counters
114  * It is used by the InspIRCd class, which internally
115  * has an instance of it.
116  */
117 class serverstats
118 {
119   public:
120         /** Number of accepted connections
121          */
122         unsigned long Accept;
123         /** Number of failed accepts
124          */
125         unsigned long Refused;
126         /** Number of unknown commands seen
127          */
128         unsigned long Unknown;
129         /** Number of nickname collisions handled
130          */
131         unsigned long Collisions;
132         /** Number of DNS queries sent out
133          */
134         unsigned long Dns;
135         /** Number of good DNS replies received
136          * NOTE: This may not tally to the number sent out,
137          * due to timeouts and other latency issues.
138          */
139         unsigned long DnsGood;
140         /** Number of bad (negative) DNS replies received
141          * NOTE: This may not tally to the number sent out,
142          * due to timeouts and other latency issues.
143          */
144         unsigned long DnsBad;
145         /** Number of inbound connections seen
146          */
147         unsigned long Connects;
148         /** Total bytes of data transmitted
149          */
150         unsigned long Sent;
151         /** Total bytes of data received
152          */
153         unsigned long Recv;
154 #ifdef _WIN32
155         /** Cpu usage at last sample
156         */
157         FILETIME LastCPU;
158         /** Time QP sample was read
159         */
160         LARGE_INTEGER LastSampled;
161         /** QP frequency
162         */
163         LARGE_INTEGER QPFrequency;
164 #else
165         /** Cpu usage at last sample
166          */
167         timeval LastCPU;
168         /** Time last sample was read
169          */
170         timespec LastSampled;
171 #endif
172         /** The constructor initializes all the counts to zero
173          */
174         serverstats()
175                 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
176                 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
177         {
178         }
179 };
180
181 /** The main class of the irc server.
182  * This class contains instances of all the other classes in this software.
183  * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
184  * object, and a list of active Module objects, and facilities for Module
185  * objects to interact with the core system it implements.
186  */
187 class CoreExport InspIRCd
188 {
189  private:
190         /** The current time, updated in the mainloop
191          */
192         struct timespec TIME;
193
194         /** A 64k buffer used to read socket data into
195          * NOTE: update ValidateNetBufferSize if you change this
196          */
197         char ReadBuffer[65535];
198
199         ClientProtocol::RFCEvents rfcevents;
200
201  public:
202
203         UIDGenerator UIDGen;
204
205         /** Global cull list, will be processed on next iteration
206          */
207         CullList GlobalCulls;
208         /** Actions that must happen outside of the current call stack */
209         ActionList AtomicActions;
210
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
212          * Reason for it:
213          * kludge alert!
214          * SendMode expects a User* to send the numeric replies
215          * back to, so we create it a fake user that isn't in the user
216          * hash and set its descriptor to FD_MAGIC_NUMBER so the data
217          * falls into the abyss :p
218          */
219         FakeUser* FakeClient;
220
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
224          */
225         User* FindUUID(const std::string &uid);
226
227         /** Time this ircd was booted
228          */
229         time_t startup_time;
230
231         /** Config file pathname specified on the commandline or via ./configure
232          */
233         std::string ConfigFileName;
234
235         ExtensionManager Extensions;
236
237         /** Mode handler, handles mode setting and removal
238          */
239         ModeParser Modes;
240
241         /** Command parser, handles client to server commands
242          */
243         CommandParser Parser;
244
245         /** Thread engine, Handles threading where required
246          */
247         ThreadEngine Threads;
248
249         /** The thread/class used to read config files in REHASH and on startup
250          */
251         ConfigReaderThread* ConfigThread;
252
253         /** LogManager handles logging.
254          */
255         LogManager Logs;
256
257         /** ModuleManager contains everything related to loading/unloading
258          * modules.
259          */
260         ModuleManager Modules;
261
262         /** BanCacheManager is used to speed up checking of restrictions on connection
263          * to the IRCd.
264          */
265         BanCacheManager BanCache;
266
267         /** Stats class, holds miscellaneous stats counters
268          */
269         serverstats stats;
270
271         /**  Server Config class, holds configuration file data
272          */
273         ServerConfig* Config;
274
275         /** Snomask manager - handles routing of snomask messages
276          * to opers.
277          */
278         SnomaskManager SNO;
279
280         /** Timer manager class, triggers Timer timer events
281          */
282         TimerManager Timers;
283
284         /** X-line manager. Handles G/K/Q/E-line setting, removal and matching
285          */
286         XLineManager* XLines;
287
288         /** User manager. Various methods and data associated with users.
289          */
290         UserManager Users;
291
292         /** Channel list, a hash_map containing all channels XXX move to channel manager class
293          */
294         chan_hash chanlist;
295
296         /** List of the open ports
297          */
298         std::vector<ListenSocket*> ports;
299
300         /** Set to the current signal received
301          */
302         static sig_atomic_t s_signal;
303
304         /** Protocol interface, overridden by server protocol modules
305          */
306         ProtocolInterface* PI;
307
308         /** Default implementation of the ProtocolInterface, does nothing
309          */
310         ProtocolInterface DefaultProtocolInterface;
311
312         /** Manages the generation and transmission of ISUPPORT. */
313         ISupportManager ISupport;
314
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)
319          */
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. */
324         void UpdateTime();
325
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)
330          */
331         std::string GenRandomStr(unsigned int length, bool printable = true);
332         /** Generate a random integer.
333          * This is generally more secure than rand()
334          */
335         unsigned long GenRandomInt(unsigned long max);
336
337         /** Fill a buffer with random bits */
338         TR1NS::function<void(char*, size_t)> GenRandom;
339
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.
344          */
345         static void DefaultGenRandom(char* output, size_t max);
346
347         /** Bind to a specific port from a config tag.
348          * @param tag the tag that contains bind information.
349          * @param sa The endpoint to listen on.
350          * @param old_ports Previously listening ports that may be on the same endpoint.
351          */
352         bool BindPort(ConfigTag* tag, const irc::sockets::sockaddrs& sa, std::vector<ListenSocket*>& old_ports);
353
354         /** Bind all ports specified in the configuration file.
355          * @return The number of ports bound without error
356          */
357         size_t BindPorts(FailedPortList &failed_ports);
358
359         /** Find a user in the nick hash.
360          * If the user cant be found in the nick hash check the uuid hash
361          * @param nick The nickname to find
362          * @return A pointer to the user, or NULL if the user does not exist
363          */
364         User* FindNick(const std::string &nick);
365
366         /** Find a user in the nick hash ONLY
367          */
368         User* FindNickOnly(const std::string &nick);
369
370         /** Find a channel in the channels hash
371          * @param chan The channel to find
372          * @return A pointer to the channel, or NULL if the channel does not exist
373          */
374         Channel* FindChan(const std::string &chan);
375
376         /** Get a hash map containing all channels, keyed by their name
377          * @return A hash map mapping channel names to Channel pointers
378          */
379         chan_hash& GetChans() { return chanlist; }
380
381         /** Determines whether an channel name is valid. */
382         TR1NS::function<bool(const std::string&)> IsChannel;
383
384         /** Determines whether a channel name is valid according to the RFC 1459 rules.
385          * This is the default function for InspIRCd::IsChannel.
386          * @param channel The channel name to validate.
387          * @return True if the channel name is valid according to RFC 1459 rules; otherwise, false.
388         */
389         static bool DefaultIsChannel(const std::string& channel);
390
391         /** Determines whether a hostname is valid according to RFC 5891 rules.
392          * @param host The hostname to validate.
393          * @return True if the hostname is valid; otherwise, false.
394          */
395         static bool IsHost(const std::string& host);
396
397         /** Return true if str looks like a server ID
398          * @param sid string to check against
399          */
400         static bool IsSID(const std::string& sid);
401
402         /** Handles incoming signals after being set
403          * @param signal the signal received
404          */
405         void SignalHandler(int signal);
406
407         /** Sets the signal received
408          * @param signal the signal received
409          */
410         static void SetSignal(int signal);
411
412         /** Causes the server to exit after unloading modules and
413          * closing all open file descriptors.
414          *
415          * @param status The exit code to give to the operating system
416          * (See the ExitStatus enum for valid values)
417          */
418         void Exit(int status);
419
420         /** Formats the input string with the specified arguments.
421         * @param formatString The string to format
422         * @param ... A variable number of format arguments.
423         * @return The formatted string
424         */
425         static std::string Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
426         static std::string Format(va_list& vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
427
428         /** Determines whether a nickname is valid. */
429         TR1NS::function<bool(const std::string&)> IsNick;
430
431         /** Determines whether a nickname is valid according to the RFC 1459 rules.
432          * This is the default function for InspIRCd::IsNick.
433          * @param nick The nickname to validate.
434          * @return True if the nickname is valid according to RFC 1459 rules; otherwise, false.
435          */
436         static bool DefaultIsNick(const std::string& nick);
437
438         /** Determines whether an ident is valid. */
439         TR1NS::function<bool(const std::string&)> IsIdent;
440
441         /** Determines whether a ident is valid according to the RFC 1459 rules.
442          * This is the default function for InspIRCd::IsIdent.
443          * @param ident The ident to validate.
444          * @return True if the ident is valid according to RFC 1459 rules; otherwise, false.
445         */
446         static bool DefaultIsIdent(const std::string& ident);
447
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          * @param str The literal string to match against
451          * @param mask The glob pattern to match against.
452          * @param map The character map to use when matching.
453          */
454         static bool Match(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
455         static bool Match(const char* str, const char* mask, unsigned const char* map = NULL);
456
457         /** Match two strings using pattern matching, optionally, with a map
458          * to check case against (may be NULL). If map is null, match will be case insensitive.
459          * Supports CIDR patterns as well as globs.
460          * @param str The literal string to match against
461          * @param mask The glob or CIDR pattern to match against.
462          * @param map The character map to use when matching.
463          */
464         static bool MatchCIDR(const std::string& str, const std::string& mask, unsigned const char* map = NULL);
465         static bool MatchCIDR(const char* str, const char* mask, unsigned const char* map = NULL);
466
467         /** Matches a hostname and IP against a space delimited list of hostmasks.
468          * @param masks The space delimited masks to match against.
469          * @param hostname The hostname to try and match.
470          * @param ipaddr The IP address to try and match.
471          */
472         static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
473
474         /** Return true if the given parameter is a valid nick!user\@host mask
475          * @param mask A nick!user\@host masak to match against
476          * @return True i the mask is valid
477          */
478         static bool IsValidMask(const std::string& mask);
479
480         /** Strips all color and control codes except 001 from the given string
481          * @param sentence The string to strip from
482          */
483         static void StripColor(std::string &sentence);
484
485         /** Parses color codes from string values to actual color codes
486          * @param input The data to process
487          */
488         static void ProcessColors(file_cache& input);
489
490         /** Rehash the local server
491          * @param uuid The uuid of the user who started the rehash, can be empty
492          */
493         void Rehash(const std::string& uuid = "");
494
495         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
496          * @param str A string containing a time in the form 1y2w3d4h6m5s
497          * (one year, two weeks, three days, four hours, six minutes and five seconds)
498          * @return The total number of seconds
499          */
500         static unsigned long Duration(const std::string& str);
501
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          * @param duration The location to place the parsed duration valur
506          * @return Whether the duration was a valid format or not
507          */
508         static bool Duration(const std::string& str, unsigned long& duration);
509
510         /** Determines whether a string contains a valid duration.
511          * @param str A string containing a time in the form 1y2w3d4h6m5s
512          * @return True if the string is a valid duration; otherwise, false.
513          */
514         static bool IsValidDuration(const std::string& str);
515
516         /** Return a duration in seconds as a human-readable string.
517          * @param duration The duration in seconds to convert to a human-readable string.
518          * @return A string representing the given duration.
519          */
520         static std::string DurationString(time_t duration);
521
522         /** Attempt to compare a password to a string from the config file.
523          * This will be passed to handling modules which will compare the data
524          * against possible hashed equivalents in the input string.
525          * @param ex The object (user, server, whatever) causing the comparison.
526          * @param data The data from the config file
527          * @param input The data input by the oper
528          * @param hashtype The hash from the config file
529          * @return True if the strings match, false if they do not
530          */
531         bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
532
533         /** Returns the full version string of this ircd
534          * @return The version string
535          */
536         std::string GetVersionString(bool getFullVersion = false);
537
538         /** Attempt to write the process id to a given file
539          * @param filename The PID file to attempt to write to
540          * @param exitonfail If true and the PID fail cannot be written log to stdout and exit, otherwise only log on failure
541          * @return This function may bail if the file cannot be written
542          */
543         void WritePID(const std::string& filename, bool exitonfail = true);
544
545         /** This constructor initialises all the subsystems and reads the config file.
546          * @param argc The argument count passed to main()
547          * @param argv The argument list passed to main()
548          * @throw <anything> If anything is thrown from here and makes it to
549          * you, you should probably just give up and go home. Yes, really.
550          * It's that bad. Higher level classes should catch any non-fatal exceptions.
551          */
552         InspIRCd(int argc, char** argv);
553
554         /** Prepare the ircd for restart or shutdown.
555          * This function unloads all modules which can be unloaded,
556          * closes all open sockets, and closes the logfile.
557          */
558         void Cleanup();
559
560         /** Return a time_t as a human-readable string.
561          * @param format The format to retrieve the date/time in. See `man 3 strftime`
562          * for more information. If NULL, "%a %b %d %T %Y" is assumed.
563          * @param curtime The timestamp to convert to a human-readable string.
564          * @param utc True to convert the time to string as-is, false to convert it to local time first.
565          * @return A string representing the given date/time.
566          */
567         static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
568
569         /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
570          * returns false immediately (leaking information about the length), otherwise it compares each
571          * character and only returns after all characters have been compared.
572          * @param one First string
573          * @param two Second string
574          * @return True if the strings match, false if they don't
575          */
576         static bool TimingSafeCompare(const std::string& one, const std::string& two);
577
578         /** Begin execution of the server.
579          * NOTE: this function NEVER returns. Internally,
580          * it will repeatedly loop.
581          */
582         void Run();
583
584         char* GetReadBuffer()
585         {
586                 return this->ReadBuffer;
587         }
588
589         ClientProtocol::RFCEvents& GetRFCEvents() { return rfcevents; }
590 };
591
592 ENTRYPOINT;
593
594 inline void stdalgo::culldeleter::operator()(classbase* item)
595 {
596         if (item)
597                 ServerInstance->GlobalCulls.AddItem(item);
598 }
599
600 inline void Channel::Write(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg, char status, const CUList& except_list)
601 {
602         ClientProtocol::Event event(protoevprov, msg);
603         Write(event, status, except_list);
604 }
605
606 inline void LocalUser::Send(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg)
607 {
608         ClientProtocol::Event event(protoevprov, msg);
609         Send(event);
610 }
611
612 #include "numericbuilder.h"
613 #include "clientprotocolmsg.h"
614 #include "clientprotocolevent.h"