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 /* Some misc defines */
37 #define ETIREDGERBILS EAGAIN
39 /** Debug levels for use with InspIRCd::Log()
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
55 #define IS_SINGLE(x,y) ( (*x == y) && (*(x+1) == 0) )
57 #define DELETE(x) {if (x) { delete x; x = NULL; }}
59 template<typename T> inline std::string ConvToStr(const T &in)
61 std::stringstream tmp;
62 if (!(tmp << in)) return std::string();
66 class serverstats : public classbase
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;
79 unsigned long BoundPortCount;
83 statsAccept = statsRefused = statsUnknown = 0;
84 statsCollisions = statsDns = statsDnsGood = 0;
85 statsDnsBad = statsConnects = 0;
86 statsSent = statsRecv = 0.0;
93 class InspIRCd : public classbase
96 /** Holds a string describing the last module error to occur
100 /** This is an internal flag used by the mainloop
104 /** List of server names we've seen.
106 servernamelist servernames;
108 /** Remove a ModuleFactory pointer
110 void EraseFactory(int j);
112 /** Remove a Module pointer
114 void EraseModule(int j);
116 /** Build the ISUPPORT string by triggering all modules On005Numeric events
118 void BuildISupport();
120 /** Move a given module to a specific slot in the list
122 void MoveTo(std::string modulename,int slot);
124 /** Display the startup banner
128 /** Set up the signal handlers
130 void SetSignals(bool SEGVHandler);
132 /** Daemonize the ircd and close standard input/output streams
136 /** Build the upper/lowercase comparison table
140 /** Moves the given module to the last slot in the list
142 void MoveToLast(std::string modulename);
144 /** Moves the given module to the first slot in the list
146 void MoveToFirst(std::string modulename);
148 /** Moves one module to be placed after another in the list
150 void MoveAfter(std::string modulename, std::string after);
152 /** Moves one module to be placed before another in the list
154 void MoveBefore(std::string modulename, std::string before);
156 /** Process a user whos socket has been flagged as active
158 void ProcessUser(userrec* cu);
160 /** Iterate the list of InspSocket objects, removing ones which have timed out
162 void DoSocketTimeouts(time_t TIME);
164 /** Perform background user events such as PING checks
166 void DoBackgroundUserStuff(time_t TIME);
168 /** Returns true when all modules have done pre-registration checks on a user
170 bool AllModulesReportReady(userrec* user);
172 /** Total number of modules loaded into the ircd, minus one
176 /** Logfile pathname specified on the commandline, or empty string
178 char LogFileName[MAXBUF];
180 /** The feature names published by various modules
182 featurelist Features;
184 /** The current time, updated in the mainloop
188 /** The time that was recorded last time around the mainloop
192 /** A 64k buffer used to read client lines into
194 char ReadBuffer[65535];
196 /** Number of seconds in a minute
198 const long duration_m;
200 /** Number of seconds in an hour
202 const long duration_h;
204 /** Number of seconds in a day
206 const long duration_d;
208 /** Number of seconds in a week
210 const long duration_w;
212 /** Number of seconds in a year
214 const long duration_y;
217 /** Time this ircd was booted
221 /** Mode handler, handles mode setting and removal
225 /** Command parser, handles client to server commands
227 CommandParser* Parser;
229 /** Socket engine, handles socket activity events
233 /** Stats class, holds miscellaneous stats counters
237 /** Server Config class, holds configuration file data
239 ServerConfig* Config;
241 /** Module sockets list, holds the active set of InspSocket classes
243 std::vector<InspSocket*> module_sockets;
245 /** Socket reference table, provides fast lookup of fd to InspSocket*
247 InspSocket* socket_ref[MAX_DESCRIPTORS];
249 /** user reference table, provides fast lookup of fd to userrec*
251 userrec* fd_ref_table[MAX_DESCRIPTORS];
253 /** Client list, a hash_map containing all clients, local and remote
255 user_hash clientlist;
257 /** Channel list, a hash_map containing all channels
261 /** Local client list, a vector containing only local clients
263 std::vector<userrec*> local_users;
265 /** Oper list, a vector containing all local and remote opered users
267 std::vector<userrec*> all_opers;
269 /** Whowas container, contains a map of vectors of users tracked by WHOWAS
271 irc::whowas::whowas_users whowas;
273 /** DNS class, provides resolver facilities to the core and modules
277 /** Timer manager class, triggers InspTimer timer events
279 TimerManager* Timers;
281 /** Command list, a hash_map of command names to command_t*
283 command_table cmdlist;
285 /** X-Line manager. Handles G/K/Q/E line setting, removal and matching
287 XLineManager* XLines;
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()
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()
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.
307 /** Get the total number of currently loaded modules
309 int GetModuleCount();
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
315 Module* FindModule(const std::string &name);
317 /** Bind all ports specified in the configuration file.
318 * @param bail True if the function should bail back to the shell on failure
320 int BindPorts(bool bail);
322 /** Returns true if this server has the given port bound to the given address
324 bool HasPort(int port, char* addr);
326 /** Binds a socket on an already open file descriptor
328 bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr);
330 /** Adds a server name to the list of servers we've seen
332 void AddServerName(const std::string &servername);
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
337 const char* FindServerNamePtr(const std::string &servername);
339 /** Returns true if we've seen the given server name before
341 bool FindServerName(const std::string &servername);
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.
348 std::string GetServerDescription(const char* servername);
350 /** Write text to all opers connected to this server
352 void WriteOpers(const char* text, ...);
354 /** Write text to all opers connected to this server
356 void WriteOpers(const std::string &text);
358 /** Find a nickname in the nick hash
360 userrec* FindNick(const std::string &nick);
362 /** Find a nickname in the nick hash
364 userrec* FindNick(const char* nick);
366 /** Find a channel in the channels hash
368 chanrec* FindChan(const std::string &chan);
370 /** Find a channel in the channels hash
372 chanrec* FindChan(const char* chan);
374 /** Called by the constructor to load all modules from the config file.
376 void LoadAllModules();
378 /** Check for a 'die' tag in the config file, and abort if found
382 /** Check we aren't running as root, and exit if we are
386 /** Determine the right path for, and open, the logfile
388 void OpenLog(char** argv, int argc);
390 /** Convert a user to a pseudoclient, disconnecting the real user
392 bool UserToPseudo(userrec* user, const std::string &message);
394 /** Convert a pseudoclient to a real user, discarding the pseudoclient
396 bool PseudoToUser(userrec* alive, userrec* zombie, const std::string &message);
398 /** Send a server notice to all local users
400 void ServerNoticeAll(char* text, ...);
402 /** Send a server message (PRIVMSG) to all local users
404 void ServerPrivmsgAll(char* text, ...);
406 /** Send text to all users with a specific set of modes
408 void WriteMode(const char* modes, int flags, const char* text, ...);
410 /** Return true if a channel name is valid
412 bool IsChannel(const char *chname);
414 /** Rehash the local server
416 static void Rehash(int status);
418 /** Causes the server to exit immediately
420 static void Exit(int status);
422 /** Return a count of users, unknown and known connections
426 /** Return a count of fully registered connections only
428 int RegisteredUserCount();
430 /** Return a count of invisible (umode +i) users only
432 int InvisibleUserCount();
434 /** Return a count of opered (umode +o) users only
438 /** Return a count of unregistered (before NICK/USER) users only
440 int UnregisteredUserCount();
442 /** Return a count of channels on the network
446 /** Return a count of local users on this server only
448 long LocalUserCount();
450 /** Send an error notice to all local users, opered and unopered
452 void SendError(const char *s);
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
462 long PriorityBefore(const std::string &modulename);
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
472 long PriorityAfter(const std::string &modulename);
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
488 bool PublishFeature(const std::string &FeatureName, Module* Mod);
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
495 bool UnpublishFeature(const std::string &FeatureName);
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.
509 Module* FindFeature(const std::string &FeatureName);
511 /** Given a pointer to a Module, return its filename
513 const std::string& GetModuleName(Module* m);
515 /** Return true if a nickname is valid
517 bool IsNick(const char* n);
519 /** Return true if an ident is valid
521 bool IsIdent(const char* n);
523 /** Find a username by their file descriptor.
524 * It is preferred to use this over directly accessing the fd_ref_table array.
526 userrec* FindDescriptor(int socket);
528 /** Add a new mode to this server's mode parser
530 bool AddMode(ModeHandler* mh, const unsigned char modechar);
532 /** Add a new mode watcher to this server's mode parser
534 bool AddModeWatcher(ModeWatcher* mw);
536 /** Delete a mode watcher from this server's mode parser
538 bool DelModeWatcher(ModeWatcher* mw);
540 /** Add a dns Resolver class to this server's active set
542 bool AddResolver(Resolver* r);
544 /** Add a command to this server's command parser
546 void AddCommand(command_t *f);
548 /** Send a modechange.
549 * The parameters provided are identical to that sent to the
550 * handler for class cmd_mode.
552 void SendMode(const char **parameters, int pcnt, userrec *user);
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
559 bool MatchText(const std::string &sliteral, const std::string &spattern);
561 /** Call the handler for a given command.
562 * @return True if the command handler was called successfully
564 bool CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user);
566 /** Return true if the command is a module-implemented command and the given parameters are valid for it
568 bool IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user);
570 /** Add a gline and apply it
572 void AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
574 /** Add a qline and apply it
576 void AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname);
578 /** Add a zline and apply it
580 void AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr);
582 /** Add a kline and apply it
584 void AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
588 void AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask);
592 bool DelGLine(const std::string &hostmask);
596 bool DelQLine(const std::string &nickname);
600 bool DelZLine(const std::string &ipaddr);
604 bool DelKLine(const std::string &hostmask);
608 bool DelELine(const std::string &hostmask);
610 /** Return true if the given parameter is a valid nick!user@host mask
612 bool IsValidMask(const std::string &mask);
614 /** Add an InspSocket class to the active set
616 void AddSocket(InspSocket* sock);
618 /** Remove an InspSocket class from the active set
620 void RemoveSocket(InspSocket* sock);
622 /** Delete a socket immediately
623 * XXX: How does this relate to InspIRCd::RemoveSocket()?
625 void DelSocket(InspSocket* sock);
627 /** Rehash the local server
631 /** Return the channel whos index number matches that provided
633 chanrec* GetChannelIndex(long index);
635 /** Dump text to a user target, splitting it appropriately to fit
637 void DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream);
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);
646 std::string GetRevision();
647 std::string GetVersionString();
648 void WritePID(const std::string &filename);
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);