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