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