]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/inspircd.h
Tons more docs
[user/henk/code/inspircd.git] / include / inspircd.h
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #ifndef __INSPIRCD_H__
18 #define __INSPIRCD_H__
19
20 #include <time.h>
21 #include <string>
22 #include <sstream>
23 #include "inspircd_config.h"
24 #include "users.h"
25 #include "channels.h"
26 #include "socket.h"
27 #include "mode.h"
28 #include "helperfuncs.h"
29 #include "socketengine.h"
30 #include "command_parse.h"
31
32 /** Returned by some functions to indicate failure,
33  * and the exit code of the program if it terminates.
34  */
35 #define ERROR -1
36
37 /** Crucial defines
38  */
39 #define ETIREDGERBILS EAGAIN
40
41 /** Debug levels for use with InspIRCd::Log()
42  */
43 enum DebugLevel
44 {
45         DEBUG           =       10,
46         VERBOSE         =       20,
47         DEFAULT         =       30,
48         SPARSE          =       40,
49         NONE            =       50,
50 };
51
52 /**
53  * This define is used in place of strcmp when we 
54  * want to check if a char* string contains only one
55  * letter. Pretty fast, its just two compares and an
56  * addition.
57  */
58 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
59
60 /** Delete a pointer, and NULL its value
61  */
62 #define DELETE(x) {if (x) { delete x; x = NULL; }}
63
64 /** Template function to convert any input type to std::string
65  */
66 template<typename T> inline std::string ConvToStr(const T &in)
67 {
68         std::stringstream tmp;
69         if (!(tmp << in)) return std::string();
70         return tmp.str();
71 }
72
73 /** This class contains various STATS counters
74  * It is used by the InspIRCd class, which internally
75  * has an instance of it.
76  */
77 class serverstats : public classbase
78 {
79   public:
80         /** Number of accepted connections
81          */
82         unsigned long statsAccept;
83         /** Number of failed accepts
84          */
85         unsigned long statsRefused;
86         /** Number of unknown commands seen
87          */
88         unsigned long statsUnknown;
89         /** Number of nickname collisions handled
90          */
91         unsigned long statsCollisions;
92         /** Number of DNS queries sent out
93          */
94         unsigned long statsDns;
95         /** Number of good DNS replies received
96          * NOTE: This may not tally to the number sent out,
97          * due to timeouts and other latency issues.
98          */
99         unsigned long statsDnsGood;
100         /** Number of bad (negative) DNS replies received
101          * NOTE: This may not tally to the number sent out,
102          * due to timeouts and other latency issues.
103          */
104         unsigned long statsDnsBad;
105         /** Number of inbound connections seen
106          */
107         unsigned long statsConnects;
108         /** Total bytes of data transmitted
109          */
110         double statsSent;
111         /** Total bytes of data received
112          */
113         double statsRecv;
114         /** Number of bound listening ports
115          */
116         unsigned long BoundPortCount;
117
118         /** The constructor initializes all the counts to zero
119          */
120         serverstats()
121                 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
122                 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0),
123                 BoundPortCount(0)
124         {
125         }
126 };
127
128 class XLineManager;
129
130 /** The main singleton class of the irc server.
131  * This class contains instances of all the other classes
132  * in this software, with the exception of the base class,
133  * classbase. Amongst other things, it contains a ModeParser,
134  * a DNS object, a CommandParser object, and a list of active
135  * Module objects, and facilities for Module objects to
136  * interact with the core system it implements. You should
137  * NEVER attempt to instantiate a class of type InspIRCd
138  * yourself. If you do, this is equivalent to spawning a second
139  * IRC server, and could have catastrophic consequences for the
140  * program in terms of ram usage (basically, you could create
141  * an obese forkbomb built from recursively spawning irc servers!)
142  */
143 class InspIRCd : public classbase
144 {
145  private:
146         /** Holds a string describing the last module error to occur
147          */
148         char MODERR[MAXBUF];
149
150         /** This is an internal flag used by the mainloop
151          */
152         bool expire_run;
153
154         /** List of server names we've seen.
155          */
156         servernamelist servernames;
157  
158         /** Remove a ModuleFactory pointer
159          */
160         void EraseFactory(int j);
161
162         /** Remove a Module pointer
163          */
164         void EraseModule(int j);
165
166         /** Build the ISUPPORT string by triggering all modules On005Numeric events
167          */
168         void BuildISupport();
169
170         /** Move a given module to a specific slot in the list
171          */
172         void MoveTo(std::string modulename,int slot);
173
174         /** Display the startup banner
175          */
176         void Start();
177
178         /** Set up the signal handlers
179          */
180         void SetSignals(bool SEGVHandler);
181
182         /** Daemonize the ircd and close standard input/output streams
183          */
184         bool DaemonSeed();
185
186         /** Build the upper/lowercase comparison table
187          */
188         void MakeLowerMap();
189
190         /** Moves the given module to the last slot in the list
191          */
192         void MoveToLast(std::string modulename);
193
194         /** Moves the given module to the first slot in the list
195          */
196         void MoveToFirst(std::string modulename);
197
198         /** Moves one module to be placed after another in the list
199          */
200         void MoveAfter(std::string modulename, std::string after);
201
202         /** Moves one module to be placed before another in the list
203          */
204         void MoveBefore(std::string modulename, std::string before);
205
206         /** Process a user whos socket has been flagged as active
207          */
208         void ProcessUser(userrec* cu);
209
210         /** Iterate the list of InspSocket objects, removing ones which have timed out
211          */
212         void DoSocketTimeouts(time_t TIME);
213
214         /** Perform background user events such as PING checks
215          */
216         void DoBackgroundUserStuff(time_t TIME);
217
218         /** Returns true when all modules have done pre-registration checks on a user
219          */
220         bool AllModulesReportReady(userrec* user);
221
222         /** Total number of modules loaded into the ircd, minus one
223          */
224         int ModCount;
225
226         /** Logfile pathname specified on the commandline, or empty string
227          */
228         char LogFileName[MAXBUF];
229
230         /** The feature names published by various modules
231          */
232         featurelist Features;
233
234         /** The current time, updated in the mainloop
235          */
236         time_t TIME;
237
238         /** The time that was recorded last time around the mainloop
239          */
240         time_t OLDTIME;
241
242         /** A 64k buffer used to read client lines into
243          */
244         char ReadBuffer[65535];
245
246         /** Number of seconds in a minute
247          */
248         const long duration_m;
249
250         /** Number of seconds in an hour
251          */
252         const long duration_h;
253
254         /** Number of seconds in a day
255          */
256         const long duration_d;
257
258         /** Number of seconds in a week
259          */
260         const long duration_w;
261
262         /** Number of seconds in a year
263          */
264         const long duration_y;
265
266  public:
267         /** Time this ircd was booted
268          */
269         time_t startup_time;
270
271         /** Mode handler, handles mode setting and removal
272          */
273         ModeParser* Modes;
274
275         /** Command parser, handles client to server commands
276          */
277         CommandParser* Parser;
278
279         /** Socket engine, handles socket activity events
280          */
281         SocketEngine* SE;
282
283         /** Stats class, holds miscellaneous stats counters
284          */
285         serverstats* stats;
286
287         /**  Server Config class, holds configuration file data
288          */
289         ServerConfig* Config;
290
291         /** Module sockets list, holds the active set of InspSocket classes
292          */
293         std::vector<InspSocket*> module_sockets;
294
295         /** Socket reference table, provides fast lookup of fd to InspSocket*
296          */
297         InspSocket* socket_ref[MAX_DESCRIPTORS];
298
299         /** user reference table, provides fast lookup of fd to userrec*
300          */
301         userrec* fd_ref_table[MAX_DESCRIPTORS];
302
303         /** Client list, a hash_map containing all clients, local and remote
304          */
305         user_hash clientlist;
306
307         /** Channel list, a hash_map containing all channels
308          */
309         chan_hash chanlist;
310
311         /** Local client list, a vector containing only local clients
312          */
313         std::vector<userrec*> local_users;
314
315         /** Oper list, a vector containing all local and remote opered users
316          */
317         std::vector<userrec*> all_opers;
318
319         /** Whowas container, contains a map of vectors of users tracked by WHOWAS
320          */
321         irc::whowas::whowas_users whowas;
322
323         /** DNS class, provides resolver facilities to the core and modules
324          */
325         DNS* Res;
326
327         /** Timer manager class, triggers InspTimer timer events
328          */
329         TimerManager* Timers;
330
331         /** Command list, a hash_map of command names to command_t*
332          */
333         command_table cmdlist;
334
335         /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
336          */
337         XLineManager* XLines;
338
339         /** A list of Module* module classes
340          * Note that this list is always exactly 255 in size.
341          * The actual number of loaded modules is available from GetModuleCount()
342          */
343         ModuleList modules;
344
345         /** A list of ModuleFactory* module factories
346          * Note that this list is always exactly 255 in size.
347          * The actual number of loaded modules is available from GetModuleCount()
348          */
349         FactoryList factory;
350
351         /** Get the current time
352          * Because this only calls time() once every time around the mainloop,
353          * it is much faster than calling time() directly.
354          */
355         time_t Time();
356
357         /** Get the total number of currently loaded modules
358          */
359         int GetModuleCount();
360
361         /** Find a module by name, and return a Module* to it.
362          * This is preferred over iterating the module lists yourself.
363          * @param name The module name to look up
364          */
365         Module* FindModule(const std::string &name);
366
367         /** Bind all ports specified in the configuration file.
368          * @param bail True if the function should bail back to the shell on failure
369          */
370         int BindPorts(bool bail);
371
372         /** Returns true if this server has the given port bound to the given address
373          */
374         bool HasPort(int port, char* addr);
375
376         /** Binds a socket on an already open file descriptor
377          */
378         bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
379
380         /** Adds a server name to the list of servers we've seen
381          */
382         void AddServerName(const std::string &servername);
383
384         /** Finds a cached char* pointer of a server name,
385          * This is used to optimize userrec by storing only the pointer to the name
386          */
387         const char* FindServerNamePtr(const std::string &servername);
388
389         /** Returns true if we've seen the given server name before
390          */
391         bool FindServerName(const std::string &servername);
392
393         /** Gets the GECOS (description) field of the given server.
394          * If the servername is not that of the local server, the name
395          * is passed to handling modules which will attempt to determine
396          * the GECOS that bleongs to the given servername.
397          */
398         std::string GetServerDescription(const char* servername);
399
400         /** Write text to all opers connected to this server
401          */
402         void WriteOpers(const char* text, ...);
403
404         /** Write text to all opers connected to this server
405          */
406         void WriteOpers(const std::string &text);
407         
408         /** Find a nickname in the nick hash
409          */
410         userrec* FindNick(const std::string &nick);
411
412         /** Find a nickname in the nick hash
413          */
414         userrec* FindNick(const char* nick);
415
416         /** Find a channel in the channels hash
417          */
418         chanrec* FindChan(const std::string &chan);
419
420         /** Find a channel in the channels hash
421          */
422         chanrec* FindChan(const char* chan);
423
424         /** Called by the constructor to load all modules from the config file.
425          */
426         void LoadAllModules();
427
428         /** Check for a 'die' tag in the config file, and abort if found
429          */
430         void CheckDie();
431
432         /** Check we aren't running as root, and exit if we are
433          */
434         void CheckRoot();
435
436         /** Determine the right path for, and open, the logfile
437          */
438         void OpenLog(char** argv, int argc);
439
440         /** Convert a user to a pseudoclient, disconnecting the real user
441          */
442         bool UserToPseudo(userrec* user, const std::string &message);
443
444         /** Convert a pseudoclient to a real user, discarding the pseudoclient
445          */
446         bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
447
448         /** Send a server notice to all local users
449          */
450         void ServerNoticeAll(char* text, ...);
451
452         /** Send a server message (PRIVMSG) to all local users
453          */
454         void ServerPrivmsgAll(char* text, ...);
455
456         /** Send text to all users with a specific set of modes
457          */
458         void WriteMode(const char* modes, int flags, const char* text, ...);
459
460         /** Return true if a channel name is valid
461          */
462         bool IsChannel(const char *chname);
463
464         /** Rehash the local server
465          */
466         static void Rehash(int status);
467
468         /** Causes the server to exit immediately
469          */
470         static void Exit(int status);
471
472         /** Return a count of users, unknown and known connections
473          */
474         int UserCount();
475
476         /** Return a count of fully registered connections only
477          */
478         int RegisteredUserCount();
479
480         /** Return a count of invisible (umode +i) users only
481          */
482         int InvisibleUserCount();
483
484         /** Return a count of opered (umode +o) users only
485          */
486         int OperCount();
487
488         /** Return a count of unregistered (before NICK/USER) users only
489          */
490         int UnregisteredUserCount();
491
492         /** Return a count of channels on the network
493          */
494         long ChannelCount();
495
496         /** Return a count of local users on this server only
497          */
498         long LocalUserCount();
499
500         /** Send an error notice to all local users, opered and unopered
501          */
502         void SendError(const char *s);
503
504         /** For use with Module::Prioritize().
505          * When the return value of this function is returned from
506          * Module::Prioritize(), this specifies that the module wishes
507          * to be ordered exactly BEFORE 'modulename'. For more information
508          * please see Module::Prioritize().
509          * @param modulename The module your module wants to be before in the call list
510          * @returns a priority ID which the core uses to relocate the module in the list
511          */
512         long PriorityBefore(const std::string &modulename);
513
514         /** For use with Module::Prioritize().
515          * When the return value of this function is returned from
516          * Module::Prioritize(), this specifies that the module wishes
517          * to be ordered exactly AFTER 'modulename'. For more information please
518          * see Module::Prioritize().
519          * @param modulename The module your module wants to be after in the call list
520          * @returns a priority ID which the core uses to relocate the module in the list
521          */
522         long PriorityAfter(const std::string &modulename);
523
524         /** Publish a 'feature'.
525          * There are two ways for a module to find another module it depends on.
526          * Either by name, using InspIRCd::FindModule, or by feature, using this
527          * function. A feature is an arbitary string which identifies something this
528          * module can do. For example, if your module provides SSL support, but other
529          * modules provide SSL support too, all the modules supporting SSL should
530          * publish an identical 'SSL' feature. This way, any module requiring use
531          * of SSL functions can just look up the 'SSL' feature using FindFeature,
532          * then use the module pointer they are given.
533          * @param FeatureName The case sensitive feature name to make available
534          * @param Mod a pointer to your module class
535          * @returns True on success, false if the feature is already published by
536          * another module.
537          */
538         bool PublishFeature(const std::string &FeatureName, Module* Mod);
539
540         /** Unpublish a 'feature'.
541          * When your module exits, it must call this method for every feature it
542          * is providing so that the feature table is cleaned up.
543          * @param FeatureName the feature to remove
544          */
545         bool UnpublishFeature(const std::string &FeatureName);
546
547         /** Find a 'feature'.
548          * There are two ways for a module to find another module it depends on.
549          * Either by name, using InspIRCd::FindModule, or by feature, using the
550          * InspIRCd::PublishFeature method. A feature is an arbitary string which
551          * identifies something this module can do. For example, if your module
552          * provides SSL support, but other modules provide SSL support too, all
553          * the modules supporting SSL should publish an identical 'SSL' feature.
554          * To find a module capable of providing the feature you want, simply
555          * call this method with the feature name you are looking for.
556          * @param FeatureName The feature name you wish to obtain the module for
557          * @returns A pointer to a valid module class on success, NULL on failure.
558          */
559         Module* FindFeature(const std::string &FeatureName);
560
561         /** Given a pointer to a Module, return its filename
562          */
563         const std::string& GetModuleName(Module* m);
564
565         /** Return true if a nickname is valid
566          */
567         bool IsNick(const char* n);
568
569         /** Return true if an ident is valid
570          */
571         bool IsIdent(const char* n);
572
573         /** Find a username by their file descriptor.
574          * It is preferred to use this over directly accessing the fd_ref_table array.
575          */
576         userrec* FindDescriptor(int socket);
577
578         /** Add a new mode to this server's mode parser
579          */
580         bool AddMode(ModeHandler* mh, const unsigned char modechar);
581
582         /** Add a new mode watcher to this server's mode parser
583          */
584         bool AddModeWatcher(ModeWatcher* mw);
585
586         /** Delete a mode watcher from this server's mode parser
587          */
588         bool DelModeWatcher(ModeWatcher* mw);
589
590         /** Add a dns Resolver class to this server's active set
591          */
592         bool AddResolver(Resolver* r);
593
594         /** Add a command to this server's command parser
595          */
596         void AddCommand(command_t *f);
597
598         /** Send a modechange.
599          * The parameters provided are identical to that sent to the
600          * handler for class cmd_mode.
601          */
602         void SendMode(const char **parameters, int pcnt, userrec *user);
603
604         /** Match two strings using pattern matching.
605          * This operates identically to the global function match(),
606          * except for that it takes std::string arguments rather than
607          * const char* ones.
608          */
609         bool MatchText(const std::string &sliteral, const std::string &spattern);
610
611         /** Call the handler for a given command.
612          * @return True if the command handler was called successfully
613          */
614         bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
615
616         /** Return true if the command is a module-implemented command and the given parameters are valid for it
617          */
618         bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
619
620         /** Add a gline and apply it
621          */
622         void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
623
624         /** Add a qline and apply it
625          */
626         void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
627
628         /** Add a zline and apply it
629          */
630         void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
631
632         /** Add a kline and apply it
633          */
634         void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
635
636         /** Add an eline
637          */
638         void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
639
640         /** Delete a gline
641          */
642         bool DelGLine(const std::string &hostmask);
643
644         /** Delete a qline
645          */
646         bool DelQLine(const std::string &nickname);
647
648         /** Delete a zline
649          */
650         bool DelZLine(const std::string &ipaddr);
651
652         /** Delete a kline
653          */
654         bool DelKLine(const std::string &hostmask);
655
656         /** Delete an eline
657          */
658         bool DelELine(const std::string &hostmask);
659
660         /** Return true if the given parameter is a valid nick!user@host mask
661          */
662         bool IsValidMask(const std::string &mask);
663
664         /** Add an InspSocket class to the active set
665          */
666         void AddSocket(InspSocket* sock);
667
668         /** Remove an InspSocket class from the active set at next time around the loop
669          */
670         void RemoveSocket(InspSocket* sock);
671
672         /** Delete a socket immediately without waiting for the next iteration of the mainloop
673          */
674         void DelSocket(InspSocket* sock);
675
676         /** Rehash the local server
677          */
678         void RehashServer();
679
680         /** Return the channel whos index number matches that provided
681          */
682         chanrec* GetChannelIndex(long index);
683
684         /** Dump text to a user target, splitting it appropriately to fit
685          */
686         void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
687
688         /** Check if the given nickmask matches too many users, send errors to the given user
689          */
690         bool NickMatchesEveryone(const std::string &nick, userrec* user);
691
692         /** Check if the given IP mask matches too many users, send errors to the given user
693          */
694         bool IPMatchesEveryone(const std::string &ip, userrec* user);
695
696         /** Check if the given hostmask matches too many users, send errors to the given user
697          */
698         bool HostMatchesEveryone(const std::string &mask, userrec* user);
699
700         /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
701          */
702         long Duration(const char* str);
703
704         /** Attempt to compare an oper password to a string from the config file.
705          * This will be passed to handling modules which will compare the data
706          * against possible hashed equivalents in the input string.
707          */
708         int OperPassCompare(const char* data,const char* input);
709
710         /** Check if a given server is a uline.
711          * An empty string returns true, this is by design.
712          */
713         bool ULine(const char* server);
714
715         /** Returns the subversion revision ID of this ircd
716          */
717         std::string GetRevision();
718
719         /** Returns the full version string of this ircd
720          */
721         std::string GetVersionString();
722
723         /** Attempt to write the process id to a given file
724          */
725         void WritePID(const std::string &filename);
726
727         /** Returns text describing the last module error
728          */
729         char* ModuleError();
730
731         /** Load a given module file
732          */
733         bool LoadModule(const char* filename);
734
735         /** Unload a given module file
736          */
737         bool UnloadModule(const char* filename);
738
739         /** This constructor initialises all the subsystems and reads the config file.
740          */
741         InspIRCd(int argc, char** argv);
742
743         /** Do one iteration of the mainloop
744          */
745         void DoOneIteration(bool process_module_sockets);
746
747         /** Output a log message to the ircd.log file
748          */
749         void Log(int level, const char* text, ...);
750
751         /** Output a log message to the ircd.log file
752          */
753         void Log(int level, const std::string &text);
754
755         /** Begin execution of the server.
756          * NOTE: this function NEVER returns. Internally,
757          * after performing some initialisation routines,
758          * it will repeatedly call DoOneIteration in a loop.
759          */
760         int Run();
761 };
762
763 #endif
764