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