Compare commits

..

4 Commits

37 changed files with 492 additions and 1059 deletions

View File

@ -1,36 +1,17 @@
language: bash
language: cpp
dist: xenial
compiler:
- gcc
- clang
os:
- linux
- osx
matrix:
include:
# macOS
- os: osx
compiler: clang
script:
- python test/run.py
- make ws
exclude:
# GCC fails on recent Travis OSX images.
- compiler: gcc
os: osx
# Linux
- os: linux
dist: xenial
script:
- python test/run.py
- make ws
env:
- CC=gcc
- CXX=g++
# Clang + Linux disabled for now
# - os: linux
# dist: xenial
# script: python test/run.py
# env:
# - CC=clang
# - CXX=clang++
# Windows
- os: windows
env:
- CMAKE_PATH="/c/Program Files/CMake/bin"
script:
- export PATH=$CMAKE_PATH:$PATH
- python test/run.py
script: python test/run.py

View File

@ -41,8 +41,6 @@ set( IXWEBSOCKET_SOURCES
ixwebsocket/IXSelectInterrupt.cpp
ixwebsocket/IXSelectInterruptFactory.cpp
ixwebsocket/IXConnectionState.cpp
ixwebsocket/IXWebSocketCloseConstants.cpp
ixwebsocket/IXWebSocketMessageQueue.cpp
)
set( IXWEBSOCKET_HEADERS
@ -72,8 +70,6 @@ set( IXWEBSOCKET_HEADERS
ixwebsocket/IXSelectInterrupt.h
ixwebsocket/IXSelectInterruptFactory.h
ixwebsocket/IXConnectionState.h
ixwebsocket/IXWebSocketCloseConstants.h
ixwebsocket/IXWebSocketMessageQueue.h
)
if (UNIX)
@ -159,6 +155,6 @@ install(TARGETS ixwebsocket
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_PREFIX}/include/ixwebsocket/
)
if (USE_WS)
if (NOT WIN32)
add_subdirectory(ws)
endif()

View File

@ -16,7 +16,6 @@ ENV PATH="${CMAKE_BIN_PATH}:${PATH}"
RUN yum install -y python
RUN yum install -y libtsan
RUN yum install -y zlib-devel
COPY . .
# RUN ["make", "test"]

View File

@ -19,7 +19,7 @@
namespace ix
{
enum class HttpErrorCode : int
enum class HttpErrorCode
{
Ok = 0,
CannotConnect = 1,

View File

@ -129,7 +129,7 @@ namespace ix
}
// Wake up from poll/select by writing to the pipe which is watched by select
bool Socket::wakeUpFromPoll(uint64_t wakeUpCode)
bool Socket::wakeUpFromPoll(uint8_t wakeUpCode)
{
return _selectInterrupt->notify(wakeUpCode);
}

View File

@ -57,7 +57,7 @@ namespace ix
// Functions to check whether there is activity on the socket
PollResultType poll(int timeoutMs = kDefaultPollTimeout);
bool wakeUpFromPoll(uint64_t wakeUpCode);
bool wakeUpFromPoll(uint8_t wakeUpCode);
PollResultType isReadyToWrite(int timeoutMs);
PollResultType isReadyToRead(int timeoutMs);

View File

@ -142,10 +142,9 @@ namespace ix
_thread = std::thread(&WebSocket::run, this);
}
void WebSocket::stop(uint16_t code,
const std::string& reason)
void WebSocket::stop()
{
close(code, reason);
close();
if (_thread.joinable())
{
@ -293,9 +292,6 @@ namespace ix
break;
}
// We cannot enter poll which might block forever if we are stopping
if (_stop) break;
// 2. Poll to see if there's any new data available
WebSocketTransport::PollResult pollResult = _ws.poll();
@ -463,11 +459,6 @@ namespace ix
_automaticReconnection = false;
}
bool WebSocket::isAutomaticReconnectionEnabled() const
{
return _automaticReconnection;
}
size_t WebSocket::bufferedAmount() const
{
return _ws.bufferedAmount();

View File

@ -19,7 +19,6 @@
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketCloseConstants.h"
#include "IXProgressCallback.h"
namespace ix
@ -100,10 +99,8 @@ namespace ix
// Run asynchronously, by calling start and stop.
void start();
// stop is synchronous
void stop(uint16_t code = WebSocketCloseConstants::kNormalClosureCode,
const std::string& reason = WebSocketCloseConstants::kNormalClosureMessage);
void stop();
// Run in blocking mode, by connecting first manually, and then calling run.
WebSocketInitResult connect(int timeoutSecs);
@ -116,6 +113,8 @@ namespace ix
const OnProgressCallback& onProgressCallback = nullptr);
WebSocketSendInfo ping(const std::string& text);
// A close frame can provide a code and a reason
// FIXME: use constants
void close(uint16_t code = 1000,
const std::string& reason = "Normal closure");
@ -135,7 +134,6 @@ namespace ix
void enableAutomaticReconnection();
void disableAutomaticReconnection();
bool isAutomaticReconnectionEnabled() const;
private:

View File

@ -1,23 +0,0 @@
/*
* IXWebSocketCloseConstants.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#include "IXWebSocketCloseConstants.h"
namespace ix
{
const uint16_t WebSocketCloseConstants::kNormalClosureCode(1000);
const uint16_t WebSocketCloseConstants::kInternalErrorCode(1011);
const uint16_t WebSocketCloseConstants::kAbnormalCloseCode(1006);
const uint16_t WebSocketCloseConstants::kProtocolErrorCode(1002);
const uint16_t WebSocketCloseConstants::kNoStatusCodeErrorCode(1005);
const std::string WebSocketCloseConstants::kNormalClosureMessage("Normal closure");
const std::string WebSocketCloseConstants::kInternalErrorMessage("Internal error");
const std::string WebSocketCloseConstants::kAbnormalCloseMessage("Abnormal closure");
const std::string WebSocketCloseConstants::kPingTimeoutMessage("Ping timeout");
const std::string WebSocketCloseConstants::kProtocolErrorMessage("Protocol error");
const std::string WebSocketCloseConstants::kNoStatusCodeErrorMessage("No status code");
}

View File

@ -1,29 +0,0 @@
/*
* IXWebSocketCloseConstants.h
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <cstdint>
#include <string>
namespace ix
{
struct WebSocketCloseConstants
{
static const uint16_t kNormalClosureCode;
static const uint16_t kInternalErrorCode;
static const uint16_t kAbnormalCloseCode;
static const uint16_t kProtocolErrorCode;
static const uint16_t kNoStatusCodeErrorCode;
static const std::string kNormalClosureMessage;
static const std::string kInternalErrorMessage;
static const std::string kAbnormalCloseMessage;
static const std::string kPingTimeoutMessage;
static const std::string kProtocolErrorMessage;
static const std::string kNoStatusCodeErrorMessage;
};
}

View File

@ -242,7 +242,7 @@ namespace ix
}
char output[29] = {};
WebSocketHandshakeKeyGen::generate(secWebSocketKey, output);
WebSocketHandshakeKeyGen::generate(secWebSocketKey.c_str(), output);
if (std::string(output) != headers["sec-websocket-accept"])
{
std::string errorMsg("Invalid Sec-WebSocket-Accept value");
@ -348,7 +348,7 @@ namespace ix
}
char output[29] = {};
WebSocketHandshakeKeyGen::generate(headers["sec-websocket-key"], output);
WebSocketHandshakeKeyGen::generate(headers["sec-websocket-key"].c_str(), output);
std::stringstream ss;
ss << "HTTP/1.1 101 Switching Protocols\r\n";

View File

@ -1,121 +0,0 @@
/*
* IXWebSocketMessageQueue.cpp
* Author: Korchynskyi Dmytro
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
*/
#include "IXWebSocketMessageQueue.h"
namespace ix
{
WebSocketMessageQueue::WebSocketMessageQueue(WebSocket* websocket)
{
bindWebsocket(websocket);
}
WebSocketMessageQueue::~WebSocketMessageQueue()
{
if (!_messages.empty())
{
// not handled all messages
}
bindWebsocket(nullptr);
}
void WebSocketMessageQueue::bindWebsocket(WebSocket * websocket)
{
if (_websocket == websocket) return;
// unbind old
if (_websocket)
{
// set dummy callback just to avoid crash
_websocket->setOnMessageCallback([](
WebSocketMessageType,
const std::string&,
size_t,
const WebSocketErrorInfo&,
const WebSocketOpenInfo&,
const WebSocketCloseInfo&)
{});
}
_websocket = websocket;
// bind new
if (_websocket)
{
_websocket->setOnMessageCallback([this](
WebSocketMessageType type,
const std::string& str,
size_t wireSize,
const WebSocketErrorInfo& errorInfo,
const WebSocketOpenInfo& openInfo,
const WebSocketCloseInfo& closeInfo)
{
MessagePtr message(new Message());
message->type = type;
message->str = str;
message->wireSize = wireSize;
message->errorInfo = errorInfo;
message->openInfo = openInfo;
message->closeInfo = closeInfo;
{
std::lock_guard<std::mutex> lock(_messagesMutex);
_messages.emplace_back(std::move(message));
}
});
}
}
void WebSocketMessageQueue::setOnMessageCallback(const OnMessageCallback& callback)
{
_onMessageUserCallback = callback;
}
void WebSocketMessageQueue::setOnMessageCallback(OnMessageCallback&& callback)
{
_onMessageUserCallback = std::move(callback);
}
WebSocketMessageQueue::MessagePtr WebSocketMessageQueue::popMessage()
{
MessagePtr message;
std::lock_guard<std::mutex> lock(_messagesMutex);
if (!_messages.empty())
{
message = std::move(_messages.front());
_messages.pop_front();
}
return message;
}
void WebSocketMessageQueue::poll(int count)
{
if (!_onMessageUserCallback)
return;
MessagePtr message;
while (count > 0 && (message = popMessage()))
{
_onMessageUserCallback(
message->type,
message->str,
message->wireSize,
message->errorInfo,
message->openInfo,
message->closeInfo
);
--count;
}
}
}

View File

@ -1,53 +0,0 @@
/*
* IXWebSocketMessageQueue.h
* Author: Korchynskyi Dmytro
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include "IXWebSocket.h"
#include <thread>
#include <list>
#include <memory>
namespace ix
{
//
// A helper class to dispatch websocket message callbacks in your thread.
//
class WebSocketMessageQueue
{
public:
WebSocketMessageQueue(WebSocket* websocket = nullptr);
~WebSocketMessageQueue();
void bindWebsocket(WebSocket* websocket);
void setOnMessageCallback(const OnMessageCallback& callback);
void setOnMessageCallback(OnMessageCallback&& callback);
void poll(int count = 512);
protected:
struct Message
{
WebSocketMessageType type;
std::string str;
size_t wireSize;
WebSocketErrorInfo errorInfo;
WebSocketOpenInfo openInfo;
WebSocketCloseInfo closeInfo;
};
using MessagePtr = std::shared_ptr<Message>;
MessagePtr popMessage();
private:
WebSocket* _websocket = nullptr;
OnMessageCallback _onMessageUserCallback;
std::mutex _messagesMutex;
std::list<MessagePtr> _messages;
};
}

View File

@ -74,11 +74,21 @@ namespace ix
const int WebSocketTransport::kClosingMaximumWaitingDelayInMs(200);
constexpr size_t WebSocketTransport::kChunkSize;
const uint16_t WebSocketTransport::kInternalErrorCode(1011);
const uint16_t WebSocketTransport::kAbnormalCloseCode(1006);
const uint16_t WebSocketTransport::kProtocolErrorCode(1002);
const uint16_t WebSocketTransport::kNoStatusCodeErrorCode(1005);
const std::string WebSocketTransport::kInternalErrorMessage("Internal error");
const std::string WebSocketTransport::kAbnormalCloseMessage("Abnormal closure");
const std::string WebSocketTransport::kPingTimeoutMessage("Ping timeout");
const std::string WebSocketTransport::kProtocolErrorMessage("Protocol error");
const std::string WebSocketTransport::kNoStatusCodeErrorMessage("No status code");
WebSocketTransport::WebSocketTransport() :
_useMask(true),
_readyState(ReadyState::CLOSED),
_closeCode(WebSocketCloseConstants::kInternalErrorCode),
_closeReason(WebSocketCloseConstants::kInternalErrorMessage),
_closeCode(kInternalErrorCode),
_closeReason(kInternalErrorMessage),
_closeWireSize(0),
_closeRemote(false),
_enablePerMessageDeflate(false),
@ -130,8 +140,6 @@ namespace ix
WebSocketInitResult WebSocketTransport::connectToUrl(const std::string& url,
int timeoutSecs)
{
std::lock_guard<std::mutex> lock(_socketMutex);
std::string protocol, host, path, query;
int port;
@ -141,8 +149,8 @@ namespace ix
std::string("Could not parse URL ") + url);
}
std::string errorMsg;
bool tls = protocol == "wss";
std::string errorMsg;
_socket = createSocket(tls, errorMsg);
if (!_socket)
@ -168,8 +176,6 @@ namespace ix
// Server
WebSocketInitResult WebSocketTransport::connectToSocket(int fd, int timeoutSecs)
{
std::lock_guard<std::mutex> lock(_socketMutex);
// Server should not mask the data it sends to the client
_useMask = false;
@ -209,8 +215,8 @@ namespace ix
{
std::lock_guard<std::mutex> lock(_closeDataMutex);
_onCloseCallback(_closeCode, _closeReason, _closeWireSize, _closeRemote);
_closeCode = WebSocketCloseConstants::kInternalErrorCode;
_closeReason = WebSocketCloseConstants::kInternalErrorMessage;
_closeCode = kInternalErrorCode;
_closeReason = kInternalErrorMessage;
_closeWireSize = 0;
_closeRemote = false;
}
@ -280,8 +286,7 @@ namespace ix
// ping response (PONG) exceeds the maximum delay, then close the connection
if (pingTimeoutExceeded())
{
close(WebSocketCloseConstants::kInternalErrorCode,
WebSocketCloseConstants::kPingTimeoutMessage);
close(kInternalErrorCode, kPingTimeoutMessage);
}
// If ping is enabled and no ping has been sent for a duration
// exceeding our ping interval, send a ping to the server.
@ -315,20 +320,9 @@ namespace ix
}
#ifdef _WIN32
// Windows does not have select interrupt capabilities, so wait with a small timeout
if (lastingTimeoutDelayInMs <= 0)
{
lastingTimeoutDelayInMs = 20;
}
if (lastingTimeoutDelayInMs <= 0) lastingTimeoutDelayInMs = 20;
#endif
// If we are requesting a cancellation, pass in a positive and small timeout
// to never poll forever without a timeout.
if (_requestInitCancellation)
{
lastingTimeoutDelayInMs = 100;
}
// poll the socket
PollResultType pollResult = _socket->poll(lastingTimeoutDelayInMs);
@ -344,7 +338,7 @@ namespace ix
if (result == PollResultType::Error)
{
closeSocket();
_socket->close();
setReadyState(ReadyState::CLOSED);
break;
}
@ -369,7 +363,7 @@ namespace ix
// if there are received data pending to be processed, then delay the abnormal closure
// to after dispatch (other close code/reason could be read from the buffer)
closeSocket();
_socket->close();
return PollResult::AbnormalClose;
}
@ -383,18 +377,18 @@ namespace ix
}
else if (pollResult == PollResultType::Error)
{
closeSocket();
_socket->close();
}
else if (pollResult == PollResultType::CloseRequest)
{
closeSocket();
_socket->close();
}
if (_readyState == ReadyState::CLOSING && closingDelayExceeded())
{
_rxbuf.clear();
// close code and reason were set when calling close()
closeSocket();
_socket->close();
setReadyState(ReadyState::CLOSED);
}
@ -626,8 +620,8 @@ namespace ix
else
{
// no close code received
code = WebSocketCloseConstants::kNoStatusCodeErrorCode;
reason = WebSocketCloseConstants::kNoStatusCodeErrorMessage;
code = kNoStatusCodeErrorCode;
reason = kNoStatusCodeErrorMessage;
}
// We receive a CLOSE frame from remote and are NOT the ones who triggered the close
@ -661,9 +655,8 @@ namespace ix
else
{
// Unexpected frame type
close(WebSocketCloseConstants::kProtocolErrorCode,
WebSocketCloseConstants::kProtocolErrorMessage,
_rxbuf.size());
close(kProtocolErrorCode, kProtocolErrorMessage, _rxbuf.size());
}
// Erase the message that has been processed from the input/read buffer
@ -680,15 +673,13 @@ namespace ix
// if we previously closed the connection (CLOSING state), then set state to CLOSED (code/reason were set before)
if (_readyState == ReadyState::CLOSING)
{
closeSocket();
_socket->close();
setReadyState(ReadyState::CLOSED);
}
// if we weren't closing, then close using abnormal close code and message
else if (_readyState != ReadyState::CLOSED)
{
closeSocketAndSwitchToClosedState(WebSocketCloseConstants::kAbnormalCloseCode,
WebSocketCloseConstants::kAbnormalCloseMessage,
0, false);
closeSocketAndSwitchToClosedState(kAbnormalCloseCode, kAbnormalCloseMessage, 0, false);
}
}
}
@ -958,19 +949,13 @@ namespace ix
_enablePerMessageDeflate, onProgressCallback);
}
ssize_t WebSocketTransport::send()
{
std::lock_guard<std::mutex> lock(_socketMutex);
return _socket->send((char*)&_txbuf[0], _txbuf.size());
}
void WebSocketTransport::sendOnSocket()
{
std::lock_guard<std::mutex> lock(_txbufMutex);
while (_txbuf.size())
{
ssize_t ret = send();
ssize_t ret = _socket->send((char*)&_txbuf[0], _txbuf.size());
if (ret < 0 && Socket::isWaitNeeded())
{
@ -978,7 +963,8 @@ namespace ix
}
else if (ret <= 0)
{
closeSocket();
_socket->close();
setReadyState(ReadyState::CLOSED);
break;
}
@ -994,7 +980,7 @@ namespace ix
bool compress = false;
// if a status is set/was read
if (code != WebSocketCloseConstants::kNoStatusCodeErrorCode)
if (code != kNoStatusCodeErrorCode)
{
// See list of close events here:
// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
@ -1012,17 +998,9 @@ namespace ix
}
}
void WebSocketTransport::closeSocket()
void WebSocketTransport::closeSocketAndSwitchToClosedState(uint16_t code, const std::string& reason, size_t closeWireSize, bool remote)
{
std::lock_guard<std::mutex> lock(_socketMutex);
_socket->close();
}
void WebSocketTransport::closeSocketAndSwitchToClosedState(
uint16_t code, const std::string& reason, size_t closeWireSize, bool remote)
{
closeSocket();
{
std::lock_guard<std::mutex> lock(_closeDataMutex);
_closeCode = code;
@ -1030,13 +1008,10 @@ namespace ix
_closeWireSize = closeWireSize;
_closeRemote = remote;
}
setReadyState(ReadyState::CLOSED);
_requestInitCancellation = false;
}
void WebSocketTransport::close(
uint16_t code, const std::string& reason, size_t closeWireSize, bool remote)
void WebSocketTransport::close(uint16_t code, const std::string& reason, size_t closeWireSize, bool remote)
{
_requestInitCancellation = true;

View File

@ -25,7 +25,6 @@
#include "IXCancellationRequest.h"
#include "IXWebSocketHandshake.h"
#include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h"
namespace ix
{
@ -92,14 +91,11 @@ namespace ix
const OnProgressCallback& onProgressCallback);
WebSocketSendInfo sendPing(const std::string& message);
void close(uint16_t code = WebSocketCloseConstants::kNormalClosureCode,
const std::string& reason = WebSocketCloseConstants::kNormalClosureMessage,
void close(uint16_t code = 1000,
const std::string& reason = "Normal closure",
size_t closeWireSize = 0,
bool remote = false);
void closeSocket();
ssize_t send();
ReadyState getReadyState() const;
void setReadyState(ReadyState readyState);
void setOnCloseCallback(const OnCloseCallback& onCloseCallback);
@ -155,7 +151,6 @@ namespace ix
// Underlying TCP socket
std::shared_ptr<Socket> _socket;
std::mutex _socketMutex;
// Hold the state of the connection (OPEN, CLOSED, etc...)
std::atomic<ReadyState> _readyState;
@ -179,6 +174,17 @@ namespace ix
std::chrono::time_point<std::chrono::steady_clock>_closingTimePoint;
static const int kClosingMaximumWaitingDelayInMs;
// Constants for dealing with closing conneections
static const uint16_t kInternalErrorCode;
static const uint16_t kAbnormalCloseCode;
static const uint16_t kProtocolErrorCode;
static const uint16_t kNoStatusCodeErrorCode;
static const std::string kInternalErrorMessage;
static const std::string kAbnormalCloseMessage;
static const std::string kPingTimeoutMessage;
static const std::string kProtocolErrorMessage;
static const std::string kNoStatusCodeErrorMessage;
// enable auto response to ping
std::atomic<bool> _enablePong;
static const bool kDefaultEnablePong;

View File

@ -20,8 +20,6 @@
#include <cstdint>
#include <cstddef>
#include <string>
#include <string.h>
class WebSocketHandshakeKeyGen {
template <int N, typename T>
@ -102,12 +100,7 @@ class WebSocketHandshakeKeyGen {
}
public:
static inline void generate(const std::string& inputStr, char output[28]) {
char input[25] = {};
strncpy(input, inputStr.c_str(), 25 - 1);
input[25 - 1] = '\0';
static inline void generate(const char input[24], char output[28]) {
uint32_t b_output[5] = {
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0
};

View File

@ -9,10 +9,7 @@ install: brew
# on osx it is good practice to make /usr/local user writable
# sudo chown -R `whoami`/staff /usr/local
brew:
mkdir -p build && (cd build ; cmake -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j install)
ws:
mkdir -p build && (cd build ; cmake -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j)
mkdir -p build && (cd build ; cmake -DUSE_TLS=1 .. ; make -j install)
uninstall:
xargs rm -fv < build/install_manifest.txt
@ -51,8 +48,8 @@ test_server:
test:
python2.7 test/run.py
ws_test: ws
(cd ws ; env DEBUG=1 PATH=../ws/build:$$PATH bash test_ws.sh)
ws_test: all
(cd ws ; bash test_ws.sh)
# For the fork that is configured with appveyor
rebase_upstream:
@ -67,4 +64,3 @@ install_cmake_for_linux:
.PHONY: test
.PHONY: build
.PHONY: ws

View File

@ -7,7 +7,7 @@ project (ixwebsocket_unittest)
set (CMAKE_CXX_STANDARD 14)
if (NOT WIN32)
if (UNIX)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../third_party/sanitizers-cmake/cmake" ${CMAKE_MODULE_PATH})
find_package(Sanitizers)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread")
@ -31,31 +31,29 @@ set (SOURCES
../third_party/msgpack11/msgpack11.cpp
../ws/ixcore/utils/IXCoreLogger.cpp
IXDNSLookupTest.cpp
IXSocketTest.cpp
IXSocketConnectTest.cpp
IXWebSocketServerTest.cpp
IXWebSocketPingTest.cpp
IXWebSocketTestConnectionDisconnection.cpp
IXUrlParserTest.cpp
IXWebSocketServerTest.cpp
IXWebSocketPingTest.cpp
)
# Some unittest don't work on windows yet
if (UNIX)
list(APPEND SOURCES
IXDNSLookupTest.cpp
# IXWebSocketPingTimeoutTest.cpp # This test isn't reliable # (multiple platforms), disabling in master
# IXWebSocketCloseTest.cpp #
cmd_websocket_chat.cpp
)
endif()
# Disable tests for now that are failing or not reliable
# IXWebSocketPingTest.cpp
# IXWebSocketPingTimeoutTest.cpp
# IXWebSocketCloseTest.cpp
# IXWebSocketMessageQTest.cpp (trigger a segfault on Linux)
add_executable(ixwebsocket_unittest ${SOURCES})
if (NOT WIN32)
if (UNIX)
add_sanitizers(ixwebsocket_unittest)
endif()

View File

@ -17,12 +17,8 @@ TEST_CASE("socket_connect", "[net]")
{
SECTION("Test connecting to a known hostname")
{
int port = getFreePort();
ix::WebSocketServer server(port);
REQUIRE(startWebSocketEchoServer(server));
std::string errMsg;
int fd = SocketConnect::connect("127.0.0.1", port, errMsg, [] { return false; });
int fd = SocketConnect::connect("www.google.com", 80, errMsg, [] { return false; });
std::cerr << "Error message: " << errMsg << std::endl;
REQUIRE(fd != -1);
}
@ -38,13 +34,9 @@ TEST_CASE("socket_connect", "[net]")
SECTION("Test connecting to a good hostname, with cancellation")
{
int port = getFreePort();
ix::WebSocketServer server(port);
REQUIRE(startWebSocketEchoServer(server));
std::string errMsg;
// The callback returning true means we are requesting cancellation
int fd = SocketConnect::connect("127.0.0.1", port, errMsg, [] { return true; });
int fd = SocketConnect::connect("www.google.com", 80, errMsg, [] { return true; });
std::cerr << "Error message: " << errMsg << std::endl;
REQUIRE(fd == -1);
}

View File

@ -53,17 +53,13 @@ namespace ix
TEST_CASE("socket", "[socket]")
{
SECTION("Connect to a local websocket server over a free port. Send GET request without header. Should return 400")
SECTION("Connect to google HTTP server. Send GET request without header. Should return 200")
{
// Start a server first which we'll hit with our socket code
int port = getFreePort();
ix::WebSocketServer server(port);
REQUIRE(startWebSocketEchoServer(server));
std::string errMsg;
bool tls = false;
std::shared_ptr<Socket> socket = createSocket(tls, errMsg);
std::string host("127.0.0.1");
std::string host("www.google.com");
int port = 80;
std::stringstream ss;
ss << "GET / HTTP/1.1\r\n";
@ -71,14 +67,14 @@ TEST_CASE("socket", "[socket]")
ss << "\r\n";
std::string request(ss.str());
int expectedStatus = 400;
int expectedStatus = 200;
int timeoutSecs = 3;
testSocket(host, port, request, socket, expectedStatus, timeoutSecs);
}
#if defined(__APPLE__) || defined(__linux__)
SECTION("Connect to google HTTPS server over port 443. Send GET request without header. Should return 200")
SECTION("Connect to google HTTPS server. Send GET request without header. Should return 200")
{
std::string errMsg;
bool tls = true;

View File

@ -170,58 +170,4 @@ namespace ix
std::cout << prefix << ": " << s << " => " << ss.str() << std::endl;
}
bool startWebSocketEchoServer(ix::WebSocketServer& server)
{
server.setOnConnectionCallback(
[&server](std::shared_ptr<ix::WebSocket> webSocket,
std::shared_ptr<ConnectionState> connectionState)
{
webSocket->setOnMessageCallback(
[webSocket, connectionState, &server](ix::WebSocketMessageType messageType,
const std::string& str,
size_t wireSize,
const ix::WebSocketErrorInfo& error,
const ix::WebSocketOpenInfo& openInfo,
const ix::WebSocketCloseInfo& closeInfo)
{
if (messageType == ix::WebSocketMessageType::Open)
{
Logger() << "New connection";
Logger() << "Uri: " << openInfo.uri;
Logger() << "Headers:";
for (auto it : openInfo.headers)
{
Logger() << it.first << ": " << it.second;
}
}
else if (messageType == ix::WebSocketMessageType::Close)
{
Logger() << "Closed connection";
}
else if (messageType == ix::WebSocketMessageType::Message)
{
for (auto&& client : server.getClients())
{
if (client != webSocket)
{
client->send(str);
}
}
}
}
);
}
);
auto res = server.listen();
if (!res.first)
{
Logger() << res.second;
return false;
}
server.start();
return true;
}
}

View File

@ -11,8 +11,6 @@
#include <sstream>
#include <iostream>
#include <mutex>
#include <spdlog/spdlog.h>
#include <ixwebsocket/IXWebSocketServer.h>
namespace ix
{
@ -34,9 +32,8 @@ namespace ix
{
std::lock_guard<std::mutex> lock(_mutex);
std::stringstream ss;
ss << obj;
spdlog::info(ss.str());
std::cerr << obj;
std::cerr << std::endl;
return *this;
}
@ -47,6 +44,4 @@ namespace ix
void log(const std::string& msg);
int getFreePort();
bool startWebSocketEchoServer(ix::WebSocketServer& server);
}

View File

@ -86,7 +86,8 @@ namespace
void WebSocketClient::stop(uint16_t code, const std::string& reason)
{
_webSocket.stop(code, reason);
_webSocket.close(code, reason);
_webSocket.stop();
}
void WebSocketClient::start()

View File

@ -1,191 +0,0 @@
/*
* IXWebSocketMessageQTest.cpp
* Author: Korchynskyi Dmytro
* Copyright (c) 2019 Machine Zone. All rights reserved.
*/
#include <ixwebsocket/IXWebSocket.h>
#include <ixwebsocket/IXWebSocketServer.h>
#include <ixwebsocket/IXWebSocketMessageQueue.h>
#include "IXTest.h"
#include "catch.hpp"
#include <thread>
using namespace ix;
namespace
{
bool startServer(ix::WebSocketServer& server)
{
server.setOnConnectionCallback(
[&server](std::shared_ptr<ix::WebSocket> webSocket,
std::shared_ptr<ConnectionState> connectionState)
{
webSocket->setOnMessageCallback(
[connectionState, &server](ix::WebSocketMessageType messageType,
const std::string & str,
size_t wireSize,
const ix::WebSocketErrorInfo & error,
const ix::WebSocketOpenInfo & openInfo,
const ix::WebSocketCloseInfo & closeInfo)
{
if (messageType == ix::WebSocketMessageType::Open)
{
Logger() << "New connection";
connectionState->computeId();
Logger() << "id: " << connectionState->getId();
Logger() << "Uri: " << openInfo.uri;
Logger() << "Headers:";
for (auto it : openInfo.headers)
{
Logger() << it.first << ": " << it.second;
}
}
else if (messageType == ix::WebSocketMessageType::Close)
{
Logger() << "Closed connection";
}
else if (messageType == ix::WebSocketMessageType::Message)
{
Logger() << "Message received: " << str;
for (auto&& client : server.getClients())
{
client->send(str);
}
}
}
);
}
);
auto res = server.listen();
if (!res.first)
{
Logger() << res.second;
return false;
}
server.start();
return true;
}
class MsgQTestClient
{
public:
MsgQTestClient()
{
msgQ.bindWebsocket(&ws);
msgQ.setOnMessageCallback([this](WebSocketMessageType messageType,
const std::string & str,
size_t wireSize,
const WebSocketErrorInfo & error,
const WebSocketOpenInfo & openInfo,
const WebSocketCloseInfo & closeInfo)
{
REQUIRE(mainThreadId == std::this_thread::get_id());
std::stringstream ss;
if (messageType == WebSocketMessageType::Open)
{
log("client connected");
sendNextMessage();
}
else if (messageType == WebSocketMessageType::Close)
{
log("client disconnected");
}
else if (messageType == WebSocketMessageType::Error)
{
ss << "Error ! " << error.reason;
log(ss.str());
testDone = true;
}
else if (messageType == WebSocketMessageType::Pong)
{
ss << "Received pong message " << str;
log(ss.str());
}
else if (messageType == WebSocketMessageType::Ping)
{
ss << "Received ping message " << str;
log(ss.str());
}
else if (messageType == WebSocketMessageType::Message)
{
REQUIRE(str.compare("Hey dude!") == 0);
++receivedCount;
ss << "Received message " << str;
log(ss.str());
sendNextMessage();
}
else
{
ss << "Invalid WebSocketMessageType";
log(ss.str());
testDone = true;
}
});
}
void sendNextMessage()
{
if (receivedCount >= 3)
{
testDone = true;
succeeded = true;
}
else
{
auto info = ws.sendText("Hey dude!");
if (info.success)
log("sent message");
else
log("send failed");
}
}
void run(const std::string& url)
{
mainThreadId = std::this_thread::get_id();
testDone = false;
receivedCount = 0;
ws.setUrl(url);
ws.start();
while (!testDone)
{
msgQ.poll();
msleep(50);
}
}
bool isSucceeded() const { return succeeded; }
private:
WebSocket ws;
WebSocketMessageQueue msgQ;
bool testDone = false;
uint32_t receivedCount = 0;
std::thread::id mainThreadId;
bool succeeded = false;
};
}
TEST_CASE("Websocket_message_queue", "[websocket_message_q]")
{
SECTION("Send several messages")
{
int port = getFreePort();
WebSocketServer server(port);
REQUIRE(startServer(server));
MsgQTestClient testClient;
testClient.run("ws://127.0.0.1:" + std::to_string(port));
REQUIRE(testClient.isSucceeded());
}
}

View File

@ -359,13 +359,12 @@ TEST_CASE("Websocket_no_ping_but_timeout", "[setPingTimeout]")
REQUIRE(webSocketClient.isClosed() == false);
REQUIRE(webSocketClient.closedDueToPingTimeout() == false);
ix::msleep(300);
ix::msleep(200);
// Here we test ping timeout, timeout
REQUIRE(serverReceivedPingMessages == 0);
REQUIRE(webSocketClient.getReceivedPongMessages() == 0);
// Ensure client close was by ping timeout
ix::msleep(300);
// Ensure client close was not by ping timeout
REQUIRE(webSocketClient.isClosed() == true);
REQUIRE(webSocketClient.closedDueToPingTimeout() == true);
@ -416,8 +415,7 @@ TEST_CASE("Websocket_ping_timeout", "[setPingTimeout]")
// Here we test ping timeout, timeout
REQUIRE(serverReceivedPingMessages == 1);
REQUIRE(webSocketClient.getReceivedPongMessages() == 0);
// Ensure client close was by ping timeout
ix::msleep(300);
// Ensure client close was not by ping timeout
REQUIRE(webSocketClient.isClosed() == true);
REQUIRE(webSocketClient.closedDueToPingTimeout() == true);

View File

@ -62,33 +62,33 @@ namespace
std::stringstream ss;
if (messageType == ix::WebSocketMessageType::Open)
{
log("TestConnectionDisconnection: connected !");
log("cmd_websocket_satori_chat: connected !");
}
else if (messageType == ix::WebSocketMessageType::Close)
{
log("TestConnectionDisconnection: disconnected !");
log("cmd_websocket_satori_chat: disconnected !");
}
else if (messageType == ix::WebSocketMessageType::Error)
{
ss << "TestConnectionDisconnection: Error! ";
ss << "cmd_websocket_satori_chat: Error! ";
ss << error.reason;
log(ss.str());
}
else if (messageType == ix::WebSocketMessageType::Message)
{
log("TestConnectionDisconnection: received message.!");
log("cmd_websocket_satori_chat: received message.!");
}
else if (messageType == ix::WebSocketMessageType::Ping)
{
log("TestConnectionDisconnection: received ping message.!");
log("cmd_websocket_satori_chat: received ping message.!");
}
else if (messageType == ix::WebSocketMessageType::Pong)
{
log("TestConnectionDisconnection: received pong message.!");
log("cmd_websocket_satori_chat: received pong message.!");
}
else if (messageType == ix::WebSocketMessageType::Fragment)
{
log("TestConnectionDisconnection: received fragment.!");
log("cmd_websocket_satori_chat: received fragment.!");
}
else
{
@ -96,12 +96,6 @@ namespace
}
});
_webSocket.enableAutomaticReconnection();
REQUIRE(_webSocket.isAutomaticReconnectionEnabled() == true);
_webSocket.disableAutomaticReconnection();
REQUIRE(_webSocket.isAutomaticReconnectionEnabled() == false);
// Start the connection
_webSocket.start();
}
@ -129,38 +123,26 @@ TEST_CASE("websocket_connections", "[websocket]")
SECTION("Try to connect and disconnect with different timing, not enough time to succesfully connect")
{
IXWebSocketTestConnectionDisconnection test;
log(std::string("50 Runs"));
for (int i = 0; i < 50; ++i)
{
log(std::string("Run: ") + std::to_string(i));
test.start(WEBSOCKET_DOT_ORG_URL);
log(std::string("Sleeping"));
ix::msleep(i);
log(std::string("Stopping"));
test.stop();
}
}
// This test breaks on travis CI - Ubuntu Xenial + gcc + tsan
// We should fix this.
SECTION("Try to connect and disconnect with different timing, from not enough time to successfull connect")
/*SECTION("Try to connect and disconnect with different timing, from not enough time to successfull connect")
{
IXWebSocketTestConnectionDisconnection test;
log(std::string("20 Runs"));
for (int i = 0; i < 20; ++i)
{
log(std::string("Run: ") + std::to_string(i));
test.start(WEBSOCKET_DOT_ORG_URL);
log(std::string("Sleeping"));
ix::msleep(i*50);
log(std::string("Stopping"));
test.stop();
}
}
}*/
}

View File

@ -1,4 +1,10 @@
#!/usr/bin/env python2.7
'''
Windows notes:
generator = '-G"NMake Makefiles"'
make = 'nmake'
testBinary ='ixwebsocket_unittest.exe'
'''
from __future__ import print_function
@ -97,8 +103,7 @@ def runCMake(sanitizer, buildDir):
if platform.system() == 'Windows':
#generator = '"NMake Makefiles"'
#generator = '"Visual Studio 16 2019"'
generator = '"Visual Studio 15 2017"'
generator = '"Visual Studio 16 2019"'
else:
generator = '"Unix Makefiles"'
@ -269,12 +274,12 @@ def executeJob(job):
return job
def executeJobs(jobs, cpuCount):
def executeJobs(jobs):
'''Execute a list of job concurrently on multiple CPU/cores'''
print('Using {} cores to execute the unittest'.format(cpuCount))
poolSize = multiprocessing.cpu_count()
pool = multiprocessing.Pool(cpuCount)
pool = multiprocessing.Pool(poolSize)
results = pool.map(executeJob, jobs)
pool.close()
pool.join()
@ -346,22 +351,26 @@ def generateXmlOutput(results, xmlOutput, testRunName, runTime):
f.write(content.encode('utf-8'))
def run(testName, buildDir, sanitizer, xmlOutput,
testRunName, buildOnly, useLLDB, cpuCount):
def run(testName, buildDir, sanitizer, xmlOutput, testRunName, buildOnly, useLLDB):
'''Main driver. Run cmake, compiles, execute and validate the testsuite.'''
# gen build files with CMake
runCMake(sanitizer, buildDir)
if platform.system() == 'Linux':
# build with make -j
runCommand('make -C {} -j 2'.format(buildDir))
elif platform.system() == 'Darwin':
# build with make
runCommand('make -C {} -j 8'.format(buildDir))
else:
# build with cmake on recent
runCommand('cmake --build --parallel {}'.format(buildDir))
#makeCmd = 'cmake --build '
#jobs = '-j8'
#if platform.system() == 'Windows':
# makeCmd = 'nmake'
# nmake does not have a -j option
# jobs = ''
#runCommand('{} -C {} {}'.format(makeCmd, buildDir, jobs))
# build with cmake
runCommand('cmake --build ' + buildDir)
if buildOnly:
return
@ -406,7 +415,7 @@ def run(testName, buildDir, sanitizer, xmlOutput,
})
start = time.time()
results = executeJobs(jobs, cpuCount)
results = executeJobs(jobs)
runTime = time.time() - start
generateXmlOutput(results, xmlOutput, testRunName, runTime)
@ -456,8 +465,6 @@ def main():
help='Run the test through lldb.')
parser.add_argument('--run_name', '-n',
help='Name of the test run.')
parser.add_argument('--cpu_count', '-j', type=int, default=multiprocessing.cpu_count(),
help='Number of cpus to use for running the tests.')
args = parser.parse_args()
@ -503,7 +510,7 @@ def main():
args.lldb = False
return run(args.test, buildDir, sanitizer, xmlOutput,
testRunName, args.build_only, args.lldb, args.cpu_count)
testRunName, args.build_only, args.lldb)
if __name__ == '__main__':

View File

@ -61,4 +61,4 @@ sleep 2
kill `cat /tmp/ws_test/pidfile.transfer`
kill `cat /tmp/ws_test/pidfile.receive`
kill `cat /tmp/ws_test/pidfile.send`
exit 0