]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
ee02a32b5188e14853903cbbbcb28b025f83c425
[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         /** Build the ISUPPORT string by triggering all modules On005Numeric events
312          */
313         void BuildISupport();
314
315         /** Move a given module to a specific slot in the list
316          * @param modulename The module name to relocate
317          * @param slot The slot to move the module into
318          */
319         void MoveTo(std::string modulename,int slot);
320
321         /** Display the startup banner
322          */
323         void Start();
324
325         /** Set up the signal handlers
326          */
327         void SetSignals();
328
329         /** Daemonize the ircd and close standard input/output streams
330          * @return True if the program daemonized succesfully
331          */
332         bool DaemonSeed();
333
334         /** Moves the given module to the last slot in the list
335          * @param modulename The module name to relocate
336          */
337         void MoveToLast(std::string modulename);
338
339         /** Moves the given module to the first slot in the list
340          * @param modulename The module name to relocate
341          */
342         void MoveToFirst(std::string modulename);
343
344         /** Moves one module to be placed after another in the list
345          * @param modulename The module name to relocate
346          * @param after The module name to place the module after
347          */
348         void MoveAfter(std::string modulename, std::string after);
349
350         /** Moves one module to be placed before another in the list
351          * @param modulename The module name to relocate
352          * @param after The module name to place the module before
353          */
354         void MoveBefore(std::string modulename, std::string before);
355
356         /** Iterate the list of InspSocket objects, removing ones which have timed out
357          * @param TIME the current time
358          */
359         void DoSocketTimeouts(time_t TIME);
360
361         /** Perform background user events such as PING checks
362          * @param TIME the current time
363          */
364         void DoBackgroundUserStuff(time_t TIME);
365
366         /** Returns true when all modules have done pre-registration checks on a user
367          * @param user The user to verify
368          * @return True if all modules have finished checking this user
369          */
370         bool AllModulesReportReady(userrec* user);
371
372         /** Total number of modules loaded into the ircd, minus one
373          */
374         int ModCount;
375
376         /** Logfile pathname specified on the commandline, or empty string
377          */
378         char LogFileName[MAXBUF];
379
380         /** The feature names published by various modules
381          */
382         featurelist Features;
383
384         /** The interface names published by various modules
385          */
386         interfacelist Interfaces;
387
388         /** The current time, updated in the mainloop
389          */
390         time_t TIME;
391
392         /** The time that was recorded last time around the mainloop
393          */
394         time_t OLDTIME;
395
396         /** A 64k buffer used to read client lines into
397          */
398         char ReadBuffer[65535];
399
400         /** Number of seconds in a minute
401          */
402         const long duration_m;
403
404         /** Number of seconds in an hour
405          */
406         const long duration_h;
407
408         /** Number of seconds in a day
409          */
410         const long duration_d;
411
412         /** Number of seconds in a week
413          */
414         const long duration_w;
415
416         /** Number of seconds in a year
417          */
418         const long duration_y;
419
420         /** Used when connecting clients
421          */
422         insp_sockaddr client, server;
423
424         /** Used when connecting clients
425          */
426         socklen_t length;
427
428         /** Nonblocking file writer
429          */
430         FileLogger* Logger;
431
432         /** Time offset in seconds
433          * This offset is added to all calls to Time(). Use SetTimeDelta() to update
434          */
435         int time_delta;
436
437  public:
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         /** Mode handler, handles mode setting and removal
453          */
454         ModeParser* Modes;
455
456         /** Command parser, handles client to server commands
457          */
458         CommandParser* Parser;
459
460         /** Socket engine, handles socket activity events
461          */
462         SocketEngine* SE;
463
464         /** Stats class, holds miscellaneous stats counters
465          */
466         serverstats* stats;
467
468         /**  Server Config class, holds configuration file data
469          */
470         ServerConfig* Config;
471
472         /** Snomask manager - handles routing of snomask messages
473          * to opers.
474          */
475         SnomaskManager* SNO;
476
477         /** Client list, a hash_map containing all clients, local and remote
478          */
479         user_hash* clientlist;
480
481         /** Channel list, a hash_map containing all channels
482          */
483         chan_hash* chanlist;
484
485         /** Local client list, a vector containing only local clients
486          */
487         std::vector<userrec*> local_users;
488
489         /** Oper list, a vector containing all local and remote opered users
490          */
491         std::vector<userrec*> all_opers;
492
493         clonemap local_clones;
494
495         clonemap global_clones;
496
497         /** DNS class, provides resolver facilities to the core and modules
498          */
499         DNS* Res;
500
501         /** Timer manager class, triggers InspTimer timer events
502          */
503         TimerManager* Timers;
504
505         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
506          */
507         XLineManager* XLines;
508
509         /** A list of Module* module classes
510          * Note that this list is always exactly 255 in size.
511          * The actual number of loaded modules is available from GetModuleCount()
512          */
513         ModuleList modules;
514
515         /** A list of ModuleFactory* module factories
516          * Note that this list is always exactly 255 in size.
517          * The actual number of loaded modules is available from GetModuleCount()
518          */
519         FactoryList factory;
520
521         /** The time we next call our ping timeout and reg timeout checks
522          */
523         time_t next_call;
524
525         /** Global cull list, will be processed on next iteration
526          */
527         CullList GlobalCulls;
528
529         /** Get the current time
530          * Because this only calls time() once every time around the mainloop,
531          * it is much faster than calling time() directly.
532          * @param delta True to use the delta as an offset, false otherwise
533          * @return The current time as an epoch value (time_t)
534          */
535         time_t Time(bool delta = false);
536
537         /** Set the time offset in seconds
538          * This offset is added to Time() to offset the system time by the specified
539          * number of seconds.
540          * @param delta The number of seconds to offset
541          * @return The old time delta
542          */
543         int SetTimeDelta(int delta);
544
545         void AddLocalClone(userrec* user);
546
547         void AddGlobalClone(userrec* user);
548
549         /** Number of users with a certain mode set on them
550          */
551         int ModeCount(const char mode);
552
553         /** Get the time offset in seconds
554          * @return The current time delta (in seconds)
555          */
556         int GetTimeDelta();
557
558         /** Process a user whos socket has been flagged as active
559          * @param cu The user to process
560          * @return There is no actual return value, however upon exit, the user 'cu' may have been deleted
561          */
562         void ProcessUser(userrec* cu);
563
564         /** Get the total number of currently loaded modules
565          * @return The number of loaded modules
566          */
567         int GetModuleCount();
568
569         /** Find a module by name, and return a Module* to it.
570          * This is preferred over iterating the module lists yourself.
571          * @param name The module name to look up
572          * @return A pointer to the module, or NULL if the module cannot be found
573          */
574         Module* FindModule(const std::string &name);
575
576         /** Bind all ports specified in the configuration file.
577          * @param bail True if the function should bail back to the shell on failure
578          * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
579          * @return The number of ports actually bound without error
580          */
581         int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
582
583         /** Returns true if this server has the given port bound to the given address
584          * @param port The port number
585          * @param addr The address
586          * @return True if we have a port listening on this address
587          */
588         bool HasPort(int port, char* addr);
589
590         /** Binds a socket on an already open file descriptor
591          * @param sockfd A valid file descriptor of an open socket
592          * @param port The port number to bind to
593          * @param addr The address to bind to (IP only)
594          * @return True if the port was bound successfully
595          */
596         bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
597
598         /** Adds a server name to the list of servers we've seen
599          * @param The servername to add
600          */
601         void AddServerName(const std::string &servername);
602
603         /** Finds a cached char* pointer of a server name,
604          * This is used to optimize userrec by storing only the pointer to the name
605          * @param The servername to find
606          * @return A pointer to this name, gauranteed to never become invalid
607          */
608         const char* FindServerNamePtr(const std::string &servername);
609
610         /** Returns true if we've seen the given server name before
611          * @param The servername to find
612          * @return True if we've seen this server name before
613          */
614         bool FindServerName(const std::string &servername);
615
616         /** Gets the GECOS (description) field of the given server.
617          * If the servername is not that of the local server, the name
618          * is passed to handling modules which will attempt to determine
619          * the GECOS that bleongs to the given servername.
620          * @param servername The servername to find the description of
621          * @return The description of this server, or of the local server
622          */
623         std::string GetServerDescription(const char* servername);
624
625         /** Write text to all opers connected to this server
626          * @param text The text format string
627          * @param ... Format args
628          */
629         void WriteOpers(const char* text, ...);
630
631         /** Write text to all opers connected to this server
632          * @param text The text to send
633          */
634         void WriteOpers(const std::string &text);
635
636         /** Find a nickname in the nick hash
637          * @param nick The nickname to find
638          * @return A pointer to the user, or NULL if the user does not exist
639          */
640         userrec* FindNick(const std::string &nick);
641
642         /** Find a nickname in the nick hash
643          * @param nick The nickname to find
644          * @return A pointer to the user, or NULL if the user does not exist
645          */
646         userrec* FindNick(const char* nick);
647
648         /** Find a channel in the channels hash
649          * @param chan The channel to find
650          * @return A pointer to the channel, or NULL if the channel does not exist
651          */
652         chanrec* FindChan(const std::string &chan);
653
654         /** Find a channel in the channels hash
655          * @param chan The channel to find
656          * @return A pointer to the channel, or NULL if the channel does not exist
657          */
658         chanrec* FindChan(const char* chan);
659
660         /** Called by the constructor to load all modules from the config file.
661          */
662         void LoadAllModules();
663
664         /** Check for a 'die' tag in the config file, and abort if found
665          * @return Depending on the configuration, this function may never return
666          */
667         void CheckDie();
668
669         /** Check we aren't running as root, and exit if we are
670          * @return Depending on the configuration, this function may never return
671          */
672         void CheckRoot();
673
674         /** Determine the right path for, and open, the logfile
675          * @param argv The argv passed to main() initially, used to calculate program path
676          * @param argc The argc passed to main() initially, used to calculate program path
677          */
678         void OpenLog(char** argv, int argc);
679
680         void CloseLog();
681
682         /** Convert a user to a pseudoclient, disconnecting the real user
683          * @param user The user to convert
684          * @param message The quit message to display when exiting the user
685          * @return True if the operation succeeded
686          */
687         bool UserToPseudo(userrec* user, const std::string &message);
688
689         /** Convert a pseudoclient to a real user, discarding the pseudoclient
690          * @param alive A live client
691          * @param zombie A pseudoclient
692          * @param message The message to display when quitting the pseudoclient
693          * @return True if the operation succeeded
694          */
695         bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
696
697         /** Send a server notice to all local users
698          * @param text The text format string to send
699          * @param ... The format arguments
700          */
701         void ServerNoticeAll(char* text, ...);
702
703         /** Send a server message (PRIVMSG) to all local users
704          * @param text The text format string to send
705          * @param ... The format arguments
706          */
707         void ServerPrivmsgAll(char* text, ...);
708
709         /** Send text to all users with a specific set of modes
710          * @param modes The modes to check against, without a +, e.g. 'og'
711          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
712          * mode characters in the first parameter causes receipt of the message, and
713          * if you specify WM_OR, all the modes must be present.
714          * @param text The text format string to send
715          * @param ... The format arguments
716          */
717         void WriteMode(const char* modes, int flags, const char* text, ...);
718
719         /** Return true if a channel name is valid
720          * @param chname A channel name to verify
721          * @return True if the name is valid
722          */
723         bool IsChannel(const char *chname);
724
725         /** Rehash the local server
726          * @param status This value is unused, and required for signal handler functions
727          */
728         static void Rehash(int status);
729
730         /** Causes the server to exit immediately
731          * @param The exit code to give to the operating system
732          * (See the ExitStatus enum for valid values)
733          */
734         static void Exit(int status);
735
736         /** Return a count of users, unknown and known connections
737          * @return The number of users
738          */
739         int UserCount();
740
741         /** Return a count of fully registered connections only
742          * @return The number of registered users
743          */
744         int RegisteredUserCount();
745
746         /** Return a count of invisible (umode +i) users only
747          * @return The number of invisible users
748          */
749         int InvisibleUserCount();
750
751         /** Return a count of opered (umode +o) users only
752          * @return The number of opers
753          */
754         int OperCount();
755
756         /** Return a count of unregistered (before NICK/USER) users only
757          * @return The number of unregistered (unknown) connections
758          */
759         int UnregisteredUserCount();
760
761         /** Return a count of channels on the network
762          * @return The number of channels
763          */
764         long ChannelCount();
765
766         /** Return a count of local users on this server only
767          * @return The number of local users
768          */
769         long LocalUserCount();
770
771         /** Send an error notice to all local users, opered and unopered
772          * @param s The error string to send
773          */
774         void SendError(const std::string &s);
775
776         /** For use with Module::Prioritize().
777          * When the return value of this function is returned from
778          * Module::Prioritize(), this specifies that the module wishes
779          * to be ordered exactly BEFORE 'modulename'. For more information
780          * please see Module::Prioritize().
781          * @param modulename The module your module wants to be before in the call list
782          * @returns a priority ID which the core uses to relocate the module in the list
783          */
784         long PriorityBefore(const std::string &modulename);
785
786         /** For use with Module::Prioritize().
787          * When the return value of this function is returned from
788          * Module::Prioritize(), this specifies that the module wishes
789          * to be ordered exactly AFTER 'modulename'. For more information please
790          * see Module::Prioritize().
791          * @param modulename The module your module wants to be after in the call list
792          * @returns a priority ID which the core uses to relocate the module in the list
793          */
794         long PriorityAfter(const std::string &modulename);
795
796         /** Publish a 'feature'.
797          * There are two ways for a module to find another module it depends on.
798          * Either by name, using InspIRCd::FindModule, or by feature, using this
799          * function. A feature is an arbitary string which identifies something this
800          * module can do. For example, if your module provides SSL support, but other
801          * modules provide SSL support too, all the modules supporting SSL should
802          * publish an identical 'SSL' feature. This way, any module requiring use
803          * of SSL functions can just look up the 'SSL' feature using FindFeature,
804          * then use the module pointer they are given.
805          * @param FeatureName The case sensitive feature name to make available
806          * @param Mod a pointer to your module class
807          * @returns True on success, false if the feature is already published by
808          * another module.
809          */
810         bool PublishFeature(const std::string &FeatureName, Module* Mod);
811
812         /** Publish a module to an 'interface'.
813          * Modules which implement the same interface (the same way of communicating
814          * with other modules) can publish themselves to an interface, using this
815          * method. When they do so, they become part of a list of related or
816          * compatible modules, and a third module may then query for that list
817          * and know that all modules within that list offer the same API.
818          * A prime example of this is the hashing modules, which all accept the
819          * same types of Request class. Consider this to be similar to PublishFeature,
820          * except for that multiple modules may publish the same 'feature'.
821          * @param InterfaceName The case sensitive interface name to make available
822          * @param Mod a pointer to your module class
823          * @returns True on success, false on failure (there are currently no failure
824          * cases)
825          */
826         bool PublishInterface(const std::string &InterfaceName, Module* Mod);
827
828         /** Return a pair saying how many other modules are currently using the
829          * interfaces provided by module m.
830          * @param m The module to count usage for
831          * @return A pair, where the first value is the number of uses of the interface,
832          * and the second value is the interface name being used.
833          */
834         std::pair<int,std::string> GetInterfaceInstanceCount(Module* m);
835
836         /** Mark your module as using an interface.
837          * If you mark your module as using an interface, then that interface
838          * module may not unload until your module has unloaded first.
839          * This can be used to prevent crashes by ensuring code you depend on
840          * is always in memory while your module is active.
841          * @param InterfaceName The interface to use
842          */
843         void UseInterface(const std::string &InterfaceName);
844
845         /** Mark your module as finished with an interface.
846          * If you used UseInterface() above, you should use this method when
847          * your module is finished with the interface (usually in its destructor)
848          * to allow the modules which implement the given interface to be unloaded.
849          * @param InterfaceName The interface you are finished with using.
850          */
851         void DoneWithInterface(const std::string &InterfaceName);
852
853         /** Unpublish a 'feature'.
854          * When your module exits, it must call this method for every feature it
855          * is providing so that the feature table is cleaned up.
856          * @param FeatureName the feature to remove
857          */
858         bool UnpublishFeature(const std::string &FeatureName);
859
860         /** Unpublish your module from an interface
861          * When your module exits, it must call this method for every interface
862          * it is part of so that the interfaces table is cleaned up. Only when
863          * the last item is deleted from an interface does the interface get
864          * removed.
865          * @param InterfaceName the interface to be removed from
866          * @param Mod The module to remove from the interface list
867          */
868         bool UnpublishInterface(const std::string &InterfaceName, Module* Mod);
869
870         /** Find a 'feature'.
871          * There are two ways for a module to find another module it depends on.
872          * Either by name, using InspIRCd::FindModule, or by feature, using the
873          * InspIRCd::PublishFeature method. A feature is an arbitary string which
874          * identifies something this module can do. For example, if your module
875          * provides SSL support, but other modules provide SSL support too, all
876          * the modules supporting SSL should publish an identical 'SSL' feature.
877          * To find a module capable of providing the feature you want, simply
878          * call this method with the feature name you are looking for.
879          * @param FeatureName The feature name you wish to obtain the module for
880          * @returns A pointer to a valid module class on success, NULL on failure.
881          */
882         Module* FindFeature(const std::string &FeatureName);
883
884         /** Find an 'interface'.
885          * An interface is a list of modules which all implement the same API.
886          * @param InterfaceName The Interface you wish to obtain the module
887          * list of.
888          * @return A pointer to a deque of Module*, or NULL if the interface
889          * does not exist.
890          */
891         modulelist* FindInterface(const std::string &InterfaceName);
892
893         /** Given a pointer to a Module, return its filename
894          * @param m The module pointer to identify
895          * @return The module name or an empty string
896          */
897         const std::string& GetModuleName(Module* m);
898
899         /** Return true if a nickname is valid
900          * @param n A nickname to verify
901          * @return True if the nick is valid
902          */
903         bool IsNick(const char* n);
904
905         /** Return true if an ident is valid
906          * @param An ident to verify
907          * @return True if the ident is valid
908          */
909         bool IsIdent(const char* n);
910
911         /** Find a username by their file descriptor.
912          * It is preferred to use this over directly accessing the fd_ref_table array.
913          * @param socket The file descriptor of a user
914          * @return A pointer to the user if the user exists locally on this descriptor
915          */
916         userrec* FindDescriptor(int socket);
917
918         /** Add a new mode to this server's mode parser
919          * @param mh The modehandler to add
920          * @param modechar The mode character this modehandler handles
921          * @return True if the mode handler was added
922          */
923         bool AddMode(ModeHandler* mh, const unsigned char modechar);
924
925         /** Add a new mode watcher to this server's mode parser
926          * @param mw The modewatcher to add
927          * @return True if the modewatcher was added
928          */
929         bool AddModeWatcher(ModeWatcher* mw);
930
931         /** Delete a mode watcher from this server's mode parser
932          * @param mw The modewatcher to delete
933          * @return True if the modewatcher was deleted
934          */
935         bool DelModeWatcher(ModeWatcher* mw);
936
937         /** Add a dns Resolver class to this server's active set
938          * @param r The resolver to add
939          * @param cached If this value is true, then the cache will
940          * be searched for the DNS result, immediately. If the value is
941          * false, then a request will be sent to the nameserver, and the
942          * result will not be immediately available. You should usually
943          * use the boolean value which you passed to the Resolver
944          * constructor, which Resolver will set appropriately depending
945          * on if cached results are available and haven't expired. It is
946          * however safe to force this value to false, forcing a remote DNS
947          * lookup, but not an update of the cache.
948          * @return True if the operation completed successfully. Note that
949          * if this method returns true, you should not attempt to access
950          * the resolver class you pass it after this call, as depending upon
951          * the request given, the object may be deleted!
952          */
953         bool AddResolver(Resolver* r, bool cached);
954
955         /** Add a command to this server's command parser
956          * @param f A command_t command handler object to add
957          * @throw ModuleException Will throw ModuleExcption if the command already exists
958          */
959         void AddCommand(command_t *f);
960
961         /** Send a modechange.
962          * The parameters provided are identical to that sent to the
963          * handler for class cmd_mode.
964          * @param parameters The mode parameters
965          * @param pcnt The number of items you have given in the first parameter
966          * @param user The user to send error messages to
967          */
968         void SendMode(const char **parameters, int pcnt, userrec *user);
969
970         /** Match two strings using pattern matching.
971          * This operates identically to the global function match(),
972          * except for that it takes std::string arguments rather than
973          * const char* ones.
974          * @param sliteral The literal string to match against
975          * @param spattern The pattern to match against. CIDR and globs are supported.
976          */
977         bool MatchText(const std::string &sliteral, const std::string &spattern);
978
979         /** Call the handler for a given command.
980          * @param commandname The command whos handler you wish to call
981          * @param parameters The mode parameters
982          * @param pcnt The number of items you have given in the first parameter
983          * @param user The user to execute the command as
984          * @return True if the command handler was called successfully
985          */
986         bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
987
988         /** Return true if the command is a module-implemented command and the given parameters are valid for it
989          * @param parameters The mode parameters
990          * @param pcnt The number of items you have given in the first parameter
991          * @param user The user to test-execute the command as
992          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
993          */
994         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
995
996         /** Add a gline and apply it
997          * @param duration How long the line should last
998          * @param source Who set the line
999          * @param reason The reason for the line
1000          * @param hostmask The hostmask to set the line against
1001          */
1002         void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1003
1004         /** Add a qline and apply it
1005          * @param duration How long the line should last
1006          * @param source Who set the line
1007          * @param reason The reason for the line
1008          * @param nickname The nickmask to set the line against
1009          */
1010         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
1011
1012         /** Add a zline and apply it
1013          * @param duration How long the line should last
1014          * @param source Who set the line
1015          * @param reason The reason for the line
1016          * @param ipaddr The ip-mask to set the line against
1017          */
1018         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
1019
1020         /** Add a kline and apply it
1021          * @param duration How long the line should last
1022          * @param source Who set the line
1023          * @param reason The reason for the line
1024          * @param hostmask The hostmask to set the line against
1025          */
1026         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1027
1028         /** Add an eline
1029          * @param duration How long the line should last
1030          * @param source Who set the line
1031          * @param reason The reason for the line
1032          * @param hostmask The hostmask to set the line against
1033          */
1034         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
1035
1036         /** Delete a gline
1037          * @param hostmask The gline to delete
1038          * @return True if the item was removed
1039          */
1040         bool DelGLine(const std::string &hostmask);
1041
1042         /** Delete a qline
1043          * @param nickname The qline to delete
1044          * @return True if the item was removed
1045          */
1046         bool DelQLine(const std::string &nickname);
1047
1048         /** Delete a zline
1049          * @param ipaddr The zline to delete
1050          * @return True if the item was removed
1051          */
1052         bool DelZLine(const std::string &ipaddr);
1053
1054         /** Delete a kline
1055          * @param hostmask The kline to delete
1056          * @return True if the item was removed
1057          */
1058         bool DelKLine(const std::string &hostmask);
1059
1060         /** Delete an eline
1061          * @param hostmask The kline to delete
1062          * @return True if the item was removed
1063          */
1064         bool DelELine(const std::string &hostmask);
1065
1066         /** Return true if the given parameter is a valid nick!user\@host mask
1067          * @param mask A nick!user\@host masak to match against
1068          * @return True i the mask is valid
1069          */
1070         bool IsValidMask(const std::string &mask);
1071
1072         /** Rehash the local server
1073          */
1074         void RehashServer();
1075
1076         /** Return the channel whos index number matches that provided
1077          * @param The index number of the channel to fetch
1078          * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
1079          */
1080         chanrec* GetChannelIndex(long index);
1081
1082         /** Dump text to a user target, splitting it appropriately to fit
1083          * @param User the user to dump the text to
1084          * @param LinePrefix text to prefix each complete line with
1085          * @param TextStream the text to send to the user
1086          */
1087         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
1088
1089         /** Check if the given nickmask matches too many users, send errors to the given user
1090          * @param nick A nickmask to match against
1091          * @param user A user to send error text to
1092          * @return True if the nick matches too many users
1093          */
1094         bool NickMatchesEveryone(const std::string &nick, userrec* user);
1095
1096         /** Check if the given IP mask matches too many users, send errors to the given user
1097          * @param ip An ipmask to match against
1098          * @param user A user to send error text to
1099          * @return True if the ip matches too many users
1100          */
1101         bool IPMatchesEveryone(const std::string &ip, userrec* user);
1102
1103         /** Check if the given hostmask matches too many users, send errors to the given user
1104          * @param mask A hostmask to match against
1105          * @param user A user to send error text to
1106          * @return True if the host matches too many users
1107          */
1108         bool HostMatchesEveryone(const std::string &mask, userrec* user);
1109
1110         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
1111          * @param str A string containing a time in the form 1y2w3d4h6m5s
1112          * (one year, two weeks, three days, four hours, six minutes and five seconds)
1113          * @return The total number of seconds
1114          */
1115         long Duration(const char* str);
1116
1117         /** Attempt to compare an oper password to a string from the config file.
1118          * This will be passed to handling modules which will compare the data
1119          * against possible hashed equivalents in the input string.
1120          * @param data The data from the config file
1121          * @param input The data input by the oper
1122          * @param tagnum the tag number of the oper's tag in the config file
1123          * @return 0 if the strings match, 1 or -1 if they do not
1124          */
1125         int OperPassCompare(const char* data,const char* input, int tagnum);
1126
1127         /** Check if a given server is a uline.
1128          * An empty string returns true, this is by design.
1129          * @param server The server to check for uline status
1130          * @return True if the server is a uline OR the string is empty
1131          */
1132         bool ULine(const char* server);
1133
1134         /** Returns the subversion revision ID of this ircd
1135          * @return The revision ID or an empty string
1136          */
1137         std::string GetRevision();
1138
1139         /** Returns the full version string of this ircd
1140          * @return The version string
1141          */
1142         std::string GetVersionString();
1143
1144         /** Attempt to write the process id to a given file
1145          * @param filename The PID file to attempt to write to
1146          * @return This function may bail if the file cannot be written
1147          */
1148         void WritePID(const std::string &filename);
1149
1150         /** Returns text describing the last module error
1151          * @return The last error message to occur
1152          */
1153         char* ModuleError();
1154
1155         /** Load a given module file
1156          * @param filename The file to load
1157          * @return True if the module was found and loaded
1158          */
1159         bool LoadModule(const char* filename);
1160
1161         /** Unload a given module file
1162          * @param filename The file to unload
1163          * @return True if the module was unloaded
1164          */
1165         bool UnloadModule(const char* filename);
1166
1167         /** This constructor initialises all the subsystems and reads the config file.
1168          * @param argc The argument count passed to main()
1169          * @param argv The argument list passed to main()
1170          * @throw <anything> If anything is thrown from here and makes it to
1171          * you, you should probably just give up and go home. Yes, really.
1172          * It's that bad. Higher level classes should catch any non-fatal exceptions.
1173          */
1174         InspIRCd(int argc, char** argv);
1175
1176         /** Do one iteration of the mainloop
1177          * @param process_module_sockets True if module sockets are to be processed
1178          * this time around the event loop. The is the default.
1179          */
1180         void DoOneIteration(bool process_module_sockets = true);
1181
1182         /** Output a log message to the ircd.log file
1183          * The text will only be output if the current loglevel
1184          * is less than or equal to the level you provide
1185          * @param level A log level from the DebugLevel enum
1186          * @param text Format string of to write to the log
1187          * @param ... Format arguments of text to write to the log
1188          */
1189         void Log(int level, const char* text, ...);
1190
1191         /** Output a log message to the ircd.log file
1192          * The text will only be output if the current loglevel
1193          * is less than or equal to the level you provide
1194          * @param level A log level from the DebugLevel enum
1195          * @param text Text to write to the log
1196          */
1197         void Log(int level, const std::string &text);
1198
1199         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1200
1201         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1202
1203         /** Restart the server.
1204          * This function will not return. If an error occurs,
1205          * it will throw an instance of CoreException.
1206          * @param reason The restart reason to show to all clients
1207          * @throw CoreException An instance of CoreException indicating the error from execv().
1208          */
1209         void Restart(const std::string &reason);
1210
1211         /** Prepare the ircd for restart or shutdown.
1212          * This function unloads all modules which can be unloaded,
1213          * closes all open sockets, and closes the logfile.
1214          */
1215         void Cleanup();
1216
1217         /** This copies the user and channel hash_maps into new hash maps.
1218          * This frees memory used by the hash_map allocator (which it neglects
1219          * to free, most of the time, using tons of ram)
1220          */
1221         void RehashUsersAndChans();
1222
1223         /** Resets the cached max bans value on all channels.
1224          * Called by rehash.
1225          */
1226         void ResetMaxBans();
1227
1228         /** Begin execution of the server.
1229          * NOTE: this function NEVER returns. Internally,
1230          * after performing some initialisation routines,
1231          * it will repeatedly call DoOneIteration in a loop.
1232          * @return The return value for this function is undefined.
1233          */
1234         int Run();
1235 };
1236
1237 #endif
1238