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