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