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