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