]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Switch <stdint.h> test to use a test file too.
[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 #ifndef INSPIRCD_H
27 #define INSPIRCD_H
28
29 #define _FILE_OFFSET_BITS 64
30 #ifndef _LARGEFILE_SOURCE
31 #define _LARGEFILE_SOURCE
32 #endif
33
34 #ifndef _WIN32
35 #define DllExport
36 #define CoreExport
37 #else
38 #include "inspircd_win32wrapper.h"
39 /** Windows defines these already */
40 #undef ERROR
41 #endif
42
43 #ifdef __GNUC__
44 #define CUSTOM_PRINTF(STRING, FIRST) __attribute__((format(printf, STRING, FIRST)))
45 #else
46 #define CUSTOM_PRINTF(STRING, FIRST)
47 #endif
48
49 // Required system headers.
50 #include <csignal>
51 #include <ctime>
52 #include <cstdarg>
53 #include <algorithm>
54 #include <cmath>
55 #include <cstring>
56 #include <climits>
57 #include <cstdio>
58 #ifndef _WIN32
59 #include <unistd.h>
60 #endif
61
62 #include <sstream>
63 #include <string>
64 #include <vector>
65 #include <list>
66 #include <deque>
67 #include <map>
68 #include <bitset>
69 #include <set>
70 #include <time.h>
71 #include "inspircd_config.h"
72 #include "inspircd_version.h"
73 #include "typedefs.h"
74 #include "consolecolors.h"
75
76 CoreExport extern InspIRCd* ServerInstance;
77
78 #include "caller.h"
79 #include "cull_list.h"
80 #include "extensible.h"
81 #include "numerics.h"
82 #include "uid.h"
83 #include "users.h"
84 #include "channels.h"
85 #include "timer.h"
86 #include "hashcomp.h"
87 #include "logger.h"
88 #include "usermanager.h"
89 #include "socket.h"
90 #include "ctables.h"
91 #include "command_parse.h"
92 #include "mode.h"
93 #include "socketengine.h"
94 #include "snomasks.h"
95 #include "filelogger.h"
96 #include "modules.h"
97 #include "threadengine.h"
98 #include "configreader.h"
99 #include "inspstring.h"
100 #include "protocol.h"
101
102 #ifndef PATH_MAX
103 #warning Potentially broken system, PATH_MAX undefined
104 #define PATH_MAX 4096
105 #endif
106
107 /**
108  * Used to define the maximum number of parameters a command may have.
109  */
110 #define MAXPARAMETERS 127
111
112 /** Returned by some functions to indicate failure.
113  */
114 #define ERROR -1
115
116 /** Support for librodent -
117  * see http://www.chatspike.net/index.php?z=64
118  */
119 #define ETIREDHAMSTERS EAGAIN
120
121 /** Template function to convert any input type to std::string
122  */
123 template<typename T> inline std::string ConvNumeric(const T &in)
124 {
125         if (in == 0) return "0";
126         char res[MAXBUF];
127         char* out = res;
128         T quotient = in;
129         while (quotient) {
130                 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
131                 ++out;
132                 quotient /= 10;
133         }
134         if (in < 0)
135                 *out++ = '-';
136         *out = 0;
137         std::reverse(res,out);
138         return res;
139 }
140
141 /** Template function to convert any input type to std::string
142  */
143 inline std::string ConvToStr(const int in)
144 {
145         return ConvNumeric(in);
146 }
147
148 /** Template function to convert any input type to std::string
149  */
150 inline std::string ConvToStr(const long in)
151 {
152         return ConvNumeric(in);
153 }
154
155 /** Template function to convert any input type to std::string
156  */
157 inline std::string ConvToStr(const char* in)
158 {
159         return in;
160 }
161
162 /** Template function to convert any input type to std::string
163  */
164 inline std::string ConvToStr(const bool in)
165 {
166         return (in ? "1" : "0");
167 }
168
169 /** Template function to convert any input type to std::string
170  */
171 inline std::string ConvToStr(char in)
172 {
173         return std::string(1, in);
174 }
175
176 /** Template function to convert any input type to std::string
177  */
178 template <class T> inline std::string ConvToStr(const T &in)
179 {
180         std::stringstream tmp;
181         if (!(tmp << in)) return std::string();
182         return tmp.str();
183 }
184
185 /** Template function to convert any input type to any other type
186  * (usually an integer or numeric type)
187  */
188 template<typename T> inline long ConvToInt(const T &in)
189 {
190         std::stringstream tmp;
191         if (!(tmp << in)) return 0;
192         return atol(tmp.str().c_str());
193 }
194
195 /** This class contains various STATS counters
196  * It is used by the InspIRCd class, which internally
197  * has an instance of it.
198  */
199 class serverstats
200 {
201   public:
202         /** Number of accepted connections
203          */
204         unsigned long statsAccept;
205         /** Number of failed accepts
206          */
207         unsigned long statsRefused;
208         /** Number of unknown commands seen
209          */
210         unsigned long statsUnknown;
211         /** Number of nickname collisions handled
212          */
213         unsigned long statsCollisions;
214         /** Number of DNS queries sent out
215          */
216         unsigned long statsDns;
217         /** Number of good DNS replies received
218          * NOTE: This may not tally to the number sent out,
219          * due to timeouts and other latency issues.
220          */
221         unsigned long statsDnsGood;
222         /** Number of bad (negative) DNS replies received
223          * NOTE: This may not tally to the number sent out,
224          * due to timeouts and other latency issues.
225          */
226         unsigned long statsDnsBad;
227         /** Number of inbound connections seen
228          */
229         unsigned long statsConnects;
230         /** Total bytes of data transmitted
231          */
232         unsigned long statsSent;
233         /** Total bytes of data received
234          */
235         unsigned long statsRecv;
236 #ifdef _WIN32
237         /** Cpu usage at last sample
238         */
239         FILETIME LastCPU;
240         /** Time QP sample was read
241         */
242         LARGE_INTEGER LastSampled;
243         /** QP frequency
244         */
245         LARGE_INTEGER QPFrequency;
246 #else
247         /** Cpu usage at last sample
248          */
249         timeval LastCPU;
250         /** Time last sample was read
251          */
252         timespec LastSampled;
253 #endif
254         /** The constructor initializes all the counts to zero
255          */
256         serverstats()
257                 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
258                 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0), statsRecv(0)
259         {
260         }
261 };
262
263 DEFINE_HANDLER2(IsNickHandler, bool, const char*, size_t);
264 DEFINE_HANDLER2(GenRandomHandler, void, char*, size_t);
265 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
266 DEFINE_HANDLER1(FloodQuitUserHandler, void, User*);
267 DEFINE_HANDLER2(IsChannelHandler, bool, const char*, size_t);
268 DEFINE_HANDLER1(IsSIDHandler, bool, const std::string&);
269 DEFINE_HANDLER1(RehashHandler, void, const std::string&);
270 DEFINE_HANDLER3(OnCheckExemptionHandler, ModResult, User*, Channel*, const std::string&);
271
272 class TestSuite;
273
274 /** The main class of the irc server.
275  * This class contains instances of all the other classes in this software.
276  * Amongst other things, it contains a ModeParser, a DNS object, a CommandParser
277  * object, and a list of active Module objects, and facilities for Module
278  * objects to interact with the core system it implements.
279  */
280 class CoreExport InspIRCd
281 {
282  private:
283         /** Holds the current UID. Used to generate the next one.
284          */
285         char current_uid[UUID_LENGTH];
286
287         /** Set up the signal handlers
288          */
289         void SetSignals();
290
291         /** Daemonize the ircd and close standard input/output streams
292          * @return True if the program daemonized succesfully
293          */
294         bool DaemonSeed();
295
296         /** Iterate the list of BufferedSocket objects, removing ones which have timed out
297          * @param TIME the current time
298          */
299         void DoSocketTimeouts(time_t TIME);
300
301         /** Increments the current UID by one.
302          */
303         void IncrementUID(int pos);
304
305         /** Perform background user events such as PING checks
306          */
307         void DoBackgroundUserStuff();
308
309         /** Returns true when all modules have done pre-registration checks on a user
310          * @param user The user to verify
311          * @return True if all modules have finished checking this user
312          */
313         bool AllModulesReportReady(LocalUser* user);
314
315         /** The current time, updated in the mainloop
316          */
317         struct timespec TIME;
318
319         /** A 64k buffer used to read socket data into
320          * NOTE: update ValidateNetBufferSize if you change this
321          */
322         char ReadBuffer[65535];
323
324  public:
325
326         /** Global cull list, will be processed on next iteration
327          */
328         CullList GlobalCulls;
329         /** Actions that must happen outside of the current call stack */
330         ActionList AtomicActions;
331
332         /**** Functors ****/
333
334         IsNickHandler HandleIsNick;
335         IsIdentHandler HandleIsIdent;
336         FloodQuitUserHandler HandleFloodQuitUser;
337         OnCheckExemptionHandler HandleOnCheckExemption;
338         IsChannelHandler HandleIsChannel;
339         IsSIDHandler HandleIsSID;
340         RehashHandler HandleRehash;
341         GenRandomHandler HandleGenRandom;
342
343         /** 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
344          * Reason for it:
345          * kludge alert!
346          * SendMode expects a User* to send the numeric replies
347          * back to, so we create it a fake user that isnt in the user
348          * hash and set its descriptor to FD_MAGIC_NUMBER so the data
349          * falls into the abyss :p
350          */
351         FakeUser* FakeClient;
352
353         /** Returns the next available UID for this server.
354          */
355         std::string GetUID();
356
357         static const char LogHeader[];
358
359         /** Find a user in the UUID hash
360          * @param uid The UUID to find
361          * @return A pointer to the user, or NULL if the user does not exist
362          */
363         User* FindUUID(const std::string &uid);
364
365         /** Find a user in the UUID hash
366          * @param uid The UUID to find
367          * @return A pointer to the user, or NULL if the user does not exist
368          */
369         User* FindUUID(const char *uid);
370
371         /** Build the ISUPPORT string by triggering all modules On005Numeric events
372          */
373         void BuildISupport();
374
375         /** Time this ircd was booted
376          */
377         time_t startup_time;
378
379         /** Config file pathname specified on the commandline or via ./configure
380          */
381         std::string ConfigFileName;
382
383         ExtensionManager Extensions;
384
385         /** Mode handler, handles mode setting and removal
386          */
387         ModeParser* Modes;
388
389         /** Command parser, handles client to server commands
390          */
391         CommandParser* Parser;
392
393         /** Socket engine, handles socket activity events
394          */
395         SocketEngine* SE;
396
397         /** Thread engine, Handles threading where required
398          */
399         ThreadEngine* Threads;
400
401         /** The thread/class used to read config files in REHASH and on startup
402          */
403         ConfigReaderThread* ConfigThread;
404
405         /** LogManager handles logging.
406          */
407         LogManager *Logs;
408
409         /** ModuleManager contains everything related to loading/unloading
410          * modules.
411          */
412         ModuleManager* Modules;
413
414         /** BanCacheManager is used to speed up checking of restrictions on connection
415          * to the IRCd.
416          */
417         BanCacheManager *BanCache;
418
419         /** Stats class, holds miscellaneous stats counters
420          */
421         serverstats* stats;
422
423         /**  Server Config class, holds configuration file data
424          */
425         ServerConfig* Config;
426
427         /** Snomask manager - handles routing of snomask messages
428          * to opers.
429          */
430         SnomaskManager* SNO;
431
432         /** DNS class, provides resolver facilities to the core and modules
433          */
434         DNS* Res;
435
436         /** Timer manager class, triggers Timer timer events
437          */
438         TimerManager* Timers;
439
440         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
441          */
442         XLineManager* XLines;
443
444         /** User manager. Various methods and data associated with users.
445          */
446         UserManager *Users;
447
448         /** Channel list, a hash_map containing all channels XXX move to channel manager class
449          */
450         chan_hash* chanlist;
451
452         /** List of the open ports
453          */
454         std::vector<ListenSocket*> ports;
455
456         /** Set to the current signal recieved
457          */
458         static sig_atomic_t s_signal;
459
460         /** Protocol interface, overridden by server protocol modules
461          */
462         ProtocolInterface* PI;
463
464         /** Holds extensible for user nickforced
465          */
466         LocalIntExt NICKForced;
467
468         /** Holds extensible for user operquit
469          */
470         LocalStringExt OperQuit;
471
472         /** Get the current time
473          * Because this only calls time() once every time around the mainloop,
474          * it is much faster than calling time() directly.
475          * @return The current time as an epoch value (time_t)
476          */
477         inline time_t Time() { return TIME.tv_sec; }
478         /** The fractional time at the start of this mainloop iteration (nanoseconds) */
479         inline long Time_ns() { return TIME.tv_nsec; }
480         /** Update the current time. Don't call this unless you have reason to do so. */
481         void UpdateTime();
482
483         /** Generate a random string with the given length
484          * @param length The length in bytes
485          * @param printable if false, the string will use characters 0-255; otherwise,
486          * it will be limited to 0x30-0x7E ('0'-'~', nonspace printable characters)
487          */
488         std::string GenRandomStr(int length, bool printable = true);
489         /** Generate a random integer.
490          * This is generally more secure than rand()
491          */
492         unsigned long GenRandomInt(unsigned long max);
493
494         /** Fill a buffer with random bits */
495         caller2<void, char*, size_t> GenRandom;
496
497         /** Bind all ports specified in the configuration file.
498          * @return The number of ports bound without error
499          */
500         int BindPorts(FailedPortList &failed_ports);
501
502         /** Binds a socket on an already open file descriptor
503          * @param sockfd A valid file descriptor of an open socket
504          * @param port The port number to bind to
505          * @param addr The address to bind to (IP only)
506          * @param dolisten Should this port be listened on?
507          * @return True if the port was bound successfully
508          */
509         bool BindSocket(int sockfd, int port, const char* addr, bool dolisten = true);
510
511         /** Gets the GECOS (description) field of the given server.
512          * If the servername is not that of the local server, the name
513          * is passed to handling modules which will attempt to determine
514          * the GECOS that bleongs to the given servername.
515          * @param servername The servername to find the description of
516          * @return The description of this server, or of the local server
517          */
518         std::string GetServerDescription(const std::string& servername);
519
520         /** Find a user in the nick hash.
521          * If the user cant be found in the nick hash check the uuid hash
522          * @param nick The nickname to find
523          * @return A pointer to the user, or NULL if the user does not exist
524          */
525         User* FindNick(const std::string &nick);
526
527         /** Find a user in the nick hash.
528          * If the user cant be found in the nick hash check the uuid hash
529          * @param nick The nickname to find
530          * @return A pointer to the user, or NULL if the user does not exist
531          */
532         User* FindNick(const char* nick);
533
534         /** Find a user in the nick hash ONLY
535          */
536         User* FindNickOnly(const char* nick);
537
538         /** Find a user in the nick hash ONLY
539          */
540         User* FindNickOnly(const std::string &nick);
541
542         /** Find a channel in the channels hash
543          * @param chan The channel to find
544          * @return A pointer to the channel, or NULL if the channel does not exist
545          */
546         Channel* FindChan(const std::string &chan);
547
548         /** Find a channel in the channels hash
549          * @param chan The channel to find
550          * @return A pointer to the channel, or NULL if the channel does not exist
551          */
552         Channel* FindChan(const char* chan);
553
554         /** Check we aren't running as root, and exit if we are
555          * @return Depending on the configuration, this function may never return
556          */
557         void CheckRoot();
558
559         /** Determine the right path for, and open, the logfile
560          * @param argv The argv passed to main() initially, used to calculate program path
561          * @param argc The argc passed to main() initially, used to calculate program path
562          * @return True if the log could be opened, false if otherwise
563          */
564         bool OpenLog(char** argv, int argc);
565
566         /** Return true if a channel name is valid
567          * @param chname A channel name to verify
568          * @return True if the name is valid
569          */
570         caller2<bool, const char*, size_t> IsChannel;
571
572         /** Return true if str looks like a server ID
573          * @param string to check against
574          */
575         caller1<bool, const std::string&> IsSID;
576
577         /** Rehash the local server
578          */
579         caller1<void, const std::string&> Rehash;
580
581         /** Handles incoming signals after being set
582          * @param signal the signal recieved
583          */
584         void SignalHandler(int signal);
585
586         /** Sets the signal recieved
587          * @param signal the signal recieved
588          */
589         static void SetSignal(int signal);
590
591         /** Causes the server to exit after unloading modules and
592          * closing all open file descriptors.
593          *
594          * @param status The exit code to give to the operating system
595          * (See the ExitStatus enum for valid values)
596          */
597         void Exit(int status);
598
599         /** Causes the server to exit immediately with exit code 0.
600          * The status code is required for signal handlers, and ignored.
601          */
602         static void QuickExit(int status);
603
604         /** Return a count of channels on the network
605          * @return The number of channels
606          */
607         long ChannelCount();
608
609         /** Send an error notice to all local users, opered and unopered
610          * @param s The error string to send
611          */
612         void SendError(const std::string &s);
613
614         /** Return true if a nickname is valid
615          * @param n A nickname to verify
616          * @return True if the nick is valid
617          */
618         caller2<bool, const char*, size_t> IsNick;
619
620         /** Return true if an ident is valid
621          * @param An ident to verify
622          * @return True if the ident is valid
623          */
624         caller1<bool, const char*> IsIdent;
625
626         /** Add a dns Resolver class to this server's active set
627          * @param r The resolver to add
628          * @param cached If this value is true, then the cache will
629          * be searched for the DNS result, immediately. If the value is
630          * false, then a request will be sent to the nameserver, and the
631          * result will not be immediately available. You should usually
632          * use the boolean value which you passed to the Resolver
633          * constructor, which Resolver will set appropriately depending
634          * on if cached results are available and haven't expired. It is
635          * however safe to force this value to false, forcing a remote DNS
636          * lookup, but not an update of the cache.
637          * @return True if the operation completed successfully. Note that
638          * if this method returns true, you should not attempt to access
639          * the resolver class you pass it after this call, as depending upon
640          * the request given, the object may be deleted!
641          */
642         bool AddResolver(Resolver* r, bool cached);
643
644         /** Add a command to this server's command parser
645          * @param f A Command command handler object to add
646          * @throw ModuleException Will throw ModuleExcption if the command already exists
647          */
648         inline void AddCommand(Command *f)
649         {
650                 Modules->AddService(*f);
651         }
652
653         /** Send a modechange.
654          * The parameters provided are identical to that sent to the
655          * handler for class cmd_mode.
656          * @param parameters The mode parameters
657          * @param user The user to send error messages to
658          */
659         void SendMode(const std::vector<std::string>& parameters, User *user);
660
661         /** Send a modechange and route it to the network.
662          * The parameters provided are identical to that sent to the
663          * handler for class cmd_mode.
664          * @param parameters The mode parameters
665          * @param user The user to send error messages to
666          */
667         void SendGlobalMode(const std::vector<std::string>& parameters, User *user);
668
669         /** Match two strings using pattern matching, optionally, with a map
670          * to check case against (may be NULL). If map is null, match will be case insensitive.
671          * @param str The literal string to match against
672          * @param mask The glob pattern to match against.
673          * @param map The character map to use when matching.
674          */
675         static bool Match(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
676         static bool Match(const  char *str, const char *mask, unsigned const char *map = NULL);
677
678         /** Match two strings using pattern matching, optionally, with a map
679          * to check case against (may be NULL). If map is null, match will be case insensitive.
680          * Supports CIDR patterns as well as globs.
681          * @param str The literal string to match against
682          * @param mask The glob or CIDR pattern to match against.
683          * @param map The character map to use when matching.
684          */
685         static bool MatchCIDR(const std::string &str, const std::string &mask, unsigned const char *map = NULL);
686         static bool MatchCIDR(const  char *str, const char *mask, unsigned const char *map = NULL);
687
688         /** Call the handler for a given command.
689          * @param commandname The command whos handler you wish to call
690          * @param parameters The mode parameters
691          * @param user The user to execute the command as
692          * @return True if the command handler was called successfully
693          */
694         CmdResult CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user);
695
696         /** Return true if the command is a module-implemented command and the given parameters are valid for it
697          * @param commandname The command name to check
698          * @param pcnt The parameter count
699          * @param user The user to test-execute the command as
700          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
701          */
702         bool IsValidModuleCommand(const std::string &commandname, int pcnt, User* user);
703
704         /** Return true if the given parameter is a valid nick!user\@host mask
705          * @param mask A nick!user\@host masak to match against
706          * @return True i the mask is valid
707          */
708         bool IsValidMask(const std::string &mask);
709
710         /** Strips all color codes from the given string
711          * @param sentence The string to strip from
712          */
713         static void StripColor(std::string &sentence);
714
715         /** Parses color codes from string values to actual color codes
716          * @param input The data to process
717          */
718         static void ProcessColors(file_cache& input);
719
720         /** Rehash the local server
721          */
722         void RehashServer();
723
724         /** Check if the given nickmask matches too many users, send errors to the given user
725          * @param nick A nickmask to match against
726          * @param user A user to send error text to
727          * @return True if the nick matches too many users
728          */
729         bool NickMatchesEveryone(const std::string &nick, User* user);
730
731         /** Check if the given IP mask matches too many users, send errors to the given user
732          * @param ip An ipmask to match against
733          * @param user A user to send error text to
734          * @return True if the ip matches too many users
735          */
736         bool IPMatchesEveryone(const std::string &ip, User* user);
737
738         /** Check if the given hostmask matches too many users, send errors to the given user
739          * @param mask A hostmask to match against
740          * @param user A user to send error text to
741          * @return True if the host matches too many users
742          */
743         bool HostMatchesEveryone(const std::string &mask, User* user);
744
745         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
746          * @param str A string containing a time in the form 1y2w3d4h6m5s
747          * (one year, two weeks, three days, four hours, six minutes and five seconds)
748          * @return The total number of seconds
749          */
750         long Duration(const std::string &str);
751
752         /** Attempt to compare a password to a string from the config file.
753          * This will be passed to handling modules which will compare the data
754          * against possible hashed equivalents in the input string.
755          * @param ex The object (user, server, whatever) causing the comparison.
756          * @param data The data from the config file
757          * @param input The data input by the oper
758          * @param hashtype The hash from the config file
759          * @return 0 if the strings match, 1 or -1 if they do not
760          */
761         int PassCompare(Extensible* ex, const std::string &data, const std::string &input, const std::string &hashtype);
762
763         /** Check if a given server is a uline.
764          * An empty string returns true, this is by design.
765          * @param server The server to check for uline status
766          * @return True if the server is a uline OR the string is empty
767          */
768         bool ULine(const std::string& server);
769
770         /** Returns true if the uline is 'silent' (doesnt generate
771          * remote connect notices etc).
772          */
773         bool SilentULine(const std::string& server);
774
775         /** Returns the full version string of this ircd
776          * @return The version string
777          */
778         std::string GetVersionString(bool rawversion = false);
779
780         /** Attempt to write the process id to a given file
781          * @param filename The PID file to attempt to write to
782          * @return This function may bail if the file cannot be written
783          */
784         void WritePID(const std::string &filename);
785
786         /** This constructor initialises all the subsystems and reads the config file.
787          * @param argc The argument count passed to main()
788          * @param argv The argument list passed to main()
789          * @throw <anything> If anything is thrown from here and makes it to
790          * you, you should probably just give up and go home. Yes, really.
791          * It's that bad. Higher level classes should catch any non-fatal exceptions.
792          */
793         InspIRCd(int argc, char** argv);
794
795         /** Send a line of WHOIS data to a user.
796          * @param user user to send the line to
797          * @param dest user being WHOISed
798          * @param numeric Numeric to send
799          * @param text Text of the numeric
800          */
801         void SendWhoisLine(User* user, User* dest, int numeric, const std::string &text);
802
803         /** Send a line of WHOIS data to a user.
804          * @param user user to send the line to
805          * @param dest user being WHOISed
806          * @param numeric Numeric to send
807          * @param format Format string for the numeric
808          * @param ... Parameters for the format string
809          */
810         void SendWhoisLine(User* user, User* dest, int numeric, const char* format, ...) CUSTOM_PRINTF(5, 6);
811
812         /** Handle /WHOIS
813          */
814         void DoWhois(User* user, User* dest,unsigned long signon, unsigned long idle, const char* nick);
815
816         /** Quit a user for excess flood, and if they are not
817          * fully registered yet, temporarily zline their IP.
818          * @param current user to quit
819          */
820         caller1<void, User*> FloodQuitUser;
821
822         /** Called to check whether a channel restriction mode applies to a user
823          * @param User that is attempting some action
824          * @param Channel that the action is being performed on
825          * @param Action name
826          */
827         caller3<ModResult, User*, Channel*, const std::string&> OnCheckExemption;
828
829         /** Restart the server.
830          * This function will not return. If an error occurs,
831          * it will throw an instance of CoreException.
832          * @param reason The restart reason to show to all clients
833          * @throw CoreException An instance of CoreException indicating the error from execv().
834          */
835         void Restart(const std::string &reason);
836
837         /** Prepare the ircd for restart or shutdown.
838          * This function unloads all modules which can be unloaded,
839          * closes all open sockets, and closes the logfile.
840          */
841         void Cleanup();
842
843         /** This copies the user and channel hash_maps into new hash maps.
844          * This frees memory used by the hash_map allocator (which it neglects
845          * to free, most of the time, using tons of ram)
846          */
847         void RehashUsersAndChans();
848
849         /** Resets the cached max bans value on all channels.
850          * Called by rehash.
851          */
852         void ResetMaxBans();
853
854         /** Return a time_t as a human-readable string.
855          */
856         std::string TimeString(time_t curtime);
857
858         /** Begin execution of the server.
859          * NOTE: this function NEVER returns. Internally,
860          * it will repeatedly loop.
861          * @return The return value for this function is undefined.
862          */
863         int Run();
864
865         /** Adds an extban char to the 005 token.
866          */
867         void AddExtBanChar(char c);
868
869         char* GetReadBuffer()
870         {
871                 return this->ReadBuffer;
872         }
873
874         friend class TestSuite;
875 };
876
877 ENTRYPOINT;
878
879 template<class Cmd>
880 class CommandModule : public Module
881 {
882         Cmd cmd;
883  public:
884         CommandModule() : cmd(this)
885         {
886         }
887
888         void init()
889         {
890                 ServerInstance->Modules->AddService(cmd);
891         }
892
893         Version GetVersion()
894         {
895                 return Version(cmd.name, VF_VENDOR|VF_CORE);
896         }
897 };
898
899 #endif