]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Add a pointless WriteOpers
[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         /** Perform background user events such as PING checks
277          * @param TIME the current time
278          */
279         void DoBackgroundUserStuff(time_t TIME);
280
281         /** Returns true when all modules have done pre-registration checks on a user
282          * @param user The user to verify
283          * @return True if all modules have finished checking this user
284          */
285         bool AllModulesReportReady(userrec* user);
286
287         /** Logfile pathname specified on the commandline, or empty string
288          */
289         char LogFileName[MAXBUF];
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         /** Used when connecting clients
304          */
305         insp_sockaddr client, server;
306
307         /** Used when connecting clients
308          */
309         socklen_t length;
310
311         /** Nonblocking file writer
312          */
313         FileLogger* Logger;
314
315         /** Time offset in seconds
316          * This offset is added to all calls to Time(). Use SetTimeDelta() to update
317          */
318         int time_delta;
319
320 #ifdef WIN32
321         IPC* WindowsIPC;
322 #endif
323
324  public:
325
326         /** Global cull list, will be processed on next iteration
327          */
328         CullList GlobalCulls;
329
330         /**** Functors ****/
331
332         ProcessUserHandler HandleProcessUser;
333         IsNickHandler HandleIsNick;
334         IsIdentHandler HandleIsIdent;
335         FindDescriptorHandler HandleFindDescriptor;
336         FloodQuitUserHandler HandleFloodQuitUser;
337
338         /** InspSocket classes pending deletion after being closed.
339          * We don't delete these immediately as this may cause a segmentation fault.
340          */
341         std::map<InspSocket*,InspSocket*> SocketCull;
342
343         /** 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
344          * Reason for it:
345          * kludge alert!
346          * SendMode expects a userrec* to send the numeric replies
347          * back to, so we create it a fake user that isnt in the user
348          * hash and set its descriptor to FD_MAGIC_NUMBER so the data
349          * falls into the abyss :p
350          */
351         userrec *FakeClient;
352
353         /** Returns the next available UID for this server.
354          */
355         std::string GetUID();
356
357         /** Find a user in the UUID hash
358          * @param nick The nickname to find
359          * @return A pointer to the user, or NULL if the user does not exist
360          */
361         userrec *FindUUID(const std::string &);
362
363         /** Find a user in the UUID hash
364          * @param nick The nickname to find
365          * @return A pointer to the user, or NULL if the user does not exist
366          */
367         userrec *FindUUID(const char *);
368
369         /** Build the ISUPPORT string by triggering all modules On005Numeric events
370          */
371         void BuildISupport();
372
373         /** Number of unregistered users online right now.
374          * (Unregistered means before USER/NICK/dns)
375          */
376         int unregistered_count;
377
378         /** List of server names we've seen.
379          */
380         servernamelist servernames;
381
382         /** Time this ircd was booted
383          */
384         time_t startup_time;
385
386         /** Config file pathname specified on the commandline or via ./configure
387          */
388         char ConfigFileName[MAXBUF];
389
390         /** Mode handler, handles mode setting and removal
391          */
392         ModeParser* Modes;
393
394         /** Command parser, handles client to server commands
395          */
396         CommandParser* Parser;
397
398         /** Socket engine, handles socket activity events
399          */
400         SocketEngine* SE;
401         
402         /** ModuleManager contains everything related to loading/unloading
403          * modules.
404          */
405         ModuleManager* Modules;
406
407         /** Stats class, holds miscellaneous stats counters
408          */
409         serverstats* stats;
410
411         /**  Server Config class, holds configuration file data
412          */
413         ServerConfig* Config;
414
415         /** Snomask manager - handles routing of snomask messages
416          * to opers.
417          */
418         SnomaskManager* SNO;
419
420         /** Client list, a hash_map containing all clients, local and remote
421          */
422         user_hash* clientlist;
423
424         /** Client list stored by UUID. Contains all clients, and is updated
425          * automatically by the constructor and destructor of userrec.
426          */
427         user_hash* uuidlist;
428
429         /** Channel list, a hash_map containing all channels
430          */
431         chan_hash* chanlist;
432
433         /** Local client list, a vector containing only local clients
434          */
435         std::vector<userrec*> local_users;
436
437         /** Oper list, a vector containing all local and remote opered users
438          */
439         std::vector<userrec*> all_opers;
440
441         /** Map of local ip addresses for clone counting
442          */
443         clonemap local_clones;
444
445         /** Map of global ip addresses for clone counting
446          */
447         clonemap global_clones;
448
449         /** DNS class, provides resolver facilities to the core and modules
450          */
451         DNS* Res;
452
453         /** Timer manager class, triggers InspTimer timer events
454          */
455         TimerManager* Timers;
456
457         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
458          */
459         XLineManager* XLines;
460
461         /** The time we next call our ping timeout and reg timeout checks
462          */
463         time_t next_call;
464
465         /** Set to the current signal recieved
466          */
467         int s_signal;
468
469         /** Get the current time
470          * Because this only calls time() once every time around the mainloop,
471          * it is much faster than calling time() directly.
472          * @param delta True to use the delta as an offset, false otherwise
473          * @return The current time as an epoch value (time_t)
474          */
475         time_t Time(bool delta = false);
476
477         /** Set the time offset in seconds
478          * This offset is added to Time() to offset the system time by the specified
479          * number of seconds.
480          * @param delta The number of seconds to offset
481          * @return The old time delta
482          */
483         int SetTimeDelta(int delta);
484
485         /** Add a user to the local clone map
486          * @param user The user to add
487          */
488         void AddLocalClone(userrec* user);
489
490         /** Add a user to the global clone map
491          * @param user The user to add
492          */
493         void AddGlobalClone(userrec* user);
494         
495         /** Number of users with a certain mode set on them
496          */
497         int ModeCount(const char mode);
498
499         /** Get the time offset in seconds
500          * @return The current time delta (in seconds)
501          */
502         int GetTimeDelta();
503
504         /** Process a user whos socket has been flagged as active
505          * @param cu The user to process
506          * @return There is no actual return value, however upon exit, the user 'cu' may have been
507          * marked for deletion in the global CullList.
508          */
509         caller1<void, userrec*> ProcessUser;
510
511         /** Bind all ports specified in the configuration file.
512          * @param bail True if the function should bail back to the shell on failure
513          * @param found_ports The actual number of ports found in the config, as opposed to the number actually bound
514          * @return The number of ports actually bound without error
515          */
516         int BindPorts(bool bail, int &found_ports, FailedPortList &failed_ports);
517
518         /** Binds a socket on an already open file descriptor
519          * @param sockfd A valid file descriptor of an open socket
520          * @param port The port number to bind to
521          * @param addr The address to bind to (IP only)
522          * @return True if the port was bound successfully
523          */
524         bool BindSocket(int sockfd, int port, char* addr, bool dolisten = true);
525
526         /** Adds a server name to the list of servers we've seen
527          * @param The servername to add
528          */
529         void AddServerName(const std::string &servername);
530
531         /** Finds a cached char* pointer of a server name,
532          * This is used to optimize userrec by storing only the pointer to the name
533          * @param The servername to find
534          * @return A pointer to this name, gauranteed to never become invalid
535          */
536         const char* FindServerNamePtr(const std::string &servername);
537
538         /** Returns true if we've seen the given server name before
539          * @param The servername to find
540          * @return True if we've seen this server name before
541          */
542         bool FindServerName(const std::string &servername);
543
544         /** Gets the GECOS (description) field of the given server.
545          * If the servername is not that of the local server, the name
546          * is passed to handling modules which will attempt to determine
547          * the GECOS that bleongs to the given servername.
548          * @param servername The servername to find the description of
549          * @return The description of this server, or of the local server
550          */
551         std::string GetServerDescription(const char* servername);
552
553         /** Write text to all opers connected to this server
554          * @param text The text format string
555          * @param ... Format args
556          */
557         void WriteOpers(const char* text, ...);
558
559         /** Write text to all opers connected to this server
560          * @param text The text to send
561          */
562         void WriteOpers(const std::string &text);
563
564         /** Find a user in the nick hash.
565          * If the user cant be found in the nick hash check the uuid hash
566          * @param nick The nickname to find
567          * @return A pointer to the user, or NULL if the user does not exist
568          */
569         userrec* FindNick(const std::string &nick);
570
571         /** Find a user in the nick hash.
572          * If the user cant be found in the nick hash check the uuid hash
573          * @param nick The nickname to find
574          * @return A pointer to the user, or NULL if the user does not exist
575          */
576         userrec* FindNick(const char* nick);
577
578         /** Find a user in the nick hash ONLY
579          */
580         userrec* FindNickOnly(const char* nick);
581
582         /** Find a user in the nick hash ONLY
583          */
584         userrec* FindNickOnly(const std::string &nick);
585
586         /** Find a channel in the channels hash
587          * @param chan The channel to find
588          * @return A pointer to the channel, or NULL if the channel does not exist
589          */
590         chanrec* FindChan(const std::string &chan);
591
592         /** Find a channel in the channels hash
593          * @param chan The channel to find
594          * @return A pointer to the channel, or NULL if the channel does not exist
595          */
596         chanrec* FindChan(const char* chan);
597
598         /** Check for a 'die' tag in the config file, and abort if found
599          * @return Depending on the configuration, this function may never return
600          */
601         void CheckDie();
602
603         /** Check we aren't running as root, and exit if we are
604          * @return Depending on the configuration, this function may never return
605          */
606         void CheckRoot();
607
608         /** Determine the right path for, and open, the logfile
609          * @param argv The argv passed to main() initially, used to calculate program path
610          * @param argc The argc passed to main() initially, used to calculate program path
611          * @return True if the log could be opened, false if otherwise
612          */
613         bool OpenLog(char** argv, int argc);
614
615         /** Close the currently open log file
616          */
617         void CloseLog();
618
619         /** Send a server notice to all local users
620          * @param text The text format string to send
621          * @param ... The format arguments
622          */
623         void ServerNoticeAll(char* text, ...);
624
625         /** Send a server message (PRIVMSG) to all local users
626          * @param text The text format string to send
627          * @param ... The format arguments
628          */
629         void ServerPrivmsgAll(char* text, ...);
630
631         /** Send text to all users with a specific set of modes
632          * @param modes The modes to check against, without a +, e.g. 'og'
633          * @param flags one of WM_OR or WM_AND. If you specify WM_OR, any one of the
634          * mode characters in the first parameter causes receipt of the message, and
635          * if you specify WM_OR, all the modes must be present.
636          * @param text The text format string to send
637          * @param ... The format arguments
638          */
639         void WriteMode(const char* modes, int flags, const char* text, ...);
640
641         /** Return true if a channel name is valid
642          * @param chname A channel name to verify
643          * @return True if the name is valid
644          */
645         bool IsChannel(const char *chname);
646
647         /** Rehash the local server
648          */
649         void Rehash();
650
651         /** Handles incoming signals after being set
652          * @param signal the signal recieved
653          */
654         void SignalHandler(int signal);
655
656         /** Sets the signal recieved    
657          * @param signal the signal recieved
658          */
659         static void SetSignal(int signal);
660
661         /** Causes the server to exit after unloading modules and
662          * closing all open file descriptors.
663          *
664          * @param The exit code to give to the operating system
665          * (See the ExitStatus enum for valid values)
666          */
667         void Exit(int status);
668
669         /** Causes the server to exit immediately with exit code 0.
670          * The status code is required for signal handlers, and ignored.
671          */
672         static void QuickExit(int status);
673
674         /** Return a count of users, unknown and known connections
675          * @return The number of users
676          */
677         int UserCount();
678
679         /** Return a count of fully registered connections only
680          * @return The number of registered users
681          */
682         int RegisteredUserCount();
683
684         /** Return a count of invisible (umode +i) users only
685          * @return The number of invisible users
686          */
687         int InvisibleUserCount();
688
689         /** Return a count of opered (umode +o) users only
690          * @return The number of opers
691          */
692         int OperCount();
693
694         /** Return a count of unregistered (before NICK/USER) users only
695          * @return The number of unregistered (unknown) connections
696          */
697         int UnregisteredUserCount();
698
699         /** Return a count of channels on the network
700          * @return The number of channels
701          */
702         long ChannelCount();
703
704         /** Return a count of local users on this server only
705          * @return The number of local users
706          */
707         long LocalUserCount();
708
709         /** Send an error notice to all local users, opered and unopered
710          * @param s The error string to send
711          */
712         void SendError(const std::string &s);
713
714         /** Return true if a nickname is valid
715          * @param n A nickname to verify
716          * @return True if the nick is valid
717          */
718         caller1<bool, const char*> IsNick;
719
720         /** Return true if an ident is valid
721          * @param An ident to verify
722          * @return True if the ident is valid
723          */
724         caller1<bool, const char*> IsIdent;
725
726         /** Find a username by their file descriptor.
727          * It is preferred to use this over directly accessing the fd_ref_table array.
728          * @param socket The file descriptor of a user
729          * @return A pointer to the user if the user exists locally on this descriptor
730          */
731         caller1<userrec*, int> FindDescriptor;
732
733         /** Add a new mode to this server's mode parser
734          * @param mh The modehandler to add
735          * @param modechar The mode character this modehandler handles
736          * @return True if the mode handler was added
737          */
738         bool AddMode(ModeHandler* mh, const unsigned char modechar);
739
740         /** Add a new mode watcher to this server's mode parser
741          * @param mw The modewatcher to add
742          * @return True if the modewatcher was added
743          */
744         bool AddModeWatcher(ModeWatcher* mw);
745
746         /** Delete a mode watcher from this server's mode parser
747          * @param mw The modewatcher to delete
748          * @return True if the modewatcher was deleted
749          */
750         bool DelModeWatcher(ModeWatcher* mw);
751
752         /** Add a dns Resolver class to this server's active set
753          * @param r The resolver to add
754          * @param cached If this value is true, then the cache will
755          * be searched for the DNS result, immediately. If the value is
756          * false, then a request will be sent to the nameserver, and the
757          * result will not be immediately available. You should usually
758          * use the boolean value which you passed to the Resolver
759          * constructor, which Resolver will set appropriately depending
760          * on if cached results are available and haven't expired. It is
761          * however safe to force this value to false, forcing a remote DNS
762          * lookup, but not an update of the cache.
763          * @return True if the operation completed successfully. Note that
764          * if this method returns true, you should not attempt to access
765          * the resolver class you pass it after this call, as depending upon
766          * the request given, the object may be deleted!
767          */
768         bool AddResolver(Resolver* r, bool cached);
769
770         /** Add a command to this server's command parser
771          * @param f A command_t command handler object to add
772          * @throw ModuleException Will throw ModuleExcption if the command already exists
773          */
774         void AddCommand(command_t *f);
775
776         /** Send a modechange.
777          * The parameters provided are identical to that sent to the
778          * handler for class cmd_mode.
779          * @param parameters The mode parameters
780          * @param pcnt The number of items you have given in the first parameter
781          * @param user The user to send error messages to
782          */
783         void SendMode(const char **parameters, int pcnt, userrec *user);
784
785         /** Match two strings using pattern matching.
786          * This operates identically to the global function match(),
787          * except for that it takes std::string arguments rather than
788          * const char* ones.
789          * @param sliteral The literal string to match against
790          * @param spattern The pattern to match against. CIDR and globs are supported.
791          */
792         bool MatchText(const std::string &sliteral, const std::string &spattern);
793
794         /** Call the handler for a given command.
795          * @param commandname The command whos handler you wish to call
796          * @param parameters The mode parameters
797          * @param pcnt The number of items you have given in the first parameter
798          * @param user The user to execute the command as
799          * @return True if the command handler was called successfully
800          */
801         CmdResult CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
802
803         /** Return true if the command is a module-implemented command and the given parameters are valid for it
804          * @param parameters The mode parameters
805          * @param pcnt The number of items you have given in the first parameter
806          * @param user The user to test-execute the command as
807          * @return True if the command handler is a module command, and there are enough parameters and the user has permission to the command
808          */
809         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
810
811         /** Add a gline and apply it
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 AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
818
819         /** Add a qline and apply it
820          * @param duration How long the line should last
821          * @param source Who set the line
822          * @param reason The reason for the line
823          * @param nickname The nickmask to set the line against
824          */
825         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
826
827         /** Add a zline and apply it
828          * @param duration How long the line should last
829          * @param source Who set the line
830          * @param reason The reason for the line
831          * @param ipaddr The ip-mask to set the line against
832          */
833         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
834
835         /** Add a kline and apply it
836          * @param duration How long the line should last
837          * @param source Who set the line
838          * @param reason The reason for the line
839          * @param hostmask The hostmask to set the line against
840          */
841         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
842
843         /** Add an eline
844          * @param duration How long the line should last
845          * @param source Who set the line
846          * @param reason The reason for the line
847          * @param hostmask The hostmask to set the line against
848          */
849         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
850
851         /** Delete a gline
852          * @param hostmask The gline to delete
853          * @return True if the item was removed
854          */
855         bool DelGLine(const std::string &hostmask);
856
857         /** Delete a qline
858          * @param nickname The qline to delete
859          * @return True if the item was removed
860          */
861         bool DelQLine(const std::string &nickname);
862
863         /** Delete a zline
864          * @param ipaddr The zline to delete
865          * @return True if the item was removed
866          */
867         bool DelZLine(const std::string &ipaddr);
868
869         /** Delete a kline
870          * @param hostmask The kline to delete
871          * @return True if the item was removed
872          */
873         bool DelKLine(const std::string &hostmask);
874
875         /** Delete an eline
876          * @param hostmask The kline to delete
877          * @return True if the item was removed
878          */
879         bool DelELine(const std::string &hostmask);
880
881         /** Return true if the given parameter is a valid nick!user\@host mask
882          * @param mask A nick!user\@host masak to match against
883          * @return True i the mask is valid
884          */
885         bool IsValidMask(const std::string &mask);
886
887         /** Rehash the local server
888          */
889         void RehashServer();
890
891         /** Return the channel whos index number matches that provided
892          * @param The index number of the channel to fetch
893          * @return A channel record, or NUll if index < 0 or index >= InspIRCd::ChannelCount()
894          */
895         chanrec* GetChannelIndex(long index);
896
897         /** Dump text to a user target, splitting it appropriately to fit
898          * @param User the user to dump the text to
899          * @param LinePrefix text to prefix each complete line with
900          * @param TextStream the text to send to the user
901          */
902         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
903
904         /** Check if the given nickmask matches too many users, send errors to the given user
905          * @param nick A nickmask to match against
906          * @param user A user to send error text to
907          * @return True if the nick matches too many users
908          */
909         bool NickMatchesEveryone(const std::string &nick, userrec* user);
910
911         /** Check if the given IP mask matches too many users, send errors to the given user
912          * @param ip An ipmask to match against
913          * @param user A user to send error text to
914          * @return True if the ip matches too many users
915          */
916         bool IPMatchesEveryone(const std::string &ip, userrec* user);
917
918         /** Check if the given hostmask matches too many users, send errors to the given user
919          * @param mask A hostmask to match against
920          * @param user A user to send error text to
921          * @return True if the host matches too many users
922          */
923         bool HostMatchesEveryone(const std::string &mask, userrec* user);
924
925         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
926          * @param str A string containing a time in the form 1y2w3d4h6m5s
927          * (one year, two weeks, three days, four hours, six minutes and five seconds)
928          * @return The total number of seconds
929          */
930         long Duration(const std::string &str);
931
932         /** Attempt to compare an oper password to a string from the config file.
933          * This will be passed to handling modules which will compare the data
934          * against possible hashed equivalents in the input string.
935          * @param data The data from the config file
936          * @param input The data input by the oper
937          * @param tagnum the tag number of the oper's tag in the config file
938          * @return 0 if the strings match, 1 or -1 if they do not
939          */
940         int OperPassCompare(const char* data,const char* input, int tagnum);
941
942         /** Check if a given server is a uline.
943          * An empty string returns true, this is by design.
944          * @param server The server to check for uline status
945          * @return True if the server is a uline OR the string is empty
946          */
947         bool ULine(const char* server);
948
949         /** Returns true if the uline is 'silent' (doesnt generate
950          * remote connect notices etc).
951          */
952         bool SilentULine(const char* server);
953
954         /** Returns the subversion revision ID of this ircd
955          * @return The revision ID or an empty string
956          */
957         std::string GetRevision();
958
959         /** Returns the full version string of this ircd
960          * @return The version string
961          */
962         std::string GetVersionString();
963
964         /** Attempt to write the process id to a given file
965          * @param filename The PID file to attempt to write to
966          * @return This function may bail if the file cannot be written
967          */
968         void WritePID(const std::string &filename);
969
970         /** This constructor initialises all the subsystems and reads the config file.
971          * @param argc The argument count passed to main()
972          * @param argv The argument list passed to main()
973          * @throw <anything> If anything is thrown from here and makes it to
974          * you, you should probably just give up and go home. Yes, really.
975          * It's that bad. Higher level classes should catch any non-fatal exceptions.
976          */
977         InspIRCd(int argc, char** argv);
978
979         /** Do one iteration of the mainloop
980          * @param process_module_sockets True if module sockets are to be processed
981          * this time around the event loop. The is the default.
982          */
983         void DoOneIteration(bool process_module_sockets = true);
984
985         /** Output a log message to the ircd.log file
986          * The text will only be output if the current loglevel
987          * is less than or equal to the level you provide
988          * @param level A log level from the DebugLevel enum
989          * @param text Format string of to write to the log
990          * @param ... Format arguments of text to write to the log
991          */
992         void Log(int level, const char* text, ...);
993
994         /** Output a log message to the ircd.log file
995          * The text will only be output if the current loglevel
996          * is less than or equal to the level you provide
997          * @param level A log level from the DebugLevel enum
998          * @param text Text to write to the log
999          */
1000         void Log(int level, const std::string &text);
1001
1002         /** Send a line of WHOIS data to a user.
1003          * @param user user to send the line to
1004          * @param dest user being WHOISed
1005          * @param numeric Numeric to send
1006          * @param text Text of the numeric
1007          */
1008         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const std::string &text);
1009
1010         /** Send a line of WHOIS data to a user.
1011          * @param user user to send the line to
1012          * @param dest user being WHOISed
1013          * @param numeric Numeric to send
1014          * @param format Format string for the numeric
1015          * @param ... Parameters for the format string
1016          */
1017         void SendWhoisLine(userrec* user, userrec* dest, int numeric, const char* format, ...);
1018
1019         /** Quit a user for excess flood, and if they are not
1020          * fully registered yet, temporarily zline their IP.
1021          * @param current user to quit
1022          */
1023         caller1<void, userrec*> FloodQuitUser;
1024
1025         /** Restart the server.
1026          * This function will not return. If an error occurs,
1027          * it will throw an instance of CoreException.
1028          * @param reason The restart reason to show to all clients
1029          * @throw CoreException An instance of CoreException indicating the error from execv().
1030          */
1031         void Restart(const std::string &reason);
1032
1033         /** Prepare the ircd for restart or shutdown.
1034          * This function unloads all modules which can be unloaded,
1035          * closes all open sockets, and closes the logfile.
1036          */
1037         void Cleanup();
1038
1039         /** This copies the user and channel hash_maps into new hash maps.
1040          * This frees memory used by the hash_map allocator (which it neglects
1041          * to free, most of the time, using tons of ram)
1042          */
1043         void RehashUsersAndChans();
1044
1045         /** Resets the cached max bans value on all channels.
1046          * Called by rehash.
1047          */
1048         void ResetMaxBans();
1049
1050         /** Return a time_t as a human-readable string.
1051          */
1052         std::string TimeString(time_t curtime);
1053
1054         /** Begin execution of the server.
1055          * NOTE: this function NEVER returns. Internally,
1056          * after performing some initialisation routines,
1057          * it will repeatedly call DoOneIteration in a loop.
1058          * @return The return value for this function is undefined.
1059          */
1060         int Run();
1061
1062         /** Force all InspSockets to be removed which are due to
1063          * be culled.
1064          */
1065         void InspSocketCull();
1066
1067         char* GetReadBuffer()
1068         {
1069                 return this->ReadBuffer;
1070         }
1071 };
1072
1073 #endif