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