]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
4aa61e943ba254175248b4a7005619a10128c3f1
[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         /** Convert a user to a pseudoclient, disconnecting the real user
608          * @param user The user to convert
609          * @param message The quit message to display when exiting the user
610          * @return True if the operation succeeded
611          */
612         bool UserToPseudo(userrec* user, const std::string &message);
613
614         /** Convert a pseudoclient to a real user, discarding the pseudoclient
615          * @param alive A live client
616          * @param zombie A pseudoclient
617          * @param message The message to display when quitting the pseudoclient
618          * @return True if the operation succeeded
619          */
620         bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
621
622         /** Send a server notice to all local users
623          * @param text The text format string to send
624          * @param ... The format arguments
625          */
626         void ServerNoticeAll(char* text, ...);
627
628         /** Send a server message (PRIVMSG) to all local users
629          * @param text The text format string to send
630          * @param ... The format arguments
631          */
632         void ServerPrivmsgAll(char* text, ...);
633
634         /** Send text to all users with a specific set of modes
635          * @param modes The modes to check against, without a +, e.g. 'og'
636          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the 
637          * mode characters in the first parameter causes receipt of the message, and
638          * if you specify WM_OR, all the modes must be present.
639          * @param text The text format string to send
640          * @param ... The format arguments
641          */
642         void WriteMode(const char* modes, int flags, const char* text, ...);
643
644         /** Return true if a channel name is valid
645          * @param chname A channel name to verify
646          * @return True if the name is valid
647          */
648         bool IsChannel(const char *chname);
649
650         /** Rehash the local server
651          * @param status This value is unused, and required for signal handler functions
652          */
653         static void Rehash(int status);
654
655         /** Causes the server to exit immediately
656          * @param The exit code to give to the operating system
657          * (See the ExitStatus enum for valid values)
658          */
659         static void Exit(int status);
660
661         /** Return a count of users, unknown and known connections
662          * @return The number of users
663          */
664         int UserCount();
665
666         /** Return a count of fully registered connections only
667          * @return The number of registered users
668          */
669         int RegisteredUserCount();
670
671         /** Return a count of invisible (umode +i) users only
672          * @return The number of invisible users
673          */
674         int InvisibleUserCount();
675
676         /** Return a count of opered (umode +o) users only
677          * @return The number of opers
678          */
679         int OperCount();
680
681         /** Return a count of unregistered (before NICK/USER) users only
682          * @return The number of unregistered (unknown) connections
683          */
684         int UnregisteredUserCount();
685
686         /** Return a count of channels on the network
687          * @return The number of channels
688          */
689         long ChannelCount();
690
691         /** Return a count of local users on this server only
692          * @return The number of local users
693          */
694         long LocalUserCount();
695
696         /** Send an error notice to all local users, opered and unopered
697          * @param s The error string to send
698          */
699         void SendError(const std::string &s);
700
701         /** For use with Module::Prioritize().
702          * When the return value of this function is returned from
703          * Module::Prioritize(), this specifies that the module wishes
704          * to be ordered exactly BEFORE 'modulename'. For more information
705          * please see Module::Prioritize().
706          * @param modulename The module your module wants to be before in the call list
707          * @returns a priority ID which the core uses to relocate the module in the list
708          */
709         long PriorityBefore(const std::string &modulename);
710
711         /** For use with Module::Prioritize().
712          * When the return value of this function is returned from
713          * Module::Prioritize(), this specifies that the module wishes
714          * to be ordered exactly AFTER 'modulename'. For more information please
715          * see Module::Prioritize().
716          * @param modulename The module your module wants to be after in the call list
717          * @returns a priority ID which the core uses to relocate the module in the list
718          */
719         long PriorityAfter(const std::string &modulename);
720
721         /** Publish a 'feature'.
722          * There are two ways for a module to find another module it depends on.
723          * Either by name, using InspIRCd::FindModule, or by feature, using this
724          * function. A feature is an arbitary string which identifies something this
725          * module can do. For example, if your module provides SSL support, but other
726          * modules provide SSL support too, all the modules supporting SSL should
727          * publish an identical 'SSL' feature. This way, any module requiring use
728          * of SSL functions can just look up the 'SSL' feature using FindFeature,
729          * then use the module pointer they are given.
730          * @param FeatureName The case sensitive feature name to make available
731          * @param Mod a pointer to your module class
732          * @returns True on success, false if the feature is already published by
733          * another module.
734          */
735         bool PublishFeature(const std::string &FeatureName, Module* Mod);
736
737         /** Publish a module to an 'interface'.
738          * Modules which implement the same interface (the same way of communicating
739          * with other modules) can publish themselves to an interface, using this
740          * method. When they do so, they become part of a list of related or
741          * compatible modules, and a third module may then query for that list
742          * and know that all modules within that list offer the same API.
743          * A prime example of this is the hashing modules, which all accept the
744          * same types of Request class. Consider this to be similar to PublishFeature,
745          * except for that multiple modules may publish the same 'feature'.
746          * @param InterfaceName The case sensitive interface name to make available
747          * @param Mod a pointer to your module class
748          * @returns True on success, false on failure (there are currently no failure
749          * cases)
750          */
751         bool PublishInterface(const std::string &InterfaceName, Module* Mod);
752
753         /** Return a pair saying how many other modules are currently using the
754          * interfaces provided by module m.
755          * @param m The module to count usage for
756          * @return A pair, where the first value is the number of uses of the interface,
757          * and the second value is the interface name being used.
758          */
759         std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
760
761         /** Mark your module as using an interface.
762          * If you mark your module as using an interface, then that interface
763          * module may not unload until your module has unloaded first.
764          * This can be used to prevent crashes by ensuring code you depend on
765          * is always in memory while your module is active.
766          * @param InterfaceName The interface to use
767          */
768         void UseInterface(const std::string &InterfaceName);
769
770         /** Mark your module as finished with an interface.
771          * If you used UseInterface() above, you should use this method when
772          * your module is finished with the interface (usually in its destructor)
773          * to allow the modules which implement the given interface to be unloaded.
774          * @param InterfaceName The interface you are finished with using.
775          */
776         void DoneWithInterface(const std::string &InterfaceName);
777
778         /** Unpublish a 'feature'.
779          * When your module exits, it must call this method for every feature it
780          * is providing so that the feature table is cleaned up.
781          * @param FeatureName the feature to remove
782          */
783         bool UnpublishFeature(const std::string &FeatureName);
784
785         /** Unpublish your module from an interface
786          * When your module exits, it must call this method for every interface
787          * it is part of so that the interfaces table is cleaned up. Only when
788          * the last item is deleted from an interface does the interface get
789          * removed.
790          * @param InterfaceName the interface to be removed from
791          * @param Mod The module to remove from the interface list
792          */
793         bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
794
795         /** Find a 'feature'.
796          * There are two ways for a module to find another module it depends on.
797          * Either by name, using InspIRCd::FindModule, or by feature, using the
798          * InspIRCd::PublishFeature method. A feature is an arbitary string which
799          * identifies something this module can do. For example, if your module
800          * provides SSL support, but other modules provide SSL support too, all
801          * the modules supporting SSL should publish an identical 'SSL' feature.
802          * To find a module capable of providing the feature you want, simply
803          * call this method with the feature name you are looking for.
804          * @param FeatureName The feature name you wish to obtain the module for
805          * @returns A pointer to a valid module class on success, NULL on failure.
806          */
807         Module* FindFeature(const std::string &FeatureName);
808
809         /** Find an 'interface'.
810          * An interface is a list of modules which all implement the same API.
811          * @param InterfaceName The Interface you wish to obtain the module
812          * list of.
813          * @return A pointer to a deque of Module*, or NULL if the interface
814          * does not exist.
815          */
816         modulelist* FindInterface(const std::string &InterfaceName);
817
818         /** Given a pointer to a Module, return its filename
819          * @param m The module pointer to identify
820          * @return The module name or an empty string
821          */
822         const std::string& GetModuleName(Module* m);
823
824         /** Return true if a nickname is valid
825          * @param n A nickname to verify
826          * @return True if the nick is valid
827          */
828         bool IsNick(const char* n);
829
830         /** Return true if an ident is valid
831          * @param An ident to verify
832          * @return True if the ident is valid
833          */
834         bool IsIdent(const char* n);
835
836         /** Find a username by their file descriptor.
837          * It is preferred to use this over directly accessing the fd_ref_table array.
838          * @param socket The file descriptor of a user
839          * @return A pointer to the user if the user exists locally on this descriptor
840          */
841         userrec* FindDescriptor(int socket);
842
843         /** Add a new mode to this server's mode parser
844          * @param mh The modehandler to add
845          * @param modechar The mode character this modehandler handles
846          * @return True if the mode handler was added
847          */
848         bool AddMode(ModeHandler* mh, const unsigned char modechar);
849
850         /** Add a new mode watcher to this server's mode parser
851          * @param mw The modewatcher to add
852          * @return True if the modewatcher was added
853          */
854         bool AddModeWatcher(ModeWatcher* mw);
855
856         /** Delete a mode watcher from this server's mode parser
857          * @param mw The modewatcher to delete
858          * @return True if the modewatcher was deleted
859          */
860         bool DelModeWatcher(ModeWatcher* mw);
861
862         /** Add a dns Resolver class to this server's active set
863          * @param r The resolver to add
864          * @return True if the resolver was added
865          */
866         bool AddResolver(Resolver* r);
867
868         /** Add a command to this server's command parser
869          * @param f A command_t command handler object to add
870          * @throw ModuleException Will throw ModuleExcption if the command already exists
871          */
872         void AddCommand(command_t *f);
873
874         /** Send a modechange.
875          * The parameters provided are identical to that sent to the
876          * handler for class cmd_mode.
877          * @param parameters The mode parameters
878          * @param pcnt The number of items you have given in the first parameter
879          * @param user The user to send error messages to
880          */
881         void SendMode(const char **parameters, int pcnt, userrec *user);
882
883         /** Match two strings using pattern matching.
884          * This operates identically to the global function match(),
885          * except for that it takes std::string arguments rather than
886          * const char* ones.
887          * @param sliteral The literal string to match against
888          * @param spattern The pattern to match against. CIDR and globs are supported.
889          */
890         bool MatchText(const std::string &sliteral, const std::string &spattern);
891
892         /** Call the handler for a given command.
893          * @param commandname The command whos handler you wish to call
894          * @param parameters The mode parameters
895          * @param pcnt The number of items you have given in the first parameter
896          * @param user The user to execute the command as
897          * @return True if the command handler was called successfully
898          */
899         bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
900
901         /** Return true if the command is a module-implemented command and the given parameters are valid for it
902          * @param parameters The mode parameters
903          * @param pcnt The number of items you have given in the first parameter
904          * @param user The user to test-execute the command as
905          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
906          */
907         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
908
909         /** Add a gline and apply it
910          * @param duration How long the line should last
911          * @param source Who set the line
912          * @param reason The reason for the line
913          * @param hostmask The hostmask to set the line against
914          */
915         void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
916
917         /** Add a qline and apply it
918          * @param duration How long the line should last
919          * @param source Who set the line
920          * @param reason The reason for the line
921          * @param nickname The nickmask to set the line against
922          */
923         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
924
925         /** Add a zline and apply it
926          * @param duration How long the line should last
927          * @param source Who set the line
928          * @param reason The reason for the line
929          * @param ipaddr The ip-mask to set the line against
930          */
931         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
932
933         /** Add a kline and apply it
934          * @param duration How long the line should last
935          * @param source Who set the line
936          * @param reason The reason for the line
937          * @param hostmask The hostmask to set the line against
938          */
939         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
940
941         /** Add an eline
942          * @param duration How long the line should last
943          * @param source Who set the line
944          * @param reason The reason for the line
945          * @param hostmask The hostmask to set the line against
946          */
947         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
948
949         /** Delete a gline
950          * @param hostmask The gline to delete
951          * @return True if the item was removed
952          */
953         bool DelGLine(const std::string &hostmask);
954
955         /** Delete a qline
956          * @param nickname The qline to delete
957          * @return True if the item was removed
958          */
959         bool DelQLine(const std::string &nickname);
960
961         /** Delete a zline
962          * @param ipaddr The zline to delete
963          * @return True if the item was removed
964          */
965         bool DelZLine(const std::string &ipaddr);
966
967         /** Delete a kline
968          * @param hostmask The kline to delete
969          * @return True if the item was removed
970          */
971         bool DelKLine(const std::string &hostmask);
972
973         /** Delete an eline
974          * @param hostmask The kline to delete
975          * @return True if the item was removed
976          */
977         bool DelELine(const std::string &hostmask);
978
979         /** Return true if the given parameter is a valid nick!user\@host mask
980          * @param mask A nick!user\@host masak to match against 
981          * @return True i the mask is valid
982          */
983         bool IsValidMask(const std::string &mask);
984
985         /** Rehash the local server
986          */
987         void RehashServer();
988
989         /** Return the channel whos index number matches that provided
990          * @param The index number of the channel to fetch
991          * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
992          */
993         chanrec* GetChannelIndex(long index);
994
995         /** Dump text to a user target, splitting it appropriately to fit
996          * @param User the user to dump the text to
997          * @param LinePrefix text to prefix each complete line with
998          * @param TextStream the text to send to the user
999          */
1000         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1001
1002         /** Check if the given nickmask matches too many users, send errors to the given user
1003          * @param nick A nickmask to match against
1004          * @param user A user to send error text to
1005          * @return True if the nick matches too many users
1006          */
1007         bool NickMatchesEveryone(const std::string &nick, userrec* user);
1008
1009         /** Check if the given IP mask matches too many users, send errors to the given user
1010          * @param ip An ipmask to match against
1011          * @param user A user to send error text to
1012          * @return True if the ip matches too many users
1013          */
1014         bool IPMatchesEveryone(const std::string &ip, userrec* user);
1015
1016         /** Check if the given hostmask matches too many users, send errors to the given user
1017          * @param mask A hostmask to match against
1018          * @param user A user to send error text to
1019          * @return True if the host matches too many users
1020          */
1021         bool HostMatchesEveryone(const std::string &mask, userrec* user);
1022
1023         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1024          * @param str A string containing a time in the form 1y2w3d4h6m5s
1025          * (one year, two weeks, three days, four hours, six minutes and five seconds)
1026          * @return The total number of seconds
1027          */
1028         long Duration(const char* str);
1029
1030         /** Attempt to compare an oper password to a string from the config file.
1031          * This will be passed to handling modules which will compare the data
1032          * against possible hashed equivalents in the input string.
1033          * @param data The data from the config file
1034          * @param input The data input by the oper
1035          * @param tagnum the tag number of the oper's tag in the config file
1036          * @return 0 if the strings match, 1 or -1 if they do not
1037          */
1038         int OperPassCompare(const char* data,const char* input, int tagnum);
1039
1040         /** Check if a given server is a uline.
1041          * An empty string returns true, this is by design.
1042          * @param server The server to check for uline status
1043          * @return True if the server is a uline OR the string is empty
1044          */
1045         bool ULine(const char* server);
1046
1047         /** Returns the subversion revision ID of this ircd
1048          * @return The revision ID or an empty string
1049          */
1050         std::string GetRevision();
1051
1052         /** Returns the full version string of this ircd
1053          * @return The version string
1054          */
1055         std::string GetVersionString();
1056
1057         /** Attempt to write the process id to a given file
1058          * @param filename The PID file to attempt to write to
1059          * @return This function may bail if the file cannot be written
1060          */
1061         void WritePID(const std::string &filename);
1062
1063         /** Returns text describing the last module error
1064          * @return The last error message to occur
1065          */
1066         char* ModuleError();
1067
1068         /** Load a given module file
1069          * @param filename The file to load
1070          * @return True if the module was found and loaded
1071          */
1072         bool LoadModule(const char* filename);
1073
1074         /** Unload a given module file
1075          * @param filename The file to unload
1076          * @return True if the module was unloaded
1077          */
1078         bool UnloadModule(const char* filename);
1079
1080         /** This constructor initialises all the subsystems and reads the config file.
1081          * @param argc The argument count passed to main()
1082          * @param argv The argument list passed to main()
1083          * @throw <anything> If anything is thrown from here and makes it to
1084          * you, you should probably just give up and go home. Yes, really.
1085          * It's that bad. Higher level classes should catch any non-fatal exceptions.
1086          */
1087         InspIRCd(int argc, char** argv);
1088
1089         /** Do one iteration of the mainloop
1090          * @param process_module_sockets True if module sockets are to be processed
1091          * this time around the event loop. The is the default.
1092          */
1093         void DoOneIteration(bool process_module_sockets = true);
1094
1095         /** Output a log message to the ircd.log file
1096          * The text will only be output if the current loglevel
1097          * is less than or equal to the level you provide
1098          * @param level A log level from the DebugLevel enum
1099          * @param text Format string of to write to the log
1100          * @param ... Format arguments of text to write to the log
1101          */
1102         void Log(int level, const char* text, ...);
1103
1104         /** Output a log message to the ircd.log file
1105          * The text will only be output if the current loglevel
1106          * is less than or equal to the level you provide
1107          * @param level A log level from the DebugLevel enum
1108          * @param text Text to write to the log
1109          */
1110         void Log(int level, const std::string &text);
1111
1112         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1113
1114         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1115
1116         /** Restart the server.
1117          * This function will not return. If an error occurs,
1118          * it will throw an instance of CoreException.
1119          * @param reason The restart reason to show to all clients
1120          * @throw CoreException An instance of CoreException indicating the error from execv().
1121          */
1122         void Restart(const std::string &reason);
1123
1124         /** Prepare the ircd for restart or shutdown.
1125          * This function unloads all modules which can be unloaded,
1126          * closes all open sockets, and closes the logfile.
1127          */
1128         void Cleanup();
1129
1130         /** Begin execution of the server.
1131          * NOTE: this function NEVER returns. Internally,
1132          * after performing some initialisation routines,
1133          * it will repeatedly call DoOneIteration in a loop.
1134          * @return The return value for this function is undefined.
1135          */
1136         int Run();
1137 };
1138
1139 #endif
1140