1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 #ifndef __INSPIRCD_H__
18 #define __INSPIRCD_H__
23 #include "inspircd_config.h"
28 #include "helperfuncs.h"
29 #include "socketengine.h"
30 #include "command_parse.h"
32 /** Returned by some functions to indicate failure,
33 * and the exit code of the program if it terminates.
39 #define ETIREDGERBILS EAGAIN
41 /** Debug levels for use with InspIRCd::Log()
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
58 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
60 /** Delete a pointer, and NULL its value
62 #define DELETE(x) {if (x) { delete x; x = NULL; }}
64 /** Template function to convert any input type to std::string
66 template<typename T> inline std::string ConvToStr(const T &in)
68 std::stringstream tmp;
69 if (!(tmp << in)) return std::string();
73 /** This class contains various STATS counters
74 * It is used by the InspIRCd class, which internally
75 * has an instance of it.
77 class serverstats : public classbase
80 /** Number of accepted connections
82 unsigned long statsAccept;
83 /** Number of failed accepts
85 unsigned long statsRefused;
86 /** Number of unknown commands seen
88 unsigned long statsUnknown;
89 /** Number of nickname collisions handled
91 unsigned long statsCollisions;
92 /** Number of DNS queries sent out
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.
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.
104 unsigned long statsDnsBad;
105 /** Number of inbound connections seen
107 unsigned long statsConnects;
108 /** Total bytes of data transmitted
111 /** Total bytes of data received
114 /** Number of bound listening ports
116 unsigned long BoundPortCount;
118 /** The constructor initializes all the counts to zero
121 : statsAccept(0), statsRefused(0), statsUnknown(0), statsCollisions(0), statsDns(0),
122 statsDnsGood(0), statsDnsBad(0), statsConnects(0), statsSent(0.0), statsRecv(0.0),
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!)
143 class InspIRCd : public classbase
146 /** Holds a string describing the last module error to occur
150 /** This is an internal flag used by the mainloop
154 /** List of server names we've seen.
156 servernamelist servernames;
158 /** Remove a ModuleFactory pointer
160 void EraseFactory(int j);
162 /** Remove a Module pointer
164 void EraseModule(int j);
166 /** Build the ISUPPORT string by triggering all modules On005Numeric events
168 void BuildISupport();
170 /** Move a given module to a specific slot in the list
172 void MoveTo(std::string modulename,int slot);
174 /** Display the startup banner
178 /** Set up the signal handlers
180 void SetSignals(bool SEGVHandler);
182 /** Daemonize the ircd and close standard input/output streams
186 /** Build the upper/lowercase comparison table
190 /** Moves the given module to the last slot in the list
192 void MoveToLast(std::string modulename);
194 /** Moves the given module to the first slot in the list
196 void MoveToFirst(std::string modulename);
198 /** Moves one module to be placed after another in the list
200 void MoveAfter(std::string modulename, std::string after);
202 /** Moves one module to be placed before another in the list
204 void MoveBefore(std::string modulename, std::string before);
206 /** Process a user whos socket has been flagged as active
208 void ProcessUser(userrec* cu);
210 /** Iterate the list of InspSocket objects, removing ones which have timed out
212 void DoSocketTimeouts(time_t TIME);
214 /** Perform background user events such as PING checks
216 void DoBackgroundUserStuff(time_t TIME);
218 /** Returns true when all modules have done pre-registration checks on a user
220 bool AllModulesReportReady(userrec* user);
222 /** Total number of modules loaded into the ircd, minus one
226 /** Logfile pathname specified on the commandline, or empty string
228 char LogFileName[MAXBUF];
230 /** The feature names published by various modules
232 featurelist Features;
234 /** The current time, updated in the mainloop
238 /** The time that was recorded last time around the mainloop
242 /** A 64k buffer used to read client lines into
244 char ReadBuffer[65535];
246 /** Number of seconds in a minute
248 const long duration_m;
250 /** Number of seconds in an hour
252 const long duration_h;
254 /** Number of seconds in a day
256 const long duration_d;
258 /** Number of seconds in a week
260 const long duration_w;
262 /** Number of seconds in a year
264 const long duration_y;
267 /** Time this ircd was booted
271 /** Mode handler, handles mode setting and removal
275 /** Command parser, handles client to server commands
277 CommandParser* Parser;
279 /** Socket engine, handles socket activity events
283 /** Stats class, holds miscellaneous stats counters
287 /** Server Config class, holds configuration file data
289 ServerConfig* Config;
291 /** Module sockets list, holds the active set of InspSocket classes
293 std::vector<InspSocket*> module_sockets;
295 /** Socket reference table, provides fast lookup of fd to InspSocket*
297 InspSocket* socket_ref[MAX_DESCRIPTORS];
299 /** user reference table, provides fast lookup of fd to userrec*
301 userrec* fd_ref_table[MAX_DESCRIPTORS];
303 /** Client list, a hash_map containing all clients, local and remote
305 user_hash clientlist;
307 /** Channel list, a hash_map containing all channels
311 /** Local client list, a vector containing only local clients
313 std::vector<userrec*> local_users;
315 /** Oper list, a vector containing all local and remote opered users
317 std::vector<userrec*> all_opers;
319 /** Whowas container, contains a map of vectors of users tracked by WHOWAS
321 irc::whowas::whowas_users whowas;
323 /** DNS class, provides resolver facilities to the core and modules
327 /** Timer manager class, triggers InspTimer timer events
329 TimerManager* Timers;
331 /** Command list, a hash_map of command names to command_t*
333 command_table cmdlist;
335 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
337 XLineManager* XLines;
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()
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()
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.
357 /** Get the total number of currently loaded modules
359 int GetModuleCount();
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
365 Module* FindModule(const std::string &name);
367 /** Bind all ports specified in the configuration file.
368 * @param bail True if the function should bail back to the shell on failure
370 int BindPorts(bool bail);
372 /** Returns true if this server has the given port bound to the given address
374 bool HasPort(int port, char* addr);
376 /** Binds a socket on an already open file descriptor
378 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
380 /** Adds a server name to the list of servers we've seen
382 void AddServerName(const std::string &servername);
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
387 const char* FindServerNamePtr(const std::string &servername);
389 /** Returns true if we've seen the given server name before
391 bool FindServerName(const std::string &servername);
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.
398 std::string GetServerDescription(const char* servername);
400 /** Write text to all opers connected to this server
402 void WriteOpers(const char* text, ...);
404 /** Write text to all opers connected to this server
406 void WriteOpers(const std::string &text);
408 /** Find a nickname in the nick hash
410 userrec* FindNick(const std::string &nick);
412 /** Find a nickname in the nick hash
414 userrec* FindNick(const char* nick);
416 /** Find a channel in the channels hash
418 chanrec* FindChan(const std::string &chan);
420 /** Find a channel in the channels hash
422 chanrec* FindChan(const char* chan);
424 /** Called by the constructor to load all modules from the config file.
426 void LoadAllModules();
428 /** Check for a 'die' tag in the config file, and abort if found
432 /** Check we aren't running as root, and exit if we are
436 /** Determine the right path for, and open, the logfile
438 void OpenLog(char** argv, int argc);
440 /** Convert a user to a pseudoclient, disconnecting the real user
442 bool UserToPseudo(userrec* user, const std::string &message);
444 /** Convert a pseudoclient to a real user, discarding the pseudoclient
446 bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
448 /** Send a server notice to all local users
450 void ServerNoticeAll(char* text, ...);
452 /** Send a server message (PRIVMSG) to all local users
454 void ServerPrivmsgAll(char* text, ...);
456 /** Send text to all users with a specific set of modes
458 void WriteMode(const char* modes, int flags, const char* text, ...);
460 /** Return true if a channel name is valid
462 bool IsChannel(const char *chname);
464 /** Rehash the local server
466 static void Rehash(int status);
468 /** Causes the server to exit immediately
470 static void Exit(int status);
472 /** Return a count of users, unknown and known connections
476 /** Return a count of fully registered connections only
478 int RegisteredUserCount();
480 /** Return a count of invisible (umode +i) users only
482 int InvisibleUserCount();
484 /** Return a count of opered (umode +o) users only
488 /** Return a count of unregistered (before NICK/USER) users only
490 int UnregisteredUserCount();
492 /** Return a count of channels on the network
496 /** Return a count of local users on this server only
498 long LocalUserCount();
500 /** Send an error notice to all local users, opered and unopered
502 void SendError(const char *s);
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
512 long PriorityBefore(const std::string &modulename);
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
522 long PriorityAfter(const std::string &modulename);
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
538 bool PublishFeature(const std::string &FeatureName, Module* Mod);
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
545 bool UnpublishFeature(const std::string &FeatureName);
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.
559 Module* FindFeature(const std::string &FeatureName);
561 /** Given a pointer to a Module, return its filename
563 const std::string& GetModuleName(Module* m);
565 /** Return true if a nickname is valid
567 bool IsNick(const char* n);
569 /** Return true if an ident is valid
571 bool IsIdent(const char* n);
573 /** Find a username by their file descriptor.
574 * It is preferred to use this over directly accessing the fd_ref_table array.
576 userrec* FindDescriptor(int socket);
578 /** Add a new mode to this server's mode parser
580 bool AddMode(ModeHandler* mh, const unsigned char modechar);
582 /** Add a new mode watcher to this server's mode parser
584 bool AddModeWatcher(ModeWatcher* mw);
586 /** Delete a mode watcher from this server's mode parser
588 bool DelModeWatcher(ModeWatcher* mw);
590 /** Add a dns Resolver class to this server's active set
592 bool AddResolver(Resolver* r);
594 /** Add a command to this server's command parser
596 void AddCommand(command_t *f);
598 /** Send a modechange.
599 * The parameters provided are identical to that sent to the
600 * handler for class cmd_mode.
602 void SendMode(const char **parameters, int pcnt, userrec *user);
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
609 bool MatchText(const std::string &sliteral, const std::string &spattern);
611 /** Call the handler for a given command.
612 * @return True if the command handler was called successfully
614 bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
616 /** Return true if the command is a module-implemented command and the given parameters are valid for it
618 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
620 /** Add a gline and apply it
622 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
624 /** Add a qline and apply it
626 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
628 /** Add a zline and apply it
630 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
632 /** Add a kline and apply it
634 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
638 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
642 bool DelGLine(const std::string &hostmask);
646 bool DelQLine(const std::string &nickname);
650 bool DelZLine(const std::string &ipaddr);
654 bool DelKLine(const std::string &hostmask);
658 bool DelELine(const std::string &hostmask);
660 /** Return true if the given parameter is a valid nick!user@host mask
662 bool IsValidMask(const std::string &mask);
664 /** Add an InspSocket class to the active set
666 void AddSocket(InspSocket* sock);
668 /** Remove an InspSocket class from the active set at next time around the loop
670 void RemoveSocket(InspSocket* sock);
672 /** Delete a socket immediately without waiting for the next iteration of the mainloop
674 void DelSocket(InspSocket* sock);
676 /** Rehash the local server
680 /** Return the channel whos index number matches that provided
682 chanrec* GetChannelIndex(long index);
684 /** Dump text to a user target, splitting it appropriately to fit
686 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
688 /** Check if the given nickmask matches too many users, send errors to the given user
690 bool NickMatchesEveryone(const std::string &nick, userrec* user);
692 /** Check if the given IP mask matches too many users, send errors to the given user
694 bool IPMatchesEveryone(const std::string &ip, userrec* user);
696 /** Check if the given hostmask matches too many users, send errors to the given user
698 bool HostMatchesEveryone(const std::string &mask, userrec* user);
700 /** Calculate a duration in seconds from a string in the form 1y2w3d4h6m5s
702 long Duration(const char* str);
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.
708 int OperPassCompare(const char* data,const char* input);
710 /** Check if a given server is a uline.
711 * An empty string returns true, this is by design.
713 bool ULine(const char* server);
715 /** Returns the subversion revision ID of this ircd
717 std::string GetRevision();
719 /** Returns the full version string of this ircd
721 std::string GetVersionString();
723 /** Attempt to write the process id to a given file
725 void WritePID(const std::string &filename);
727 /** Returns text describing the last module error
731 /** Load a given module file
733 bool LoadModule(const char* filename);
735 /** Unload a given module file
737 bool UnloadModule(const char* filename);
739 /** This constructor initialises all the subsystems and reads the config file.
741 InspIRCd(int argc, char** argv);
743 /** Do one iteration of the mainloop
745 void DoOneIteration(bool process_module_sockets);
747 /** Output a log message to the ircd.log file
749 void Log(int level, const char* text, ...);
751 /** Output a log message to the ircd.log file
753 void Log(int level, const std::string &text);
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.