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