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