summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/Makefile.am2
-rw-r--r--lib/icap/Makefile.am4
-rw-r--r--lib/icap/util.cpp127
-rw-r--r--lib/icap/util.h34
-rw-r--r--lib/socket/Makefile.am4
-rw-r--r--lib/socket/socket.cpp472
-rw-r--r--lib/socket/socket.h427
7 files changed, 83 insertions, 987 deletions
diff --git a/lib/Makefile.am b/lib/Makefile.am
index bcd3933..af3b92e 100644
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -1,3 +1,3 @@
## [bitz-server] lib/
-SUBDIRS = socket icap
+SUBDIRS = icap
diff --git a/lib/icap/Makefile.am b/lib/icap/Makefile.am
index 02d8bb4..f73a8f6 100644
--- a/lib/icap/Makefile.am
+++ b/lib/icap/Makefile.am
@@ -1,9 +1,9 @@
## [icap-library] lib/icap/
-AM_CPPFLAGS = -I$(top_srcdir)/lib
+AM_CPPFLAGS = -I$(top_srcdir)/lib ${psocksxx_CFLAGS}
libicapincludedir = $(includedir)/icap
lib_LTLIBRARIES = libicap.la
-libicap_la_LIBADD = $(top_builddir)/lib/socket/libsocket.la
+libicap_la_LIBADD = ${psocksxx_LIBS}
libicap_la_LDFLAGS = -version-info @ICAP_LT_VERSION@ -no-undefined
libicap_la_SOURCES = \
header.cpp \
diff --git a/lib/icap/util.cpp b/lib/icap/util.cpp
index c383261..91a73e1 100644
--- a/lib/icap/util.cpp
+++ b/lib/icap/util.cpp
@@ -55,41 +55,45 @@ namespace icap {
}
- int read_line( socketlibrary::TCPSocket * socket, char * buf, int buf_length, bool incl_endl ) throw() {
+ int read_line( psocksxx::iosockstream * socket, char * buf, int buf_length, bool incl_endl ) throw() {
- int i = 0, n;
- char c = '\0';
+ int i = 0;
+ char c = '\0';
+ char c_last = '\0';
while ( i < ( buf_length - 1 ) ) {
- n = socket->recv( &c, 1 );
-
- if ( n > 0 ) {
- if ( c == '\r' ) {
+ // read a char
+ if ( ( c = socket->get() ) > 0 ) {
- if ( incl_endl ) {
- buf[i] = c;
- i++;
- }
+ // check last read char for \r
+ if ( c_last == '\r' ) {
- // peak for \n
- n = socket->peek( &c, 1 );
-
- if ( ( n > 0 ) && ( c == '\n' ) ) {
-
- n = socket->recv( &c, 1 );
+ // check for \n
+ if ( c == '\n' ) {
+ // include \r\n in the read buffer?
if ( incl_endl ) {
buf[i] = c;
i++;
+ } else {
+
+ // remove \r
+ i--;
+
}
- break; // end of line
+ break;
+
}
+
}
buf[i] = c;
i++;
+
+ c_last = c;
+
} else {
break; // nothing read from socket
}
@@ -102,52 +106,44 @@ namespace icap {
}
- std::string read_line( socketlibrary::TCPSocket * socket, bool incl_endl ) throw() {
+ std::string read_line( psocksxx::iosockstream * socket, bool incl_endl ) throw() {
int n;
std::string line;
char c = '\0';
+ char c_last = '\0';
- try {
- while ( ( n = socket->recv( &c, 1 ) ) > 0 ) {
+ while ( ( c = socket->get() ) > 0 ) {
- if ( c == '\r' ) {
+ if ( c_last == '\r' ) {
+
+ if ( c == '\n' ) {
if ( incl_endl ) {
line += c;
+ } else {
+ line.erase( line.size() - 1 );
}
- // peak for \n
- n = socket->peek( &c, 1 );
-
- if ( ( n > 0 ) && ( c == '\n' ) ) {
-
- n = socket->recv( &c, 1 );
-
- if ( incl_endl ) {
- line += c;
- }
+ break;
- break; // end of line
- }
}
- line += c;
-
}
- } catch ( socketlibrary::SocketException &sex ) {
- // TODO: log error?
- line = "";
+ line += c;
+ c_last = c;
+
}
+
return line;
}
- std::string read_data( socketlibrary::TCPSocket * socket, int size ) throw() {
+ std::string read_data( psocksxx::iosockstream * socket, int size ) throw() {
char buffer[ICAP_BUFFER_SIZE];
std::string data = "";
@@ -159,20 +155,20 @@ namespace icap {
try {
// read from socket
- n = socket->recv( buffer, min( size, ICAP_BUFFER_SIZE ) );
+ socket->read( buffer, std::min( size, ICAP_BUFFER_SIZE ) );
// sanity check
- if ( n == 0 ) {
+ if (! socket->good() ) {
break;
}
// append to data
- data.append( buffer, n );
+ data.append( buffer, socket->gcount() );
// update size with remaining bytes
- size -= n;
+ size -= socket->gcount();
- } catch ( socketlibrary::SocketException &sex ) {
+ } catch ( psocksxx::sockexception &e ) {
// TODO: log errors ??
}
@@ -183,7 +179,7 @@ namespace icap {
}
- unsigned int read_chunk_size( socketlibrary::TCPSocket * socket ) throw() {
+ unsigned int read_chunk_size( psocksxx::iosockstream * socket ) throw() {
std::string line;
std::vector<std::string> chunk_header;
@@ -196,7 +192,7 @@ namespace icap {
}
- void read_chunk_header( socketlibrary::TCPSocket * socket, chunk_t &chunk ) throw() {
+ void read_chunk_header( psocksxx::iosockstream * socket, chunk_t &chunk ) throw() {
std::string line;
std::vector<std::string> chunk_header;
@@ -223,7 +219,7 @@ namespace icap {
}
- chunk_t read_chunk( socketlibrary::TCPSocket * socket ) throw() {
+ chunk_t read_chunk( psocksxx::iosockstream * socket ) throw() {
chunk_t chunk;
std::string line;
@@ -250,7 +246,7 @@ namespace icap {
}
- std::string read_chunked( socketlibrary::TCPSocket * socket ) throw() {
+ std::string read_chunked( psocksxx::iosockstream * socket ) throw() {
unsigned int chunk_size = 0;
unsigned int offset = 0;
@@ -282,7 +278,7 @@ namespace icap {
}
- bool read_chunked_payload( socketlibrary::TCPSocket * socket, std::string &payload ) throw() {
+ bool read_chunked_payload( psocksxx::iosockstream * socket, std::string &payload ) throw() {
chunk_t chunk;
bool ieof = false;
@@ -313,12 +309,12 @@ namespace icap {
}
- bool send_line( const std::string &line, socketlibrary::TCPSocket * socket ) throw() {
+ bool send_line( const std::string &line, psocksxx::iosockstream * socket ) throw() {
try {
- socket->send( line.c_str(), line.length() );
- socket->send( "\r\n", 2 );
- } catch ( socketlibrary::SocketException &sex ) {
+ socket->write( line.c_str(), line.length() );
+ socket->write( "\r\n", 2 );
+ } catch ( psocksxx::sockexception &e ) {
// TODO: log errors
return false;
}
@@ -328,11 +324,11 @@ namespace icap {
}
- bool send_data( const std::string &data, socketlibrary::TCPSocket * socket ) throw() {
+ bool send_data( const std::string &data, psocksxx::iosockstream * socket ) throw() {
try {
- socket->send( data.c_str(), data.size() );
- } catch( socketlibrary::SocketException &sex ) {
+ socket->write( data.c_str(), data.size() );
+ } catch ( psocksxx::sockexception &e ) {
// TODO: log errors
return false;
}
@@ -342,7 +338,7 @@ namespace icap {
}
- bool send_chunked( const std::string &data, socketlibrary::TCPSocket * socket ) throw() {
+ bool send_chunked( const std::string &data, psocksxx::iosockstream * socket ) throw() {
std::string chunked_data = "";
unsigned int offset = 0;
@@ -388,7 +384,7 @@ namespace icap {
return false;
}
- } catch ( socketlibrary::SocketException &sex ) {
+ } catch ( psocksxx::sockexception &e ) {
// TODO: log errors ??
return false;
}
@@ -432,7 +428,7 @@ namespace icap {
}
- icap::RequestHeader * read_req_header( socketlibrary::TCPSocket * socket ) throw() {
+ icap::RequestHeader * read_req_header( psocksxx::iosockstream * socket ) throw() {
char buffer[ICAP_BUFFER_SIZE];
int n = 0;
@@ -448,7 +444,7 @@ namespace icap {
}
- bool read_req_data( icap::Request * request, socketlibrary::TCPSocket * socket ) throw() {
+ bool read_req_data( icap::Request * request, psocksxx::iosockstream * socket ) throw() {
int data_offset = 0;
int data_length = 0;
@@ -529,7 +525,7 @@ namespace icap {
}
- bool read_req_continue_data( icap::Request * request, socketlibrary::TCPSocket * socket ) throw() {
+ bool read_req_continue_data( icap::Request * request, psocksxx::iosockstream * socket ) throw() {
std::vector<icap::Header::encapsulated_header_data_t> sorted_encaps_header;
icap::Header::encapsulated_header_data_t header_idx;
@@ -574,7 +570,7 @@ namespace icap {
}
- bool send_headers( icap::Header * header, socketlibrary::TCPSocket * socket ) throw() {
+ bool send_headers( icap::Header * header, psocksxx::iosockstream * socket ) throw() {
std::string line;
icap::Header::headers_index_t i;
@@ -612,7 +608,7 @@ namespace icap {
}
- bool send_response( icap::Response * response, socketlibrary::TCPSocket * socket ) throw() {
+ bool send_response( icap::Response * response, psocksxx::iosockstream * socket ) throw() {
bool r_success = true;
@@ -660,6 +656,9 @@ namespace icap {
}
+ // flush-out socket stream buffer
+ socket->flush();
+
return r_success;
}
diff --git a/lib/icap/util.h b/lib/icap/util.h
index 366bb9c..14765ac 100644
--- a/lib/icap/util.h
+++ b/lib/icap/util.h
@@ -22,7 +22,7 @@
#include <sstream>
-#include <socket/socket.h>
+#include <psocksxx/iosockstream.h>
#include "request.h"
#include "response.h"
@@ -80,7 +80,7 @@ namespace icap {
* default is false.
* @return number of bytes read
*/
- int read_line( socketlibrary::TCPSocket * socket, char * buf, int buf_length, bool incl_endl = false ) throw();
+ int read_line( psocksxx::iosockstream * socket, char * buf, int buf_length, bool incl_endl = false ) throw();
/**
* Read a line (ending with \r\n) from the socket
@@ -90,7 +90,7 @@ namespace icap {
* default is false.
* @return read data
*/
- std::string read_line( socketlibrary::TCPSocket * socket, bool incl_endl = false ) throw();
+ std::string read_line( psocksxx::iosockstream * socket, bool incl_endl = false ) throw();
/**
* Read data from the socket
@@ -99,7 +99,7 @@ namespace icap {
* @param size size / length of data to be read
* @return read data
*/
- std::string read_data( socketlibrary::TCPSocket * socket, int size ) throw();
+ std::string read_data( psocksxx::iosockstream * socket, int size ) throw();
/**
* Read chunk size. This is a helper method used by read_chunked().
@@ -107,7 +107,7 @@ namespace icap {
* @param socket socket instance to read from
* @return chunk size
*/
- unsigned int read_chunk_size( socketlibrary::TCPSocket * socket ) throw();
+ unsigned int read_chunk_size( psocksxx::iosockstream * socket ) throw();
/**
* Read chunk header from the given socket.
@@ -115,7 +115,7 @@ namespace icap {
* @param socket socket instance to read data from
* @param chunk chunk data structure to store header data
*/
- void read_chunk_header( socketlibrary::TCPSocket * socket, chunk_t &chunk ) throw();
+ void read_chunk_header( psocksxx::iosockstream * socket, chunk_t &chunk ) throw();
/**
* Read a data chunk from a HTTP chunked transfer encoded data stream.
@@ -123,7 +123,7 @@ namespace icap {
* @param socket socket instance to read data from
* @return chunk data structure
*/
- chunk_t read_chunk( socketlibrary::TCPSocket * socket ) throw();
+ chunk_t read_chunk( psocksxx::iosockstream * socket ) throw();
/**
* Read chunked data from the given socket
@@ -131,7 +131,7 @@ namespace icap {
* @param socket socket instance to read data from
* @return read data (without the control characters)
*/
- std::string read_chunked( socketlibrary::TCPSocket * socket ) throw();
+ std::string read_chunked( psocksxx::iosockstream * socket ) throw();
/**
* Read chunked payload data from the given socket
@@ -140,7 +140,7 @@ namespace icap {
* @param payload payload to read data into
* @return boolean flag to denote the presence of "ieof"
*/
- bool read_chunked_payload( socketlibrary::TCPSocket * socket, std::string &payload ) throw();
+ bool read_chunked_payload( psocksxx::iosockstream * socket, std::string &payload ) throw();
/**
* Send / write a line (ending with \r\n) to the socket
@@ -149,7 +149,7 @@ namespace icap {
* @param socket socket object to write the data to
* @return boolean to denote success or failure
*/
- bool send_line( const std::string &line, socketlibrary::TCPSocket * socket ) throw();
+ bool send_line( const std::string &line, psocksxx::iosockstream * socket ) throw();
/**
* Send / write data to the socket.
@@ -160,7 +160,7 @@ namespace icap {
* @param socket socket instance to write to
* @return boolean to denote success or failure
*/
- bool send_data( const std::string &data, socketlibrary::TCPSocket * socket ) throw();
+ bool send_data( const std::string &data, psocksxx::iosockstream * socket ) throw();
/**
* Send / write data to the socket using chunked transfer encoding
@@ -169,7 +169,7 @@ namespace icap {
* @param socket socket instance to write to
* @return boolean to denote success or failure
*/
- bool send_chunked( const std::string &data, socketlibrary::TCPSocket * socket ) throw();
+ bool send_chunked( const std::string &data, psocksxx::iosockstream * socket ) throw();
/**
* split a string into a vector by the given delimiter
@@ -209,7 +209,7 @@ namespace icap {
* @param socket socket object to read data from
* @return icap request header object
*/
- icap::RequestHeader * read_req_header( socketlibrary::TCPSocket * socket ) throw();
+ icap::RequestHeader * read_req_header( psocksxx::iosockstream * socket ) throw();
/**
* Read icap request into the icap::Request instance
@@ -219,7 +219,7 @@ namespace icap {
* @param socket socket object to read data from
* @return boolean to denote success or failure
*/
- bool read_req_data( icap::Request * request, socketlibrary::TCPSocket * socket ) throw();
+ bool read_req_data( icap::Request * request, psocksxx::iosockstream * socket ) throw();
/**
* Read icap request data after a '100 Continue' response. This will not look for any
@@ -229,7 +229,7 @@ namespace icap {
* @param socket socket object to read data from
* @return boolean to denote success or failure
*/
- bool read_req_continue_data( icap::Request * request, socketlibrary::TCPSocket * socket ) throw();
+ bool read_req_continue_data( icap::Request * request, psocksxx::iosockstream * socket ) throw();
/**
* Send / write header data to a socket
@@ -238,7 +238,7 @@ namespace icap {
* @param socket socket object to write the data to
* @return boolean to denote success or failure
*/
- bool send_headers( icap::Header::headers_t headers, socketlibrary::TCPSocket * socket ) throw();
+ bool send_headers( icap::Header::headers_t headers, psocksxx::iosockstream * socket ) throw();
/**
* Output a response using the passed in icap::Response class to the
@@ -248,7 +248,7 @@ namespace icap {
* @param socket socket object to send the data to
* @return boolean to denote success or failure
*/
- bool send_response( icap::Response * response, socketlibrary::TCPSocket * socket ) throw();
+ bool send_response( icap::Response * response, psocksxx::iosockstream * socket ) throw();
/**
* Returns the response status text for the given status
diff --git a/lib/socket/Makefile.am b/lib/socket/Makefile.am
deleted file mode 100644
index 93f98a5..0000000
--- a/lib/socket/Makefile.am
+++ /dev/null
@@ -1,4 +0,0 @@
-## [socket-library] lib/
-noinst_LTLIBRARIES = libsocket.la
-libsocket_la_SOURCES = socket.h socket.cpp
-
diff --git a/lib/socket/socket.cpp b/lib/socket/socket.cpp
deleted file mode 100644
index a086d95..0000000
--- a/lib/socket/socket.cpp
+++ /dev/null
@@ -1,472 +0,0 @@
-/*
- * C++ sockets on Unix and Windows
- * Copyright (C) 2002 <unknown>
- * Copyright (C) 2010 Uditha Atukorala
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include <socket.h>
-
-#ifndef WIN32
- #include <sys/types.h> // For data types
- #include <sys/socket.h> // For socket(), connect(), send(), and recv()
- #include <netdb.h> // For gethostbyname()
- #include <arpa/inet.h> // For inet_addr()
- #include <unistd.h> // For close()
-#endif
-
-#include <cerrno> // For errno
-#include <cstring> // For strerror
-#include <cstdlib> // For atoi()
-
-using namespace std;
-
-namespace socketlibrary {
-
-#ifdef WIN32
- static bool initialized = false;
-#endif
-
-// SocketException Code
-
-SocketException::SocketException(const string &message, bool inclSysMsg) throw() : userMessage(message) {
- if (inclSysMsg) {
- userMessage.append(": ");
- userMessage.append(strerror(errno));
- }
-}
-
-SocketException::~SocketException() throw() {
-}
-
-const char *SocketException::what() const throw() {
- return userMessage.c_str();
-}
-
-// Function to fill in address structure given an address and port
-void fillAddr(const string &address, unsigned short port, sockaddr_in &addr) {
-
- memset(&addr, 0, sizeof(addr)); // Zero out address structure
- addr.sin_family = AF_INET; // Internet address
-
- hostent *host; // Resolve name
- if ((host = gethostbyname(address.c_str())) == NULL) {
- // strerror() will not work for gethostbyname() and hstrerror()
- // is supposedly obsolete
- throw SocketException("Failed to resolve name (gethostbyname())");
- }
-
- addr.sin_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
- addr.sin_port = htons(port); // Assign port in network byte order
-
-}
-
-// Socket Code
-
-Socket::Socket(int type, int protocol) throw(SocketException) {
-#ifdef WIN32
- if (!initialized) {
- WORD wVersionRequested;
- WSADATA wsaData;
-
- wVersionRequested = MAKEWORD(2, 0); // Request WinSock v2.0
- if (WSAStartup(wVersionRequested, &wsaData) != 0) { // Load WinSock DLL
- throw SocketException("Unable to load WinSock DLL");
- }
- initialized = true;
- }
-#endif
-
- // Make a new socket
- if ((sock = socket(PF_INET, type, protocol)) < 0) {
- throw SocketException("Socket creation failed (socket())", true);
- }
-}
-
-Socket::Socket(int sock) {
- this->sock = sock;
-}
-
-Socket::~Socket() {
-
-#ifdef WIN32
- ::closesocket(sock);
-#else
- ::close(sock);
-#endif
- sock = -1;
-}
-
-string Socket::getLocalAddress() throw(SocketException) {
- sockaddr_in addr;
- unsigned int addr_len = sizeof(addr);
-
- if (getsockname(sock, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
- throw SocketException("Fetch of local address failed (getsockname())", true);
- }
- return inet_ntoa(addr.sin_addr);
-}
-
-unsigned short Socket::getLocalPort() throw(SocketException) {
- sockaddr_in addr;
- unsigned int addr_len = sizeof(addr);
-
- if (getsockname(sock, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
- throw SocketException("Fetch of local port failed (getsockname())", true);
- }
- return ntohs(addr.sin_port);
-}
-
-void Socket::setLocalPort(unsigned short localPort) throw(SocketException) {
- // Bind the socket to its port
- sockaddr_in localAddr;
- memset(&localAddr, 0, sizeof(localAddr));
- localAddr.sin_family = AF_INET;
- localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- localAddr.sin_port = htons(localPort);
-
- if (bind(sock, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
- throw SocketException("Set of local port failed (bind())", true);
- }
-}
-
-void Socket::setLocalAddressAndPort(const string &localAddress, unsigned short localPort) throw(SocketException) {
- // Get the address of the requested host
- sockaddr_in localAddr;
- fillAddr(localAddress, localPort, localAddr);
-
- if (bind(sock, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
- throw SocketException("Set of local address and port failed (bind())", true);
- }
-}
-
-void Socket::cleanUp() throw(SocketException) {
-#ifdef WIN32
- if (WSACleanup() != 0) {
- throw SocketException("WSACleanup() failed");
- }
-#endif
-}
-
-unsigned short Socket::resolveService(const string &service, const string &protocol) {
-
- struct servent *serv; /* Structure containing service information */
-
- if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL)
- return atoi(service.c_str()); /* Service is port number */
- else
- return ntohs(serv->s_port); /* Found port (network byte order) by name */
-
-}
-
-// CommunicatingSocket Code
-
-CommunicatingSocket::CommunicatingSocket(int type, int protocol) throw(SocketException) : Socket(type, protocol) {
-}
-
-CommunicatingSocket::CommunicatingSocket(int newSD) : Socket(newSD) {
-}
-
-void CommunicatingSocket::connect(const string &foreignAddress, unsigned short foreignPort) throw(SocketException) {
- // Get the address of the requested host
- sockaddr_in destAddr;
- fillAddr(foreignAddress, foreignPort, destAddr);
-
- // Try to connect to the given port
- if (::connect(sock, (sockaddr *) &destAddr, sizeof(destAddr)) < 0) {
- throw SocketException("Connect failed (connect())", true);
- }
-}
-
-void CommunicatingSocket::send(const void *buffer, int bufferLen) throw(SocketException) {
- if (::send(sock, (raw_type *) buffer, bufferLen, 0) < 0) {
- throw SocketException("Send failed (send())", true);
- }
-}
-
-int CommunicatingSocket::recv(void *buffer, int bufferLen) throw(SocketException) {
- int rtn;
- if ((rtn = ::recv(sock, (raw_type *) buffer, bufferLen, 0)) < 0) {
- throw SocketException("Received failed (recv()) for socket ", true);
- }
- return rtn;
-}
-
-int CommunicatingSocket::peek(void *buffer, int bufferLen) throw(SocketException) {
- int rtn;
- if ((rtn = ::recv(sock, (raw_type *) buffer, bufferLen, MSG_PEEK)) < 0) {
- throw SocketException("Received failed (recv()) for socket ", true);
- }
- return rtn;
-}
-
-int CommunicatingSocket::readLine(char *buffer, int bufferLen, const char delimiter) throw(SocketException) {
-
- int n, rc;
- char c;
-
- for (n = 1; n < bufferLen; n++) {
- if ((rc = recv(&c, 1)) == 1) {
- *buffer++ = c;
- if (c == delimiter) {
- break;
- }
- } else if (rc == 0) {
- if (n == 1) {
- return 0; // EOF, no data read
- } else {
- break; // EOF, read some data
- }
- } else {
- throw SocketException("Failed to read data from socket ", true);
- }
- }
-
- *buffer = '\0';
- return n;
-
-}
-
-string CommunicatingSocket::getForeignAddress() throw(SocketException) {
- sockaddr_in addr;
- unsigned int addr_len = sizeof(addr);
-
- if (getpeername(sock, (sockaddr *) &addr,(socklen_t *) &addr_len) < 0) {
- throw SocketException("Fetch of foreign address failed (getpeername())", true);
- }
- return inet_ntoa(addr.sin_addr);
-}
-
-unsigned short CommunicatingSocket::getForeignPort() throw(SocketException) {
- sockaddr_in addr;
- unsigned int addr_len = sizeof(addr);
-
- if (getpeername(sock, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
- throw SocketException("Fetch of foreign port failed (getpeername())", true);
- }
- return ntohs(addr.sin_port);
-}
-
-// TCPSocket Code
-
-TCPSocket::TCPSocket() throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
-}
-
-TCPSocket::TCPSocket(const string &foreignAddress, unsigned short foreignPort) throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
- connect(foreignAddress, foreignPort);
-}
-
-TCPSocket::TCPSocket(int newSD) : CommunicatingSocket(newSD) {
-}
-
-// TCPServerSocket Code
-
-TCPServerSocket::TCPServerSocket(unsigned short localPort, int queueLen) throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
- setLocalPort(localPort);
- setListen(queueLen);
-}
-
-TCPServerSocket::TCPServerSocket(const string &localAddress, unsigned short localPort, int queueLen) throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
- setLocalAddressAndPort(localAddress, localPort);
- setListen(queueLen);
-}
-
-TCPSocket *TCPServerSocket::accept() throw(SocketException) {
- int newSD;
- if ((newSD = ::accept(sock, NULL, 0)) < 0) {
- throw SocketException("Accept failed (accept())", true);
- }
- return new TCPSocket(newSD);
-}
-
-void TCPServerSocket::setListen(int queueLen) throw(SocketException) {
- if (listen(sock, queueLen) < 0) {
- throw SocketException("Set listening socket failed (listen())", true);
- }
-}
-
-// TCPServerSocketM Code
-
-TCPServerSocketM::TCPServerSocketM(unsigned short localPort, int queueLen) throw(SocketException) : TCPServerSocket(localPort, queueLen) {
-
- FD_ZERO(&fds_master); // clear the master and temp sets
-
- FD_SET(sock, &fds_master); // Add ourself to the master set
- fdmax = sock; // keep track of the biggest file descriptor, only ourself for the moment
-
-}
-
-TCPSocket *TCPServerSocketM::accept() throw(SocketException) {
-
- TCPSocket *newClient = TCPServerSocket::accept();
- int newSD = newClient->sock;
-
- FD_SET(newSD, &fds_master); // add to master set
- if (newSD > fdmax) { // keep track of the max
- fdmax = newSD;
- }
-
- v_clients.push_back(newClient);
- return newClient;
-
-}
-
-bool TCPServerSocketM::pendingConnections() throw (SocketException) {
-
- fd_set read_fds;
- FD_ZERO(&read_fds);
-
- read_fds = fds_master;
- if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
- throw SocketException("Failed to select read fds (select())", true);
- }
-
- if (FD_ISSET(sock, &read_fds)) {
- return true;
- } else {
- return false;
- }
-
-}
-
-int TCPServerSocketM::getWaitingClients(vector<TCPSocket *> &clients) throw (SocketException) {
-
- fd_set read_fds;
- FD_ZERO(&read_fds);
-
- int cl_count = 0;
-
- read_fds = fds_master;
- if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
- throw SocketException("Failed to select read fds (select())", true);
- }
-
- // resize the vector so it doesn't contain any old information
- clients.resize(0);
-
- for(unsigned int i=0; i<v_clients.size(); i++) {
- if (FD_ISSET(v_clients.at(i)->sock, &read_fds)) { // we got one!!
- clients.push_back(v_clients.at(i));
- cl_count++;
- }
- }
-
- return cl_count;
-}
-
-void TCPServerSocketM::closeClientConnection(TCPSocket * client) {
-
- for(unsigned int i=0; i<v_clients.size(); i++) {
- if (client->sock == v_clients.at(i)->sock) {
- FD_CLR(client->sock, &fds_master);
- v_clients.erase(v_clients.begin() + i);
- delete client;
- break;
- }
- }
-
-}
-
-
-// UDPSocket Code
-
-UDPSocket::UDPSocket() throw(SocketException) : CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
- setBroadcast();
-}
-
-UDPSocket::UDPSocket(unsigned short localPort) throw(SocketException) : CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
- setLocalPort(localPort);
- setBroadcast();
-}
-
-UDPSocket::UDPSocket(const string &localAddress, unsigned short localPort) throw(SocketException) : CommunicatingSocket(SOCK_DGRAM, IPPROTO_UDP) {
- setLocalAddressAndPort(localAddress, localPort);
- setBroadcast();
-}
-
-void UDPSocket::setBroadcast() {
- // If this fails, we'll hear about it when we try to send. This will allow
- // system that cannot broadcast to continue if they don't plan to broadcast
- int broadcastPermission = 1;
- setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (raw_type *) &broadcastPermission, sizeof(broadcastPermission));
-}
-
-void UDPSocket::disconnect() throw(SocketException) {
- sockaddr_in nullAddr;
- memset(&nullAddr, 0, sizeof(nullAddr));
- nullAddr.sin_family = AF_UNSPEC;
-
- // Try to disconnect
- if (::connect(sock, (sockaddr *) &nullAddr, sizeof(nullAddr)) < 0) {
-#ifdef WIN32
- if (errno != WSAEAFNOSUPPORT) {
-#else
- if (errno != EAFNOSUPPORT) {
-#endif
- throw SocketException("Disconnect failed (connect())", true);
- }
- }
-}
-
-void UDPSocket::sendTo(const void *buffer, int bufferLen, const string &foreignAddress, unsigned short foreignPort) throw(SocketException) {
- sockaddr_in destAddr;
- fillAddr(foreignAddress, foreignPort, destAddr);
-
- // Write out the whole buffer as a single message.
- if (sendto(sock, (raw_type *) buffer, bufferLen, 0, (sockaddr *) &destAddr, sizeof(destAddr)) != bufferLen) {
- throw SocketException("Send failed (sendto())", true);
- }
-}
-
-int UDPSocket::recvFrom(void *buffer, int bufferLen, string &sourceAddress, unsigned short &sourcePort) throw(SocketException) {
- sockaddr_in clntAddr;
- socklen_t addrLen = sizeof(clntAddr);
- int rtn;
- if ((rtn = recvfrom(sock, (raw_type *) buffer, bufferLen, 0, (sockaddr *) &clntAddr, (socklen_t *) &addrLen)) < 0) {
- throw SocketException("Receive failed (recvfrom())", true);
- }
- sourceAddress = inet_ntoa(clntAddr.sin_addr);
- sourcePort = ntohs(clntAddr.sin_port);
- return rtn;
-}
-
-void UDPSocket::setMulticastTTL(unsigned char multicastTTL) throw(SocketException) {
- if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (raw_type *) &multicastTTL, sizeof(multicastTTL)) < 0) {
- throw SocketException("Multicast TTL set failed (setsockopt())", true);
- }
-}
-
-void UDPSocket::joinGroup(const string &multicastGroup) throw(SocketException) {
- struct ip_mreq multicastRequest;
-
- multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
- multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
- if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (raw_type *) &multicastRequest, sizeof(multicastRequest)) < 0) {
- throw SocketException("Multicast group join failed (setsockopt())", true);
- }
-}
-
-void UDPSocket::leaveGroup(const string &multicastGroup) throw(SocketException) {
- struct ip_mreq multicastRequest;
-
- multicastRequest.imr_multiaddr.s_addr = inet_addr(multicastGroup.c_str());
- multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
- if (setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (raw_type *) &multicastRequest, sizeof(multicastRequest)) < 0) {
- throw SocketException("Multicast group leave failed (setsockopt())", true);
- }
-}
-
-} // End of namespace SocketLibrary
diff --git a/lib/socket/socket.h b/lib/socket/socket.h
deleted file mode 100644
index 2c4d777..0000000
--- a/lib/socket/socket.h
+++ /dev/null
@@ -1,427 +0,0 @@
-/*
- * C++ sockets on Unix and Windows
- * Copyright (C) 2002 <unknown>
- * Copyright (C) 2010 Uditha Atukorala
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef SL_SOCKET_H
-#define SL_SOCKET_H
-
-#include <string> // For string
-#include <exception> // For exception class
-#include <vector> // For vectors
-
-#ifdef WIN32
- #include <winsock.h> // For socket(), connect(), send(), and recv()
- typedef int socklen_t;
- typedef char raw_type; // Type used for raw data on this platform
-#else
- #include <netinet/in.h> // For sockaddr_in
- typedef void raw_type; // Type used for raw data on this platform
-#endif
-
-using namespace std;
-
-namespace socketlibrary {
-
-/**
- * Function to fill in address structure given an address and port
- */
-void fillAddr(const string &address, unsigned short port, sockaddr_in &addr);
-
-/**
- * Signals a problem with the execution of a socket call.
- */
-class SocketException : public exception {
-public:
- /**
- * Construct a SocketException with a explanatory message.
- * @param message explanatory message
- * @param incSysMsg true if system message (from strerror(errno))
- * should be postfixed to the user provided message
- */
- SocketException(const string &message, bool inclSysMsg = false) throw();
-
- /**
- * Provided just to guarantee that no exceptions are thrown.
- */
- ~SocketException() throw();
-
- /**
- * Get the exception message
- * @return exception message
- */
- const char *what() const throw();
-
-private:
- string userMessage; // Exception message
-};
-
-
-/**
- * Base class representing basic communication endpoint
- */
-class Socket {
-public:
- /**
- * Close and deallocate this socket
- */
- ~Socket();
-
- /**
- * Get the local address
- * @return local address of socket
- * @exception SocketException thrown if fetch fails
- */
- string getLocalAddress() throw(SocketException);
-
- /**
- * Get the local port
- * @return local port of socket
- * @exception SocketException thrown if fetch fails
- */
- unsigned short getLocalPort() throw(SocketException);
-
- /**
- * Set the local port to the specified port and the local address
- * to any interface
- * @param localPort local port
- * @exception SocketException thrown if setting local port fails
- */
- void setLocalPort(unsigned short localPort) throw(SocketException);
-
- /**
- * Set the local port to the specified port and the local address
- * to the specified address. If you omit the port, a random port
- * will be selected.
- * @param localAddress local address
- * @param localPort local port
- * @exception SocketException thrown if setting local port or address fails
- */
- void setLocalAddressAndPort(const string &localAddress, unsigned short localPort = 0) throw(SocketException);
-
- /**
- * If WinSock, unload the WinSock DLLs; otherwise do nothing. We ignore
- * this in our sample client code but include it in the library for
- * completeness. If you are running on Windows and you are concerned
- * about DLL resource consumption, call this after you are done with all
- * Socket instances. If you execute this on Windows while some instance of
- * Socket exists, you are toast. For portability of client code, this is
- * an empty function on non-Windows platforms so you can always include it.
- * @param buffer buffer to receive the data
- * @param bufferLen maximum number of bytes to read into buffer
- * @return number of bytes read, 0 for EOF, and -1 for error
- * @exception SocketException thrown WinSock clean up fails
- */
- static void cleanUp() throw(SocketException);
-
- /**
- * Resolve the specified service for the specified protocol to the
- * corresponding port number in host byte order
- * @param service service to resolve (e.g., "http")
- * @param protocol protocol of service to resolve. Default is "tcp".
- */
- static unsigned short resolveService(const string &service, const string &protocol = "tcp");
-
-private:
- // Prevent the user from trying to use value semantics on this object
- Socket(const Socket &sock);
- void operator=(const Socket &sock);
-
-protected:
- int sock; // Socket descriptor
- Socket(int type, int protocol) throw(SocketException);
- Socket(int sock);
-};
-
-/**
- * Socket which is able to connect, send, and receive
- */
-class CommunicatingSocket : public Socket {
-public:
- /**
- * Establish a socket connection with the given foreign
- * address and port
- * @param foreignAddress foreign address (IP address or name)
- * @param foreignPort foreign port
- * @exception SocketException thrown if unable to establish connection
- */
- void connect(const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
-
- /**
- * Write the given buffer to this socket. Call connect() before
- * calling send()
- * @param buffer buffer to be written
- * @param bufferLen number of bytes from buffer to be written
- * @exception SocketException thrown if unable to send data
- */
- void send(const void *buffer, int bufferLen) throw(SocketException);
-
- /**
- * Read into the given buffer up to bufferLen bytes data from this
- * socket. Call connect() before calling recv()
- * @param buffer buffer to receive the data
- * @param bufferLen maximum number of bytes to read into buffer
- * @return number of bytes read, 0 for EOF, and -1 for error
- * @exception SocketException thrown if unable to receive data
- */
- int recv(void *buffer, int bufferLen) throw(SocketException);
-
- /**
- * Read into the given buffer up to bufferLen bytes data from this
- * socket but don't remove the read bytes from the socket read buffer.
- * Call connect() before calling peek()
- *
- * @param buffer buffer to receive the data
- * @param bufferLen maximum number of bytes to read into buffer
- * @return number of bytes read, 0 for EOF, and -1 for error
- * @exception SocketException thrown if unable to receive data
- */
- int peek(void *buffer, int bufferLen) throw(SocketException);
-
- /**
- * Read a line into the given buffer from this socket.
- * Call connect() before calling recv()
- *
- * @param buffer buffer to receive the data
- * @param bufferLen maximum number of bytes to read into buffer
- * @param delimiter (optional) end of line delimiter
- * @return number of bytes read, 0 for EOF, and -1 for error
- * @exception SocketException thrown if unable to receive data
- */
- int readLine(char *buffer, int bufferLen, const char delimiter = '\n') throw(SocketException);
-
- /**
- * Get the foreign address. Call connect() before calling recv()
- * @return foreign address
- * @exception SocketException thrown if unable to fetch foreign address
- */
- string getForeignAddress() throw(SocketException);
-
- /**
- * Get the foreign port. Call connect() before calling recv()
- * @return foreign port
- * @exception SocketException thrown if unable to fetch foreign port
- */
- unsigned short getForeignPort() throw(SocketException);
-
-protected:
- CommunicatingSocket(int type, int protocol) throw(SocketException);
- CommunicatingSocket(int newSD);
-};
-
-/**
- * TCP socket for communication with other TCP sockets
- */
-class TCPSocket : public CommunicatingSocket {
-public:
- /**
- * Construct a TCP socket with no connection
- * @exception SocketException thrown if unable to create TCP socket
- */
- TCPSocket() throw(SocketException);
-
- /**
- * Construct a TCP socket with a connection to the given foreign address
- * and port
- * @param foreignAddress foreign address (IP address or name)
- * @param foreignPort foreign port
- * @exception SocketException thrown if unable to create TCP socket
- */
- TCPSocket(const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
-
-private:
- friend class TCPServerSocket; // Access for TCPServerSocket::accept() connection creation
- friend class TCPServerSocketM; // Access for TCPServerSocketM::accept() connection creation
- TCPSocket(int newSD);
-};
-
-/**
- * TCP socket class for servers
- */
-class TCPServerSocket : public Socket {
-public:
- /**
- * Construct a TCP socket for use with a server, accepting connections
- * on the specified port on any interface
- * @param localPort local port of server socket, a value of zero will
- * give a system-assigned unused port
- * @param queueLen maximum queue length for outstanding
- * connection requests (default 5)
- * @exception SocketException thrown if unable to create TCP server socket
- */
- TCPServerSocket(unsigned short localPort, int queueLen = 5) throw(SocketException);
-
- /**
- * Construct a TCP socket for use with a server, accepting connections
- * on the specified port on the interface specified by the given address
- * @param localAddress local interface (address) of server socket
- * @param localPort local port of server socket
- * @param queueLen maximum queue length for outstanding
- * connection requests (default 5)
- * @exception SocketException thrown if unable to create TCP server socket
- */
- TCPServerSocket(const string &localAddress, unsigned short localPort, int queueLen = 5) throw(SocketException);
-
- /**
- * Blocks until a new connection is established on this socket or error
- * @return new connection socket
- * @exception SocketException thrown if attempt to accept a new connection fails
- */
- TCPSocket *accept() throw(SocketException);
-
-private:
- void setListen(int queueLen) throw(SocketException);
-};
-
-/**
- * TCP socket class for multi-client servers
- */
-class TCPServerSocketM : public TCPServerSocket {
-public:
-
- /**
- * Construct a TCP socket for use with a server, accepting connections
- * on the specified port on any interface
- * @param localPort local port of server socket, a value of zero will
- * give a system-assigned unused port
- * @param queueLen maximum queue length for outstanding
- * connection requests (default 5)
- * @exception SocketException thrown if unable to create TCP server socket
- */
- TCPServerSocketM(unsigned short localPort, int queueLen = 5) throw(SocketException);
-
- /**
- * Blocks until a new connection is established on this socket or error
- * @return new connection socket
- * @exception SocketException thrown if attempt to accept a new connection fails
- */
- TCPSocket *accept() throw(SocketException);
-
- /**
- * Checks for incoming connections or error
- * @return boolean (true if incoming connections are present)
- * @exception SocketException thrown if attempt to check for new connections fail
- */
- bool pendingConnections() throw(SocketException);
-
- /**
- * Checks for read waiting clients
- * @param clients a vector of TCPSocket pointers to get the waiting clients
- * @return number of clients waiting
- * @exception SocketException thrown if attempt to check for waiting clients fail
- */
- int getWaitingClients(vector<TCPSocket *> &clients) throw (SocketException);
-
- /**
- * Closes the connection to a client
- * @param client the client TCPSocket to close
- */
- void closeClientConnection(TCPSocket *client);
-
-private:
- fd_set fds_master; // master file descriptor list
- int fdmax; // maximum file descriptor number
-
- vector<TCPSocket *> v_clients;
-};
-
-/**
- * UDP socket class
- */
-class UDPSocket : public CommunicatingSocket {
-public:
- /**
- * Construct a UDP socket
- * @exception SocketException thrown if unable to create UDP socket
- */
- UDPSocket() throw(SocketException);
-
- /**
- * Construct a UDP socket with the given local port
- * @param localPort local port
- * @exception SocketException thrown if unable to create UDP socket
- */
- UDPSocket(unsigned short localPort) throw(SocketException);
-
- /**
- * Construct a UDP socket with the given local port and address
- * @param localAddress local address
- * @param localPort local port
- * @exception SocketException thrown if unable to create UDP socket
- */
- UDPSocket(const string &localAddress, unsigned short localPort) throw(SocketException);
-
- /**
- * Unset foreign address and port
- * @return true if disassociation is successful
- * @exception SocketException thrown if unable to disconnect UDP socket
- */
- void disconnect() throw(SocketException);
-
- /**
- * Send the given buffer as a UDP datagram to the
- * specified address/port
- * @param buffer buffer to be written
- * @param bufferLen number of bytes to write
- * @param foreignAddress address (IP address or name) to send to
- * @param foreignPort port number to send to
- * @return true if send is successful
- * @exception SocketException thrown if unable to send datagram
- */
- void sendTo(const void *buffer, int bufferLen, const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
-
- /**
- * Read read up to bufferLen bytes data from this socket. The given buffer
- * is where the data will be placed
- * @param buffer buffer to receive data
- * @param bufferLen maximum number of bytes to receive
- * @param sourceAddress address of datagram source
- * @param sourcePort port of data source
- * @return number of bytes received and -1 for error
- * @exception SocketException thrown if unable to receive datagram
- */
- int recvFrom(void *buffer, int bufferLen, string &sourceAddress, unsigned short &sourcePort) throw(SocketException);
-
- /**
- * Set the multicast TTL
- * @param multicastTTL multicast TTL
- * @exception SocketException thrown if unable to set TTL
- */
- void setMulticastTTL(unsigned char multicastTTL) throw(SocketException);
-
- /**
- * Join the specified multicast group
- * @param multicastGroup multicast group address to join
- * @exception SocketException thrown if unable to join group
- */
- void joinGroup(const string &multicastGroup) throw(SocketException);
-
- /**
- * Leave the specified multicast group
- * @param multicastGroup multicast group address to leave
- * @exception SocketException thrown if unable to leave group
- */
- void leaveGroup(const string &multicastGroup) throw(SocketException);
-
-private:
- void setBroadcast();
-};
-
-} // End of namespace SocketLibrary
-
-#endif /* !SL_SOCKET_H */