]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
567b172c21e8ea4010c87707812d7c4078203d65
[user/henk/code/inspircd.git] / include / inspircd.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #ifndef __INSPIRCD_H__
15 #define __INSPIRCD_H__
16
17 #ifndef WIN32
18 #define DllExport 
19 #define CoreExport 
20 #define printf_c printf
21 #else
22 #include "inspircd_win32wrapper.h"
23 /** Windows defines these already */
24 #undef DELETE
25 #undef ERROR
26 #endif
27
28 #include <time.h>
29 #include <string>
30 #include <sstream>
31 #include "inspircd_config.h"
32 #include "uid.h"
33 #include "users.h"
34 #include "channels.h"
35 #include "socket.h"
36 #include "mode.h"
37 #include "socketengine.h"
38 #include "command_parse.h"
39 #include "snomasks.h"
40 #include "cull_list.h"
41 #include "filelogger.h"
42 #include "caller.h"
43
44 /**
45  * Used to define the maximum number of parameters a command may have.
46  */
47 #define MAXPARAMETERS 127
48
49 /** Returned by some functions to indicate failure.
50  */
51 #define ERROR -1
52
53 /** Support for librodent -
54  * see http://www.chatspike.net/index.php?z=64
55  */
56 #define ETIREDHAMSTERS EAGAIN
57
58 /** Delete a pointer, and NULL its value
59  */
60 template<typename T> inline void DELETE(T* x)
61 {
62         delete x;
63         x = NULL;
64 }
65
66 /** Template function to convert any input type to std::string
67  */
68 template<typename T> inline std::string ConvNumeric(const T &in)
69 {
70         if (in == 0) return "0";
71         char res[MAXBUF];
72         char* out = res;
73         T quotient = in;
74         while (quotient) {
75                 *out = "0123456789"[ std::abs( (long)quotient % 10 ) ];
76                 ++out;
77                 quotient /= 10;
78         }
79         if ( in < 0)
80                 *out++ = '-';
81         *out = 0;
82         std::reverse(res,out);
83         return res;
84 }
85
86 /** Template function to convert any input type to std::string
87  */
88 inline std::string ConvToStr(const int in)
89 {
90         return ConvNumeric(in);
91 }
92
93 /** Template function to convert any input type to std::string
94  */
95 inline std::string ConvToStr(const long in)
96 {
97         return ConvNumeric(in);
98 }
99
100 /** Template function to convert any input type to std::string
101  */
102 inline std::string ConvToStr(const unsigned long in)
103 {
104         return ConvNumeric(in);
105 }
106
107 /** Template function to convert any input type to std::string
108  */
109 inline std::string ConvToStr(const char* in)
110 {
111         return in;
112 }
113
114 /** Template function to convert any input type to std::string
115  */
116 inline std::string ConvToStr(const bool in)
117 {
118         return (in ? "1" : "0");
119 }
120
121 /** Template function to convert any input type to std::string
122  */
123 inline std::string ConvToStr(char in)
124 {
125         return std::string(in,1);
126 }
127
128 /** Template function to convert any input type to std::string
129  */
130 template <class T> inline std::string ConvToStr(const T &in)
131 {
132         std::stringstream tmp;
133         if (!(tmp << in)) return std::string();
134         return tmp.str();
135 }
136
137 /** Template function to convert any input type to any other type
138  * (usually an integer or numeric type)
139  */
140 template<typename T> inline long ConvToInt(const T &in)
141 {
142         std::stringstream tmp;
143         if (!(tmp << in)) return 0;
144         return atoi(tmp.str().c_str());
145 }
146
147 /** Template function to convert integer to char, storing result in *res and
148  * also returning the pointer to res. Based on Stuart Lowe's C/C++ Pages.
149  * @param T input value
150  * @param V result value
151  * @param R base to convert to
152  */
153 template<typename T, typename V, typename R> inline char* itoa(const T &in, V *res, R base)
154 {
155         if (base < 2 || base > 16) { *res = 0; return res; }
156         char* out = res;
157         int quotient = in;
158         while (quotient) {
159                 *out = "0123456789abcdef"[ std::abs( quotient % base ) ];
160                 ++out;
161                 quotient /= base;
162         }
163         if ( in < 0 && base == 10) *out++ = '-';
164         std::reverse( res, out );
165         *out = 0;
166         return res;
167 }
168
169 /** This class contains various STATS counters
170  * It is used by the InspIRCd class, which internally
171  * has an instance of it.
172  */
173 class serverstats : public classbase
174 {
175   public:
176         /** Number of accepted connections
177          */
178         unsigned long statsAccept;
179         /** Number of failed accepts
180          */
181         unsigned long statsRefused;
182         /** Number of unknown commands seen
183          */
184         unsigned long statsUnknown;
185         /** Number of nickname collisions handled
186          */
187         unsigned long statsCollisions;
188         /** Number of DNS queries sent out
189          */
190         unsigned long statsDns;
191         /** Number of good DNS replies received
192          * NOTE: This may not tally to the number sent out,
193          * due to timeouts and other latency issues.
194          */
195         unsigned long statsDnsGood;
196         /** Number of bad (negative) DNS replies received
197          * NOTE: This may not tally to the number sent out,
198          * due to timeouts and other latency issues.
199          */
200         unsigned long statsDnsBad;
201         /** Number of inbound connections seen
202          */
203         unsigned long statsConnects;
204         /** Total bytes of data transmitted
205          */
206         double statsSent;
207         /** Total bytes of data received
208          */
209         double statsRecv;
210         /** Cpu usage at last sample
211          */
212         timeval LastCPU;
213         /** Time last sample was read
214          */
215         timeval LastSampled;
216         /** The constructor initializes all the counts to zero
217          */
218         serverstats()
219                 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
220                 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0)
221         {
222         }
223 };
224
225 /** A list of failed port bindings, used for informational purposes on startup */
226 typedef std::vector<std::pair<std::string, long> > FailedPortList;
227
228 /** A list of ip addresses cross referenced against clone counts */
229 typedef std::map<irc::string, unsigned int> clonemap;
230
231 class InspIRCd;
232
233 DEFINE_HANDLER1(ProcessUserHandler, void, userrec*);
234 DEFINE_HANDLER1(IsNickHandler, bool, const char*);
235 DEFINE_HANDLER1(IsIdentHandler, bool, const char*);
236 DEFINE_HANDLER1(FindDescriptorHandler, userrec*, int);
237 DEFINE_HANDLER1(FloodQuitUserHandler, void, userrec*);
238
239 /* Forward declaration - required */
240 class XLineManager;
241
242 /** The main class of the irc server.
243  * This class contains instances of all the other classes
244  * in this software, with the exception of the base class,
245  * classbase. Amongst other things, it contains a ModeParser,
246  * a DNS object, a CommandParser object, and a list of active
247  * Module objects, and facilities for Module objects to
248  * interact with the core system it implements. You should
249  * NEVER attempt to instantiate a class of type InspIRCd
250  * yourself. If you do, this is equivalent to spawning a second
251  * IRC server, and could have catastrophic consequences for the
252  * program in terms of ram usage (basically, you could create
253  * an obese forkbomb built from recursively spawning irc servers!)
254  */
255 class CoreExport InspIRCd : public classbase
256 {
257  private:
258         /** Holds the current UID. Used to generate the next one.
259          */
260         char current_uid[UUID_LENGTH];
261
262         /** Set up the signal handlers
263          */
264         void SetSignals();
265
266         /** Daemonize the ircd and close standard input/output streams
267          * @return True if the program daemonized succesfully
268          */
269         bool DaemonSeed();
270
271         /** Iterate the list of InspSocket objects, removing ones which have timed out
272          * @param TIME the current time
273          */
274         void DoSocketTimeouts(time_t TIME);
275
276         /** Sets up UID subsystem
277          */
278         void InitialiseUID();
279
280         /** Perform background user events such as PING checks
281          * @param TIME the current time
282          */
283         void DoBackgroundUserStuff(time_t TIME);
284
285         /** Returns true when all modules have done pre-registration checks on a user
286          * @param user The user to verify
287          * @return True if all modules have finished checking this user
288          */
289         bool AllModulesReportReady(userrec* user);
290
291         /** Logfile pathname specified on the commandline, or empty string
292          */
293         char LogFileName[MAXBUF];
294
295         /** The current time, updated in the mainloop
296          */
297         time_t TIME;
298
299         /** The time that was recorded last time around the mainloop
300          */
301         time_t OLDTIME;
302
303         /** A 64k buffer used to read client lines into
304          */
305         char ReadBuffer[65535];
306
307         /** Used when connecting clients
308          */
309         insp_sockaddr client, server;
310
311         /** Used when connecting clients
312          */
313         socklen_t length;
314
315         /** Nonblocking file writer
316          */
317         FileLogger* Logger;
318
319         /** Time offset in seconds
320          * This offset is added to all calls to Time(). Use SetTimeDelta() to update
321          */
322         int time_delta;
323
324 #ifdef WIN32
325         IPC* WindowsIPC;
326 #endif
327
328  public:
329
330         /** Global cull list, will be processed on next iteration
331          */
332         CullList GlobalCulls;
333
334         /**** Functors ****/
335
336         ProcessUserHandler HandleProcessUser;
337         IsNickHandler HandleIsNick;
338         IsIdentHandler HandleIsIdent;
339         FindDescriptorHandler HandleFindDescriptor;
340         FloodQuitUserHandler HandleFloodQuitUser;
341
342         /** InspSocket classes pending deletion after being closed.
343          * We don't delete these immediately as this may cause a segmentation fault.
344          */
345         std::map<InspSocket*,InspSocket*> SocketCull;
346
347         /** Globally accessible fake user record. This is used to force mode changes etc across s2s, etc.. bit ugly, but.. better than how this was done in 1.1
348          * Reason for it:
349          * kludge alert!
350          * SendMode expects a userrec* to send the numeric replies
351          * back to, so we create it a fake user that isnt in the user
352          * hash and set its descriptor to FD_MAGIC_NUMBER so the data
353          * falls into the abyss :p
354          */
355         userrec *FakeClient;
356
357         /** Returns the next available UID for this server.
358          */
359         std::string GetUID();
360
361         /** Find a user in the UUID hash
362          * @param nick The nickname to find
363          * @return A pointer to the user, or NULL if the user does not exist
364          */
365         userrec *FindUUID(const std::string &);
366
367         /** Find a user in the UUID hash
368          * @param nick The nickname to find
369          * @return A pointer to the user, or NULL if the user does not exist
370          */
371         userrec *FindUUID(const char *);
372
373         /** Build the ISUPPORT string by triggering all modules On005Numeric events
374          */
375         void BuildISupport();
376
377         /** Number of unregistered users online right now.
378          * (Unregistered means before USER/NICK/dns)
379          */
380         int unregistered_count;
381
382         /** List of server names we've seen.
383          */
384         servernamelist servernames;
385
386         /** Time this ircd was booted
387          */
388         time_t startup_time;
389
390         /** Config file pathname specified on the commandline or via ./configure
391          */
392         char ConfigFileName[MAXBUF];
393
394         /** Mode handler, handles mode setting and removal
395          */
396         ModeParser* Modes;
397
398         /** Command parser, handles client to server commands
399          */
400         CommandParser* Parser;
401
402         /** Socket engine, handles socket activity events
403          */
404         SocketEngine* SE;
405         
406         /** ModuleManager contains everything related to loading/unloading
407          * modules.
408          */
409         ModuleManager* Modules;
410
411         /** Stats class, holds miscellaneous stats counters
412          */
413         serverstats* stats;
414
415         /**  Server Config class, holds configuration file data
416          */
417         ServerConfig* Config;
418
419         /** Snomask manager - handles routing of snomask messages
420          * to opers.
421          */
422         SnomaskManager* SNO;
423
424         /** Client list, a hash_map containing all clients, local and remote
425          */
426         user_hash* clientlist;
427
428         /** Client list stored by UUID. Contains all clients, and is updated
429          * automatically by the constructor and destructor of userrec.
430          */
431         user_hash* uuidlist;
432
433         /** Channel list, a hash_map containing all channels
434          */
435         chan_hash* chanlist;
436
437         /** Local client list, a vector containing only local clients
438          */
439         std::vector<userrec*> local_users;
440
441         /** Oper list, a vector containing all local and remote opered users
442          */
443         std::vector<userrec*> all_opers;
444
445         /** Map of local ip addresses for clone counting
446          */
447         clonemap local_clones;
448
449         /** Map of global ip addresses for clone counting
450          */
451         clonemap global_clones;
452
453         /** DNS class, provides resolver facilities to the core and modules
454          */
455         DNS* Res;
456
457         /** Timer manager class, triggers InspTimer timer events
458          */
459         TimerManager* Timers;
460
461         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
462          */
463         XLineManager* XLines;
464
465         /** The time we next call our ping timeout and reg timeout checks
466          */
467         time_t next_call;
468
469         /** Set to the current signal recieved
470          */
471         int s_signal;
472
473         /** Get the current time
474          * Because this only calls time() once every time around the mainloop,
475          * it is much faster than calling time() directly.
476          * @param delta True to use the delta as an offset, false otherwise
477          * @return The current time as an epoch value (time_t)
478          */
479         time_t Time(bool delta = false);
480
481         /** Set the time offset in seconds
482          * This offset is added to Time() to offset the system time by the specified
483          * number of seconds.
484          * @param delta The number of seconds to offset
485          * @return The old time delta
486          */
487         int SetTimeDelta(int delta);
488
489         /** Add a user to the local clone map
490          * @param user The user to add
491          */
492         void AddLocalClone(userrec* user);
493
494         /** Add a user to the global clone map
495          * @param user The user to add
496          */
497         void AddGlobalClone(userrec* user);
498         
499         /** Number of users with a certain mode set on them
500          */
501         int ModeCount(const char mode);
502
503         /** Get the time offset in seconds
504          * @return The current time delta (in seconds)
505          */
506         int GetTimeDelta();
507
508         /** Process a user whos socket has been flagged as active
509          * @param cu The user to process
510          * @return There is no actual return value, however upon exit, the user 'cu' may have been
511          * marked for deletion in the global CullList.
512          */
513         caller1<void, userrec*> ProcessUser;
514
515         /** Bind all ports specified in the configuration file.
516          * @param bail True if the function should bail back to the shell on failure
517          * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
518          * @return The number of ports actually bound without error
519          */
520         int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
521
522         /** Binds a socket on an already open file descriptor
523          * @param sockfd A valid file descriptor of an open socket
524          * @param port The port number to bind to
525          * @param addr The address to bind to (IP only)
526          * @return True if the port was bound successfully
527          */
528         bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
529
530         /** Adds a server name to the list of servers we've seen
531          * @param The servername to add
532          */
533         void AddServerName(const std::string &servername);
534
535         /** Finds a cached char* pointer of a server name,
536          * This is used to optimize userrec by storing only the pointer to the name
537          * @param The servername to find
538          * @return A pointer to this name, gauranteed to never become invalid
539          */
540         const char* FindServerNamePtr(const std::string &servername);
541
542         /** Returns true if we've seen the given server name before
543          * @param The servername to find
544          * @return True if we've seen this server name before
545          */
546         bool FindServerName(const std::string &servername);
547
548         /** Gets the GECOS (description) field of the given server.
549          * If the servername is not that of the local server, the name
550          * is passed to handling modules which will attempt to determine
551          * the GECOS that bleongs to the given servername.
552          * @param servername The servername to find the description of
553          * @return The description of this server, or of the local server
554          */
555         std::string GetServerDescription(const char* servername);
556
557         /** Write text to all opers connected to this server
558          * @param text The text format string
559          * @param ... Format args
560          */
561         void WriteOpers(const char* text, ...);
562
563         /** Write text to all opers connected to this server
564          * @param text The text to send
565          */
566         void WriteOpers(const std::string &text);
567
568         /** Find a user in the nick hash.
569          * If the user cant be found in the nick hash check the uuid hash
570          * @param nick The nickname to find
571          * @return A pointer to the user, or NULL if the user does not exist
572          */
573         userrec* FindNick(const std::string &nick);
574
575         /** Find a user in the nick hash.
576          * If the user cant be found in the nick hash check the uuid hash
577          * @param nick The nickname to find
578          * @return A pointer to the user, or NULL if the user does not exist
579          */
580         userrec* FindNick(const char* nick);
581
582         /** Find a user in the nick hash ONLY
583          */
584         userrec* FindNickOnly(const char* nick);
585
586         /** Find a user in the nick hash ONLY
587          */
588         userrec* FindNickOnly(const std::string &nick);
589
590         /** Find a channel in the channels hash
591          * @param chan The channel to find
592          * @return A pointer to the channel, or NULL if the channel does not exist
593          */
594         chanrec* FindChan(const std::string &chan);
595
596         /** Find a channel in the channels hash
597          * @param chan The channel to find
598          * @return A pointer to the channel, or NULL if the channel does not exist
599          */
600         chanrec* FindChan(const char* chan);
601
602         /** Check for a 'die' tag in the config file, and abort if found
603          * @return Depending on the configuration, this function may never return
604          */
605         void CheckDie();
606
607         /** Check we aren't running as root, and exit if we are
608          * @return Depending on the configuration, this function may never return
609          */
610         void CheckRoot();
611
612         /** Determine the right path for, and open, the logfile
613          * @param argv The argv passed to main() initially, used to calculate program path
614          * @param argc The argc passed to main() initially, used to calculate program path
615          * @return True if the log could be opened, false if otherwise
616          */
617         bool OpenLog(char** argv, int argc);
618
619         /** Close the currently open log file
620          */
621         void CloseLog();
622
623         /** Send a server notice to all local users
624          * @param text The text format string to send
625          * @param ... The format arguments
626          */
627         void ServerNoticeAll(char* text, ...);
628
629         /** Send a server message (PRIVMSG) to all local users
630          * @param text The text format string to send
631          * @param ... The format arguments
632          */
633         void ServerPrivmsgAll(char* text, ...);
634
635         /** Send text to all users with a specific set of modes
636          * @param modes The modes to check against, without a +, e.g. 'og'
637          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
638          * mode characters in the first parameter causes receipt of the message, and
639          * if you specify WM_OR, all the modes must be present.
640          * @param text The text format string to send
641          * @param ... The format arguments
642          */
643         void WriteMode(const char* modes, int flags, const char* text, ...);
644
645         /** Return true if a channel name is valid
646          * @param chname A channel name to verify
647          * @return True if the name is valid
648          */
649         bool IsChannel(const char *chname);
650
651         /** Rehash the local server
652          */
653         void Rehash();
654
655         /** Handles incoming signals after being set
656          * @param signal the signal recieved
657          */
658         void SignalHandler(int signal);
659
660         /** Sets the signal recieved    
661          * @param signal the signal recieved
662          */
663         static void SetSignal(int signal);
664
665         /** Causes the server to exit after unloading modules and
666          * closing all open file descriptors.
667          *
668          * @param The exit code to give to the operating system
669          * (See the ExitStatus enum for valid values)
670          */
671         void Exit(int status);
672
673         /** Causes the server to exit immediately with exit code 0.
674          * The status code is required for signal handlers, and ignored.
675          */
676         static void QuickExit(int status);
677
678         /** Return a count of users, unknown and known connections
679          * @return The number of users
680          */
681         int UserCount();
682
683         /** Return a count of fully registered connections only
684          * @return The number of registered users
685          */
686         int RegisteredUserCount();
687
688         /** Return a count of invisible (umode +i) users only
689          * @return The number of invisible users
690          */
691         int InvisibleUserCount();
692
693         /** Return a count of opered (umode +o) users only
694          * @return The number of opers
695          */
696         int OperCount();
697
698         /** Return a count of unregistered (before NICK/USER) users only
699          * @return The number of unregistered (unknown) connections
700          */
701         int UnregisteredUserCount();
702
703         /** Return a count of channels on the network
704          * @return The number of channels
705          */
706         long ChannelCount();
707
708         /** Return a count of local users on this server only
709          * @return The number of local users
710          */
711         long LocalUserCount();
712
713         /** Send an error notice to all local users, opered and unopered
714          * @param s The error string to send
715          */
716         void SendError(const std::string &s);
717
718         /** Return true if a nickname is valid
719          * @param n A nickname to verify
720          * @return True if the nick is valid
721          */
722         caller1<bool, const char*> IsNick;
723
724         /** Return true if an ident is valid
725          * @param An ident to verify
726          * @return True if the ident is valid
727          */
728         caller1<bool, const char*> IsIdent;
729
730         /** Find a username by their file descriptor.
731          * It is preferred to use this over directly accessing the fd_ref_table array.
732          * @param socket The file descriptor of a user
733          * @return A pointer to the user if the user exists locally on this descriptor
734          */
735         caller1<userrec*, int> FindDescriptor;
736
737         /** Add a new mode to this server's mode parser
738          * @param mh The modehandler to add
739          * @param modechar The mode character this modehandler handles
740          * @return True if the mode handler was added
741          */
742         bool AddMode(ModeHandler* mh, const unsigned char modechar);
743
744         /** Add a new mode watcher to this server's mode parser
745          * @param mw The modewatcher to add
746          * @return True if the modewatcher was added
747          */
748         bool AddModeWatcher(ModeWatcher* mw);
749
750         /** Delete a mode watcher from this server's mode parser
751          * @param mw The modewatcher to delete
752          * @return True if the modewatcher was deleted
753          */
754         bool DelModeWatcher(ModeWatcher* mw);
755
756         /** Add a dns Resolver class to this server's active set
757          * @param r The resolver to add
758          * @param cached If this value is true, then the cache will
759          * be searched for the DNS result, immediately. If the value is
760          * false, then a request will be sent to the nameserver, and the
761          * result will not be immediately available. You should usually
762          * use the boolean value which you passed to the Resolver
763          * constructor, which Resolver will set appropriately depending
764          * on if cached results are available and haven't expired. It is
765          * however safe to force this value to false, forcing a remote DNS
766          * lookup, but not an update of the cache.
767          * @return True if the operation completed successfully. Note that
768          * if this method returns true, you should not attempt to access
769          * the resolver class you pass it after this call, as depending upon
770          * the request given, the object may be deleted!
771          */
772         bool AddResolver(Resolver* r, bool cached);
773
774         /** Add a command to this server's command parser
775          * @param f A command_t command handler object to add
776          * @throw ModuleException Will throw ModuleExcption if the command already exists
777          */
778         void AddCommand(command_t *f);
779
780         /** Send a modechange.
781          * The parameters provided are identical to that sent to the
782          * handler for class cmd_mode.
783          * @param parameters The mode parameters
784          * @param pcnt The number of items you have given in the first parameter
785          * @param user The user to send error messages to
786          */
787         void SendMode(const char **parameters, int pcnt, userrec *user);
788
789         /** Match two strings using pattern matching.
790          * This operates identically to the global function match(),
791          * except for that it takes std::string arguments rather than
792          * const char* ones.
793          * @param sliteral The literal string to match against
794          * @param spattern The pattern to match against. CIDR and globs are supported.
795          */
796         bool MatchText(const std::string &sliteral, const std::string &spattern);
797
798         /** Call the handler for a given command.
799          * @param commandname The command whos handler you wish to call
800          * @param parameters The mode parameters
801          * @param pcnt The number of items you have given in the first parameter
802          * @param user The user to execute the command as
803          * @return True if the command handler was called successfully
804          */
805         CmdResult CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
806
807         /** Return true if the command is a module-implemented command and the given parameters are valid for it
808          * @param parameters The mode parameters
809          * @param pcnt The number of items you have given in the first parameter
810          * @param user The user to test-execute the command as
811          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
812          */
813         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
814
815         /** Add a gline and apply it
816          * @param duration How long the line should last
817          * @param source Who set the line
818          * @param reason The reason for the line
819          * @param hostmask The hostmask to set the line against
820          */
821         void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
822
823         /** Add a qline and apply it
824          * @param duration How long the line should last
825          * @param source Who set the line
826          * @param reason The reason for the line
827          * @param nickname The nickmask to set the line against
828          */
829         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
830
831         /** Add a zline and apply it
832          * @param duration How long the line should last
833          * @param source Who set the line
834          * @param reason The reason for the line
835          * @param ipaddr The ip-mask to set the line against
836          */
837         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
838
839         /** Add a kline and apply it
840          * @param duration How long the line should last
841          * @param source Who set the line
842          * @param reason The reason for the line
843          * @param hostmask The hostmask to set the line against
844          */
845         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
846
847         /** Add an eline
848          * @param duration How long the line should last
849          * @param source Who set the line
850          * @param reason The reason for the line
851          * @param hostmask The hostmask to set the line against
852          */
853         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
854
855         /** Delete a gline
856          * @param hostmask The gline to delete
857          * @return True if the item was removed
858          */
859         bool DelGLine(const std::string &hostmask);
860
861         /** Delete a qline
862          * @param nickname The qline to delete
863          * @return True if the item was removed
864          */
865         bool DelQLine(const std::string &nickname);
866
867         /** Delete a zline
868          * @param ipaddr The zline to delete
869          * @return True if the item was removed
870          */
871         bool DelZLine(const std::string &ipaddr);
872
873         /** Delete a kline
874          * @param hostmask The kline to delete
875          * @return True if the item was removed
876          */
877         bool DelKLine(const std::string &hostmask);
878
879         /** Delete an eline
880          * @param hostmask The kline to delete
881          * @return True if the item was removed
882          */
883         bool DelELine(const std::string &hostmask);
884
885         /** Return true if the given parameter is a valid nick!user\@host mask
886          * @param mask A nick!user\@host masak to match against
887          * @return True i the mask is valid
888          */
889         bool IsValidMask(const std::string &mask);
890
891         /** Rehash the local server
892          */
893         void RehashServer();
894
895         /** Return the channel whos index number matches that provided
896          * @param The index number of the channel to fetch
897          * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
898          */
899         chanrec* GetChannelIndex(long index);
900
901         /** Dump text to a user target, splitting it appropriately to fit
902          * @param User the user to dump the text to
903          * @param LinePrefix text to prefix each complete line with
904          * @param TextStream the text to send to the user
905          */
906         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
907
908         /** Check if the given nickmask matches too many users, send errors to the given user
909          * @param nick A nickmask to match against
910          * @param user A user to send error text to
911          * @return True if the nick matches too many users
912          */
913         bool NickMatchesEveryone(const std::string &nick, userrec* user);
914
915         /** Check if the given IP mask matches too many users, send errors to the given user
916          * @param ip An ipmask to match against
917          * @param user A user to send error text to
918          * @return True if the ip matches too many users
919          */
920         bool IPMatchesEveryone(const std::string &ip, userrec* user);
921
922         /** Check if the given hostmask matches too many users, send errors to the given user
923          * @param mask A hostmask to match against
924          * @param user A user to send error text to
925          * @return True if the host matches too many users
926          */
927         bool HostMatchesEveryone(const std::string &mask, userrec* user);
928
929         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
930          * @param str A string containing a time in the form 1y2w3d4h6m5s
931          * (one year, two weeks, three days, four hours, six minutes and five seconds)
932          * @return The total number of seconds
933          */
934         long Duration(const std::string &str);
935
936         /** Attempt to compare an oper password to a string from the config file.
937          * This will be passed to handling modules which will compare the data
938          * against possible hashed equivalents in the input string.
939          * @param data The data from the config file
940          * @param input The data input by the oper
941          * @param tagnum the tag number of the oper's tag in the config file
942          * @return 0 if the strings match, 1 or -1 if they do not
943          */
944         int OperPassCompare(const char* data,const char* input, int tagnum);
945
946         /** Check if a given server is a uline.
947          * An empty string returns true, this is by design.
948          * @param server The server to check for uline status
949          * @return True if the server is a uline OR the string is empty
950          */
951         bool ULine(const char* server);
952
953         /** Returns true if the uline is 'silent' (doesnt generate
954          * remote connect notices etc).
955          */
956         bool SilentULine(const char* server);
957
958         /** Returns the subversion revision ID of this ircd
959          * @return The revision ID or an empty string
960          */
961         std::string GetRevision();
962
963         /** Returns the full version string of this ircd
964          * @return The version string
965          */
966         std::string GetVersionString();
967
968         /** Attempt to write the process id to a given file
969          * @param filename The PID file to attempt to write to
970          * @return This function may bail if the file cannot be written
971          */
972         void WritePID(const std::string &filename);
973
974         /** This constructor initialises all the subsystems and reads the config file.
975          * @param argc The argument count passed to main()
976          * @param argv The argument list passed to main()
977          * @throw <anything> If anything is thrown from here and makes it to
978          * you, you should probably just give up and go home. Yes, really.
979          * It's that bad. Higher level classes should catch any non-fatal exceptions.
980          */
981         InspIRCd(int argc, char** argv);
982
983         /** Output a log message to the ircd.log file
984          * The text will only be output if the current loglevel
985          * is less than or equal to the level you provide
986          * @param level A log level from the DebugLevel enum
987          * @param text Format string of to write to the log
988          * @param ... Format arguments of text to write to the log
989          */
990         void Log(int level, const char* text, ...);
991
992         /** Output a log message to the ircd.log file
993          * The text will only be output if the current loglevel
994          * is less than or equal to the level you provide
995          * @param level A log level from the DebugLevel enum
996          * @param text Text to write to the log
997          */
998         void Log(int level, const std::string &text);
999
1000         /** Send a line of WHOIS data to a user.
1001          * @param user user to send the line to
1002          * @param dest user being WHOISed
1003          * @param numeric Numeric to send
1004          * @param text Text of the numeric
1005          */
1006         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1007
1008         /** Send a line of WHOIS data to a user.
1009          * @param user user to send the line to
1010          * @param dest user being WHOISed
1011          * @param numeric Numeric to send
1012          * @param format Format string for the numeric
1013          * @param ... Parameters for the format string
1014          */
1015         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1016
1017         /** Quit a user for excess flood, and if they are not
1018          * fully registered yet, temporarily zline their IP.
1019          * @param current user to quit
1020          */
1021         caller1<void, userrec*> FloodQuitUser;
1022
1023         /** Restart the server.
1024          * This function will not return. If an error occurs,
1025          * it will throw an instance of CoreException.
1026          * @param reason The restart reason to show to all clients
1027          * @throw CoreException An instance of CoreException indicating the error from execv().
1028          */
1029         void Restart(const std::string &reason);
1030
1031         /** Prepare the ircd for restart or shutdown.
1032          * This function unloads all modules which can be unloaded,
1033          * closes all open sockets, and closes the logfile.
1034          */
1035         void Cleanup();
1036
1037         /** This copies the user and channel hash_maps into new hash maps.
1038          * This frees memory used by the hash_map allocator (which it neglects
1039          * to free, most of the time, using tons of ram)
1040          */
1041         void RehashUsersAndChans();
1042
1043         /** Resets the cached max bans value on all channels.
1044          * Called by rehash.
1045          */
1046         void ResetMaxBans();
1047
1048         /** Return a time_t as a human-readable string.
1049          */
1050         std::string TimeString(time_t curtime);
1051
1052         /** Begin execution of the server.
1053          * NOTE: this function NEVER returns. Internally,
1054          * it will repeatedly loop.
1055          * @return The return value for this function is undefined.
1056          */
1057         int Run();
1058
1059         /** Force all InspSockets to be removed which are due to
1060          * be culled.
1061          */
1062         void InspSocketCull();
1063
1064         char* GetReadBuffer()
1065         {
1066                 return this->ReadBuffer;
1067         }
1068 };
1069
1070 #endif