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