]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Remove debug again.
[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 "inspircd_config.h"
32 #include "users.h"
33 #include "channels.h"
34 #include "socket.h"
35 #include "mode.h"
36 #include "socketengine.h"
37 #include "command_parse.h"
38 #include "snomasks.h"
39 #include "cull_list.h"
40 #include "filelogger.h"
41 #include "caller.h"
42
43 /**
44  * Used to define the maximum number of parameters a command may have.
45  */
46 #define MAXPARAMETERS 127
47
48 /** Returned by some functions to indicate failure.
49  */
50 #define ERROR -1
51
52 /** Support for librodent -
53  * see http://www.chatspike.net/index.php?z=64
54  */
55 #define ETIREDHAMSTERS EAGAIN
56
57 /**
58  * This define is used in place of strcmp when we
59  * want to check if a char* string contains only one
60  * letter. Pretty fast, its just two compares and an
61  * addition.
62  */
63 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
64
65 /** Delete a pointer, and NULL its value
66  */
67 template<typename T> inline void DELETE(T* x)
68 {
69         delete x;
70         x = NULL;
71 }
72
73 /** Template function to convert any input type to std::string
74  */
75 template<typename T> inline std::string ConvNumeric(const T &in)
76 {
77         if (in == 0) return "0";
78         char res[MAXBUF];
79         char* out = res;
80         T quotient = in;
81         while (quotient) {
82                 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
83                 ++out;
84                 quotient /= 10;
85         }
86         if ( in < 0)
87                 *out++ = '-';
88         *out = 0;
89         std::reverse(res,out);
90         return res;
91 }
92
93 /** Template function to convert any input type to std::string
94  */
95 inline std::string ConvToStr(const int in)
96 {
97         return ConvNumeric(in);
98 }
99
100 /** Template function to convert any input type to std::string
101  */
102 inline std::string ConvToStr(const long in)
103 {
104         return ConvNumeric(in);
105 }
106
107 /** Template function to convert any input type to std::string
108  */
109 inline std::string ConvToStr(const unsigned long in)
110 {
111         return ConvNumeric(in);
112 }
113
114 /** Template function to convert any input type to std::string
115  */
116 inline std::string ConvToStr(const char* in)
117 {
118         return in;
119 }
120
121 /** Template function to convert any input type to std::string
122  */
123 inline std::string ConvToStr(const bool in)
124 {
125         return (in ? "1" : "0");
126 }
127
128 /** Template function to convert any input type to std::string
129  */
130 inline std::string ConvToStr(char in)
131 {
132         return std::string(in,1);
133 }
134
135 /** Template function to convert any input type to std::string
136  */
137 template <class T> inline std::string ConvToStr(const T &in)
138 {
139         std::stringstream tmp;
140         if (!(tmp << in)) return std::string();
141         return tmp.str();
142 }
143
144 /** Template function to convert any input type to any other type
145  * (usually an integer or numeric type)
146  */
147 template<typename T> inline long ConvToInt(const T &in)
148 {
149         std::stringstream tmp;
150         if (!(tmp << in)) return 0;
151         return atoi(tmp.str().c_str());
152 }
153
154 /** Template function to convert integer to char, storing result in *res and
155  * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
156  * @param T input value
157  * @param V result value
158  * @param R base to convert to
159  */
160 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
161 {
162         if (base < 2 || base > 16) { *res = 0; return res; }
163         char* out = res;
164         int quotient = in;
165         while (quotient) {
166                 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
167                 ++out;
168                 quotient /= base;
169         }
170         if ( in < 0 && base == 10) *out++ = '-';
171         std::reverse( res, out );
172         *out = 0;
173         return res;
174 }
175
176 /** This class contains various STATS counters
177  * It is used by the InspIRCd class, which internally
178  * has an instance of it.
179  */
180 class serverstats : public classbase
181 {
182   public:
183         /** Number of accepted connections
184          */
185         unsigned long statsAccept;
186         /** Number of failed accepts
187          */
188         unsigned long statsRefused;
189         /** Number of unknown commands seen
190          */
191         unsigned long statsUnknown;
192         /** Number of nickname collisions handled
193          */
194         unsigned long statsCollisions;
195         /** Number of DNS queries sent out
196          */
197         unsigned long statsDns;
198         /** Number of good DNS replies received
199          * NOTE: This may not tally to the number sent out,
200          * due to timeouts and other latency issues.
201          */
202         unsigned long statsDnsGood;
203         /** Number of bad (negative) DNS replies received
204          * NOTE: This may not tally to the number sent out,
205          * due to timeouts and other latency issues.
206          */
207         unsigned long statsDnsBad;
208         /** Number of inbound connections seen
209          */
210         unsigned long statsConnects;
211         /** Total bytes of data transmitted
212          */
213         double statsSent;
214         /** Total bytes of data received
215          */
216         double statsRecv;
217         /** Cpu usage at last sample
218          */
219         timeval LastCPU;
220         /** Time last sample was read
221          */
222         timeval LastSampled;
223         /** The constructor initializes all the counts to zero
224          */
225         serverstats()
226                 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
227                 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
228         {
229         }
230 };
231
232 /** A list of failed port bindings, used for informational purposes on startup */
233 typedef std::vector<std::pair<std::string, long> > FailedPortList;
234
235 /** A list of ip addresses cross referenced against clone counts */
236 typedef std::map<irc::string, unsigned int> clonemap;
237
238 class InspIRCd;
239
240 DEFINE_HANDLER1(ProcessUserHandler, void, userrec*);
241 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
242 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
243 DEFINE_HANDLER1(FindDescriptorHandler, userrec*, int);
244 DEFINE_HANDLER1(FloodQuitUserHandler, void, userrec*);
245
246 /* Forward declaration - required */
247 class XLineManager;
248
249 /** The main class of the irc server.
250  * This class contains instances of all the other classes
251  * in this software, with the exception of the base class,
252  * classbase. Amongst other things, it contains a ModeParser,
253  * a DNS object, a CommandParser object, and a list of active
254  * Module objects, and facilities for Module objects to
255  * interact with the core system it implements. You should
256  * NEVER attempt to instantiate a class of type InspIRCd
257  * yourself. If you do, this is equivalent to spawning a second
258  * IRC server, and could have catastrophic consequences for the
259  * program in terms of ram usage (basically, you could create
260  * an obese forkbomb built from recursively spawning irc servers!)
261  */
262 class CoreExport InspIRCd : public classbase
263 {
264  private:
265         /** Holds a string describing the last module error to occur
266          */
267         char MODERR[MAXBUF];
268
269         /** Remove a ModuleFactory pointer
270          * @param j Index number of the ModuleFactory to remove
271          */
272         void EraseFactory(int j);
273
274         /** Remove a Module pointer
275          * @param j Index number of the Module to remove
276          */
277         void EraseModule(int j);
278
279         /** Move a given module to a specific slot in the list
280          * @param modulename The module name to relocate
281          * @param slot The slot to move the module into
282          */
283         void MoveTo(std::string modulename,int slot);
284
285         /** Set up the signal handlers
286          */
287         void SetSignals();
288
289         /** Daemonize the ircd and close standard input/output streams
290          * @return True if the program daemonized succesfully
291          */
292         bool DaemonSeed();
293
294         /** Moves the given module to the last slot in the list
295          * @param modulename The module name to relocate
296          */
297         void MoveToLast(std::string modulename);
298
299         /** Moves the given module to the first slot in the list
300          * @param modulename The module name to relocate
301          */
302         void MoveToFirst(std::string modulename);
303
304         /** Moves one module to be placed after another in the list
305          * @param modulename The module name to relocate
306          * @param after The module name to place the module after
307          */
308         void MoveAfter(std::string modulename, std::string after);
309
310         /** Moves one module to be placed before another in the list
311          * @param modulename The module name to relocate
312          * @param after The module name to place the module before
313          */
314         void MoveBefore(std::string modulename, std::string before);
315
316         /** Iterate the list of InspSocket objects, removing ones which have timed out
317          * @param TIME the current time
318          */
319         void DoSocketTimeouts(time_t TIME);
320
321         /** Perform background user events such as PING checks
322          * @param TIME the current time
323          */
324         void DoBackgroundUserStuff(time_t TIME);
325
326         /** Returns true when all modules have done pre-registration checks on a user
327          * @param user The user to verify
328          * @return True if all modules have finished checking this user
329          */
330         bool AllModulesReportReady(userrec* user);
331
332         /** Total number of modules loaded into the ircd, minus one
333          */
334         int ModCount;
335
336         /** Logfile pathname specified on the commandline, or empty string
337          */
338         char LogFileName[MAXBUF];
339
340         /** The feature names published by various modules
341          */
342         featurelist Features;
343
344         /** The interface names published by various modules
345          */
346         interfacelist Interfaces;
347
348         /** The current time, updated in the mainloop
349          */
350         time_t TIME;
351
352         /** The time that was recorded last time around the mainloop
353          */
354         time_t OLDTIME;
355
356         /** A 64k buffer used to read client lines into
357          */
358         char ReadBuffer[65535];
359
360         /** Used when connecting clients
361          */
362         insp_sockaddr client, server;
363
364         /** Used when connecting clients
365          */
366         socklen_t length;
367
368         /** Nonblocking file writer
369          */
370         FileLogger* Logger;
371
372         /** Time offset in seconds
373          * This offset is added to all calls to Time(). Use SetTimeDelta() to update
374          */
375         int time_delta;
376
377 #ifdef WIN32
378         IPC* WindowsIPC;
379 #endif
380
381  public:
382
383         /** Global cull list, will be processed on next iteration
384          */
385         CullList GlobalCulls;
386
387
388         /**** Functors ****/
389
390         ProcessUserHandler HandleProcessUser;
391         IsNickHandler HandleIsNick;
392         IsIdentHandler HandleIsIdent;
393         FindDescriptorHandler HandleFindDescriptor;
394         FloodQuitUserHandler HandleFloodQuitUser;
395
396         /** InspSocket classes pending deletion after being closed.
397          * We don't delete these immediately as this may cause a segmentation fault.
398          */
399         std::map<InspSocket*,InspSocket*> SocketCull;
400
401         /** Build the ISUPPORT string by triggering all modules On005Numeric events
402          */
403         void BuildISupport();
404
405         /** Number of unregistered users online right now.
406          * (Unregistered means before USER/NICK/dns)
407          */
408         int unregistered_count;
409
410         /** List of server names we've seen.
411          */
412         servernamelist servernames;
413
414         /** Time this ircd was booted
415          */
416         time_t startup_time;
417
418         /** Config file pathname specified on the commandline or via ./configure
419          */
420         char ConfigFileName[MAXBUF];
421
422         /** Mode handler, handles mode setting and removal
423          */
424         ModeParser* Modes;
425
426         /** Command parser, handles client to server commands
427          */
428         CommandParser* Parser;
429
430         /** Socket engine, handles socket activity events
431          */
432         SocketEngine* SE;
433
434         /** Stats class, holds miscellaneous stats counters
435          */
436         serverstats* stats;
437
438         /**  Server Config class, holds configuration file data
439          */
440         ServerConfig* Config;
441
442         /** Snomask manager - handles routing of snomask messages
443          * to opers.
444          */
445         SnomaskManager* SNO;
446
447         /** Client list, a hash_map containing all clients, local and remote
448          */
449         user_hash* clientlist;
450
451         /** Channel list, a hash_map containing all channels
452          */
453         chan_hash* chanlist;
454
455         /** Local client list, a vector containing only local clients
456          */
457         std::vector<userrec*> local_users;
458
459         /** Oper list, a vector containing all local and remote opered users
460          */
461         std::vector<userrec*> all_opers;
462
463         /** Map of local ip addresses for clone counting
464          */
465         clonemap local_clones;
466
467         /** Map of global ip addresses for clone counting
468          */
469         clonemap global_clones;
470
471         /** DNS class, provides resolver facilities to the core and modules
472          */
473         DNS* Res;
474
475         /** Timer manager class, triggers InspTimer timer events
476          */
477         TimerManager* Timers;
478
479         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
480          */
481         XLineManager* XLines;
482
483         /** A list of Module* module classes
484          * Note that this list is always exactly 255 in size.
485          * The actual number of loaded modules is available from GetModuleCount()
486          */
487         ModuleList modules;
488
489         /** A list of ModuleFactory* module factories
490          * Note that this list is always exactly 255 in size.
491          * The actual number of loaded modules is available from GetModuleCount()
492          */
493         FactoryList factory;
494
495         /** The time we next call our ping timeout and reg timeout checks
496          */
497         time_t next_call;
498
499         /** Set to the current signal recieved
500          */
501         int s_signal;
502
503         /** Get the current time
504          * Because this only calls time() once every time around the mainloop,
505          * it is much faster than calling time() directly.
506          * @param delta True to use the delta as an offset, false otherwise
507          * @return The current time as an epoch value (time_t)
508          */
509         time_t Time(bool delta = false);
510
511         /** Set the time offset in seconds
512          * This offset is added to Time() to offset the system time by the specified
513          * number of seconds.
514          * @param delta The number of seconds to offset
515          * @return The old time delta
516          */
517         int SetTimeDelta(int delta);
518
519         /** Add a user to the local clone map
520          * @param user The user to add
521          */
522         void AddLocalClone(userrec* user);
523
524         /** Add a user to the global clone map
525          * @param user The user to add
526          */
527         void AddGlobalClone(userrec* user);
528
529         /** Number of users with a certain mode set on them
530          */
531         int ModeCount(const char mode);
532
533         /** Get the time offset in seconds
534          * @return The current time delta (in seconds)
535          */
536         int GetTimeDelta();
537
538         /** Process a user whos socket has been flagged as active
539          * @param cu The user to process
540          * @return There is no actual return value, however upon exit, the user 'cu' may have been
541          * marked for deletion in the global CullList.
542          */
543         caller1<void, userrec*> ProcessUser;
544
545         /** Get the total number of currently loaded modules
546          * @return The number of loaded modules
547          */
548         int GetModuleCount();
549
550         /** Find a module by name, and return a Module* to it.
551          * This is preferred over iterating the module lists yourself.
552          * @param name The module name to look up
553          * @return A pointer to the module, or NULL if the module cannot be found
554          */
555         Module* FindModule(const std::string &name);
556
557         /** Bind all ports specified in the configuration file.
558          * @param bail True if the function should bail back to the shell on failure
559          * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
560          * @return The number of ports actually bound without error
561          */
562         int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
563
564         /** Binds a socket on an already open file descriptor
565          * @param sockfd A valid file descriptor of an open socket
566          * @param port The port number to bind to
567          * @param addr The address to bind to (IP only)
568          * @return True if the port was bound successfully
569          */
570         bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
571
572         /** Adds a server name to the list of servers we've seen
573          * @param The servername to add
574          */
575         void AddServerName(const std::string &servername);
576
577         /** Finds a cached char* pointer of a server name,
578          * This is used to optimize userrec by storing only the pointer to the name
579          * @param The servername to find
580          * @return A pointer to this name, gauranteed to never become invalid
581          */
582         const char* FindServerNamePtr(const std::string &servername);
583
584         /** Returns true if we've seen the given server name before
585          * @param The servername to find
586          * @return True if we've seen this server name before
587          */
588         bool FindServerName(const std::string &servername);
589
590         /** Gets the GECOS (description) field of the given server.
591          * If the servername is not that of the local server, the name
592          * is passed to handling modules which will attempt to determine
593          * the GECOS that bleongs to the given servername.
594          * @param servername The servername to find the description of
595          * @return The description of this server, or of the local server
596          */
597         std::string GetServerDescription(const char* servername);
598
599         /** Write text to all opers connected to this server
600          * @param text The text format string
601          * @param ... Format args
602          */
603         void WriteOpers(const char* text, ...);
604
605         /** Write text to all opers connected to this server
606          * @param text The text to send
607          */
608         void WriteOpers(const std::string &text);
609
610         /** Find a nickname in the nick hash
611          * @param nick The nickname to find
612          * @return A pointer to the user, or NULL if the user does not exist
613          */
614         userrec* FindNick(const std::string &nick);
615
616         /** Find a nickname in the nick hash
617          * @param nick The nickname to find
618          * @return A pointer to the user, or NULL if the user does not exist
619          */
620         userrec* FindNick(const char* nick);
621
622         /** Find a channel in the channels hash
623          * @param chan The channel to find
624          * @return A pointer to the channel, or NULL if the channel does not exist
625          */
626         chanrec* FindChan(const std::string &chan);
627
628         /** Find a channel in the channels hash
629          * @param chan The channel to find
630          * @return A pointer to the channel, or NULL if the channel does not exist
631          */
632         chanrec* FindChan(const char* chan);
633
634         /** Called by the constructor to load all modules from the config file.
635          */
636         void LoadAllModules();
637
638         /** Check for a 'die' tag in the config file, and abort if found
639          * @return Depending on the configuration, this function may never return
640          */
641         void CheckDie();
642
643         /** Check we aren't running as root, and exit if we are
644          * @return Depending on the configuration, this function may never return
645          */
646         void CheckRoot();
647
648         /** Determine the right path for, and open, the logfile
649          * @param argv The argv passed to main() initially, used to calculate program path
650          * @param argc The argc passed to main() initially, used to calculate program path
651          */
652         void OpenLog(char** argv, int argc);
653
654         /** Close the currently open log file
655          */
656         void CloseLog();
657
658         /** Send a server notice to all local users
659          * @param text The text format string to send
660          * @param ... The format arguments
661          */
662         void ServerNoticeAll(char* text, ...);
663
664         /** Send a server message (PRIVMSG) to all local users
665          * @param text The text format string to send
666          * @param ... The format arguments
667          */
668         void ServerPrivmsgAll(char* text, ...);
669
670         /** Send text to all users with a specific set of modes
671          * @param modes The modes to check against, without a +, e.g. 'og'
672          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
673          * mode characters in the first parameter causes receipt of the message, and
674          * if you specify WM_OR, all the modes must be present.
675          * @param text The text format string to send
676          * @param ... The format arguments
677          */
678         void WriteMode(const char* modes, int flags, const char* text, ...);
679
680         /** Return true if a channel name is valid
681          * @param chname A channel name to verify
682          * @return True if the name is valid
683          */
684         bool IsChannel(const char *chname);
685
686         /** Rehash the local server
687          */
688         void Rehash();
689
690         /** Handles incoming signals after being set
691          * @param signal the signal recieved
692          */
693         void SignalHandler(int signal);
694
695         /** Sets the signal recieved    
696          * @param signal the signal recieved
697          */
698         static void SetSignal(int signal);
699
700         /** Causes the server to exit after unloading modules and
701          * closing all open file descriptors.
702          *
703          * @param The exit code to give to the operating system
704          * (See the ExitStatus enum for valid values)
705          */
706         void Exit(int status);
707
708         /** Causes the server to exit immediately with exit code 0.
709          * The status code is required for signal handlers, and ignored.
710          */
711         static void QuickExit(int status);
712
713         /** Return a count of users, unknown and known connections
714          * @return The number of users
715          */
716         int UserCount();
717
718         /** Return a count of fully registered connections only
719          * @return The number of registered users
720          */
721         int RegisteredUserCount();
722
723         /** Return a count of invisible (umode +i) users only
724          * @return The number of invisible users
725          */
726         int InvisibleUserCount();
727
728         /** Return a count of opered (umode +o) users only
729          * @return The number of opers
730          */
731         int OperCount();
732
733         /** Return a count of unregistered (before NICK/USER) users only
734          * @return The number of unregistered (unknown) connections
735          */
736         int UnregisteredUserCount();
737
738         /** Return a count of channels on the network
739          * @return The number of channels
740          */
741         long ChannelCount();
742
743         /** Return a count of local users on this server only
744          * @return The number of local users
745          */
746         long LocalUserCount();
747
748         /** Send an error notice to all local users, opered and unopered
749          * @param s The error string to send
750          */
751         void SendError(const std::string &s);
752
753         /** For use with Module::Prioritize().
754          * When the return value of this function is returned from
755          * Module::Prioritize(), this specifies that the module wishes
756          * to be ordered exactly BEFORE 'modulename'. For more information
757          * please see Module::Prioritize().
758          * @param modulename The module your module wants to be before in the call list
759          * @returns a priority ID which the core uses to relocate the module in the list
760          */
761         long PriorityBefore(const std::string &modulename);
762
763         /** For use with Module::Prioritize().
764          * When the return value of this function is returned from
765          * Module::Prioritize(), this specifies that the module wishes
766          * to be ordered exactly AFTER 'modulename'. For more information please
767          * see Module::Prioritize().
768          * @param modulename The module your module wants to be after in the call list
769          * @returns a priority ID which the core uses to relocate the module in the list
770          */
771         long PriorityAfter(const std::string &modulename);
772
773         /** Publish a 'feature'.
774          * There are two ways for a module to find another module it depends on.
775          * Either by name, using InspIRCd::FindModule, or by feature, using this
776          * function. A feature is an arbitary string which identifies something this
777          * module can do. For example, if your module provides SSL support, but other
778          * modules provide SSL support too, all the modules supporting SSL should
779          * publish an identical 'SSL' feature. This way, any module requiring use
780          * of SSL functions can just look up the 'SSL' feature using FindFeature,
781          * then use the module pointer they are given.
782          * @param FeatureName The case sensitive feature name to make available
783          * @param Mod a pointer to your module class
784          * @returns True on success, false if the feature is already published by
785          * another module.
786          */
787         bool PublishFeature(const std::string &FeatureName, Module* Mod);
788
789         /** Publish a module to an 'interface'.
790          * Modules which implement the same interface (the same way of communicating
791          * with other modules) can publish themselves to an interface, using this
792          * method. When they do so, they become part of a list of related or
793          * compatible modules, and a third module may then query for that list
794          * and know that all modules within that list offer the same API.
795          * A prime example of this is the hashing modules, which all accept the
796          * same types of Request class. Consider this to be similar to PublishFeature,
797          * except for that multiple modules may publish the same 'feature'.
798          * @param InterfaceName The case sensitive interface name to make available
799          * @param Mod a pointer to your module class
800          * @returns True on success, false on failure (there are currently no failure
801          * cases)
802          */
803         bool PublishInterface(const std::string &InterfaceName, Module* Mod);
804
805         /** Return a pair saying how many other modules are currently using the
806          * interfaces provided by module m.
807          * @param m The module to count usage for
808          * @return A pair, where the first value is the number of uses of the interface,
809          * and the second value is the interface name being used.
810          */
811         std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
812
813         /** Mark your module as using an interface.
814          * If you mark your module as using an interface, then that interface
815          * module may not unload until your module has unloaded first.
816          * This can be used to prevent crashes by ensuring code you depend on
817          * is always in memory while your module is active.
818          * @param InterfaceName The interface to use
819          */
820         void UseInterface(const std::string &InterfaceName);
821
822         /** Mark your module as finished with an interface.
823          * If you used UseInterface() above, you should use this method when
824          * your module is finished with the interface (usually in its destructor)
825          * to allow the modules which implement the given interface to be unloaded.
826          * @param InterfaceName The interface you are finished with using.
827          */
828         void DoneWithInterface(const std::string &InterfaceName);
829
830         /** Unpublish a 'feature'.
831          * When your module exits, it must call this method for every feature it
832          * is providing so that the feature table is cleaned up.
833          * @param FeatureName the feature to remove
834          */
835         bool UnpublishFeature(const std::string &FeatureName);
836
837         /** Unpublish your module from an interface
838          * When your module exits, it must call this method for every interface
839          * it is part of so that the interfaces table is cleaned up. Only when
840          * the last item is deleted from an interface does the interface get
841          * removed.
842          * @param InterfaceName the interface to be removed from
843          * @param Mod The module to remove from the interface list
844          */
845         bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
846
847         /** Find a 'feature'.
848          * There are two ways for a module to find another module it depends on.
849          * Either by name, using InspIRCd::FindModule, or by feature, using the
850          * InspIRCd::PublishFeature method. A feature is an arbitary string which
851          * identifies something this module can do. For example, if your module
852          * provides SSL support, but other modules provide SSL support too, all
853          * the modules supporting SSL should publish an identical 'SSL' feature.
854          * To find a module capable of providing the feature you want, simply
855          * call this method with the feature name you are looking for.
856          * @param FeatureName The feature name you wish to obtain the module for
857          * @returns A pointer to a valid module class on success, NULL on failure.
858          */
859         Module* FindFeature(const std::string &FeatureName);
860
861         /** Find an 'interface'.
862          * An interface is a list of modules which all implement the same API.
863          * @param InterfaceName The Interface you wish to obtain the module
864          * list of.
865          * @return A pointer to a deque of Module*, or NULL if the interface
866          * does not exist.
867          */
868         modulelist* FindInterface(const std::string &InterfaceName);
869
870         /** Given a pointer to a Module, return its filename
871          * @param m The module pointer to identify
872          * @return The module name or an empty string
873          */
874         const std::string& GetModuleName(Module* m);
875
876         /** Return true if a nickname is valid
877          * @param n A nickname to verify
878          * @return True if the nick is valid
879          */
880         caller1<bool, const char*> IsNick;
881
882         /** Return true if an ident is valid
883          * @param An ident to verify
884          * @return True if the ident is valid
885          */
886         caller1<bool, const char*> IsIdent;
887
888         /** Find a username by their file descriptor.
889          * It is preferred to use this over directly accessing the fd_ref_table array.
890          * @param socket The file descriptor of a user
891          * @return A pointer to the user if the user exists locally on this descriptor
892          */
893         caller1<userrec*, int> FindDescriptor;
894
895         /** Add a new mode to this server's mode parser
896          * @param mh The modehandler to add
897          * @param modechar The mode character this modehandler handles
898          * @return True if the mode handler was added
899          */
900         bool AddMode(ModeHandler* mh, const unsigned char modechar);
901
902         /** Add a new mode watcher to this server's mode parser
903          * @param mw The modewatcher to add
904          * @return True if the modewatcher was added
905          */
906         bool AddModeWatcher(ModeWatcher* mw);
907
908         /** Delete a mode watcher from this server's mode parser
909          * @param mw The modewatcher to delete
910          * @return True if the modewatcher was deleted
911          */
912         bool DelModeWatcher(ModeWatcher* mw);
913
914         /** Add a dns Resolver class to this server's active set
915          * @param r The resolver to add
916          * @param cached If this value is true, then the cache will
917          * be searched for the DNS result, immediately. If the value is
918          * false, then a request will be sent to the nameserver, and the
919          * result will not be immediately available. You should usually
920          * use the boolean value which you passed to the Resolver
921          * constructor, which Resolver will set appropriately depending
922          * on if cached results are available and haven't expired. It is
923          * however safe to force this value to false, forcing a remote DNS
924          * lookup, but not an update of the cache.
925          * @return True if the operation completed successfully. Note that
926          * if this method returns true, you should not attempt to access
927          * the resolver class you pass it after this call, as depending upon
928          * the request given, the object may be deleted!
929          */
930         bool AddResolver(Resolver* r, bool cached);
931
932         /** Add a command to this server's command parser
933          * @param f A command_t command handler object to add
934          * @throw ModuleException Will throw ModuleExcption if the command already exists
935          */
936         void AddCommand(command_t *f);
937
938         /** Send a modechange.
939          * The parameters provided are identical to that sent to the
940          * handler for class cmd_mode.
941          * @param parameters The mode parameters
942          * @param pcnt The number of items you have given in the first parameter
943          * @param user The user to send error messages to
944          */
945         void SendMode(const char **parameters, int pcnt, userrec *user);
946
947         /** Match two strings using pattern matching.
948          * This operates identically to the global function match(),
949          * except for that it takes std::string arguments rather than
950          * const char* ones.
951          * @param sliteral The literal string to match against
952          * @param spattern The pattern to match against. CIDR and globs are supported.
953          */
954         bool MatchText(const std::string &sliteral, const std::string &spattern);
955
956         /** Call the handler for a given command.
957          * @param commandname The command whos handler you wish to call
958          * @param parameters The mode parameters
959          * @param pcnt The number of items you have given in the first parameter
960          * @param user The user to execute the command as
961          * @return True if the command handler was called successfully
962          */
963         CmdResult CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
964
965         /** Return true if the command is a module-implemented command and the given parameters are valid for it
966          * @param parameters The mode parameters
967          * @param pcnt The number of items you have given in the first parameter
968          * @param user The user to test-execute the command as
969          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
970          */
971         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
972
973         /** Add a gline and apply it
974          * @param duration How long the line should last
975          * @param source Who set the line
976          * @param reason The reason for the line
977          * @param hostmask The hostmask to set the line against
978          */
979         void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
980
981         /** Add a qline and apply it
982          * @param duration How long the line should last
983          * @param source Who set the line
984          * @param reason The reason for the line
985          * @param nickname The nickmask to set the line against
986          */
987         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
988
989         /** Add a zline and apply it
990          * @param duration How long the line should last
991          * @param source Who set the line
992          * @param reason The reason for the line
993          * @param ipaddr The ip-mask to set the line against
994          */
995         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
996
997         /** Add a kline and apply it
998          * @param duration How long the line should last
999          * @param source Who set the line
1000          * @param reason The reason for the line
1001          * @param hostmask The hostmask to set the line against
1002          */
1003         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1004
1005         /** Add an eline
1006          * @param duration How long the line should last
1007          * @param source Who set the line
1008          * @param reason The reason for the line
1009          * @param hostmask The hostmask to set the line against
1010          */
1011         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1012
1013         /** Delete a gline
1014          * @param hostmask The gline to delete
1015          * @return True if the item was removed
1016          */
1017         bool DelGLine(const std::string &hostmask);
1018
1019         /** Delete a qline
1020          * @param nickname The qline to delete
1021          * @return True if the item was removed
1022          */
1023         bool DelQLine(const std::string &nickname);
1024
1025         /** Delete a zline
1026          * @param ipaddr The zline to delete
1027          * @return True if the item was removed
1028          */
1029         bool DelZLine(const std::string &ipaddr);
1030
1031         /** Delete a kline
1032          * @param hostmask The kline to delete
1033          * @return True if the item was removed
1034          */
1035         bool DelKLine(const std::string &hostmask);
1036
1037         /** Delete an eline
1038          * @param hostmask The kline to delete
1039          * @return True if the item was removed
1040          */
1041         bool DelELine(const std::string &hostmask);
1042
1043         /** Return true if the given parameter is a valid nick!user\@host mask
1044          * @param mask A nick!user\@host masak to match against
1045          * @return True i the mask is valid
1046          */
1047         bool IsValidMask(const std::string &mask);
1048
1049         /** Rehash the local server
1050          */
1051         void RehashServer();
1052
1053         /** Return the channel whos index number matches that provided
1054          * @param The index number of the channel to fetch
1055          * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1056          */
1057         chanrec* GetChannelIndex(long index);
1058
1059         /** Dump text to a user target, splitting it appropriately to fit
1060          * @param User the user to dump the text to
1061          * @param LinePrefix text to prefix each complete line with
1062          * @param TextStream the text to send to the user
1063          */
1064         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1065
1066         /** Check if the given nickmask matches too many users, send errors to the given user
1067          * @param nick A nickmask to match against
1068          * @param user A user to send error text to
1069          * @return True if the nick matches too many users
1070          */
1071         bool NickMatchesEveryone(const std::string &nick, userrec* user);
1072
1073         /** Check if the given IP mask matches too many users, send errors to the given user
1074          * @param ip An ipmask to match against
1075          * @param user A user to send error text to
1076          * @return True if the ip matches too many users
1077          */
1078         bool IPMatchesEveryone(const std::string &ip, userrec* user);
1079
1080         /** Check if the given hostmask matches too many users, send errors to the given user
1081          * @param mask A hostmask to match against
1082          * @param user A user to send error text to
1083          * @return True if the host matches too many users
1084          */
1085         bool HostMatchesEveryone(const std::string &mask, userrec* user);
1086
1087         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1088          * @param str A string containing a time in the form 1y2w3d4h6m5s
1089          * (one year, two weeks, three days, four hours, six minutes and five seconds)
1090          * @return The total number of seconds
1091          */
1092         long Duration(const std::string &str);
1093
1094         /** Attempt to compare an oper password to a string from the config file.
1095          * This will be passed to handling modules which will compare the data
1096          * against possible hashed equivalents in the input string.
1097          * @param data The data from the config file
1098          * @param input The data input by the oper
1099          * @param tagnum the tag number of the oper's tag in the config file
1100          * @return 0 if the strings match, 1 or -1 if they do not
1101          */
1102         int OperPassCompare(const char* data,const char* input, int tagnum);
1103
1104         /** Check if a given server is a uline.
1105          * An empty string returns true, this is by design.
1106          * @param server The server to check for uline status
1107          * @return True if the server is a uline OR the string is empty
1108          */
1109         bool ULine(const char* server);
1110
1111         /** Returns true if the uline is 'silent' (doesnt generate
1112          * remote connect notices etc).
1113          */
1114         bool SilentULine(const char* server);
1115
1116         /** Returns the subversion revision ID of this ircd
1117          * @return The revision ID or an empty string
1118          */
1119         std::string GetRevision();
1120
1121         /** Returns the full version string of this ircd
1122          * @return The version string
1123          */
1124         std::string GetVersionString();
1125
1126         /** Attempt to write the process id to a given file
1127          * @param filename The PID file to attempt to write to
1128          * @return This function may bail if the file cannot be written
1129          */
1130         void WritePID(const std::string &filename);
1131
1132         /** Returns text describing the last module error
1133          * @return The last error message to occur
1134          */
1135         char* ModuleError();
1136
1137         /** Load a given module file
1138          * @param filename The file to load
1139          * @return True if the module was found and loaded
1140          */
1141         bool LoadModule(const char* filename);
1142
1143         /** Unload a given module file
1144          * @param filename The file to unload
1145          * @return True if the module was unloaded
1146          */
1147         bool UnloadModule(const char* filename);
1148
1149         /** This constructor initialises all the subsystems and reads the config file.
1150          * @param argc The argument count passed to main()
1151          * @param argv The argument list passed to main()
1152          * @throw <anything> If anything is thrown from here and makes it to
1153          * you, you should probably just give up and go home. Yes, really.
1154          * It's that bad. Higher level classes should catch any non-fatal exceptions.
1155          */
1156         InspIRCd(int argc, char** argv);
1157
1158         /** Do one iteration of the mainloop
1159          * @param process_module_sockets True if module sockets are to be processed
1160          * this time around the event loop. The is the default.
1161          */
1162         void DoOneIteration(bool process_module_sockets = true);
1163
1164         /** Output a log message to the ircd.log file
1165          * The text will only be output if the current loglevel
1166          * is less than or equal to the level you provide
1167          * @param level A log level from the DebugLevel enum
1168          * @param text Format string of to write to the log
1169          * @param ... Format arguments of text to write to the log
1170          */
1171         void Log(int level, const char* text, ...);
1172
1173         /** Output a log message to the ircd.log file
1174          * The text will only be output if the current loglevel
1175          * is less than or equal to the level you provide
1176          * @param level A log level from the DebugLevel enum
1177          * @param text Text to write to the log
1178          */
1179         void Log(int level, const std::string &text);
1180
1181         /** Send a line of WHOIS data to a user.
1182          * @param user user to send the line to
1183          * @param dest user being WHOISed
1184          * @param numeric Numeric to send
1185          * @param text Text of the numeric
1186          */
1187         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1188
1189         /** Send a line of WHOIS data to a user.
1190          * @param user user to send the line to
1191          * @param dest user being WHOISed
1192          * @param numeric Numeric to send
1193          * @param format Format string for the numeric
1194          * @param ... Parameters for the format string
1195          */
1196         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1197
1198         /** Quit a user for excess flood, and if they are not
1199          * fully registered yet, temporarily zline their IP.
1200          * @param current user to quit
1201          */
1202         caller1<void, userrec*> FloodQuitUser;
1203
1204         /** Restart the server.
1205          * This function will not return. If an error occurs,
1206          * it will throw an instance of CoreException.
1207          * @param reason The restart reason to show to all clients
1208          * @throw CoreException An instance of CoreException indicating the error from execv().
1209          */
1210         void Restart(const std::string &reason);
1211
1212         /** Prepare the ircd for restart or shutdown.
1213          * This function unloads all modules which can be unloaded,
1214          * closes all open sockets, and closes the logfile.
1215          */
1216         void Cleanup();
1217
1218         /** This copies the user and channel hash_maps into new hash maps.
1219          * This frees memory used by the hash_map allocator (which it neglects
1220          * to free, most of the time, using tons of ram)
1221          */
1222         void RehashUsersAndChans();
1223
1224         /** Resets the cached max bans value on all channels.
1225          * Called by rehash.
1226          */
1227         void ResetMaxBans();
1228
1229         /** Return a time_t as a human-readable string.
1230          */
1231         std::string TimeString(time_t curtime);
1232
1233         /** Begin execution of the server.
1234          * NOTE: this function NEVER returns. Internally,
1235          * after performing some initialisation routines,
1236          * it will repeatedly call DoOneIteration in a loop.
1237          * @return The return value for this function is undefined.
1238          */
1239         int Run();
1240
1241         /** Force all InspSockets to be removed which are due to
1242          * be culled.
1243          */
1244         void InspSocketCull();
1245
1246         char* GetReadBuffer()
1247         {
1248                 return this->ReadBuffer;
1249         }
1250 };
1251
1252 #endif
1253