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