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