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