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