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