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