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