]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Fix various cases of broken indentation.
[user/henk/code/inspircd.git] / include / inspircd.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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 <???@???>
11  *
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.
15  *
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
19  * details.
20  *
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/>.
23  */
24
25
26 #pragma once
27
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
31
32 #include <cfloat>
33 #include <climits>
34 #include <cmath>
35 #include <csignal>
36 #include <cstdarg>
37 #include <cstdio>
38 #include <cstring>
39 #include <ctime>
40 #include <stdint.h>
41
42 #include <algorithm>
43 #include <bitset>
44 #include <deque>
45 #include <list>
46 #include <map>
47 #include <set>
48 #include <sstream>
49 #include <string>
50 #include <vector>
51
52 #include "intrusive_list.h"
53 #include "flat_map.h"
54 #include "compat.h"
55 #include "aligned_storage.h"
56 #include "typedefs.h"
57 #include "convto.h"
58 #include "stdalgo.h"
59
60 CoreExport extern InspIRCd* ServerInstance;
61
62 /** Base class for manager classes that are still accessed using -> but are no longer pointers
63  */
64 template <typename T>
65 struct fakederef
66 {
67         T* operator->()
68         {
69                 return static_cast<T*>(this);
70         }
71 };
72
73 #include "config.h"
74 #include "dynref.h"
75 #include "consolecolors.h"
76 #include "cull_list.h"
77 #include "extensible.h"
78 #include "fileutils.h"
79 #include "ctables.h"
80 #include "numerics.h"
81 #include "numeric.h"
82 #include "uid.h"
83 #include "server.h"
84 #include "users.h"
85 #include "channels.h"
86 #include "timer.h"
87 #include "hashcomp.h"
88 #include "logger.h"
89 #include "usermanager.h"
90 #include "socket.h"
91 #include "command_parse.h"
92 #include "mode.h"
93 #include "socketengine.h"
94 #include "snomasks.h"
95 #include "filelogger.h"
96 #include "message.h"
97 #include "modules.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"
105
106 /** This class contains various STATS counters
107  * It is used by the InspIRCd class, which internally
108  * has an instance of it.
109  */
110 class serverstats
111 {
112   public:
113         /** Number of accepted connections
114          */
115         unsigned long Accept;
116         /** Number of failed accepts
117          */
118         unsigned long Refused;
119         /** Number of unknown commands seen
120          */
121         unsigned long Unknown;
122         /** Number of nickname collisions handled
123          */
124         unsigned long Collisions;
125         /** Number of DNS queries sent out
126          */
127         unsigned long Dns;
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.
131          */
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.
136          */
137         unsigned long DnsBad;
138         /** Number of inbound connections seen
139          */
140         unsigned long Connects;
141         /** Total bytes of data transmitted
142          */
143         unsigned long Sent;
144         /** Total bytes of data received
145          */
146         unsigned long Recv;
147 #ifdef _WIN32
148         /** Cpu usage at last sample
149         */
150         FILETIME LastCPU;
151         /** Time QP sample was read
152         */
153         LARGE_INTEGER LastSampled;
154         /** QP frequency
155         */
156         LARGE_INTEGER QPFrequency;
157 #else
158         /** Cpu usage at last sample
159          */
160         timeval LastCPU;
161         /** Time last sample was read
162          */
163         timespec LastSampled;
164 #endif
165         /** The constructor initializes all the counts to zero
166          */
167         serverstats()
168                 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
169                 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
170         {
171         }
172 };
173
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.
179  */
180 class CoreExport InspIRCd
181 {
182  private:
183         /** Set up the signal handlers
184          */
185         void SetSignals();
186
187         /** Daemonize the ircd and close standard input/output streams
188          * @return True if the program daemonized succesfully
189          */
190         bool DaemonSeed();
191
192         /** The current time, updated in the mainloop
193          */
194         struct timespec TIME;
195
196         /** A 64k buffer used to read socket data into
197          * NOTE: update ValidateNetBufferSize if you change this
198          */
199         char ReadBuffer[65535];
200
201         ClientProtocol::RFCEvents rfcevents;
202
203         /** Check we aren't running as root, and exit if we are
204          * with exit code EXIT_STATUS_ROOT.
205          */
206         void CheckRoot();
207
208  public:
209
210         UIDGenerator UIDGen;
211
212         /** Global cull list, will be processed on next iteration
213          */
214         CullList GlobalCulls;
215         /** Actions that must happen outside of the current call stack */
216         ActionList AtomicActions;
217
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
219          * Reason for it:
220          * kludge alert!
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
225          */
226         FakeUser* FakeClient;
227
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
231          */
232         User* FindUUID(const std::string &uid);
233
234         /** Time this ircd was booted
235          */
236         time_t startup_time;
237
238         /** Config file pathname specified on the commandline or via ./configure
239          */
240         std::string ConfigFileName;
241
242         ExtensionManager Extensions;
243
244         /** Mode handler, handles mode setting and removal
245          */
246         ModeParser Modes;
247
248         /** Command parser, handles client to server commands
249          */
250         CommandParser Parser;
251
252         /** Thread engine, Handles threading where required
253          */
254         ThreadEngine Threads;
255
256         /** The thread/class used to read config files in REHASH and on startup
257          */
258         ConfigReaderThread* ConfigThread;
259
260         /** LogManager handles logging.
261          */
262         LogManager Logs;
263
264         /** ModuleManager contains everything related to loading/unloading
265          * modules.
266          */
267         ModuleManager Modules;
268
269         /** BanCacheManager is used to speed up checking of restrictions on connection
270          * to the IRCd.
271          */
272         BanCacheManager BanCache;
273
274         /** Stats class, holds miscellaneous stats counters
275          */
276         serverstats stats;
277
278         /**  Server Config class, holds configuration file data
279          */
280         ServerConfig* Config;
281
282         /** Snomask manager - handles routing of snomask messages
283          * to opers.
284          */
285         SnomaskManager SNO;
286
287         /** Timer manager class, triggers Timer timer events
288          */
289         TimerManager Timers;
290
291         /** X-line manager. Handles G/K/Q/E-line setting, removal and matching
292          */
293         XLineManager* XLines;
294
295         /** User manager. Various methods and data associated with users.
296          */
297         UserManager Users;
298
299         /** Channel list, a hash_map containing all channels XXX move to channel manager class
300          */
301         chan_hash chanlist;
302
303         /** List of the open ports
304          */
305         std::vector<ListenSocket*> ports;
306
307         /** Set to the current signal received
308          */
309         static sig_atomic_t s_signal;
310
311         /** Protocol interface, overridden by server protocol modules
312          */
313         ProtocolInterface* PI;
314
315         /** Default implementation of the ProtocolInterface, does nothing
316          */
317         ProtocolInterface DefaultProtocolInterface;
318
319         /** Manages the generation and transmission of ISUPPORT. */
320         ISupportManager ISupport;
321
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)
326          */
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. */
331         void UpdateTime();
332
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)
337          */
338         std::string GenRandomStr(unsigned int length, bool printable = true);
339         /** Generate a random integer.
340          * This is generally more secure than rand()
341          */
342         unsigned long GenRandomInt(unsigned long max);
343
344         /** Fill a buffer with random bits */
345         TR1NS::function<void(char*, size_t)> GenRandom;
346
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.
351          */
352         static void DefaultGenRandom(char* output, size_t max);
353
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.
358          */
359         bool BindPort(ConfigTag* tag, const irc::sockets::sockaddrs& sa, std::vector<ListenSocket*>& old_ports);
360
361         /** Bind all ports specified in the configuration file.
362          * @return The number of ports bound without error
363          */
364         int BindPorts(FailedPortList &failed_ports);
365
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
370          */
371         User* FindNick(const std::string &nick);
372
373         /** Find a user in the nick hash ONLY
374          */
375         User* FindNickOnly(const std::string &nick);
376
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
380          */
381         Channel* FindChan(const std::string &chan);
382
383         /** Get a hash map containing all channels, keyed by their name
384          * @return A hash map mapping channel names to Channel pointers
385          */
386         chan_hash& GetChans() { return chanlist; }
387
388         /** Determines whether an channel name is valid. */
389         TR1NS::function<bool(const std::string&)> IsChannel;
390
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.
395         */
396         static bool DefaultIsChannel(const std::string& channel);
397
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.
401          */
402         static bool IsHost(const std::string& host);
403
404         /** Return true if str looks like a server ID
405          * @param sid string to check against
406          */
407         static bool IsSID(const std::string& sid);
408
409         /** Handles incoming signals after being set
410          * @param signal the signal received
411          */
412         void SignalHandler(int signal);
413
414         /** Sets the signal received
415          * @param signal the signal received
416          */
417         static void SetSignal(int signal);
418
419         /** Causes the server to exit after unloading modules and
420          * closing all open file descriptors.
421          *
422          * @param status The exit code to give to the operating system
423          * (See the ExitStatus enum for valid values)
424          */
425         void Exit(int status);
426
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
431         */
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);
434
435         /** Determines whether a nickname is valid. */
436         TR1NS::function<bool(const std::string&)> IsNick;
437
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.
442          */
443         static bool DefaultIsNick(const std::string& nick);
444
445         /** Determines whether an ident is valid. */
446         TR1NS::function<bool(const std::string&)> IsIdent;
447
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.
452         */
453         static bool DefaultIsIdent(const std::string& ident);
454
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.
460          */
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);
463
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.
470          */
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);
473
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.
478          */
479         static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
480
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
484          */
485         static bool IsValidMask(const std::string& mask);
486
487         /** Strips all color and control codes except 001 from the given string
488          * @param sentence The string to strip from
489          */
490         static void StripColor(std::string &sentence);
491
492         /** Parses color codes from string values to actual color codes
493          * @param input The data to process
494          */
495         static void ProcessColors(file_cache& input);
496
497         /** Rehash the local server
498          * @param uuid The uuid of the user who started the rehash, can be empty
499          */
500         void Rehash(const std::string& uuid = "");
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          * @return The total number of seconds
506          */
507         static unsigned long Duration(const std::string& str);
508
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
514          */
515         static bool Duration(const std::string& str, unsigned long& duration);
516
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.
520          */
521         static bool IsValidDuration(const std::string& str);
522
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.
526          */
527         static std::string DurationString(time_t duration);
528
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
537          */
538         bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
539
540         /** Returns the full version string of this ircd
541          * @return The version string
542          */
543         std::string GetVersionString(bool getFullVersion = false);
544
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
549          */
550         void WritePID(const std::string& filename, bool exitonfail = true);
551
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.
558          */
559         InspIRCd(int argc, char** argv);
560
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.
564          */
565         void Cleanup();
566
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.
573          */
574         static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
575
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
582          */
583         static bool TimingSafeCompare(const std::string& one, const std::string& two);
584
585         /** Begin execution of the server.
586          * NOTE: this function NEVER returns. Internally,
587          * it will repeatedly loop.
588          */
589         void Run();
590
591         char* GetReadBuffer()
592         {
593                 return this->ReadBuffer;
594         }
595
596         ClientProtocol::RFCEvents& GetRFCEvents() { return rfcevents; }
597 };
598
599 ENTRYPOINT;
600
601 inline void stdalgo::culldeleter::operator()(classbase* item)
602 {
603         if (item)
604                 ServerInstance->GlobalCulls.AddItem(item);
605 }
606
607 inline void Channel::Write(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg, char status, const CUList& except_list)
608 {
609         ClientProtocol::Event event(protoevprov, msg);
610         Write(event, status, except_list);
611 }
612
613 inline void LocalUser::Send(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg)
614 {
615         ClientProtocol::Event event(protoevprov, msg);
616         Send(event);
617 }
618
619 #include "numericbuilder.h"
620 #include "clientprotocolmsg.h"
621 #include "clientprotocolevent.h"