diff options
author | om <om@e03df62e-2008-0410-955e-edbf42e46eb7> | 2006-04-08 17:05:48 +0000 |
---|---|---|
committer | om <om@e03df62e-2008-0410-955e-edbf42e46eb7> | 2006-04-08 17:05:48 +0000 |
commit | d54fbc71e2a2e0f70002e2d36c669c4aa3d59e17 (patch) | |
tree | 9e22656474f0fc034de7cf317d7aa7ae22a8abe8 /include | |
parent | 315cd88a911eaa327df520e8533be82efea0c66f (diff) |
Split inspircd_io.* insp inspsocket.* and configreader.* with a few odd bits going into inspircd.*, doesn't look like I've broken anything... :P
git-svn-id: http://svn.inspircd.org/repository/trunk/inspircd@3847 e03df62e-2008-0410-955e-edbf42e46eb7
Diffstat (limited to 'include')
-rw-r--r-- | include/ctables.h | 14 | ||||
-rw-r--r-- | include/helperfuncs.h | 10 | ||||
-rw-r--r-- | include/inspircd.h | 7 | ||||
-rw-r--r-- | include/inspircd_io.h | 406 | ||||
-rw-r--r-- | include/inspsocket.h | 374 | ||||
-rw-r--r-- | include/modules.h | 6 | ||||
-rw-r--r-- | include/socket.h | 350 |
7 files changed, 409 insertions, 758 deletions
diff --git a/include/ctables.h b/include/ctables.h index d98e1701d..c4b5aa335 100644 --- a/include/ctables.h +++ b/include/ctables.h @@ -18,18 +18,7 @@ #define __CTABLES_H__ #include "inspircd_config.h" - -#ifdef GCC3 -#include <ext/hash_map> -#else -#include <hash_map> -#endif - -#ifdef GCC3 -#define nspace __gnu_cxx -#else -#define nspace std -#endif +#include "hash_map.h" class userrec; @@ -73,4 +62,3 @@ class command_t typedef nspace::hash_map<std::string,command_t*> command_table; #endif - diff --git a/include/helperfuncs.h b/include/helperfuncs.h index ee434fd08..c9645144f 100644 --- a/include/helperfuncs.h +++ b/include/helperfuncs.h @@ -27,6 +27,14 @@ #include <deque> #include <sstream> +/** Flags for use with log() + */ +#define DEBUG 10 +#define VERBOSE 20 +#define DEFAULT 30 +#define SPARSE 40 +#define NONE 50 + void log(int level,char *text, ...); void readfile(file_cache &F, const char* fname); @@ -84,6 +92,8 @@ void ShowMOTD(userrec *user); void ShowRULES(userrec *user); bool AllModulesReportReady(userrec* user); bool DirValid(char* dirandfile); +bool FileExists(const char* file); +char* CleanFilename(char* name); std::string GetFullProgDir(char** argv, int argc); int InsertMode(std::string &output, const char* modes, unsigned short section); bool IsValidChannelName(const char *); diff --git a/include/inspircd.h b/include/inspircd.h index 822be147e..a9873ff76 100644 --- a/include/inspircd.h +++ b/include/inspircd.h @@ -127,6 +127,13 @@ class InspIRCd }; +/* Miscellaneous stuff here, moved from inspircd_io.h */ +void Exit(int status); +void Start(); +void SetSignals(); +bool DaemonSeed(); +void WritePID(const std::string &filename); + /* userrec optimization stuff */ void AddServerName(std::string servername); const char* FindServerNamePtr(std::string servername); diff --git a/include/inspircd_io.h b/include/inspircd_io.h index 158acfa79..e69de29bb 100644 --- a/include/inspircd_io.h +++ b/include/inspircd_io.h @@ -1,406 +0,0 @@ -/* +------------------------------------+ - * | Inspire Internet Relay Chat Daemon | - * +------------------------------------+ - * - * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev. - * E-mail: - * <brain@chatspike.net> - * <Craig@chatspike.net> - * - * Written by Craig Edwards, Craig McLure, and others. - * This program is free but copyrighted software; see - * the file COPYING for details. - * - * --------------------------------------------------- - */ - -#ifndef __INSPIRCD_IO_H__ -#define __INSPIRCD_IO_H__ - -#include <sstream> -#include <string> -#include <vector> -#include <map> -#include "inspircd.h" -#include "globals.h" -#include "modules.h" - -/** Flags for use with log() - */ -#define DEBUG 10 -#define VERBOSE 20 -#define DEFAULT 30 -#define SPARSE 40 -#define NONE 50 - -typedef bool (*Validator)(const char*, const char*, void*); -typedef bool (*MultiValidator)(const char*, char**, void**, int*); -typedef bool (*MultiNotify)(const char*); - -enum ConfigDataType { DT_NOTHING, DT_INTEGER, DT_CHARPTR, DT_BOOLEAN }; - -struct InitialConfig { - char* tag; - char* value; - void* val; - ConfigDataType datatype; - Validator validation_function; -}; - -struct MultiConfig { - const char* tag; - char* items[12]; - int datatype[12]; - MultiNotify init_function; - MultiValidator validation_function; - MultiNotify finish_function; -}; - -/** This class holds the bulk of the runtime configuration for the ircd. - * It allows for reading new config values, accessing configuration files, - * and storage of the configuration data needed to run the ircd, such as - * the servername, connect classes, /ADMIN data, MOTDs and filenames etc. - */ -class ServerConfig : public classbase -{ - private: - /** This variable holds the names of all - * files included from the main one. This - * is used to make sure that no files are - * recursively included. - */ - std::vector<std::string> include_stack; - - /** This private method processes one line of - * configutation, appending errors to errorstream - * and setting error if an error has occured. - */ - bool ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream); - - bool DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream); - - /** Check that there is only one of each configuration item - */ - bool CheckOnce(char* tag, bool bail, userrec* user); - - public: - - /** This holds all the information in the config file, - * it's indexed by tag name to a vector of key/values. - */ - ConfigDataHash config_data; - - /** Holds the server name of the local server - * as defined by the administrator. - */ - char ServerName[MAXBUF]; - - /* Holds the network name the local server - * belongs to. This is an arbitary field defined - * by the administrator. - */ - char Network[MAXBUF]; - - /** Holds the description of the local server - * as defined by the administrator. - */ - char ServerDesc[MAXBUF]; - - /** Holds the admin's name, for output in - * the /ADMIN command. - */ - char AdminName[MAXBUF]; - - /** Holds the email address of the admin, - * for output in the /ADMIN command. - */ - char AdminEmail[MAXBUF]; - - /** Holds the admin's nickname, for output - * in the /ADMIN command - */ - char AdminNick[MAXBUF]; - - /** The admin-configured /DIE password - */ - char diepass[MAXBUF]; - - /** The admin-configured /RESTART password - */ - char restartpass[MAXBUF]; - - /** The pathname and filename of the message of the - * day file, as defined by the administrator. - */ - char motd[MAXBUF]; - - /** The pathname and filename of the rules file, - * as defined by the administrator. - */ - char rules[MAXBUF]; - - /** The quit prefix in use, or an empty string - */ - char PrefixQuit[MAXBUF]; - - /** The last string found within a <die> tag, or - * an empty string. - */ - char DieValue[MAXBUF]; - - /** The DNS server to use for DNS queries - */ - char DNSServer[MAXBUF]; - - /** This variable contains a space-seperated list - * of commands which are disabled by the - * administrator of the server for non-opers. - */ - char DisabledCommands[MAXBUF]; - - /** The full path to the modules directory. - * This is either set at compile time, or - * overridden in the configuration file via - * the <options> tag. - */ - char ModPath[1024]; - - /** The temporary directory where modules are copied - */ - char TempDir[1024]; - - /** The full pathname to the executable, as - * given in argv[0] when the program starts. - */ - char MyExecutable[1024]; - - /** The file handle of the logfile. If this - * value is NULL, the log file is not open, - * probably due to a permissions error on - * startup (this should not happen in normal - * operation!). - */ - FILE *log_file; - - /** If this value is true, the owner of the - * server specified -nofork on the command - * line, causing the daemon to stay in the - * foreground. - */ - bool nofork; - - /** If this value if true then all log - * messages will be output, regardless of - * the level given in the config file. - * This is set with the -debug commandline - * option. - */ - bool forcedebug; - - /** If this is true then log output will be - * written to the logfile. This is the default. - * If you put -nolog on the commandline then - * the logfile will not be written. - * This is meant to be used in conjunction with - * -debug for debugging without filling up the - * hard disk. - */ - bool writelog; - - /** If this value is true, halfops have been - * enabled in the configuration file. - */ - bool AllowHalfop; - - /** The number of seconds the DNS subsystem - * will wait before timing out any request. - */ - int dns_timeout; - - /** The size of the read() buffer in the user - * handling code, used to read data into a user's - * recvQ. - */ - int NetBufferSize; - - /** The value to be used for listen() backlogs - * as default. - */ - int MaxConn; - - /** The soft limit value assigned to the irc server. - * The IRC server will not allow more than this - * number of local users. - */ - unsigned int SoftLimit; - - /** Maximum number of targets for a multi target command - * such as PRIVMSG or KICK - */ - unsigned int MaxTargets; - - /** The maximum number of /WHO results allowed - * in any single /WHO command. - */ - int MaxWhoResults; - - /** True if the DEBUG loglevel is selected. - */ - int debugging; - - /** The loglevel in use by the IRC server - */ - int LogLevel; - - /** How many seconds to wait before exiting - * the program when /DIE is correctly issued. - */ - int DieDelay; - - /** True if we're going to hide netsplits as *.net *.split for non-opers - */ - bool HideSplits; - - /** True if we're going to hide ban reasons for non-opers (e.g. G-Lines, - * K-Lines, Z-Lines) - */ - bool HideBans; - - /** If this is enabled then operators will - * see invisible (+i) channels in /whois. - */ - bool OperSpyWhois; - - /** Set to a non-empty string to obfuscate the server name of users in WHOIS - */ - char HideWhoisServer[MAXBUF]; - - /** A list of IP addresses the server is listening - * on. - */ - char addrs[MAXBUF][255]; - - /** The MOTD file, cached in a file_cache type. - */ - file_cache MOTD; - - /** The RULES file, cached in a file_cache type. - */ - file_cache RULES; - - /** The full pathname and filename of the PID - * file as defined in the configuration. - */ - char PID[1024]; - - /** The connect classes in use by the IRC server. - */ - ClassVector Classes; - - /** A list of module names (names only, no paths) - * which are currently loaded by the server. - */ - std::vector<std::string> module_names; - - /** A list of ports which the server is listening on - */ - int ports[255]; - - /** Boolean sets of which modules implement which functions - */ - char implement_lists[255][255]; - - /** Global implementation list - */ - char global_implementation[255]; - - /** A list of ports claimed by IO Modules - */ - std::map<int,Module*> IOHookModule; - - /** The 005 tokens of this server (ISUPPORT) - * populated/repopulated upon loading or unloading - * modules. - */ - std::string data005; - - /** STATS characters in this list are available - * only to operators. - */ - char OperOnlyStats[MAXBUF]; - - /** The path and filename of the ircd.log file - */ - std::string logpath; - - /** Custom version string, which if defined can replace the system info in VERSION. - */ - char CustomVersion[MAXBUF]; - - /** List of u-lined servers - */ - std::vector<irc::string> ulines; - - /** Max banlist sizes for channels (the std::string is a glob) - */ - std::map<std::string,int> maxbans; - - ServerConfig(); - - /** Clears the include stack in preperation for - * a Read() call. - */ - void ClearStack(); - - /** Read the entire configuration into memory - * and initialize this class. All other methods - * should be used only by the core. - */ - void Read(bool bail, userrec* user); - - /** Load 'filename' into 'target', with the new config parser everything is parsed into - * tag/key/value at load-time rather than at read-value time. - */ - bool LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream); - bool LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream); - - /* Both these return true if the value existed or false otherwise */ - - /* Writes 'length' chars into 'result' as a string */ - bool ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length); - bool ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result); - - /* Tries to convert the value to an integer and write it to 'result' */ - bool ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result); - bool ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result); - - /* Returns true if the value exists and has a true value, false otherwise */ - bool ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index); - bool ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index); - - /* Returns the number of occurences of tag in the config file */ - int ConfValueEnum(ConfigDataHash &target, const char* tag); - int ConfValueEnum(ConfigDataHash &target, const std::string &tag); - - /* Returns the numbers of vars inside the index'th 'tag in the config file */ - int ConfVarEnum(ConfigDataHash &target, const char* tag, int index); - int ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index); - - Module* GetIOHook(int port); - bool AddIOHook(int port, Module* iomod); - bool DelIOHook(int port); -}; - - -void Exit(int status); -void Start(); -void SetSignals(); -bool DaemonSeed(); -bool FileExists(const char* file); -int OpenTCPSocket(); -bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr); -void WritePID(const std::string &filename); -int BindPorts(bool bail); -char* CleanFilename(char* name); - -#endif diff --git a/include/inspsocket.h b/include/inspsocket.h new file mode 100644 index 000000000..caa1490b5 --- /dev/null +++ b/include/inspsocket.h @@ -0,0 +1,374 @@ +/* +------------------------------------+ + * | Inspire Internet Relay Chat Daemon | + * +------------------------------------+ + * + * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev. + * E-mail: + * <brain@chatspike.net> + * <Craig@chatspike.net> + * + * Written by Craig Edwards, Craig McLure, and others. + * This program is free but copyrighted software; see + * the file COPYING for details. + * + * --------------------------------------------------- + */ + +#ifndef __INSP_SOCKET_H__ +#define __INSP_SOCKET_H__ + +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <sstream> +#include <string> +#include <deque> +#include "dns.h" +#include "inspircd_config.h" + +/* macros to the relevant system address description structs */ +#ifdef IPV6 + +typedef struct sockaddr_in6 insp_sockaddr; +typedef struct in6_addr insp_inaddr; + +#else + +typedef struct sockaddr_in insp_sockaddr; +typedef struct in_addr insp_inaddr; + +#endif + +/** + * States which a socket may be in + */ +enum InspSocketState { I_DISCONNECTED, I_RESOLVING, I_CONNECTING, I_CONNECTED, I_LISTENING, I_ERROR }; + +/** + * Error types which a socket may exhibit + */ +enum InspSocketError { I_ERR_TIMEOUT, I_ERR_SOCKET, I_ERR_CONNECT, I_ERR_BIND, I_ERR_RESOLVE, I_ERR_WRITE }; + +/** + * InspSocket is an extendable socket class which modules + * can use for TCP socket support. It is fully integrated + * into InspIRCds socket loop and attaches its sockets to + * the core's instance of the SocketEngine class, meaning + * that any sockets you create have the same power and + * abilities as a socket created by the core itself. + * To use InspSocket, you must inherit a class from it, + * and use the InspSocket constructors to establish connections + * and bindings. + */ +class InspSocket +{ +private: + + std::deque<std::string> outbuffer; + + /** + * The file descriptor of this socket + */ + int fd; + + /** + * The resolver for this socket + */ + DNS dns; + + /** + * The hostname connected to + */ + char host[MAXBUF]; + + /** + * The port connected to, or the port + * this socket is listening on + */ + int port; + + /** + * The state for this socket, either + * listening, connecting, connected + * or error. + */ + InspSocketState state; + + /** + * The host being connected to, + * in sockaddr form + */ + insp_sockaddr addr; + + /** + * The host being connected to, + * in in_addr form + */ + insp_inaddr addy; + + /** + * When this time is reached, + * the socket times out if it is + * in the CONNECTING state + */ + time_t timeout_end; + + /** + * This value is true if the + * socket has timed out. + */ + bool timeout; + + /** + * Socket input buffer, used by read(). The class which + * extends InspSocket is expected to implement an extendable + * buffer which can grow much larger than 64k, + * this buffer is just designed to be temporary storage. + * space. + */ + char ibuf[65535]; + + /** + * The IP address being connected + * to stored in string form for + * easy retrieval by accessors. + */ + char IP[MAXBUF]; + + /** + * Client sockaddr structure used + * by accept() + */ + insp_sockaddr client; + + /** + * Server sockaddr structure used + * by accept() + */ + insp_sockaddr server; + + /** + * Used by accept() to indicate the + * sizes of the sockaddr_in structures + */ + socklen_t length; + + /** Flushes the write buffer + */ + bool FlushWriteBuffer(); + + /** Set the queue sizes + * This private method sets the operating system queue + * sizes for this socket to 65535 so that it can queue + * more information without application-level queueing + * which was required in older software. + */ + void SetQueues(int nfd); + + /** When the socket has been marked as closing, this flag + * will be set to true, then the next time the socket is + * examined, the socket is deleted and closed. + */ + bool ClosePending; + +public: + + /** + * The default constructor does nothing + * and should not be used. + */ + InspSocket(); + + /** + * This constructor is used to associate + * an existing connecting with an InspSocket + * class. The given file descriptor must be + * valid, and when initialized, the InspSocket + * will be set with the given IP address + * and placed in CONNECTED state. + */ + InspSocket(int newfd, char* ip); + + /** + * This constructor is used to create a new + * socket, either listening for connections, or an outbound connection to another host. + * Note that if you specify a hostname in the 'host' parameter, then there will be an extra + * step involved (a nonblocking DNS lookup) which will cause your connection to be established + * slower than if it was an IP. Therefore, use an IP address where it is available instead. + * @param host The hostname to connect to, or bind to + * @param port The port number to connect to, or bind to + * @param listening true to listen on the given host:port pair, or false to connect to them + * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated + */ + InspSocket(const std::string &host, int port, bool listening, unsigned long maxtime); + + /** + * This method is called when an outbound + * connection on your socket is completed. + * @return false to abort the connection, true to continue + */ + virtual bool OnConnected(); + + /** + * This method is called when an error occurs. + * A closed socket in itself is not an error, + * however errors also generate close events. + * @param e The error type which occured + */ + virtual void OnError(InspSocketError e); + + /** + * When an established connection is terminated, + * the OnDisconnect method is triggered. + */ + virtual int OnDisconnect(); + + /** + * When there is data waiting to be read on a + * socket, the OnDataReady() method is called. + * Within this method, you *MUST* call the Read() + * method to read any pending data. At its lowest + * level, this event is signalled by the core via + * the socket engine. If you return false from this + * function, the core removes your socket from its + * list and erases it from the socket engine, then + * calls InspSocket::Close() and deletes it. + * @return false to close the socket + */ + virtual bool OnDataReady(); + + /** + * When an outbound connection fails, and the + * attempt times out, you will receive this event. + * The method will trigger once maxtime seconds are + * reached (as given in the constructor) just + * before the socket's descriptor is closed. + * A failed DNS lookup may cause this event if + * the DNS server is not responding, as well as + * a failed connect() call, because DNS lookups are + * nonblocking as implemented by this class. + */ + virtual void OnTimeout(); + + /** + * Whenever close() is called, OnClose() will be + * called first. Please note that this means + * OnClose will be called alongside OnError(), + * OnTimeout(), and Close(), and also when + * cancelling a listening socket by calling + * the destructor indirectly. + */ + virtual void OnClose(); + + /** + * Reads all pending bytes from the socket + * into a char* array which can be up to + * 16 kilobytes in length. + */ + virtual char* Read(); + + /** + * Returns the IP address associated with + * this connection, or an empty string if + * no IP address exists. + */ + std::string GetIP(); + + /** + * This function checks if the socket has + * timed out yet, given the current time + * in the parameter. + * @return true if timed out, false if not timed out + */ + bool Timeout(time_t current); + + /** + * Writes a std::string to the socket. No carriage + * returns or linefeeds are appended to the string. + * @param data The data to send + */ + virtual int Write(const std::string &data); + + /** + * If your socket is a listening socket, when a new + * connection comes in on the socket this method will + * be called. Given the new file descriptor in the + * parameters, and the IP, it is recommended you copy + * them to a new instance of your socket class, + * e.g.: + * + * MySocket* newsocket = new MySocket(newfd,ip); + * + * Once you have done this, you can then associate the + * new socket with the core using Server::AddSocket(). + */ + virtual int OnIncomingConnection(int newfd, char* ip); + + /** + * Changes the socket's state. The core uses this + * to change socket states, and you should not call + * it directly. + */ + void SetState(InspSocketState s); + + /** + * Returns the current socket state. + */ + InspSocketState GetState(); + + /** + * Only the core should call this function. + * When called, it is assumed the socket is ready + * to read data, and the method call routes the + * event to the various methods of InspSocket + * for you to handle. This can also cause the + * socket's state to change. + */ + bool Poll(); + + /** + * This method returns the socket's file descriptor + * as assigned by the operating system, or -1 + * if no descriptor has been assigned. + */ + int GetFd(); + + /** + * This method causes the socket to close, and may + * also be triggered by other methods such as OnTimeout + * and OnError. + */ + virtual void Close(); + + /** + * The destructor may implicitly call OnClose(), and + * will close() and shutdown() the file descriptor + * used for this socket. + */ + virtual ~InspSocket(); + + /** + * This method attempts to resolve the hostname, + * if a hostname is given and not an IP, + * before a connection can occur. This method is + * asyncronous. + */ + virtual bool DoResolve(); + + /** + * This method attempts to connect to a hostname. + * This only occurs on a non-listening socket. This + * method is asyncronous. + */ + virtual bool DoConnect(); + + /** + * This method marks the socket closed. + * The next time the core examines a socket marked + * as closed, the socket will be closed and the + * memory reclaimed. + */ + void MarkAsClosed(); +}; + +#endif diff --git a/include/modules.h b/include/modules.h index a57fbef1a..f15341e01 100644 --- a/include/modules.h +++ b/include/modules.h @@ -68,7 +68,7 @@ enum TargetTypeFlags { #include "dynamic.h" #include "base.h" #include "ctables.h" -#include "socket.h" +#include "inspsocket.h" #include <string> #include <deque> #include <sstream> @@ -102,7 +102,7 @@ typedef std::deque<userrec*> chanuserlist; } \ catch (ModuleException& modexcept) \ { \ - log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \ + log(DEBUG,"Module exception caught: %s",modexcept.GetReason()); \ } \ } \ } @@ -1932,6 +1932,8 @@ class ModuleFactory : public classbase typedef DLLFactory<ModuleFactory> ircd_module; +typedef std::vector<Module*> ModuleList; +typedef std::vector<ircd_module*> FactoryList; bool ModeDefined(char c, int i); bool ModeDefinedOper(char c, int i); diff --git a/include/socket.h b/include/socket.h index caa1490b5..b7b2b3d40 100644 --- a/include/socket.h +++ b/include/socket.h @@ -14,16 +14,20 @@ * --------------------------------------------------- */ -#ifndef __INSP_SOCKET_H__ -#define __INSP_SOCKET_H__ +#ifndef INSPIRCD_SOCKET_H +#define INSPIRCD_SOCKET_H +/* This is where we'll define wrappers for socket IO stuff, for neat winsock compatability */ + +#include <sys/time.h> +#include <sys/resource.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> -#include <sstream> -#include <string> -#include <deque> -#include "dns.h" +#include <unistd.h> +#include <fcntl.h> +#include <poll.h> + #include "inspircd_config.h" /* macros to the relevant system address description structs */ @@ -39,336 +43,8 @@ typedef struct in_addr insp_inaddr; #endif -/** - * States which a socket may be in - */ -enum InspSocketState { I_DISCONNECTED, I_RESOLVING, I_CONNECTING, I_CONNECTED, I_LISTENING, I_ERROR }; - -/** - * Error types which a socket may exhibit - */ -enum InspSocketError { I_ERR_TIMEOUT, I_ERR_SOCKET, I_ERR_CONNECT, I_ERR_BIND, I_ERR_RESOLVE, I_ERR_WRITE }; - -/** - * InspSocket is an extendable socket class which modules - * can use for TCP socket support. It is fully integrated - * into InspIRCds socket loop and attaches its sockets to - * the core's instance of the SocketEngine class, meaning - * that any sockets you create have the same power and - * abilities as a socket created by the core itself. - * To use InspSocket, you must inherit a class from it, - * and use the InspSocket constructors to establish connections - * and bindings. - */ -class InspSocket -{ -private: - - std::deque<std::string> outbuffer; - - /** - * The file descriptor of this socket - */ - int fd; - - /** - * The resolver for this socket - */ - DNS dns; - - /** - * The hostname connected to - */ - char host[MAXBUF]; - - /** - * The port connected to, or the port - * this socket is listening on - */ - int port; - - /** - * The state for this socket, either - * listening, connecting, connected - * or error. - */ - InspSocketState state; - - /** - * The host being connected to, - * in sockaddr form - */ - insp_sockaddr addr; - - /** - * The host being connected to, - * in in_addr form - */ - insp_inaddr addy; - - /** - * When this time is reached, - * the socket times out if it is - * in the CONNECTING state - */ - time_t timeout_end; - - /** - * This value is true if the - * socket has timed out. - */ - bool timeout; - - /** - * Socket input buffer, used by read(). The class which - * extends InspSocket is expected to implement an extendable - * buffer which can grow much larger than 64k, - * this buffer is just designed to be temporary storage. - * space. - */ - char ibuf[65535]; - - /** - * The IP address being connected - * to stored in string form for - * easy retrieval by accessors. - */ - char IP[MAXBUF]; - - /** - * Client sockaddr structure used - * by accept() - */ - insp_sockaddr client; - - /** - * Server sockaddr structure used - * by accept() - */ - insp_sockaddr server; - - /** - * Used by accept() to indicate the - * sizes of the sockaddr_in structures - */ - socklen_t length; - - /** Flushes the write buffer - */ - bool FlushWriteBuffer(); - - /** Set the queue sizes - * This private method sets the operating system queue - * sizes for this socket to 65535 so that it can queue - * more information without application-level queueing - * which was required in older software. - */ - void SetQueues(int nfd); - - /** When the socket has been marked as closing, this flag - * will be set to true, then the next time the socket is - * examined, the socket is deleted and closed. - */ - bool ClosePending; - -public: - - /** - * The default constructor does nothing - * and should not be used. - */ - InspSocket(); - - /** - * This constructor is used to associate - * an existing connecting with an InspSocket - * class. The given file descriptor must be - * valid, and when initialized, the InspSocket - * will be set with the given IP address - * and placed in CONNECTED state. - */ - InspSocket(int newfd, char* ip); - - /** - * This constructor is used to create a new - * socket, either listening for connections, or an outbound connection to another host. - * Note that if you specify a hostname in the 'host' parameter, then there will be an extra - * step involved (a nonblocking DNS lookup) which will cause your connection to be established - * slower than if it was an IP. Therefore, use an IP address where it is available instead. - * @param host The hostname to connect to, or bind to - * @param port The port number to connect to, or bind to - * @param listening true to listen on the given host:port pair, or false to connect to them - * @param maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated - */ - InspSocket(const std::string &host, int port, bool listening, unsigned long maxtime); - - /** - * This method is called when an outbound - * connection on your socket is completed. - * @return false to abort the connection, true to continue - */ - virtual bool OnConnected(); - - /** - * This method is called when an error occurs. - * A closed socket in itself is not an error, - * however errors also generate close events. - * @param e The error type which occured - */ - virtual void OnError(InspSocketError e); - - /** - * When an established connection is terminated, - * the OnDisconnect method is triggered. - */ - virtual int OnDisconnect(); - - /** - * When there is data waiting to be read on a - * socket, the OnDataReady() method is called. - * Within this method, you *MUST* call the Read() - * method to read any pending data. At its lowest - * level, this event is signalled by the core via - * the socket engine. If you return false from this - * function, the core removes your socket from its - * list and erases it from the socket engine, then - * calls InspSocket::Close() and deletes it. - * @return false to close the socket - */ - virtual bool OnDataReady(); - - /** - * When an outbound connection fails, and the - * attempt times out, you will receive this event. - * The method will trigger once maxtime seconds are - * reached (as given in the constructor) just - * before the socket's descriptor is closed. - * A failed DNS lookup may cause this event if - * the DNS server is not responding, as well as - * a failed connect() call, because DNS lookups are - * nonblocking as implemented by this class. - */ - virtual void OnTimeout(); - - /** - * Whenever close() is called, OnClose() will be - * called first. Please note that this means - * OnClose will be called alongside OnError(), - * OnTimeout(), and Close(), and also when - * cancelling a listening socket by calling - * the destructor indirectly. - */ - virtual void OnClose(); - - /** - * Reads all pending bytes from the socket - * into a char* array which can be up to - * 16 kilobytes in length. - */ - virtual char* Read(); - - /** - * Returns the IP address associated with - * this connection, or an empty string if - * no IP address exists. - */ - std::string GetIP(); - - /** - * This function checks if the socket has - * timed out yet, given the current time - * in the parameter. - * @return true if timed out, false if not timed out - */ - bool Timeout(time_t current); - - /** - * Writes a std::string to the socket. No carriage - * returns or linefeeds are appended to the string. - * @param data The data to send - */ - virtual int Write(const std::string &data); - - /** - * If your socket is a listening socket, when a new - * connection comes in on the socket this method will - * be called. Given the new file descriptor in the - * parameters, and the IP, it is recommended you copy - * them to a new instance of your socket class, - * e.g.: - * - * MySocket* newsocket = new MySocket(newfd,ip); - * - * Once you have done this, you can then associate the - * new socket with the core using Server::AddSocket(). - */ - virtual int OnIncomingConnection(int newfd, char* ip); - - /** - * Changes the socket's state. The core uses this - * to change socket states, and you should not call - * it directly. - */ - void SetState(InspSocketState s); - - /** - * Returns the current socket state. - */ - InspSocketState GetState(); - - /** - * Only the core should call this function. - * When called, it is assumed the socket is ready - * to read data, and the method call routes the - * event to the various methods of InspSocket - * for you to handle. This can also cause the - * socket's state to change. - */ - bool Poll(); - - /** - * This method returns the socket's file descriptor - * as assigned by the operating system, or -1 - * if no descriptor has been assigned. - */ - int GetFd(); - - /** - * This method causes the socket to close, and may - * also be triggered by other methods such as OnTimeout - * and OnError. - */ - virtual void Close(); - - /** - * The destructor may implicitly call OnClose(), and - * will close() and shutdown() the file descriptor - * used for this socket. - */ - virtual ~InspSocket(); - - /** - * This method attempts to resolve the hostname, - * if a hostname is given and not an IP, - * before a connection can occur. This method is - * asyncronous. - */ - virtual bool DoResolve(); - - /** - * This method attempts to connect to a hostname. - * This only occurs on a non-listening socket. This - * method is asyncronous. - */ - virtual bool DoConnect(); - - /** - * This method marks the socket closed. - * The next time the core examines a socket marked - * as closed, the socket will be closed and the - * memory reclaimed. - */ - void MarkAsClosed(); -}; +int OpenTCPSocket(); +bool BindSocket(int sockfd, insp_sockaddr client, insp_sockaddr server, int port, char* addr); +int BindPorts(bool bail); #endif |