]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
9311488842374005b4c0c25cbde4707fb7b88dc5
[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 "caller.h"
72 #include "cull_list.h"
73 #include "extensible.h"
74 #include "fileutils.h"
75 #include "numerics.h"
76 #include "numeric.h"
77 #include "uid.h"
78 #include "server.h"
79 #include "users.h"
80 #include "channels.h"
81 #include "timer.h"
82 #include "hashcomp.h"
83 #include "logger.h"
84 #include "usermanager.h"
85 #include "socket.h"
86 #include "ctables.h"
87 #include "command_parse.h"
88 #include "mode.h"
89 #include "socketengine.h"
90 #include "snomasks.h"
91 #include "filelogger.h"
92 #include "modules.h"
93 #include "threadengine.h"
94 #include "configreader.h"
95 #include "inspstring.h"
96 #include "protocol.h"
97 #include "bancache.h"
98 #include "isupportmanager.h"
99
100 /** This class contains various STATS counters
101  * It is used by the InspIRCd class, which internally
102  * has an instance of it.
103  */
104 class serverstats
105 {
106   public:
107         /** Number of accepted connections
108          */
109         unsigned long Accept;
110         /** Number of failed accepts
111          */
112         unsigned long Refused;
113         /** Number of unknown commands seen
114          */
115         unsigned long Unknown;
116         /** Number of nickname collisions handled
117          */
118         unsigned long Collisions;
119         /** Number of DNS queries sent out
120          */
121         unsigned long Dns;
122         /** Number of good DNS replies received
123          * NOTE: This may not tally to the number sent out,
124          * due to timeouts and other latency issues.
125          */
126         unsigned long DnsGood;
127         /** Number of bad (negative) DNS replies received
128          * NOTE: This may not tally to the number sent out,
129          * due to timeouts and other latency issues.
130          */
131         unsigned long DnsBad;
132         /** Number of inbound connections seen
133          */
134         unsigned long Connects;
135         /** Total bytes of data transmitted
136          */
137         unsigned long Sent;
138         /** Total bytes of data received
139          */
140         unsigned long Recv;
141 #ifdef _WIN32
142         /** Cpu usage at last sample
143         */
144         FILETIME LastCPU;
145         /** Time QP sample was read
146         */
147         LARGE_INTEGER LastSampled;
148         /** QP frequency
149         */
150         LARGE_INTEGER QPFrequency;
151 #else
152         /** Cpu usage at last sample
153          */
154         timeval LastCPU;
155         /** Time last sample was read
156          */
157         timespec LastSampled;
158 #endif
159         /** The constructor initializes all the counts to zero
160          */
161         serverstats()
162                 : Accept(0), Refused(0), Unknown(0), Collisions(0), Dns(0),
163                 DnsGood(0), DnsBad(0), Connects(0), Sent(0), Recv(0)
164         {
165         }
166 };
167
168 DEFINE_HANDLER1(IsNickHandler, bool, const std::string&);
169 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
170 DEFINE_HANDLER1(IsIdentHandler, bool, const std::string&);
171 DEFINE_HANDLER1(IsChannelHandler, bool, const std::string&);
172 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
173
174 /** The main class of the irc server.
175  * This class contains instances of all the other classes in this software.
176  * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
177  * object, and a list of active Module objects, and facilities for Module
178  * objects to interact with the core system it implements.
179  */
180 class CoreExport InspIRCd
181 {
182  private:
183         /** Set up the signal handlers
184          */
185         void SetSignals();
186
187         /** Daemonize the ircd and close standard input/output streams
188          * @return True if the program daemonized succesfully
189          */
190         bool DaemonSeed();
191
192         /** The current time, updated in the mainloop
193          */
194         struct timespec TIME;
195
196         /** A 64k buffer used to read socket data into
197          * NOTE: update ValidateNetBufferSize if you change this
198          */
199         char ReadBuffer[65535];
200
201         /** Check we aren't running as root, and exit if we are
202          * with exit code EXIT_STATUS_ROOT.
203          */
204         void CheckRoot();
205
206  public:
207
208         UIDGenerator UIDGen;
209
210         /** Global cull list, will be processed on next iteration
211          */
212         CullList GlobalCulls;
213         /** Actions that must happen outside of the current call stack */
214         ActionList AtomicActions;
215
216         /**** Functors ****/
217
218         IsNickHandler HandleIsNick;
219         IsIdentHandler HandleIsIdent;
220         OnCheckExemptionHandler HandleOnCheckExemption;
221         IsChannelHandler HandleIsChannel;
222         GenRandomHandler HandleGenRandom;
223
224         /** 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
225          * Reason for it:
226          * kludge alert!
227          * SendMode expects a User* to send the numeric replies
228          * back to, so we create it a fake user that isnt in the user
229          * hash and set its descriptor to FD_MAGIC_NUMBER so the data
230          * falls into the abyss :p
231          */
232         FakeUser* FakeClient;
233
234         /** Find a user in the UUID hash
235          * @param uid The UUID to find
236          * @return A pointer to the user, or NULL if the user does not exist
237          */
238         User* FindUUID(const std::string &uid);
239
240         /** Time this ircd was booted
241          */
242         time_t startup_time;
243
244         /** Config file pathname specified on the commandline or via ./configure
245          */
246         std::string ConfigFileName;
247
248         ExtensionManager Extensions;
249
250         /** Mode handler, handles mode setting and removal
251          */
252         ModeParser Modes;
253
254         /** Command parser, handles client to server commands
255          */
256         CommandParser Parser;
257
258         /** Thread engine, Handles threading where required
259          */
260         ThreadEngine Threads;
261
262         /** The thread/class used to read config files in REHASH and on startup
263          */
264         ConfigReaderThread* ConfigThread;
265
266         /** LogManager handles logging.
267          */
268         LogManager Logs;
269
270         /** ModuleManager contains everything related to loading/unloading
271          * modules.
272          */
273         ModuleManager Modules;
274
275         /** BanCacheManager is used to speed up checking of restrictions on connection
276          * to the IRCd.
277          */
278         BanCacheManager BanCache;
279
280         /** Stats class, holds miscellaneous stats counters
281          */
282         serverstats stats;
283
284         /**  Server Config class, holds configuration file data
285          */
286         ServerConfig* Config;
287
288         /** Snomask manager - handles routing of snomask messages
289          * to opers.
290          */
291         SnomaskManager SNO;
292
293         /** Timer manager class, triggers Timer timer events
294          */
295         TimerManager Timers;
296
297         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
298          */
299         XLineManager* XLines;
300
301         /** User manager. Various methods and data associated with users.
302          */
303         UserManager Users;
304
305         /** Channel list, a hash_map containing all channels XXX move to channel manager class
306          */
307         chan_hash chanlist;
308
309         /** List of the open ports
310          */
311         std::vector<ListenSocket*> ports;
312
313         /** Set to the current signal recieved
314          */
315         static sig_atomic_t s_signal;
316
317         /** Protocol interface, overridden by server protocol modules
318          */
319         ProtocolInterface* PI;
320
321         /** Default implementation of the ProtocolInterface, does nothing
322          */
323         ProtocolInterface DefaultProtocolInterface;
324
325         /** Holds extensible for user operquit
326          */
327         StringExtItem OperQuit;
328
329         /** Manages the generation and transmission of ISUPPORT. */
330         ISupportManager ISupport;
331
332         /** Get the current time
333          * Because this only calls time() once every time around the mainloop,
334          * it is much faster than calling time() directly.
335          * @return The current time as an epoch value (time_t)
336          */
337         inline time_t Time() { return TIME.tv_sec; }
338         /** The fractional time at the start of this mainloop iteration (nanoseconds) */
339         inline long Time_ns() { return TIME.tv_nsec; }
340         /** Update the current time. Don't call this unless you have reason to do so. */
341         void UpdateTime();
342
343         /** Generate a random string with the given length
344          * @param length The length in bytes
345          * @param printable if false, the string will use characters 0-255; otherwise,
346          * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
347          */
348         std::string GenRandomStr(int length, bool printable = true);
349         /** Generate a random integer.
350          * This is generally more secure than rand()
351          */
352         unsigned long GenRandomInt(unsigned long max);
353
354         /** Fill a buffer with random bits */
355         caller2<void, char*, size_t> GenRandom;
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         /** Return true if a channel name is valid
385          * @param chname A channel name to verify
386          * @return True if the name is valid
387          */
388         caller1<bool, const std::string&> IsChannel;
389
390         /** Return true if str looks like a server ID
391          * @param sid string to check against
392          */
393         static bool IsSID(const std::string& sid);
394
395         /** Handles incoming signals after being set
396          * @param signal the signal recieved
397          */
398         void SignalHandler(int signal);
399
400         /** Sets the signal recieved
401          * @param signal the signal recieved
402          */
403         static void SetSignal(int signal);
404
405         /** Causes the server to exit after unloading modules and
406          * closing all open file descriptors.
407          *
408          * @param status The exit code to give to the operating system
409          * (See the ExitStatus enum for valid values)
410          */
411         void Exit(int status);
412
413         /** Causes the server to exit immediately with exit code 0.
414          * The status code is required for signal handlers, and ignored.
415          */
416         static void QuickExit(int status);
417
418         /** Formats the input string with the specified arguments.
419         * @param formatString The string to format
420         * @param ... A variable number of format arguments.
421         * @return The formatted string
422         */
423         static const char* Format(const char* formatString, ...) CUSTOM_PRINTF(1, 2);
424         static const char* Format(va_list &vaList, const char* formatString) CUSTOM_PRINTF(2, 0);
425
426         /** Return true if a nickname is valid
427          * @param n A nickname to verify
428          * @return True if the nick is valid
429          */
430         caller1<bool, const std::string&> IsNick;
431
432         /** Return true if an ident is valid
433          * @param An ident to verify
434          * @return True if the ident is valid
435          */
436         caller1<bool, const std::string&> IsIdent;
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          * @return This function may bail if the file cannot be written
511          */
512         void WritePID(const std::string &filename);
513
514         /** This constructor initialises all the subsystems and reads the config file.
515          * @param argc The argument count passed to main()
516          * @param argv The argument list passed to main()
517          * @throw <anything> If anything is thrown from here and makes it to
518          * you, you should probably just give up and go home. Yes, really.
519          * It's that bad. Higher level classes should catch any non-fatal exceptions.
520          */
521         InspIRCd(int argc, char** argv);
522
523         /** Called to check whether a channel restriction mode applies to a user
524          * @param User that is attempting some action
525          * @param Channel that the action is being performed on
526          * @param Action name
527          */
528         caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
529
530         /** Prepare the ircd for restart or shutdown.
531          * This function unloads all modules which can be unloaded,
532          * closes all open sockets, and closes the logfile.
533          */
534         void Cleanup();
535
536         /** Return a time_t as a human-readable string.
537          * @param format The format to retrieve the date/time in. See `man 3 strftime`
538          * for more information. If NULL, "%a %b %d %T %Y" is assumed.
539          * @param utc True to convert the time to string as-is, false to convert it to local time first.
540          * @return A string representing the given date/time.
541          */
542         static std::string TimeString(time_t curtime, const char* format = NULL, bool utc = false);
543
544         /** Compare two strings in a timing-safe way. If the lengths of the strings differ, the function
545          * returns false immediately (leaking information about the length), otherwise it compares each
546          * character and only returns after all characters have been compared.
547          * @param one First string
548          * @param two Second string
549          * @return True if the strings match, false if they don't
550          */
551         static bool TimingSafeCompare(const std::string& one, const std::string& two);
552
553         /** Begin execution of the server.
554          * NOTE: this function NEVER returns. Internally,
555          * it will repeatedly loop.
556          */
557         void Run();
558
559         char* GetReadBuffer()
560         {
561                 return this->ReadBuffer;
562         }
563 };
564
565 ENTRYPOINT;
566
567 template<class Cmd>
568 class CommandModule : public Module
569 {
570         Cmd cmd;
571  public:
572         CommandModule() : cmd(this)
573         {
574         }
575
576         Version GetVersion()
577         {
578                 return Version(cmd.name, VF_VENDOR|VF_CORE);
579         }
580 };
581
582 inline void stdalgo::culldeleter::operator()(classbase* item)
583 {
584         if (item)
585                 ServerInstance->GlobalCulls.AddItem(item);
586 }
587
588 #include "numericbuilder.h"
589 #include "modules/whois.h"