]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Rename the spanningtree module header to server.
[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 #include <climits>
29 #include <cmath>
30 #include <csignal>
31 #include <cstdarg>
32 #include <cstdio>
33 #include <cstring>
34 #include <ctime>
35 #include <stdint.h>
36
37 #include <algorithm>
38 #include <bitset>
39 #include <deque>
40 #include <list>
41 #include <map>
42 #include <set>
43 #include <sstream>
44 #include <string>
45 #include <vector>
46
47 #include "intrusive_list.h"
48 #include "flat_map.h"
49 #include "compat.h"
50 #include "aligned_storage.h"
51 #include "typedefs.h"
52 #include "stdalgo.h"
53
54 CoreExport extern InspIRCd* ServerInstance;
55
56 /** Base class for manager classes that are still accessed using -> but are no longer pointers
57  */
58 template <typename T>
59 struct fakederef
60 {
61         T* operator->()
62         {
63                 return static_cast<T*>(this);
64         }
65 };
66
67 #include "config.h"
68 #include "convto.h"
69 #include "dynref.h"
70 #include "consolecolors.h"
71 #include "cull_list.h"
72 #include "extensible.h"
73 #include "fileutils.h"
74 #include "numerics.h"
75 #include "numeric.h"
76 #include "uid.h"
77 #include "server.h"
78 #include "users.h"
79 #include "channels.h"
80 #include "timer.h"
81 #include "hashcomp.h"
82 #include "logger.h"
83 #include "usermanager.h"
84 #include "socket.h"
85 #include "ctables.h"
86 #include "command_parse.h"
87 #include "mode.h"
88 #include "socketengine.h"
89 #include "snomasks.h"
90 #include "filelogger.h"
91 #include "modules.h"
92 #include "threadengine.h"
93 #include "configreader.h"
94 #include "inspstring.h"
95 #include "protocol.h"
96 #include "bancache.h"
97 #include "isupportmanager.h"
98
99 /** This class contains various STATS counters
100  * It is used by the InspIRCd class, which internally
101  * has an instance of it.
102  */
103 class serverstats
104 {
105   public:
106         /** Number of accepted connections
107          */
108         unsigned long Accept;
109         /** Number of failed accepts
110          */
111         unsigned long Refused;
112         /** Number of unknown commands seen
113          */
114         unsigned long Unknown;
115         /** Number of nickname collisions handled
116          */
117         unsigned long Collisions;
118         /** Number of DNS queries sent out
119          */
120         unsigned long Dns;
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.
124          */
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.
129          */
130         unsigned long DnsBad;
131         /** Number of inbound connections seen
132          */
133         unsigned long Connects;
134         /** Total bytes of data transmitted
135          */
136         unsigned long Sent;
137         /** Total bytes of data received
138          */
139         unsigned long Recv;
140 #ifdef _WIN32
141         /** Cpu usage at last sample
142         */
143         FILETIME LastCPU;
144         /** Time QP sample was read
145         */
146         LARGE_INTEGER LastSampled;
147         /** QP frequency
148         */
149         LARGE_INTEGER QPFrequency;
150 #else
151         /** Cpu usage at last sample
152          */
153         timeval LastCPU;
154         /** Time last sample was read
155          */
156         timespec LastSampled;
157 #endif
158         /** The constructor initializes all the counts to zero
159          */
160         serverstats()
161                 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
162                 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
163         {
164         }
165 };
166
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.
172  */
173 class CoreExport InspIRCd
174 {
175  private:
176         /** Set up the signal handlers
177          */
178         void SetSignals();
179
180         /** Daemonize the ircd and close standard input/output streams
181          * @return True if the program daemonized succesfully
182          */
183         bool DaemonSeed();
184
185         /** The current time, updated in the mainloop
186          */
187         struct timespec TIME;
188
189         /** A 64k buffer used to read socket data into
190          * NOTE: update ValidateNetBufferSize if you change this
191          */
192         char ReadBuffer[65535];
193
194         /** Check we aren't running as root, and exit if we are
195          * with exit code EXIT_STATUS_ROOT.
196          */
197         void CheckRoot();
198
199  public:
200
201         UIDGenerator UIDGen;
202
203         /** Global cull list, will be processed on next iteration
204          */
205         CullList GlobalCulls;
206         /** Actions that must happen outside of the current call stack */
207         ActionList AtomicActions;
208
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
210          * Reason for it:
211          * kludge alert!
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
216          */
217         FakeUser* FakeClient;
218
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
222          */
223         User* FindUUID(const std::string &uid);
224
225         /** Time this ircd was booted
226          */
227         time_t startup_time;
228
229         /** Config file pathname specified on the commandline or via ./configure
230          */
231         std::string ConfigFileName;
232
233         ExtensionManager Extensions;
234
235         /** Mode handler, handles mode setting and removal
236          */
237         ModeParser Modes;
238
239         /** Command parser, handles client to server commands
240          */
241         CommandParser Parser;
242
243         /** Thread engine, Handles threading where required
244          */
245         ThreadEngine Threads;
246
247         /** The thread/class used to read config files in REHASH and on startup
248          */
249         ConfigReaderThread* ConfigThread;
250
251         /** LogManager handles logging.
252          */
253         LogManager Logs;
254
255         /** ModuleManager contains everything related to loading/unloading
256          * modules.
257          */
258         ModuleManager Modules;
259
260         /** BanCacheManager is used to speed up checking of restrictions on connection
261          * to the IRCd.
262          */
263         BanCacheManager BanCache;
264
265         /** Stats class, holds miscellaneous stats counters
266          */
267         serverstats stats;
268
269         /**  Server Config class, holds configuration file data
270          */
271         ServerConfig* Config;
272
273         /** Snomask manager - handles routing of snomask messages
274          * to opers.
275          */
276         SnomaskManager SNO;
277
278         /** Timer manager class, triggers Timer timer events
279          */
280         TimerManager Timers;
281
282         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
283          */
284         XLineManager* XLines;
285
286         /** User manager. Various methods and data associated with users.
287          */
288         UserManager Users;
289
290         /** Channel list, a hash_map containing all channels XXX move to channel manager class
291          */
292         chan_hash chanlist;
293
294         /** List of the open ports
295          */
296         std::vector<ListenSocket*> ports;
297
298         /** Set to the current signal recieved
299          */
300         static sig_atomic_t s_signal;
301
302         /** Protocol interface, overridden by server protocol modules
303          */
304         ProtocolInterface* PI;
305
306         /** Default implementation of the ProtocolInterface, does nothing
307          */
308         ProtocolInterface DefaultProtocolInterface;
309
310         /** Manages the generation and transmission of ISUPPORT. */
311         ISupportManager ISupport;
312
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)
317          */
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. */
322         void UpdateTime();
323
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)
328          */
329         std::string GenRandomStr(unsigned int length, bool printable = true);
330         /** Generate a random integer.
331          * This is generally more secure than rand()
332          */
333         unsigned long GenRandomInt(unsigned long max);
334
335         /** Fill a buffer with random bits */
336         TR1NS::function<void(char*, size_t)> GenRandom;
337
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.
342          */
343         static void DefaultGenRandom(char* output, size_t max);
344
345         /** Bind all ports specified in the configuration file.
346          * @return The number of ports bound without error
347          */
348         int BindPorts(FailedPortList &failed_ports);
349
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
354          */
355         User* FindNick(const std::string &nick);
356
357         /** Find a user in the nick hash ONLY
358          */
359         User* FindNickOnly(const std::string &nick);
360
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
364          */
365         Channel* FindChan(const std::string &chan);
366
367         /** Get a hash map containing all channels, keyed by their name
368          * @return A hash map mapping channel names to Channel pointers
369          */
370         chan_hash& GetChans() { return chanlist; }
371
372         /** Determines whether an channel name is valid. */
373         TR1NS::function<bool(const std::string&)> IsChannel;
374
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.
379         */
380         static bool DefaultIsChannel(const std::string& channel);
381
382         /** Return true if str looks like a server ID
383          * @param sid string to check against
384          */
385         static bool IsSID(const std::string& sid);
386
387         /** Handles incoming signals after being set
388          * @param signal the signal recieved
389          */
390         void SignalHandler(int signal);
391
392         /** Sets the signal recieved
393          * @param signal the signal recieved
394          */
395         static void SetSignal(int signal);
396
397         /** Causes the server to exit after unloading modules and
398          * closing all open file descriptors.
399          *
400          * @param status The exit code to give to the operating system
401          * (See the ExitStatus enum for valid values)
402          */
403         void Exit(int status);
404
405         /** Causes the server to exit immediately with exit code 0.
406          * The status code is required for signal handlers, and ignored.
407          */
408         static void QuickExit(int status);
409
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
414         */
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);
417
418         /** Determines whether a nickname is valid. */
419         TR1NS::function<bool(const std::string&)> IsNick;
420
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.
425          */
426         static bool DefaultIsNick(const std::string& nick);
427
428         /** Determines whether an ident is valid. */
429         TR1NS::function<bool(const std::string&)> IsIdent;
430
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.
435         */
436         static bool DefaultIsIdent(const std::string& ident);
437
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.
443          */
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);
446
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.
453          */
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);
456
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.
461          */
462         static bool MatchMask(const std::string& masks, const std::string& hostname, const std::string& ipaddr);
463
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
467          */
468         static bool IsValidMask(const std::string& mask);
469
470         /** Strips all color and control codes except 001 from the given string
471          * @param sentence The string to strip from
472          */
473         static void StripColor(std::string &sentence);
474
475         /** Parses color codes from string values to actual color codes
476          * @param input The data to process
477          */
478         static void ProcessColors(file_cache& input);
479
480         /** Rehash the local server
481          * @param uuid The uuid of the user who started the rehash, can be empty
482          */
483         void Rehash(const std::string& uuid = "");
484
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
489          */
490         static unsigned long Duration(const std::string& str);
491
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
500          */
501         bool PassCompare(Extensible* ex, const std::string& data, const std::string& input, const std::string& hashtype);
502
503         /** Returns the full version string of this ircd
504          * @return The version string
505          */
506         std::string GetVersionString(bool getFullVersion = false);
507
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
512          */
513         void WritePID(const std::string& filename, bool exitonfail = true);
514
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.
521          */
522         InspIRCd(int argc, char** argv);
523
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.
527          */
528         void Cleanup();
529
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.
536          */
537         static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
538
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
545          */
546         static bool TimingSafeCompare(const std::string& one, const std::string& two);
547
548         /** Begin execution of the server.
549          * NOTE: this function NEVER returns. Internally,
550          * it will repeatedly loop.
551          */
552         void Run();
553
554         char* GetReadBuffer()
555         {
556                 return this->ReadBuffer;
557         }
558 };
559
560 ENTRYPOINT;
561
562 template<class Cmd>
563 class CommandModule : public Module
564 {
565         Cmd cmd;
566  public:
567         CommandModule() : cmd(this)
568         {
569         }
570
571         Version GetVersion() CXX11_OVERRIDE
572         {
573                 return Version(cmd.name, VF_VENDOR|VF_CORE);
574         }
575 };
576
577 inline void stdalgo::culldeleter::operator()(classbase* item)
578 {
579         if (item)
580                 ServerInstance->GlobalCulls.AddItem(item);
581 }
582
583 #include "numericbuilder.h"
584 #include "modules/whois.h"
585 #include "modules/stats.h"