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