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