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