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