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