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