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