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