]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Fix bug in m_dnsbl, a condition is always matched because someone was using unsigned...
[user/henk/code/inspircd.git] / include / inspircd.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef __INSPIRCD_H__
15 #define __INSPIRCD_H__
16
17 #include <time.h>
18 #include <string>
19 #include <sstream>
20 #include "inspircd_config.h"
21 #include "users.h"
22 #include "channels.h"
23 #include "socket.h"
24 #include "mode.h"
25 #include "socketengine.h"
26 #include "command_parse.h"
27 #include "snomasks.h"
28
29 /** Returned by some functions to indicate failure,
30  * and the exit code of the program if it terminates.
31  */
32 #define ERROR -1
33
34 /** Crucial defines
35  */
36 #define ETIREDGERBILS EAGAIN
37
38 /** Debug levels for use with InspIRCd::Log()
39  */
40 enum DebugLevel
41 {
42         DEBUG           =       10,
43         VERBOSE         =       20,
44         DEFAULT         =       30,
45         SPARSE          =       40,
46         NONE            =       50,
47 };
48
49 /**
50  * This define is used in place of strcmp when we 
51  * want to check if a char* string contains only one
52  * letter. Pretty fast, its just two compares and an
53  * addition.
54  */
55 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
56
57 /** Delete a pointer, and NULL its value
58  */
59 template<typename T> inline void DELETE(T* x)
60 {
61         delete x;
62         x = NULL;
63 }
64
65 /** Template function to convert any input type to std::string
66  */
67 template<typename T> inline std::string ConvToStr(const T &in)
68 {
69         std::stringstream tmp;
70         if (!(tmp << in)) return std::string();
71         return tmp.str();
72 }
73
74 template<typename T> inline long ConvToInt(const T &in)
75 {
76         std::stringstream tmp;
77         if (!(tmp << in)) return 0;
78         return atoi(tmp.str().c_str());
79 }
80
81 /** This class contains various STATS counters
82  * It is used by the InspIRCd class, which internally
83  * has an instance of it.
84  */
85 class serverstats : public classbase
86 {
87   public:
88         /** Number of accepted connections
89          */
90         unsigned long statsAccept;
91         /** Number of failed accepts
92          */
93         unsigned long statsRefused;
94         /** Number of unknown commands seen
95          */
96         unsigned long statsUnknown;
97         /** Number of nickname collisions handled
98          */
99         unsigned long statsCollisions;
100         /** Number of DNS queries sent out
101          */
102         unsigned long statsDns;
103         /** Number of good DNS replies received
104          * NOTE: This may not tally to the number sent out,
105          * due to timeouts and other latency issues.
106          */
107         unsigned long statsDnsGood;
108         /** Number of bad (negative) DNS replies received
109          * NOTE: This may not tally to the number sent out,
110          * due to timeouts and other latency issues.
111          */
112         unsigned long statsDnsBad;
113         /** Number of inbound connections seen
114          */
115         unsigned long statsConnects;
116         /** Total bytes of data transmitted
117          */
118         double statsSent;
119         /** Total bytes of data received
120          */
121         double statsRecv;
122         /** Number of bound listening ports
123          */
124         unsigned long BoundPortCount;
125
126         /** Cpu usage at last sample
127          */
128         timeval LastCPU;
129
130         /** Time last sample was read
131          */
132         timeval LastSampled;
133
134         /** The constructor initializes all the counts to zero
135          */
136         serverstats()
137                 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
138                 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0),
139                 BoundPortCount(0)
140         {
141         }
142 };
143
144 class InspIRCd;
145
146 /** This class implements a nonblocking log-writer.
147  * Most people writing an ircd give little thought to their disk
148  * i/o. On a congested system, disk writes can block for long
149  * periods of time (e.g. if the system is busy and/or swapping
150  * a lot). If we just use a blocking fprintf() call, this could
151  * block for undesirable amounts of time (half of a second through
152  * to whole seconds). We DO NOT want this, so we make our logfile
153  * nonblocking and hook it into the SocketEngine.
154  * NB: If the operating system does not support nonblocking file
155  * I/O (linux seems to, as does freebsd) this will default to
156  * blocking behaviour.
157  */
158 class FileLogger : public EventHandler
159 {
160  protected:
161         /** The creator/owner of this object
162          */
163         InspIRCd* ServerInstance;
164         /** The log file (fd is inside this somewhere,
165          * we get it out with fileno())
166          */
167         FILE* log;
168         /** Buffer of pending log lines to be written
169          */
170         std::string buffer;
171         /** Number of write operations that have occured
172          */
173         int writeops;
174  public:
175         /** The constructor takes an already opened logfile.
176          */
177         FileLogger(InspIRCd* Instance, FILE* logfile);
178         /** This returns false, logfiles are writeable.
179          */
180         virtual bool Readable();
181         /** Handle pending write events.
182          * This will flush any waiting data to disk.
183          * If any data remains after the fprintf call,
184          * another write event is scheduled to write
185          * the rest of the data when possible.
186          */
187         virtual void HandleEvent(EventType et, int errornum = 0);
188         /** Write one or more preformatted log lines.
189          * If the data cannot be written immediately,
190          * this class will insert itself into the
191          * SocketEngine, and register a write event,
192          * and when the write event occurs it will
193          * attempt again to write the data.
194          */
195         void WriteLogLine(const std::string &line);
196         /** Close the log file and cancel any events.
197          */
198         virtual void Close();
199         /** Close the log file and cancel any events.
200          * (indirectly call Close()
201          */
202         virtual ~FileLogger();
203 };
204
205 /** A list of failed port bindings, used for informational purposes on startup */
206 typedef std::vector<std::pair<std::string, long> > FailedPortList;
207
208 /** A list of ip addresses cross referenced against clone counts */
209 typedef std::map<irc::string, unsigned int> clonemap;
210
211 class XLineManager;
212
213 /** The main class of the irc server.
214  * This class contains instances of all the other classes
215  * in this software, with the exception of the base class,
216  * classbase. Amongst other things, it contains a ModeParser,
217  * a DNS object, a CommandParser object, and a list of active
218  * Module objects, and facilities for Module objects to
219  * interact with the core system it implements. You should
220  * NEVER attempt to instantiate a class of type InspIRCd
221  * yourself. If you do, this is equivalent to spawning a second
222  * IRC server, and could have catastrophic consequences for the
223  * program in terms of ram usage (basically, you could create
224  * an obese forkbomb built from recursively spawning irc servers!)
225  */
226 class InspIRCd : public classbase
227 {
228  private:
229         /** Holds a string describing the last module error to occur
230          */
231         char MODERR[MAXBUF];
232  
233         /** Remove a ModuleFactory pointer
234          * @param j Index number of the ModuleFactory to remove
235          */
236         void EraseFactory(int j);
237
238         /** Remove a Module pointer
239          * @param j Index number of the Module to remove
240          */
241         void EraseModule(int j);
242
243         /** Build the ISUPPORT string by triggering all modules On005Numeric events
244          */
245         void BuildISupport();
246
247         /** Move a given module to a specific slot in the list
248          * @param modulename The module name to relocate
249          * @param slot The slot to move the module into
250          */
251         void MoveTo(std::string modulename,int slot);
252
253         /** Display the startup banner
254          */
255         void Start();
256
257         /** Set up the signal handlers
258          */
259         void SetSignals();
260
261         /** Daemonize the ircd and close standard input/output streams
262          * @return True if the program daemonized succesfully
263          */
264         bool DaemonSeed();
265
266         /** Moves the given module to the last slot in the list
267          * @param modulename The module name to relocate
268          */
269         void MoveToLast(std::string modulename);
270
271         /** Moves the given module to the first slot in the list
272          * @param modulename The module name to relocate
273          */
274         void MoveToFirst(std::string modulename);
275
276         /** Moves one module to be placed after another in the list
277          * @param modulename The module name to relocate
278          * @param after The module name to place the module after
279          */
280         void MoveAfter(std::string modulename, std::string after);
281
282         /** Moves one module to be placed before another in the list
283          * @param modulename The module name to relocate
284          * @param after The module name to place the module before
285          */
286         void MoveBefore(std::string modulename, std::string before);
287
288         /** Iterate the list of InspSocket objects, removing ones which have timed out
289          * @param TIME the current time
290          */
291         void DoSocketTimeouts(time_t TIME);
292
293         /** Perform background user events such as PING checks
294          * @param TIME the current time
295          */
296         void DoBackgroundUserStuff(time_t TIME);
297
298         /** Returns true when all modules have done pre-registration checks on a user
299          * @param user The user to verify
300          * @return True if all modules have finished checking this user
301          */
302         bool AllModulesReportReady(userrec* user);
303
304         /** Total number of modules loaded into the ircd, minus one
305          */
306         int ModCount;
307
308         /** Logfile pathname specified on the commandline, or empty string
309          */
310         char LogFileName[MAXBUF];
311
312         /** The feature names published by various modules
313          */
314         featurelist Features;
315
316         /** The interface names published by various modules
317          */
318         interfacelist Interfaces;
319
320         /** The current time, updated in the mainloop
321          */
322         time_t TIME;
323
324         /** The time that was recorded last time around the mainloop
325          */
326         time_t OLDTIME;
327
328         /** A 64k buffer used to read client lines into
329          */
330         char ReadBuffer[65535];
331
332         /** Number of seconds in a minute
333          */
334         const long duration_m;
335
336         /** Number of seconds in an hour
337          */
338         const long duration_h;
339
340         /** Number of seconds in a day
341          */
342         const long duration_d;
343
344         /** Number of seconds in a week
345          */
346         const long duration_w;
347
348         /** Number of seconds in a year
349          */
350         const long duration_y;
351
352         /** Used when connecting clients
353          */
354         insp_sockaddr client, server;
355
356         /** Used when connecting clients
357          */
358         socklen_t length;
359
360         /** Nonblocking file writer
361          */
362         FileLogger* Logger;
363
364         /** Time offset in seconds
365          * This offset is added to all calls to Time(). Use SetTimeDelta() to update
366          */
367         int time_delta;
368
369  public:
370         /** List of server names we've seen.
371          */
372         servernamelist servernames;
373
374         /** Time this ircd was booted
375          */
376         time_t startup_time;
377
378         /** Mode handler, handles mode setting and removal
379          */
380         ModeParser* Modes;
381
382         /** Command parser, handles client to server commands
383          */
384         CommandParser* Parser;
385
386         /** Socket engine, handles socket activity events
387          */
388         SocketEngine* SE;
389
390         /** Stats class, holds miscellaneous stats counters
391          */
392         serverstats* stats;
393
394         /**  Server Config class, holds configuration file data
395          */
396         ServerConfig* Config;
397
398         /** Snomask manager - handles routing of snomask messages
399          * to opers.
400          */
401         SnomaskManager* SNO;
402
403         /** Client list, a hash_map containing all clients, local and remote
404          */
405         user_hash clientlist;
406
407         /** Channel list, a hash_map containing all channels
408          */
409         chan_hash chanlist;
410
411         /** Local client list, a vector containing only local clients
412          */
413         std::vector<userrec*> local_users;
414
415         /** Oper list, a vector containing all local and remote opered users
416          */
417         std::vector<userrec*> all_opers;
418
419         clonemap local_clones;
420
421         clonemap global_clones;
422
423         /** Whowas container, contains a map of vectors of users tracked by WHOWAS
424          */
425         irc::whowas::whowas_users whowas;
426
427         /** Whowas container, contains a map of time_t to users tracked by WHOWAS
428          */
429         irc::whowas::whowas_users_fifo whowas_fifo;
430
431         /** DNS class, provides resolver facilities to the core and modules
432          */
433         DNS* Res;
434
435         /** Timer manager class, triggers InspTimer timer events
436          */
437         TimerManager* Timers;
438
439         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
440          */
441         XLineManager* XLines;
442
443         /** A list of Module* module classes
444          * Note that this list is always exactly 255 in size.
445          * The actual number of loaded modules is available from GetModuleCount()
446          */
447         ModuleList modules;
448
449         /** A list of ModuleFactory* module factories
450          * Note that this list is always exactly 255 in size.
451          * The actual number of loaded modules is available from GetModuleCount()
452          */
453         FactoryList factory;
454
455         /** The time we next call our ping timeout and reg timeout checks
456          */
457         time_t next_call;
458
459         /** Get the current time
460          * Because this only calls time() once every time around the mainloop,
461          * it is much faster than calling time() directly.
462          * @param delta True to use the delta as an offset, false otherwise
463          * @return The current time as an epoch value (time_t)
464          */
465         time_t Time(bool delta = false);
466
467         /** Set the time offset in seconds
468          * This offset is added to Time() to offset the system time by the specified
469          * number of seconds.
470          * @param delta The number of seconds to offset
471          * @return The old time delta
472          */
473         int SetTimeDelta(int delta);
474
475         void AddLocalClone(userrec* user);
476
477         void AddGlobalClone(userrec* user);
478
479         /** Get the time offset in seconds
480          * @return The current time delta (in seconds)
481          */
482         int GetTimeDelta();
483
484         /** Process a user whos socket has been flagged as active
485          * @param cu The user to process
486          * @return There is no actual return value, however upon exit, the user 'cu' may have been deleted
487          */
488         void ProcessUser(userrec* cu);
489
490         /** Get the total number of currently loaded modules
491          * @return The number of loaded modules
492          */
493         int GetModuleCount();
494
495         /** Find a module by name, and return a Module* to it.
496          * This is preferred over iterating the module lists yourself.
497          * @param name The module name to look up
498          * @return A pointer to the module, or NULL if the module cannot be found
499          */
500         Module* FindModule(const std::string &name);
501
502         /** Bind all ports specified in the configuration file.
503          * @param bail True if the function should bail back to the shell on failure
504          * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
505          * @return The number of ports actually bound without error
506          */
507         int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
508
509         /** Returns true if this server has the given port bound to the given address
510          * @param port The port number
511          * @param addr The address
512          * @return True if we have a port listening on this address
513          */
514         bool HasPort(int port, char* addr);
515
516         /** Binds a socket on an already open file descriptor
517          * @param sockfd A valid file descriptor of an open socket
518          * @param client A sockaddr to use as temporary storage
519          * @param server A sockaddr to use as temporary storage
520          * @param port The port number to bind to
521          * @param addr The address to bind to (IP only)
522          * @return True if the port was bound successfully
523          */
524         bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
525
526         /** Adds a server name to the list of servers we've seen
527          * @param The servername to add
528          */
529         void AddServerName(const std::string &servername);
530
531         /** Finds a cached char* pointer of a server name,
532          * This is used to optimize userrec by storing only the pointer to the name
533          * @param The servername to find
534          * @return A pointer to this name, gauranteed to never become invalid
535          */
536         const char* FindServerNamePtr(const std::string &servername);
537
538         /** Returns true if we've seen the given server name before
539          * @param The servername to find
540          * @return True if we've seen this server name before
541          */
542         bool FindServerName(const std::string &servername);
543
544         /** Gets the GECOS (description) field of the given server.
545          * If the servername is not that of the local server, the name
546          * is passed to handling modules which will attempt to determine
547          * the GECOS that bleongs to the given servername.
548          * @param servername The servername to find the description of
549          * @return The description of this server, or of the local server
550          */
551         std::string GetServerDescription(const char* servername);
552
553         /** Write text to all opers connected to this server
554          * @param text The text format string
555          * @param ... Format args
556          */
557         void WriteOpers(const char* text, ...);
558
559         /** Write text to all opers connected to this server
560          * @param text The text to send
561          */
562         void WriteOpers(const std::string &text);
563         
564         /** Find a nickname in the nick hash
565          * @param nick The nickname to find
566          * @return A pointer to the user, or NULL if the user does not exist
567          */
568         userrec* FindNick(const std::string &nick);
569
570         /** Find a nickname in the nick hash
571          * @param nick The nickname to find
572          * @return A pointer to the user, or NULL if the user does not exist
573          */
574         userrec* FindNick(const char* nick);
575
576         /** Find a channel in the channels hash
577          * @param chan The channel to find
578          * @return A pointer to the channel, or NULL if the channel does not exist
579          */
580         chanrec* FindChan(const std::string &chan);
581
582         /** Find a channel in the channels hash
583          * @param chan The channel to find
584          * @return A pointer to the channel, or NULL if the channel does not exist
585          */
586         chanrec* FindChan(const char* chan);
587
588         /** Called by the constructor to load all modules from the config file.
589          */
590         void LoadAllModules();
591
592         /** Check for a 'die' tag in the config file, and abort if found
593          * @return Depending on the configuration, this function may never return
594          */
595         void CheckDie();
596
597         /** Check we aren't running as root, and exit if we are
598          * @return Depending on the configuration, this function may never return
599          */
600         void CheckRoot();
601
602         /** Determine the right path for, and open, the logfile
603          * @param argv The argv passed to main() initially, used to calculate program path
604          * @param argc The argc passed to main() initially, used to calculate program path
605          */
606         void OpenLog(char** argv, int argc);
607
608         /** Convert a user to a pseudoclient, disconnecting the real user
609          * @param user The user to convert
610          * @param message The quit message to display when exiting the user
611          * @return True if the operation succeeded
612          */
613         bool UserToPseudo(userrec* user, const std::string &message);
614
615         /** Convert a pseudoclient to a real user, discarding the pseudoclient
616          * @param alive A live client
617          * @param zombie A pseudoclient
618          * @param message The message to display when quitting the pseudoclient
619          * @return True if the operation succeeded
620          */
621         bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
622
623         /** Send a server notice to all local users
624          * @param text The text format string to send
625          * @param ... The format arguments
626          */
627         void ServerNoticeAll(char* text, ...);
628
629         /** Send a server message (PRIVMSG) to all local users
630          * @param text The text format string to send
631          * @param ... The format arguments
632          */
633         void ServerPrivmsgAll(char* text, ...);
634
635         /** Send text to all users with a specific set of modes
636          * @param modes The modes to check against, without a +, e.g. 'og'
637          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the 
638          * mode characters in the first parameter causes receipt of the message, and
639          * if you specify WM_OR, all the modes must be present.
640          * @param text The text format string to send
641          * @param ... The format arguments
642          */
643         void WriteMode(const char* modes, int flags, const char* text, ...);
644
645         /** Return true if a channel name is valid
646          * @param chname A channel name to verify
647          * @return True if the name is valid
648          */
649         bool IsChannel(const char *chname);
650
651         /** Rehash the local server
652          * @param status This value is unused, and required for signal handler functions
653          */
654         static void Rehash(int status);
655
656         /** Causes the server to exit immediately
657          * @param The exit code to give to the operating system
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