Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members

InspSocket Class Reference

InspSocket is an extendable socket class which modules can use for TCP socket support. More...

#include <socket.h>

Collaboration diagram for InspSocket:

Collaboration graph
[legend]
List of all members.

Public Member Functions

 InspSocket ()
 The default constructor does nothing and should not be used.
 InspSocket (int newfd, char *ip)
 This constructor is used to associate an existing connecting with an InspSocket class.
 InspSocket (std::string host, int port, bool listening, unsigned long maxtime)
 This constructor is used to create a new socket, either listening for connections, or an outbound connection to another host.
virtual bool OnConnected ()
 This method is called when an outbound connection on your socket is completed.
virtual void OnError (InspSocketError e)
 This method is called when an error occurs.
virtual int OnDisconnect ()
 When an established connection is terminated, the OnDisconnect method is triggered.
virtual bool OnDataReady ()
 When there is data waiting to be read on a socket, the OnDataReady() method is called.
virtual void OnTimeout ()
 When an outbound connection fails, and the attempt times out, you will receive this event.
virtual void OnClose ()
 Whenever close() is called, OnClose() will be called first.
virtual char * Read ()
 Reads all pending bytes from the socket into a char* array which can be up to 16 kilobytes in length.
std::string GetIP ()
 Returns the IP address associated with this connection, or an empty string if no IP address exists.
bool Timeout (time_t current)
 This function checks if the socket has timed out yet, given the current time in the parameter.
virtual int Write (std::string data)
 Writes a std::string to the socket.
virtual int OnIncomingConnection (int newfd, char *ip)
 If your socket is a listening socket, when a new connection comes in on the socket this method will be called.
void SetState (InspSocketState s)
 Changes the socket's state.
InspSocketState GetState ()
 Returns the current socket state.
bool Poll ()
 Only the core should call this function.
int GetFd ()
 This method returns the socket's file descriptor as assigned by the operating system, or -1 if no descriptor has been assigned.
virtual void Close ()
 This method causes the socket to close, and may also be triggered by other methods such as OnTimeout and OnError.
virtual ~InspSocket ()
 The destructor may implicitly call OnClose(), and will close() and shutdown() the file descriptor used for this socket.

Private Member Functions

void FlushWriteBuffer ()
 Flushes the write buffer.

Private Attributes

int fd
 The file descriptor of this socket.
std::string host
 The hostname connected to.
int port
 The port connected to, or the port this socket is listening on.
InspSocketState state
 The state for this socket, either listening, connecting, connected or error.
sockaddr_in addr
 The host being connected to, in sockaddr form.
in_addr addy
 The host being connected to, in in_addr form.
time_t timeout_end
 When this time is reached, the socket times out if it is in the CONNECTING state.
bool timeout
 This value is true if the socket has timed out.
char ibuf [65535]
 Socket input buffer, used by read().
std::string Buffer
 The output buffer for this socket.
std::string IP
 The IP address being connected to stored in string form for easy retrieval by accessors.
sockaddr_in client
 Client sockaddr structure used by accept().
sockaddr_in server
 Server sockaddr structure used by accept().
socklen_t length
 Used by accept() to indicate the sizes of the sockaddr_in structures.

Detailed Description

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.

Definition at line 47 of file socket.h.


Constructor & Destructor Documentation

InspSocket::InspSocket  ) 
 

The default constructor does nothing and should not be used.

Definition at line 45 of file socket.cpp.

References I_DISCONNECTED, and state.

00046 {
00047         this->state = I_DISCONNECTED;
00048 }

InspSocket::InspSocket int  newfd,
char *  ip
 

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.

Definition at line 50 of file socket.cpp.

References SocketEngine::AddFd(), fd, I_CONNECTED, IP, InspIRCd::SE, state, and X_ESTAB_MODULE.

00051 {
00052         this->fd = newfd;
00053         this->state = I_CONNECTED;
00054         this->IP = ip;
00055         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
00056         socket_ref[this->fd] = this;
00057 }

InspSocket::InspSocket std::string  host,
int  port,
bool  listening,
unsigned long  maxtime
 

This constructor is used to create a new socket, either listening for connections, or an outbound connection to another host.

Parameters:
host The hostname to connect to, or bind to
port The port number to connect to, or bind to
listening true to listen on the given host:port pair, or false to connect to them
maxtime Number of seconds to wait, if connecting, before the connection times out and an OnTimeout() event is generated

Definition at line 59 of file socket.cpp.

References SocketEngine::AddFd(), addr, addy, BindSocket(), Close(), DEBUG, ERROR, fd, I_CONNECTING, I_ERR_BIND, I_ERR_CONNECT, I_ERR_SOCKET, I_ERROR, I_LISTENING, IP, log(), OnError(), OpenTCPSocket(), InspIRCd::SE, state, timeout, timeout_end, and X_ESTAB_MODULE.

00060 {
00061         if (listening) {
00062                 if ((this->fd = OpenTCPSocket()) == ERROR)
00063                 {
00064                         this->fd = -1;
00065                         this->state = I_ERROR;
00066                         this->OnError(I_ERR_SOCKET);
00067                         log(DEBUG,"OpenTCPSocket() error");
00068                         return;
00069                 }
00070                 else
00071                 {
00072                         if (BindSocket(this->fd,this->client,this->server,port,(char*)host.c_str()) == ERROR)
00073                         {
00074                                 this->Close();
00075                                 this->fd = -1;
00076                                 this->state = I_ERROR;
00077                                 this->OnError(I_ERR_BIND);
00078                                 log(DEBUG,"BindSocket() error %s",strerror(errno));
00079                                 return;
00080                         }
00081                         else
00082                         {
00083                                 this->state = I_LISTENING;
00084                                 ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
00085                                 socket_ref[this->fd] = this;
00086                                 log(DEBUG,"New socket now in I_LISTENING state");
00087                                 return;
00088                         }
00089                 }                       
00090         } else {
00091                 char* ip;
00092                 this->host = host;
00093                 hostent* hoste = gethostbyname(host.c_str());
00094                 if (!hoste) {
00095                         ip = (char*)host.c_str();
00096                 } else {
00097                         struct in_addr* ia = (in_addr*)hoste->h_addr;
00098                         ip = inet_ntoa(*ia);
00099                 }
00100 
00101                 this->IP = ip;
00102 
00103                 timeout_end = time(NULL)+maxtime;
00104                 timeout = false;
00105                 if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
00106                 {
00107                         this->state = I_ERROR;
00108                         this->OnError(I_ERR_SOCKET);
00109                         return;
00110                 }
00111                 this->port = port;
00112                 inet_aton(ip,&addy);
00113                 addr.sin_family = AF_INET;
00114                 addr.sin_addr = addy;
00115                 addr.sin_port = htons(this->port);
00116 
00117                 int flags;
00118                 flags = fcntl(this->fd, F_GETFL, 0);
00119                 fcntl(this->fd, F_SETFL, flags | O_NONBLOCK);
00120 
00121                 if(connect(this->fd, (sockaddr*)&this->addr,sizeof(this->addr)) == -1)
00122                 {
00123                         if (errno != EINPROGRESS)
00124                         {
00125                                 this->Close();
00126                                 this->OnError(I_ERR_CONNECT);
00127                                 this->state = I_ERROR;
00128                                 return;
00129                         }
00130                 }
00131                 this->state = I_CONNECTING;
00132                 ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
00133                 socket_ref[this->fd] = this;
00134                 return;
00135         }
00136 }

InspSocket::~InspSocket  )  [virtual]
 

The destructor may implicitly call OnClose(), and will close() and shutdown() the file descriptor used for this socket.

Definition at line 271 of file socket.cpp.

References Close().

00272 {
00273         this->Close();
00274 }


Member Function Documentation

void InspSocket::Close  )  [virtual]
 

This method causes the socket to close, and may also be triggered by other methods such as OnTimeout and OnError.

Definition at line 138 of file socket.cpp.

References fd, and OnClose().

Referenced by InspSocket(), and ~InspSocket().

00139 {
00140         if (this->fd != -1)
00141         {
00142                 this->OnClose();
00143                 shutdown(this->fd,2);
00144                 close(this->fd);
00145                 socket_ref[this->fd] = NULL;
00146                 this->fd = -1;
00147         }
00148 }

void InspSocket::FlushWriteBuffer  )  [private]
 

Flushes the write buffer.

Definition at line 181 of file socket.cpp.

References Buffer.

Referenced by Timeout(), and Write().

00182 {
00183         int result = 0;
00184         if (this->Buffer.length())
00185         {
00186                 result = send(this->fd,this->Buffer.c_str(),this->Buffer.length(),0);
00187                 if (result > 0)
00188                 {
00189                         /* If we wrote some, advance the buffer forwards */
00190                         char* n = (char*)this->Buffer.c_str();
00191                         n += result;
00192                         this->Buffer = n;
00193                 }
00194         }
00195 }

int InspSocket::GetFd  ) 
 

This method returns the socket's file descriptor as assigned by the operating system, or -1 if no descriptor has been assigned.

Definition at line 258 of file socket.cpp.

References fd.

00259 {
00260         return this->fd;
00261 }

std::string InspSocket::GetIP  ) 
 

Returns the IP address associated with this connection, or an empty string if no IP address exists.

Definition at line 150 of file socket.cpp.

References IP.

00151 {
00152         return this->IP;
00153 }

InspSocketState InspSocket::GetState  ) 
 

Returns the current socket state.

Definition at line 253 of file socket.cpp.

References state.

00254 {
00255         return this->state;
00256 }

void InspSocket::OnClose  )  [virtual]
 

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.

Definition at line 269 of file socket.cpp.

Referenced by Close().

00269 { return; }

bool InspSocket::OnConnected  )  [virtual]
 

This method is called when an outbound connection on your socket is completed.

Returns:
false to abort the connection, true to continue

Definition at line 263 of file socket.cpp.

Referenced by Poll().

00263 { return true; }

bool InspSocket::OnDataReady  )  [virtual]
 

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.

Returns:
false to close the socket

Definition at line 267 of file socket.cpp.

Referenced by Poll().

00267 { return true; }

int InspSocket::OnDisconnect  )  [virtual]
 

When an established connection is terminated, the OnDisconnect method is triggered.

Definition at line 265 of file socket.cpp.

00265 { return 0; }

void InspSocket::OnError InspSocketError  e  )  [virtual]
 

This method is called when an error occurs.

A closed socket in itself is not an error, however errors also generate close events.

Parameters:
e The error type which occured

Definition at line 264 of file socket.cpp.

Referenced by InspSocket(), and Timeout().

00264 { return; }

int InspSocket::OnIncomingConnection int  newfd,
char *  ip
[virtual]
 

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().

Definition at line 266 of file socket.cpp.

Referenced by Poll().

00266 { return 0; }

void InspSocket::OnTimeout  )  [virtual]
 

When an outbound connection fails, and the attempt times out, you will receive this event.

The mthod will trigger once maxtime secons are reached (as given in the constructor) just before the socket's descriptor is closed.

Definition at line 268 of file socket.cpp.

Referenced by Timeout().

00268 { return; }

bool InspSocket::Poll  ) 
 

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.

Definition at line 216 of file socket.cpp.

References SocketEngine::AddFd(), client, SocketEngine::DelFd(), I_CONNECTED, I_CONNECTING, I_LISTENING, length, OnConnected(), OnDataReady(), OnIncomingConnection(), InspIRCd::SE, SetState(), and X_ESTAB_MODULE.

00217 {
00218         int incoming = -1;
00219         
00220         switch (this->state)
00221         {
00222                 case I_CONNECTING:
00223                         this->SetState(I_CONNECTED);
00224                         /* Our socket was in write-state, so delete it and re-add it
00225                          * in read-state.
00226                          */
00227                         ServerInstance->SE->DelFd(this->fd);
00228                         ServerInstance->SE->AddFd(this->fd,true,X_ESTAB_MODULE);
00229                         return this->OnConnected();
00230                 break;
00231                 case I_LISTENING:
00232                         length = sizeof (client);
00233                         incoming = accept (this->fd, (sockaddr*)&client,&length);
00234                         this->OnIncomingConnection(incoming,inet_ntoa(client.sin_addr));
00235                         return true;
00236                 break;
00237                 case I_CONNECTED:
00238                         return this->OnDataReady();
00239                 break;
00240                 default:
00241                 break;
00242         }
00243 
00244         return true;
00245 }

char * InspSocket::Read  )  [virtual]
 

Reads all pending bytes from the socket into a char* array which can be up to 16 kilobytes in length.

Definition at line 155 of file socket.cpp.

References DEBUG, ibuf, and log().

00156 {
00157         int n = recv(this->fd,this->ibuf,sizeof(this->ibuf),0);
00158         if (n > 0)
00159         {
00160                 ibuf[n] = 0;
00161                 return ibuf;
00162         }
00163         else
00164         {
00165                 log(DEBUG,"EOF or error on socket");
00166                 return NULL;
00167         }
00168 }

void InspSocket::SetState InspSocketState  s  ) 
 

Changes the socket's state.

The core uses this to change socket states, and you should not call it directly.

Definition at line 247 of file socket.cpp.

References DEBUG, log(), and state.

Referenced by Poll().

00248 {
00249         log(DEBUG,"Socket state change");
00250         this->state = s;
00251 }

bool InspSocket::Timeout time_t  current  ) 
 

This function checks if the socket has timed out yet, given the current time in the parameter.

Returns:
true if timed out, false if not timed out

Definition at line 197 of file socket.cpp.

References FlushWriteBuffer(), I_CONNECTING, I_ERR_TIMEOUT, I_ERROR, OnError(), OnTimeout(), state, timeout, and timeout_end.

00198 {
00199         if ((this->state == I_CONNECTING) && (current > timeout_end))
00200         {
00201                 // for non-listening sockets, the timeout can occur
00202                 // which causes termination of the connection after
00203                 // the given number of seconds without a successful
00204                 // connection.
00205                 this->OnTimeout();
00206                 this->OnError(I_ERR_TIMEOUT);
00207                 timeout = true;
00208                 this->state = I_ERROR;
00209                 return true;
00210         }
00211         if (this->Buffer.length())
00212                 this->FlushWriteBuffer();
00213         return false;
00214 }

int InspSocket::Write std::string  data  )  [virtual]
 

Writes a std::string to the socket.

No carriage returns or linefeeds are appended to the string.

Parameters:
data The data to send

Definition at line 174 of file socket.cpp.

References Buffer, and FlushWriteBuffer().

00175 {
00176         this->Buffer = this->Buffer + data;
00177         this->FlushWriteBuffer();
00178         return data.length();
00179 }


Member Data Documentation

sockaddr_in InspSocket::addr [private]
 

The host being connected to, in sockaddr form.

Definition at line 78 of file socket.h.

Referenced by InspSocket().

in_addr InspSocket::addy [private]
 

The host being connected to, in in_addr form.

Definition at line 84 of file socket.h.

Referenced by InspSocket().

std::string InspSocket::Buffer [private]
 

The output buffer for this socket.

Definition at line 111 of file socket.h.

Referenced by FlushWriteBuffer(), and Write().

sockaddr_in InspSocket::client [private]
 

Client sockaddr structure used by accept().

Definition at line 124 of file socket.h.

Referenced by Poll().

int InspSocket::fd [private]
 

The file descriptor of this socket.

Definition at line 54 of file socket.h.

Referenced by Close(), GetFd(), and InspSocket().

std::string InspSocket::host [private]
 

The hostname connected to.

Definition at line 59 of file socket.h.

char InspSocket::ibuf[65535] [private]
 

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.

Definition at line 106 of file socket.h.

Referenced by Read().

std::string InspSocket::IP [private]
 

The IP address being connected to stored in string form for easy retrieval by accessors.

Definition at line 118 of file socket.h.

Referenced by GetIP(), and InspSocket().

socklen_t InspSocket::length [private]
 

Used by accept() to indicate the sizes of the sockaddr_in structures.

Definition at line 136 of file socket.h.

Referenced by Poll().

int InspSocket::port [private]
 

The port connected to, or the port this socket is listening on.

Definition at line 65 of file socket.h.

sockaddr_in InspSocket::server [private]
 

Server sockaddr structure used by accept().

Definition at line 130 of file socket.h.

InspSocketState InspSocket::state [private]
 

The state for this socket, either listening, connecting, connected or error.

Definition at line 72 of file socket.h.

Referenced by GetState(), InspSocket(), SetState(), and Timeout().

bool InspSocket::timeout [private]
 

This value is true if the socket has timed out.

Definition at line 97 of file socket.h.

Referenced by InspSocket(), and Timeout().

time_t InspSocket::timeout_end [private]
 

When this time is reached, the socket times out if it is in the CONNECTING state.

Definition at line 91 of file socket.h.

Referenced by InspSocket(), and Timeout().


The documentation for this class was generated from the following files:
Generated on Mon Dec 19 18:05:22 2005 for InspIRCd by  doxygen 1.4.4-20050815