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