Compare commits

..

2 Commits

20 changed files with 101 additions and 125 deletions

View File

@ -1,10 +1,6 @@
# Changelog # Changelog
All changes to this project will be documented in this file. All changes to this project will be documented in this file.
## [8.0.0] - 2020-01-26
(SocketServer) add ability to bind on an ipv6 address
## [7.9.6] - 2020-01-22 ## [7.9.6] - 2020-01-22
(ws) add a dnslookup sub-command, to get the ip address of a remote host (ws) add a dnslookup sub-command, to get the ip address of a remote host

View File

@ -33,16 +33,11 @@ vcpkg install ixwebsocket
### Conan ### Conan
[ ![Download](https://api.bintray.com/packages/conan/conan-center/ixwebsocket%3A_/images/download.svg) ](https://bintray.com/conan/conan-center/ixwebsocket%3A_/_latestVersion) Support for building with conan was contributed by Olivia Zoe (thanks!). The package name to reference is `IXWebSocket/5.0.0@LunarWatcher/stable`, and a list of the uploaded versions is available on [Bintray](https://bintray.com/oliviazoe0/conan-packages/IXWebSocket%3ALunarWatcher). The package is in the process to be published to the official conan package repo, but in the meantime, it can be accessed by adding a new remote
Conan is currently supported through a recipe in [Conan Center](https://github.com/conan-io/conan-center-index/tree/master/recipes/ixwebsocket) ([Bintray entry](https://bintray.com/conan/conan-center/ixwebsocket%3A_)). ```
conan remote add remote_name_here https://api.bintray.com/conan/oliviazoe0/conan-packages
Package reference ```
* Conan 1.21.0 and up: `ixwebsocket/7.9.2`
* Earlier versions: `ixwebsocket/7.9.2@_/_`
Note that the version listed here might not be the latest one. See Bintray or the recipe itself for the latest version. If you're migrating from the previous, custom Bintray remote, note that the package reference _has_ to be lower-case.
### Docker ### Docker

View File

@ -17,8 +17,8 @@
namespace ix namespace ix
{ {
RedisServer::RedisServer(int port, const std::string& host, int backlog, size_t maxConnections, int addressFamily) RedisServer::RedisServer(int port, const std::string& host, int backlog, size_t maxConnections)
: SocketServer(port, host, backlog, maxConnections, addressFamily) : SocketServer(port, host, backlog, maxConnections)
, _connectedClientsCount(0) , _connectedClientsCount(0)
, _stopHandlingConnections(false) , _stopHandlingConnections(false)
{ {

View File

@ -25,8 +25,7 @@ namespace ix
RedisServer(int port = SocketServer::kDefaultPort, RedisServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
int backlog = SocketServer::kDefaultTcpBacklog, int backlog = SocketServer::kDefaultTcpBacklog,
size_t maxConnections = SocketServer::kDefaultMaxConnections, size_t maxConnections = SocketServer::kDefaultMaxConnections);
int addressFamily = SocketServer::kDefaultAddressFamily);
virtual ~RedisServer(); virtual ~RedisServer();
virtual void stop() final; virtual void stop() final;

View File

@ -42,8 +42,8 @@ namespace
namespace ix namespace ix
{ {
HttpServer::HttpServer(int port, const std::string& host, int backlog, size_t maxConnections, int addressFamily) HttpServer::HttpServer(int port, const std::string& host, int backlog, size_t maxConnections)
: SocketServer(port, host, backlog, maxConnections, addressFamily) : SocketServer(port, host, backlog, maxConnections)
, _connectedClientsCount(0) , _connectedClientsCount(0)
{ {
setDefaultConnectionCallback(); setDefaultConnectionCallback();

View File

@ -28,8 +28,7 @@ namespace ix
HttpServer(int port = SocketServer::kDefaultPort, HttpServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
int backlog = SocketServer::kDefaultTcpBacklog, int backlog = SocketServer::kDefaultTcpBacklog,
size_t maxConnections = SocketServer::kDefaultMaxConnections, size_t maxConnections = SocketServer::kDefaultMaxConnections);
int addressFamily = SocketServer::kDefaultAddressFamily);
virtual ~HttpServer(); virtual ~HttpServer();
virtual void stop() final; virtual void stop() final;

View File

@ -20,6 +20,7 @@
#include <sys/time.h> #include <sys/time.h>
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include <sstream>
#define socketerrno errno #define socketerrno errno
#include <Security/SecureTransport.h> #include <Security/SecureTransport.h>
@ -31,12 +32,17 @@ namespace ix
, _sslContext(nullptr) , _sslContext(nullptr)
, _tlsOptions(tlsOptions) , _tlsOptions(tlsOptions)
{ {
; _sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
SSLSetIOFuncs(
_sslContext, SocketAppleSSL::readFromSocket, SocketAppleSSL::writeToSocket);
} }
SocketAppleSSL::~SocketAppleSSL() SocketAppleSSL::~SocketAppleSSL()
{ {
SocketAppleSSL::close(); CFRelease(_sslContext);
_sslContext = nullptr;
Socket::close();
} }
std::string SocketAppleSSL::getSSLErrorDescription(OSStatus status) std::string SocketAppleSSL::getSSLErrorDescription(OSStatus status)
@ -177,14 +183,16 @@ namespace ix
_sockfd = SocketConnect::connect(host, port, errMsg, isCancellationRequested); _sockfd = SocketConnect::connect(host, port, errMsg, isCancellationRequested);
if (_sockfd == -1) return false; if (_sockfd == -1) return false;
_sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
SSLSetIOFuncs(
_sslContext, SocketAppleSSL::readFromSocket, SocketAppleSSL::writeToSocket);
SSLSetConnection(_sslContext, (SSLConnectionRef)(long) _sockfd); SSLSetConnection(_sslContext, (SSLConnectionRef)(long) _sockfd);
SSLSetProtocolVersionMin(_sslContext, kTLSProtocol12); SSLSetProtocolVersionMin(_sslContext, kTLSProtocol12);
SSLSetPeerDomainName(_sslContext, host.c_str(), host.size()); SSLSetPeerDomainName(_sslContext, host.c_str(), host.size());
// Record a peer id, which speed up SSL connection when reconnecting to the same host
std::stringstream ss;
ss << host << ":" << port;
_peerId = ss.str();
SSLSetPeerID(_sslContext, (void*) _peerId.c_str(), _peerId.size());
if (_tlsOptions.isPeerVerifyDisabled()) if (_tlsOptions.isPeerVerifyDisabled())
{ {
Boolean option(1); Boolean option(1);
@ -227,12 +235,7 @@ namespace ix
{ {
std::lock_guard<std::mutex> lock(_mutex); std::lock_guard<std::mutex> lock(_mutex);
if (_sslContext == nullptr) return;
SSLClose(_sslContext); SSLClose(_sslContext);
CFRelease(_sslContext);
_sslContext = nullptr;
Socket::close(); Socket::close();
} }

View File

@ -41,6 +41,8 @@ namespace ix
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe mutable std::mutex _mutex; // AppleSSL routines are not thread-safe
SocketTLSOptions _tlsOptions; SocketTLSOptions _tlsOptions;
std::string _peerId;
}; };
} // namespace ix } // namespace ix

View File

@ -19,10 +19,12 @@
#include <linux/tcp.h> #include <linux/tcp.h>
#endif #endif
#include <iostream>
namespace ix namespace ix
{ {
// //
// This function can be cancelled every 50 ms // This function can be cancelled every 10 ms
// This is important so that we don't block the main UI thread when shutting down a // This is important so that we don't block the main UI thread when shutting down a
// connection which is already trying to reconnect, and can be blocked waiting for // connection which is already trying to reconnect, and can be blocked waiting for
// ::connect to respond. // ::connect to respond.
@ -44,8 +46,15 @@ namespace ix
// block us for too long // block us for too long
SocketConnect::configure(fd); SocketConnect::configure(fd);
auto start = std::chrono::system_clock::now();
int res = ::connect(fd, address->ai_addr, address->ai_addrlen); int res = ::connect(fd, address->ai_addr, address->ai_addrlen);
auto now = std::chrono::system_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
auto ms = milliseconds.count();
std::cout << "tcp connection completed in " << ms << "ms" << std::endl;
if (res == -1 && !Socket::isWaitNeeded()) if (res == -1 && !Socket::isWaitNeeded())
{ {
errMsg = strerror(Socket::getErrno()); errMsg = strerror(Socket::getErrno());
@ -98,11 +107,19 @@ namespace ix
std::string& errMsg, std::string& errMsg,
const CancellationRequest& isCancellationRequested) const CancellationRequest& isCancellationRequested)
{ {
auto start = std::chrono::system_clock::now();
// //
// First do DNS resolution // First do DNS resolution
// //
auto dnsLookup = std::make_shared<DNSLookup>(hostname, port); auto dnsLookup = std::make_shared<DNSLookup>(hostname, port);
struct addrinfo* res = dnsLookup->resolve(errMsg, isCancellationRequested); struct addrinfo* res = dnsLookup->resolve(errMsg, isCancellationRequested);
auto now = std::chrono::system_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
auto ms = milliseconds.count();
std::cout << "dns resolution completed in " << ms << "ms" << std::endl;
if (res == nullptr) if (res == nullptr)
{ {
return -1; return -1;

View File

@ -21,18 +21,15 @@ namespace ix
const std::string SocketServer::kDefaultHost("127.0.0.1"); const std::string SocketServer::kDefaultHost("127.0.0.1");
const int SocketServer::kDefaultTcpBacklog(5); const int SocketServer::kDefaultTcpBacklog(5);
const size_t SocketServer::kDefaultMaxConnections(32); const size_t SocketServer::kDefaultMaxConnections(32);
const int SocketServer::kDefaultAddressFamily(AF_INET);
SocketServer::SocketServer(int port, SocketServer::SocketServer(int port,
const std::string& host, const std::string& host,
int backlog, int backlog,
size_t maxConnections, size_t maxConnections)
int addressFamily)
: _port(port) : _port(port)
, _host(host) , _host(host)
, _backlog(backlog) , _backlog(backlog)
, _maxConnections(maxConnections) , _maxConnections(maxConnections)
, _addressFamily(addressFamily)
, _serverFd(-1) , _serverFd(-1)
, _stop(false) , _stop(false)
, _stopGc(false) , _stopGc(false)
@ -59,15 +56,10 @@ namespace ix
std::pair<bool, std::string> SocketServer::listen() std::pair<bool, std::string> SocketServer::listen()
{ {
if (_addressFamily != AF_INET && _addressFamily != AF_INET6) struct sockaddr_in server; // server address information
{
std::string errMsg("SocketServer::listen() AF_INET and AF_INET6 are currently "
"the only supported address families");
return std::make_pair(false, errMsg);
}
// Get a socket for accepting connections. // Get a socket for accepting connections.
if ((_serverFd = socket(_addressFamily, SOCK_STREAM, 0)) < 0) if ((_serverFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{ {
std::stringstream ss; std::stringstream ss;
ss << "SocketServer::listen() error creating socket): " << strerror(Socket::getErrno()); ss << "SocketServer::listen() error creating socket): " << strerror(Socket::getErrno());
@ -87,23 +79,19 @@ namespace ix
return std::make_pair(false, ss.str()); return std::make_pair(false, ss.str());
} }
if (_addressFamily == AF_INET) // Bind the socket to the server address.
{ server.sin_family = AF_INET;
struct sockaddr_in server;
server.sin_family = _addressFamily;
server.sin_port = htons(_port); server.sin_port = htons(_port);
if (inet_pton(_addressFamily, _host.c_str(), &server.sin_addr.s_addr) <= 0) // Using INADDR_ANY trigger a pop-up box as binding to any address is detected
{ // by the osx firewall. We need to codesign the binary with a self-signed cert
std::stringstream ss; // to allow that, but this is a bit of a pain. (this is what node or python would do).
ss << "SocketServer::listen() error calling inet_pton " //
<< "at address " << _host << ":" << _port << " : " << strerror(Socket::getErrno()); // Using INADDR_LOOPBACK also does not work ... while it should.
// We default to 127.0.0.1 (localhost)
//
server.sin_addr.s_addr = inet_addr(_host.c_str());
Socket::closeSocket(_serverFd);
return std::make_pair(false, ss.str());
}
// Bind the socket to the server address.
if (bind(_serverFd, (struct sockaddr*) &server, sizeof(server)) < 0) if (bind(_serverFd, (struct sockaddr*) &server, sizeof(server)) < 0)
{ {
std::stringstream ss; std::stringstream ss;
@ -113,34 +101,6 @@ namespace ix
Socket::closeSocket(_serverFd); Socket::closeSocket(_serverFd);
return std::make_pair(false, ss.str()); return std::make_pair(false, ss.str());
} }
}
else // AF_INET6
{
struct sockaddr_in6 server;
server.sin6_family = _addressFamily;
server.sin6_port = htons(_port);
if (inet_pton(_addressFamily, _host.c_str(), &server.sin6_addr) <= 0)
{
std::stringstream ss;
ss << "SocketServer::listen() error calling inet_pton "
<< "at address " << _host << ":" << _port << " : " << strerror(Socket::getErrno());
Socket::closeSocket(_serverFd);
return std::make_pair(false, ss.str());
}
// Bind the socket to the server address.
if (bind(_serverFd, (struct sockaddr*) &server, sizeof(server)) < 0)
{
std::stringstream ss;
ss << "SocketServer::listen() error calling bind "
<< "at address " << _host << ":" << _port << " : " << strerror(Socket::getErrno());
Socket::closeSocket(_serverFd);
return std::make_pair(false, ss.str());
}
}
// //
// Listen for connections. Specify the tcp backlog. // Listen for connections. Specify the tcp backlog.

View File

@ -36,8 +36,7 @@ namespace ix
SocketServer(int port = SocketServer::kDefaultPort, SocketServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
int backlog = SocketServer::kDefaultTcpBacklog, int backlog = SocketServer::kDefaultTcpBacklog,
size_t maxConnections = SocketServer::kDefaultMaxConnections, size_t maxConnections = SocketServer::kDefaultMaxConnections);
int addressFamily = SocketServer::kDefaultAddressFamily);
virtual ~SocketServer(); virtual ~SocketServer();
virtual void stop(); virtual void stop();
@ -50,7 +49,6 @@ namespace ix
const static std::string kDefaultHost; const static std::string kDefaultHost;
const static int kDefaultTcpBacklog; const static int kDefaultTcpBacklog;
const static size_t kDefaultMaxConnections; const static size_t kDefaultMaxConnections;
const static int kDefaultAddressFamily;
void start(); void start();
std::pair<bool, std::string> listen(); std::pair<bool, std::string> listen();
@ -71,7 +69,6 @@ namespace ix
std::string _host; std::string _host;
int _backlog; int _backlog;
size_t _maxConnections; size_t _maxConnections;
int _addressFamily;
// socket for accepting connections // socket for accepting connections
int _serverFd; int _serverFd;

View File

@ -15,6 +15,9 @@
#include <random> #include <random>
#include <sstream> #include <sstream>
#include <iostream>
#include <chrono>
namespace ix namespace ix
{ {
@ -97,8 +100,16 @@ namespace ix
auto isCancellationRequested = auto isCancellationRequested =
makeCancellationRequestWithTimeout(timeoutSecs, _requestInitCancellation); makeCancellationRequestWithTimeout(timeoutSecs, _requestInitCancellation);
auto start = std::chrono::system_clock::now();
std::string errMsg; std::string errMsg;
bool success = _socket->connect(host, port, errMsg, isCancellationRequested); bool success = _socket->connect(host, port, errMsg, isCancellationRequested);
auto now = std::chrono::system_clock::now();
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - start);
auto ms = milliseconds.count();
std::cout << "connection completed in " << ms << "ms" << std::endl;
if (!success) if (!success)
{ {
std::stringstream ss; std::stringstream ss;

View File

@ -23,9 +23,8 @@ namespace ix
const std::string& host, const std::string& host,
int backlog, int backlog,
size_t maxConnections, size_t maxConnections,
int handshakeTimeoutSecs, int handshakeTimeoutSecs)
int addressFamily) : SocketServer(port, host, backlog, maxConnections)
: SocketServer(port, host, backlog, maxConnections, addressFamily)
, _handshakeTimeoutSecs(handshakeTimeoutSecs) , _handshakeTimeoutSecs(handshakeTimeoutSecs)
, _enablePong(kDefaultEnablePong) , _enablePong(kDefaultEnablePong)
{ {
@ -107,6 +106,7 @@ namespace ix
} }
} }
logInfo("WebSocketServer::handleConnection() done");
connectionState->setTerminated(); connectionState->setTerminated();
} }

View File

@ -29,8 +29,7 @@ namespace ix
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
int backlog = SocketServer::kDefaultTcpBacklog, int backlog = SocketServer::kDefaultTcpBacklog,
size_t maxConnections = SocketServer::kDefaultMaxConnections, size_t maxConnections = SocketServer::kDefaultMaxConnections,
int handshakeTimeoutSecs = WebSocketServer::kDefaultHandShakeTimeoutSecs, int handshakeTimeoutSecs = WebSocketServer::kDefaultHandShakeTimeoutSecs);
int addressFamily = SocketServer::kDefaultAddressFamily);
virtual ~WebSocketServer(); virtual ~WebSocketServer();
virtual void stop() final; virtual void stop() final;
@ -42,8 +41,6 @@ namespace ix
// Get all the connected clients // Get all the connected clients
std::set<std::shared_ptr<WebSocket>> getClients(); std::set<std::shared_ptr<WebSocket>> getClients();
const static int kDefaultHandShakeTimeoutSecs;
private: private:
// Member variables // Member variables
int _handshakeTimeoutSecs; int _handshakeTimeoutSecs;
@ -54,6 +51,7 @@ namespace ix
std::mutex _clientsMutex; std::mutex _clientsMutex;
std::set<std::shared_ptr<WebSocket>> _clients; std::set<std::shared_ptr<WebSocket>> _clients;
const static int kDefaultHandShakeTimeoutSecs;
const static bool kDefaultEnablePong; const static bool kDefaultEnablePong;
// Methods // Methods

View File

@ -151,7 +151,18 @@ namespace ix
std::string errorMsg; std::string errorMsg;
bool tls = protocol == "wss"; bool tls = protocol == "wss";
if (_host == host)
{
_socket->close();
}
else
{
_socket = createSocket(tls, -1, errorMsg, _socketTLSOptions); _socket = createSocket(tls, -1, errorMsg, _socketTLSOptions);
}
// Record the host for later
_host = host;
if (!_socket) if (!_socket)
{ {

View File

@ -107,7 +107,7 @@ namespace ix
size_t bufferedAmount() const; size_t bufferedAmount() const;
private: private:
std::string _url; std::string _host;
struct wsheader_type struct wsheader_type
{ {

View File

@ -6,4 +6,4 @@
#pragma once #pragma once
#define IX_WEBSOCKET_VERSION "8.0.0" #define IX_WEBSOCKET_VERSION "7.9.6"

View File

@ -94,7 +94,6 @@ int main(int argc, char** argv)
bool disableAutomaticReconnection = false; bool disableAutomaticReconnection = false;
bool disablePerMessageDeflate = false; bool disablePerMessageDeflate = false;
bool greetings = false; bool greetings = false;
bool ipv6 = false;
bool binaryMode = false; bool binaryMode = false;
bool redirect = false; bool redirect = false;
bool version = false; bool version = false;
@ -172,7 +171,6 @@ int main(int argc, char** argv)
echoServerApp->add_option("--port", port, "Port"); echoServerApp->add_option("--port", port, "Port");
echoServerApp->add_option("--host", hostname, "Hostname"); echoServerApp->add_option("--host", hostname, "Hostname");
echoServerApp->add_flag("-g", greetings, "Verbose"); echoServerApp->add_flag("-g", greetings, "Verbose");
echoServerApp->add_flag("-6", ipv6, "IpV6");
addTLSOptions(echoServerApp); addTLSOptions(echoServerApp);
CLI::App* broadcastServerApp = app.add_subcommand("broadcast_server", "Broadcasting server"); CLI::App* broadcastServerApp = app.add_subcommand("broadcast_server", "Broadcasting server");
@ -392,7 +390,7 @@ int main(int argc, char** argv)
} }
else if (app.got_subcommand("echo_server")) else if (app.got_subcommand("echo_server"))
{ {
ret = ix::ws_echo_server_main(port, greetings, hostname, tlsOptions, ipv6); ret = ix::ws_echo_server_main(port, greetings, hostname, tlsOptions);
} }
else if (app.got_subcommand("broadcast_server")) else if (app.got_subcommand("broadcast_server"))
{ {

View File

@ -29,9 +29,7 @@ namespace ix
int ws_echo_server_main(int port, int ws_echo_server_main(int port,
bool greetings, bool greetings,
const std::string& hostname, const std::string& hostname,
const ix::SocketTLSOptions& tlsOptions, const ix::SocketTLSOptions& tlsOptions);
bool ipv6);
int ws_broadcast_server_main(int port, int ws_broadcast_server_main(int port,
const std::string& hostname, const std::string& hostname,
const ix::SocketTLSOptions& tlsOptions); const ix::SocketTLSOptions& tlsOptions);

View File

@ -5,7 +5,6 @@
*/ */
#include <ixwebsocket/IXWebSocketServer.h> #include <ixwebsocket/IXWebSocketServer.h>
#include <ixwebsocket/IXNetSystem.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <sstream> #include <sstream>
@ -14,18 +13,11 @@ namespace ix
int ws_echo_server_main(int port, int ws_echo_server_main(int port,
bool greetings, bool greetings,
const std::string& hostname, const std::string& hostname,
const ix::SocketTLSOptions& tlsOptions, const ix::SocketTLSOptions& tlsOptions)
bool ipv6)
{ {
spdlog::info("Listening on {}:{}", hostname, port); spdlog::info("Listening on {}:{}", hostname, port);
ix::WebSocketServer server(port, ix::WebSocketServer server(port, hostname);
hostname,
SocketServer::kDefaultTcpBacklog,
SocketServer::kDefaultMaxConnections,
WebSocketServer::kDefaultHandShakeTimeoutSecs,
(ipv6) ? AF_INET6 : AF_INET);
server.setTLSOptions(tlsOptions); server.setTLSOptions(tlsOptions);
server.setOnConnectionCallback( server.setOnConnectionCallback(