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