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