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