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