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