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