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