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