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