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