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