Compare commits

..

97 Commits

Author SHA1 Message Date
83c261977d add back IXWebSocketMessageQueue, with its unittest disabled 2019-05-16 22:41:39 -07:00
6ca28d96bf Linux build fix: strncpy needs <string.h> 2019-05-16 22:21:15 -07:00
c4a5647b62 Revert "Merge branch 'Dimon4eg-message-queue'"
This reverts commit 13fa325134, reversing
changes made to aecd5e9c94.
2019-05-16 22:15:17 -07:00
720d5593a5 Fix Address Sanitizer heap-buffer-overflow in WebSocketHandshakeKeyGen::generate
=================================================================
==5077==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6070000077e0 at pc 0x00010ba18c54 bp 0x70000dd45b10 sp 0x70000dd45b08
READ of size 1 at 0x6070000077e0 thread T12
    #0 0x10ba18c53 in WebSocketHandshakeKeyGen::generate(char const*, char*) libwshandshake.hpp:113
    #1 0x10ba2065a in ix::WebSocketHandshake::serverHandshake(int, int) IXWebSocketHandshake.cpp:356
    #2 0x10b9c4952 in ix::WebSocketTransport::connectToSocket(int, int) IXWebSocketTransport.cpp:190
    #3 0x10b97e4c2 in ix::WebSocket::connectToSocket(int, int) IXWebSocket.cpp:193
2019-05-16 21:59:03 -07:00
13fa325134 Merge branch 'Dimon4eg-message-queue' 2019-05-16 19:26:45 -07:00
773cbb4907 bring back socket mutex which is needed, some CI failures are happening without it 2019-05-16 19:23:32 -07:00
a696264b48 disable socket mutex usage in WebSocketTransport 2019-05-16 19:23:32 -07:00
b7db5f77fb remove dead code 2019-05-16 19:23:32 -07:00
b11678e636 refactor connect unittest so that it hits a local server instead of a remote server 2019-05-16 19:23:32 -07:00
f746070944 travis makefile fix 2019-05-16 19:23:32 -07:00
3323a51ab5 try to run ws test on linux + macOS on travis 2019-05-16 19:23:32 -07:00
0e59927384 Add constants for closing code and messages 2019-05-16 19:23:32 -07:00
5c4840f129 first socket test hit a local server instead of a remote server / this can help with a windows intermittent failure 2019-05-16 19:23:32 -07:00
9ac02323ad build ws on travis (mac + linux) 2019-05-16 19:23:32 -07:00
cdbed26d1f use a regular mutex instead of a recursive one + stop properly 2019-05-16 19:23:32 -07:00
23f171f34d adding logging to IXWebSocketTestConnectionDisconnection makes it fails reliably 2019-05-16 19:23:32 -07:00
20b625e483 Update README.md 2019-05-16 19:23:32 -07:00
f1604c6460 Update README.md 2019-05-16 19:23:32 -07:00
ba0e007c05 -j option actually work ... 2019-05-16 19:23:32 -07:00
643e1bf20f unittest / add options to set the number of jobs 2019-05-16 19:23:32 -07:00
24a32a0603 enum class HttpErrorCode derives from int 2019-05-16 19:23:32 -07:00
c5caf32b77 try to re-enable some tests 2019-05-16 19:23:32 -07:00
09956d7500 recursive mutex + enable test that was breaking on Ubuntu Xenial + gcc + tsan 2019-05-16 19:23:32 -07:00
d91c896e46 comment failing test 2019-05-16 19:23:32 -07:00
042e6a22b8 comment failing test 2019-05-16 19:23:32 -07:00
14ec12d1f0 do not build ws for now on travis 2019-05-16 19:23:32 -07:00
288b05a048 more protection against socket when closing 2019-05-16 19:23:32 -07:00
5af3096070 fix compile errors with C++ enum class 2019-05-16 19:23:32 -07:00
570fa01c04 close and stop with code and reason + docker = ubuntu xenial 2019-05-16 19:23:32 -07:00
2a69038c4c add isEnabledAutomaticReconnection (#75)
* add isEnabledAutomaticReconnection

* test isEnabledAutomaticReconnection

* rename
2019-05-16 19:23:32 -07:00
0ba127e447 Revert "Revert "fix cast warning caught on windows""
This reverts commit 25eaf730bc.
2019-05-16 19:23:32 -07:00
7714bdf7e0 Revert "fix cast warning caught on windows"
This reverts commit 4edb7447df.
2019-05-16 19:23:32 -07:00
4e5e7ae50a fix cast warning caught on windows 2019-05-16 19:23:32 -07:00
5741b2f6c1 add more time to let client close (#73) 2019-05-16 19:23:32 -07:00
76172f92e9 build with gcc on Linux 2019-05-16 19:23:32 -07:00
f8b547c028 use spdlog for logging in the unittest 2019-05-16 19:23:32 -07:00
7ccd9e1709 fix inverted conditional 2019-05-16 19:23:31 -07:00
9217b27d40 server code / add dedicated thread to close/join terminated connection threads 2019-05-16 19:23:31 -07:00
819e9025b1 travis cmake version on macOS does not know --parallel option 2019-05-16 19:23:31 -07:00
53ceab9f91 build in parallel + stop building linux + clang 2019-05-16 19:23:31 -07:00
a7ed4fe5c3 disable ping tests for now as they are not super reliable 2019-05-16 19:23:31 -07:00
3190cd322d Feature/windows ci (#76)
* close with params

* ...

* different generator

* core size = 1

* disable more tests to get something working on windows

* try to enable another test on windows

* enable all OS

* set proper version of linux

* another try

* try again with just env variables

* Revert "core size = 1"

This reverts commit 29af74bba6.

* add windows and mac

* Revert "close with params"

This reverts commit 6bb00b6788.
2019-05-16 19:23:31 -07:00
dad2b64e15 save timepoints after connect and not in contructor, adjusted tests (#72)
* save timepoints after connect and not in contructor, adjusted tests

* move call into setReadyState

* more time to detect client close in test
2019-05-16 19:20:29 -07:00
e527ab1613 fix for Windows (#69)
* fix for Windows

* fix condition

* make condition only on Windows
2019-05-16 19:20:29 -07:00
d7a0bc212d Fix run.py (#71)
* fix run.py

* run.py: fix Windows support

* fix test listing
2019-05-16 19:20:29 -07:00
aecd5e9c94 bring back socket mutex which is needed, some CI failures are happening without it 2019-05-16 15:58:20 -07:00
e0edca43d5 disable socket mutex usage in WebSocketTransport 2019-05-16 15:46:32 -07:00
ce70d3d728 remove dead code 2019-05-16 15:05:20 -07:00
d9be40a0de refactor connect unittest so that it hits a local server instead of a remote server 2019-05-16 14:25:31 -07:00
e469f04c39 travis makefile fix 2019-05-16 14:02:24 -07:00
11774e6825 try to run ws test on linux + macOS on travis 2019-05-16 13:57:33 -07:00
42bdfb51c3 Add constants for closing code and messages 2019-05-16 12:46:53 -07:00
fd637bf1e1 first socket test hit a local server instead of a remote server / this can help with a windows intermittent failure 2019-05-16 12:24:58 -07:00
8085e1416c build ws on travis (mac + linux) 2019-05-16 07:01:15 -07:00
671c9f805f use a regular mutex instead of a recursive one + stop properly 2019-05-15 19:26:02 -07:00
ace7a7ccae adding logging to IXWebSocketTestConnectionDisconnection makes it fails reliably 2019-05-15 19:26:02 -07:00
9c3bdf1a77 Update README.md 2019-05-15 19:22:05 -07:00
f5242b3102 Update README.md 2019-05-15 18:57:17 -07:00
f1272f059a -j option actually work ... 2019-05-15 18:15:45 -07:00
91595ff4c2 unittest / add options to set the number of jobs 2019-05-15 17:52:03 -07:00
3755d29a45 enum class HttpErrorCode derives from int 2019-05-15 16:50:00 -07:00
c2b75399ae try to re-enable some tests 2019-05-15 16:28:29 -07:00
a33ecd1338 recursive mutex + enable test that was breaking on Ubuntu Xenial + gcc + tsan 2019-05-15 16:01:05 -07:00
a7e29a9f36 comment failing test 2019-05-15 15:44:14 -07:00
02399dfa5c comment failing test 2019-05-15 15:37:30 -07:00
aec2941bac do not build ws for now on travis 2019-05-15 15:26:49 -07:00
9315eb5289 more protection against socket when closing 2019-05-15 15:18:46 -07:00
5b2b2ea7b0 fix compile errors with C++ enum class 2019-05-15 15:18:46 -07:00
d90b634e80 close and stop with code and reason + docker = ubuntu xenial 2019-05-15 15:18:46 -07:00
6dd8cda074 add isEnabledAutomaticReconnection (#75)
* add isEnabledAutomaticReconnection

* test isEnabledAutomaticReconnection

* rename
2019-05-14 11:26:37 -07:00
701be31554 Revert "Revert "fix cast warning caught on windows""
This reverts commit 25eaf730bc.
2019-05-13 22:16:49 -07:00
25eaf730bc Revert "fix cast warning caught on windows"
This reverts commit 4edb7447df.
2019-05-13 21:35:34 -07:00
4edb7447df fix cast warning caught on windows 2019-05-13 21:29:47 -07:00
5f3de60962 add more time to let client close (#73) 2019-05-13 21:26:34 -07:00
79c17aba49 build with gcc on Linux 2019-05-13 17:35:21 -07:00
80a90496d9 use spdlog for logging in the unittest 2019-05-13 17:32:57 -07:00
bbca803840 fix inverted conditional 2019-05-13 17:18:07 -07:00
160d3869a9 server code / add dedicated thread to close/join terminated connection threads 2019-05-13 17:17:35 -07:00
afd8f64da8 travis cmake version on macOS does not know --parallel option 2019-05-13 17:17:35 -07:00
6d2548b823 build in parallel + stop building linux + clang 2019-05-13 17:06:56 -07:00
642356d353 disable ping tests for now as they are not super reliable 2019-05-13 17:01:22 -07:00
ba0fa36c2a Feature/windows ci (#76)
* close with params

* ...

* different generator

* core size = 1

* disable more tests to get something working on windows

* try to enable another test on windows

* enable all OS

* set proper version of linux

* another try

* try again with just env variables

* Revert "core size = 1"

This reverts commit 29af74bba6.

* add windows and mac

* Revert "close with params"

This reverts commit 6bb00b6788.
2019-05-13 16:51:58 -07:00
a41d08343c Merge branch 'master' into message-queue 2019-05-12 22:00:10 +03:00
6467f98241 add setOnMessageCallback with r-value 2019-05-12 20:59:18 +03:00
b24e4334f6 correct style 2019-05-12 20:16:02 +03:00
bf8abcbf4a fix warnings 2019-05-12 20:05:28 +03:00
bb484414b1 update comment 2019-05-12 20:00:15 +03:00
fc75b13fae update test 2019-05-12 19:57:31 +03:00
78f59b4207 added message queue test 2019-05-12 01:50:41 +03:00
7c5567db56 Added WebSocketMessageQueue 2019-05-12 01:49:06 +03:00
7ecaf1f982 rename ptr 2019-05-09 01:05:47 +03:00
d0a41f3894 simplify bindWebsocket 2019-05-09 00:23:16 +03:00
57562b234f use lock_guard 2019-05-09 00:20:26 +03:00
469d127d61 update comments 2019-05-09 00:16:37 +03:00
d6e9b61c8e Rename to WebSocketMessageQueue 2019-05-09 00:09:51 +03:00
7fb1b65ddd qf 2019-05-08 22:24:39 +03:00
77c7fdc636 Added IXWebSocketPoll class 2019-05-08 22:02:56 +03:00
37 changed files with 1059 additions and 492 deletions

View File

@ -1,17 +1,36 @@
language: cpp language: bash
dist: xenial
compiler:
- gcc
- clang
os:
- linux
- osx
matrix: matrix:
exclude: include:
# GCC fails on recent Travis OSX images. # macOS
- compiler: gcc - os: osx
os: osx compiler: clang
script:
- python test/run.py
- make ws
script: python test/run.py # 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

View File

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

View File

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

View File

@ -19,7 +19,7 @@
namespace ix namespace ix
{ {
enum class HttpErrorCode enum class HttpErrorCode : int
{ {
Ok = 0, Ok = 0,
CannotConnect = 1, 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 // Wake up from poll/select by writing to the pipe which is watched by select
bool Socket::wakeUpFromPoll(uint8_t wakeUpCode) bool Socket::wakeUpFromPoll(uint64_t wakeUpCode)
{ {
return _selectInterrupt->notify(wakeUpCode); return _selectInterrupt->notify(wakeUpCode);
} }

View File

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

View File

@ -142,9 +142,10 @@ namespace ix
_thread = std::thread(&WebSocket::run, this); _thread = std::thread(&WebSocket::run, this);
} }
void WebSocket::stop() void WebSocket::stop(uint16_t code,
const std::string& reason)
{ {
close(); close(code, reason);
if (_thread.joinable()) if (_thread.joinable())
{ {
@ -262,7 +263,7 @@ namespace ix
connectErr.wait_time = duration.count(); connectErr.wait_time = duration.count();
connectErr.retries = retries; connectErr.retries = retries;
} }
connectErr.reason = status.errorStr; connectErr.reason = status.errorStr;
connectErr.http_status = status.http_status; connectErr.http_status = status.http_status;
@ -292,6 +293,9 @@ namespace ix
break; 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 // 2. Poll to see if there's any new data available
WebSocketTransport::PollResult pollResult = _ws.poll(); WebSocketTransport::PollResult pollResult = _ws.poll();
@ -459,6 +463,11 @@ namespace ix
_automaticReconnection = false; _automaticReconnection = false;
} }
bool WebSocket::isAutomaticReconnectionEnabled() const
{
return _automaticReconnection;
}
size_t WebSocket::bufferedAmount() const size_t WebSocket::bufferedAmount() const
{ {
return _ws.bufferedAmount(); return _ws.bufferedAmount();

View File

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

View File

@ -0,0 +1,23 @@
/*
* 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

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

View File

@ -0,0 +1,121 @@
/*
* 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

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

View File

@ -25,6 +25,7 @@
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include "IXWebSocketHandshake.h" #include "IXWebSocketHandshake.h"
#include "IXProgressCallback.h" #include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h"
namespace ix namespace ix
{ {
@ -91,11 +92,14 @@ namespace ix
const OnProgressCallback& onProgressCallback); const OnProgressCallback& onProgressCallback);
WebSocketSendInfo sendPing(const std::string& message); WebSocketSendInfo sendPing(const std::string& message);
void close(uint16_t code = 1000, void close(uint16_t code = WebSocketCloseConstants::kNormalClosureCode,
const std::string& reason = "Normal closure", const std::string& reason = WebSocketCloseConstants::kNormalClosureMessage,
size_t closeWireSize = 0, size_t closeWireSize = 0,
bool remote = false); bool remote = false);
void closeSocket();
ssize_t send();
ReadyState getReadyState() const; ReadyState getReadyState() const;
void setReadyState(ReadyState readyState); void setReadyState(ReadyState readyState);
void setOnCloseCallback(const OnCloseCallback& onCloseCallback); void setOnCloseCallback(const OnCloseCallback& onCloseCallback);
@ -151,6 +155,7 @@ namespace ix
// Underlying TCP socket // Underlying TCP socket
std::shared_ptr<Socket> _socket; std::shared_ptr<Socket> _socket;
std::mutex _socketMutex;
// Hold the state of the connection (OPEN, CLOSED, etc...) // Hold the state of the connection (OPEN, CLOSED, etc...)
std::atomic<ReadyState> _readyState; std::atomic<ReadyState> _readyState;
@ -169,22 +174,11 @@ namespace ix
// Used to cancel dns lookup + socket connect + http upgrade // Used to cancel dns lookup + socket connect + http upgrade
std::atomic<bool> _requestInitCancellation; std::atomic<bool> _requestInitCancellation;
mutable std::mutex _closingTimePointMutex; mutable std::mutex _closingTimePointMutex;
std::chrono::time_point<std::chrono::steady_clock>_closingTimePoint; std::chrono::time_point<std::chrono::steady_clock>_closingTimePoint;
static const int kClosingMaximumWaitingDelayInMs; 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 // enable auto response to ping
std::atomic<bool> _enablePong; std::atomic<bool> _enablePong;
static const bool kDefaultEnablePong; static const bool kDefaultEnablePong;

View File

@ -1,21 +1,21 @@
/* /*
* Lightweight URL & URI parser (RFC 1738, RFC 3986) * Lightweight URL & URI parser (RFC 1738, RFC 3986)
* https://github.com/corporateshark/LUrlParser * https://github.com/corporateshark/LUrlParser
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (C) 2015 Sergey Kosarevsky (sk@linderdaum.com) * Copyright (C) 2015 Sergey Kosarevsky (sk@linderdaum.com)
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. * copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

@ -1,21 +1,21 @@
/* /*
* Lightweight URL & URI parser (RFC 1738, RFC 3986) * Lightweight URL & URI parser (RFC 1738, RFC 3986)
* https://github.com/corporateshark/LUrlParser * https://github.com/corporateshark/LUrlParser
* *
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (C) 2015 Sergey Kosarevsky (sk@linderdaum.com) * Copyright (C) 2015 Sergey Kosarevsky (sk@linderdaum.com)
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. * copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

View File

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

View File

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

View File

@ -7,7 +7,7 @@ project (ixwebsocket_unittest)
set (CMAKE_CXX_STANDARD 14) set (CMAKE_CXX_STANDARD 14)
if (UNIX) if (NOT WIN32)
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../third_party/sanitizers-cmake/cmake" ${CMAKE_MODULE_PATH}) set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../third_party/sanitizers-cmake/cmake" ${CMAKE_MODULE_PATH})
find_package(Sanitizers) find_package(Sanitizers)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread")
@ -31,29 +31,31 @@ set (SOURCES
../third_party/msgpack11/msgpack11.cpp ../third_party/msgpack11/msgpack11.cpp
../ws/ixcore/utils/IXCoreLogger.cpp ../ws/ixcore/utils/IXCoreLogger.cpp
IXDNSLookupTest.cpp
IXSocketTest.cpp IXSocketTest.cpp
IXSocketConnectTest.cpp IXSocketConnectTest.cpp
IXWebSocketServerTest.cpp IXWebSocketServerTest.cpp
IXWebSocketPingTest.cpp
IXWebSocketTestConnectionDisconnection.cpp IXWebSocketTestConnectionDisconnection.cpp
IXUrlParserTest.cpp IXUrlParserTest.cpp
IXWebSocketServerTest.cpp IXWebSocketServerTest.cpp
IXWebSocketPingTest.cpp
) )
# Some unittest don't work on windows yet # Some unittest don't work on windows yet
if (UNIX) if (UNIX)
list(APPEND SOURCES list(APPEND SOURCES
# IXWebSocketPingTimeoutTest.cpp # This test isn't reliable # (multiple platforms), disabling in master IXDNSLookupTest.cpp
# IXWebSocketCloseTest.cpp #
cmd_websocket_chat.cpp cmd_websocket_chat.cpp
) )
endif() 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}) add_executable(ixwebsocket_unittest ${SOURCES})
if (UNIX) if (NOT WIN32)
add_sanitizers(ixwebsocket_unittest) add_sanitizers(ixwebsocket_unittest)
endif() endif()

View File

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

View File

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

View File

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

View File

@ -61,7 +61,7 @@ namespace
uint16_t WebSocketClient::getCloseCode() uint16_t WebSocketClient::getCloseCode()
{ {
std::lock_guard<std::mutex> lck(_mutexCloseData); std::lock_guard<std::mutex> lck(_mutexCloseData);
return _closeCode; return _closeCode;
} }
@ -75,7 +75,7 @@ namespace
bool WebSocketClient::getCloseRemote() bool WebSocketClient::getCloseRemote()
{ {
std::lock_guard<std::mutex> lck(_mutexCloseData); std::lock_guard<std::mutex> lck(_mutexCloseData);
return _closeRemote; return _closeRemote;
} }
@ -86,8 +86,7 @@ namespace
void WebSocketClient::stop(uint16_t code, const std::string& reason) void WebSocketClient::stop(uint16_t code, const std::string& reason)
{ {
_webSocket.close(code, reason); _webSocket.stop(code, reason);
_webSocket.stop();
} }
void WebSocketClient::start() void WebSocketClient::start()
@ -127,11 +126,11 @@ namespace
log("client disconnected"); log("client disconnected");
std::lock_guard<std::mutex> lck(_mutexCloseData); std::lock_guard<std::mutex> lck(_mutexCloseData);
_closeCode = closeInfo.code; _closeCode = closeInfo.code;
_closeReason = std::string(closeInfo.reason); _closeReason = std::string(closeInfo.reason);
_closeRemote = closeInfo.remote; _closeRemote = closeInfo.remote;
_webSocket.disableAutomaticReconnection(); _webSocket.disableAutomaticReconnection();
} }
else if (messageType == ix::WebSocketMessageType::Error) else if (messageType == ix::WebSocketMessageType::Error)
@ -210,7 +209,7 @@ namespace
//Logger() << closeInfo.remote; //Logger() << closeInfo.remote;
std::lock_guard<std::mutex> lck(mutexWrite); std::lock_guard<std::mutex> lck(mutexWrite);
receivedCloseCode = closeInfo.code; receivedCloseCode = closeInfo.code;
receivedCloseReason = std::string(closeInfo.reason); receivedCloseReason = std::string(closeInfo.reason);
receivedCloseRemote = closeInfo.remote; receivedCloseRemote = closeInfo.remote;
@ -240,7 +239,7 @@ TEST_CASE("Websocket_client_close_default", "[close]")
int port = getFreePort(); int port = getFreePort();
ix::WebSocketServer server(port); ix::WebSocketServer server(port);
uint16_t serverReceivedCloseCode(0); uint16_t serverReceivedCloseCode(0);
bool serverReceivedCloseRemote(false); bool serverReceivedCloseRemote(false);
std::string serverReceivedCloseReason(""); std::string serverReceivedCloseReason("");
@ -275,7 +274,7 @@ TEST_CASE("Websocket_client_close_default", "[close]")
{ {
std::lock_guard<std::mutex> lck(mutexWrite); std::lock_guard<std::mutex> lck(mutexWrite);
// Here we read the code/reason received by the server, and ensure that remote is true // Here we read the code/reason received by the server, and ensure that remote is true
REQUIRE(serverReceivedCloseCode == 1000); REQUIRE(serverReceivedCloseCode == 1000);
REQUIRE(serverReceivedCloseReason == "Normal closure"); REQUIRE(serverReceivedCloseReason == "Normal closure");
@ -298,7 +297,7 @@ TEST_CASE("Websocket_client_close_params_given", "[close]")
int port = getFreePort(); int port = getFreePort();
ix::WebSocketServer server(port); ix::WebSocketServer server(port);
uint16_t serverReceivedCloseCode(0); uint16_t serverReceivedCloseCode(0);
bool serverReceivedCloseRemote(false); bool serverReceivedCloseRemote(false);
std::string serverReceivedCloseReason(""); std::string serverReceivedCloseReason("");
@ -333,7 +332,7 @@ TEST_CASE("Websocket_client_close_params_given", "[close]")
{ {
std::lock_guard<std::mutex> lck(mutexWrite); std::lock_guard<std::mutex> lck(mutexWrite);
// Here we read the code/reason received by the server, and ensure that remote is true // Here we read the code/reason received by the server, and ensure that remote is true
REQUIRE(serverReceivedCloseCode == 4000); REQUIRE(serverReceivedCloseCode == 4000);
REQUIRE(serverReceivedCloseReason == "My reason"); REQUIRE(serverReceivedCloseReason == "My reason");
@ -356,7 +355,7 @@ TEST_CASE("Websocket_server_close", "[close]")
int port = getFreePort(); int port = getFreePort();
ix::WebSocketServer server(port); ix::WebSocketServer server(port);
uint16_t serverReceivedCloseCode(0); uint16_t serverReceivedCloseCode(0);
bool serverReceivedCloseRemote(false); bool serverReceivedCloseRemote(false);
std::string serverReceivedCloseReason(""); std::string serverReceivedCloseReason("");
@ -391,7 +390,7 @@ TEST_CASE("Websocket_server_close", "[close]")
{ {
std::lock_guard<std::mutex> lck(mutexWrite); std::lock_guard<std::mutex> lck(mutexWrite);
// Here we read the code/reason received by the server, and ensure that remote is true // Here we read the code/reason received by the server, and ensure that remote is true
REQUIRE(serverReceivedCloseCode == 1000); REQUIRE(serverReceivedCloseCode == 1000);
REQUIRE(serverReceivedCloseReason == "Normal closure"); REQUIRE(serverReceivedCloseReason == "Normal closure");

View File

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

View File

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

View File

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

View File

@ -1,319 +1,319 @@
# spdlog # spdlog
Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)&nbsp; [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog) Very fast, header only, C++ logging library. [![Build Status](https://travis-ci.org/gabime/spdlog.svg?branch=master)](https://travis-ci.org/gabime/spdlog)&nbsp; [![Build status](https://ci.appveyor.com/api/projects/status/d2jnxclg20vd0o50?svg=true)](https://ci.appveyor.com/project/gabime/spdlog)
## Install ## Install
#### Just copy the headers: #### Just copy the headers:
* Copy the source [folder](https://github.com/gabime/spdlog/tree/v1.x/include/spdlog) to your build tree and use a C++11 compiler. * Copy the source [folder](https://github.com/gabime/spdlog/tree/v1.x/include/spdlog) to your build tree and use a C++11 compiler.
#### Or use your favorite package manager: #### Or use your favorite package manager:
* Ubuntu: `apt-get install libspdlog-dev` * Ubuntu: `apt-get install libspdlog-dev`
* Homebrew: `brew install spdlog` * Homebrew: `brew install spdlog`
* FreeBSD: `cd /usr/ports/devel/spdlog/ && make install clean` * FreeBSD: `cd /usr/ports/devel/spdlog/ && make install clean`
* Fedora: `yum install spdlog` * Fedora: `yum install spdlog`
* Gentoo: `emerge dev-libs/spdlog` * Gentoo: `emerge dev-libs/spdlog`
* Arch Linux: `yaourt -S spdlog-git` * Arch Linux: `yaourt -S spdlog-git`
* vcpkg: `vcpkg install spdlog` * vcpkg: `vcpkg install spdlog`
## Platforms ## Platforms
* Linux, FreeBSD, OpenBSD, Solaris, AIX * Linux, FreeBSD, OpenBSD, Solaris, AIX
* Windows (msvc 2013+, cygwin) * Windows (msvc 2013+, cygwin)
* macOS (clang 3.5+) * macOS (clang 3.5+)
* Android * Android
## Features ## Features
* Very fast (see [benchmarks](#benchmarks) below). * Very fast (see [benchmarks](#benchmarks) below).
* Headers only, just copy and use. * Headers only, just copy and use.
* Feature rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library. * Feature rich formatting, using the excellent [fmt](https://github.com/fmtlib/fmt) library.
* Fast asynchronous mode (optional) * Fast asynchronous mode (optional)
* [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting. * [Custom](https://github.com/gabime/spdlog/wiki/3.-Custom-formatting) formatting.
* Multi/Single threaded loggers. * Multi/Single threaded loggers.
* Various log targets: * Various log targets:
* Rotating log files. * Rotating log files.
* Daily log files. * Daily log files.
* Console logging (colors supported). * Console logging (colors supported).
* syslog. * syslog.
* Windows debugger (```OutputDebugString(..)```) * Windows debugger (```OutputDebugString(..)```)
* Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface). * Easily extendable with custom log targets (just implement a single function in the [sink](include/spdlog/sinks/sink.h) interface).
* Severity based filtering - threshold levels can be modified in runtime as well as in compile time. * Severity based filtering - threshold levels can be modified in runtime as well as in compile time.
* Binary data logging. * Binary data logging.
## Benchmarks ## Benchmarks
Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/bench.cpp) done in Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz Below are some [benchmarks](https://github.com/gabime/spdlog/blob/v1.x/bench/bench.cpp) done in Ubuntu 64 bit, Intel i7-4770 CPU @ 3.40GHz
#### Synchronous mode #### Synchronous mode
``` ```
******************************************************************************* *******************************************************************************
Single thread, 1,000,000 iterations Single thread, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_st... Elapsed: 0.181652 5,505,042/sec basic_st... Elapsed: 0.181652 5,505,042/sec
rotating_st... Elapsed: 0.181781 5,501,117/sec rotating_st... Elapsed: 0.181781 5,501,117/sec
daily_st... Elapsed: 0.187595 5,330,630/sec daily_st... Elapsed: 0.187595 5,330,630/sec
null_st... Elapsed: 0.0504704 19,813,602/sec null_st... Elapsed: 0.0504704 19,813,602/sec
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
basic_mt... Elapsed: 0.616035 1,623,284/sec basic_mt... Elapsed: 0.616035 1,623,284/sec
rotating_mt... Elapsed: 0.620344 1,612,008/sec rotating_mt... Elapsed: 0.620344 1,612,008/sec
daily_mt... Elapsed: 0.648353 1,542,369/sec daily_mt... Elapsed: 0.648353 1,542,369/sec
null_mt... Elapsed: 0.151972 6,580,166/sec null_mt... Elapsed: 0.151972 6,580,166/sec
``` ```
#### Asynchronous mode #### Asynchronous mode
``` ```
******************************************************************************* *******************************************************************************
10 threads sharing same logger, 1,000,000 iterations 10 threads sharing same logger, 1,000,000 iterations
******************************************************************************* *******************************************************************************
async... Elapsed: 0.350066 2,856,606/sec async... Elapsed: 0.350066 2,856,606/sec
async... Elapsed: 0.314865 3,175,960/sec async... Elapsed: 0.314865 3,175,960/sec
async... Elapsed: 0.349851 2,858,358/sec async... Elapsed: 0.349851 2,858,358/sec
``` ```
## Usage samples ## Usage samples
#### Basic usage #### Basic usage
```c++ ```c++
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
int main() int main()
{ {
spdlog::info("Welcome to spdlog!"); spdlog::info("Welcome to spdlog!");
spdlog::error("Some error message with arg: {}", 1); spdlog::error("Some error message with arg: {}", 1);
spdlog::warn("Easy padding in numbers like {:08d}", 12); spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456); spdlog::info("Support for floats {:03.2f}", 1.23456);
spdlog::info("Positional args are {1} {0}..", "too", "supported"); spdlog::info("Positional args are {1} {0}..", "too", "supported");
spdlog::info("{:<30}", "left aligned"); spdlog::info("{:<30}", "left aligned");
spdlog::set_level(spdlog::level::debug); // Set global log level to debug spdlog::set_level(spdlog::level::debug); // Set global log level to debug
spdlog::debug("This message should be displayed.."); spdlog::debug("This message should be displayed..");
// change log pattern // change log pattern
spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v"); spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");
// Compile time log levels // Compile time log levels
// define SPDLOG_ACTIVE_LEVEL to desired level // define SPDLOG_ACTIVE_LEVEL to desired level
SPDLOG_TRACE("Some trace message with param {}", {}); SPDLOG_TRACE("Some trace message with param {}", {});
SPDLOG_DEBUG("Some debug message"); SPDLOG_DEBUG("Some debug message");
} }
``` ```
#### create stdout/stderr logger object #### create stdout/stderr logger object
```c++ ```c++
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/stdout_color_sinks.h"
void stdout_example() void stdout_example()
{ {
// create color multi threaded logger // create color multi threaded logger
auto console = spdlog::stdout_color_mt("console"); auto console = spdlog::stdout_color_mt("console");
auto err_logger = spdlog::stderr_color_mt("stderr"); auto err_logger = spdlog::stderr_color_mt("stderr");
spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)"); spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
} }
``` ```
--- ---
#### Basic file logger #### Basic file logger
```c++ ```c++
#include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/basic_file_sink.h"
void basic_logfile_example() void basic_logfile_example()
{ {
try try
{ {
auto my_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt"); auto my_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
} }
catch (const spdlog::spdlog_ex &ex) catch (const spdlog::spdlog_ex &ex)
{ {
std::cout << "Log init failed: " << ex.what() << std::endl; std::cout << "Log init failed: " << ex.what() << std::endl;
} }
} }
``` ```
--- ---
#### Rotating files #### Rotating files
```c++ ```c++
#include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/rotating_file_sink.h"
void rotating_example() void rotating_example()
{ {
// Create a file rotating logger with 5mb size max and 3 rotated files // Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3); auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
} }
``` ```
--- ---
#### Daily files #### Daily files
```c++ ```c++
#include "spdlog/sinks/daily_file_sink.h" #include "spdlog/sinks/daily_file_sink.h"
void daily_example() void daily_example()
{ {
// Create a daily logger - a new file is created every day on 2:30am // Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30); auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
} }
``` ```
--- ---
#### Cloning loggers #### Cloning loggers
```c++ ```c++
// clone a logger and give it new name. // clone a logger and give it new name.
// Useful for creating subsystem loggers from some "root" logger // Useful for creating subsystem loggers from some "root" logger
void clone_example() void clone_example()
{ {
auto network_logger = spdlog::get("root")->clone("network"); auto network_logger = spdlog::get("root")->clone("network");
network_logger->info("Logging network stuff.."); network_logger->info("Logging network stuff..");
} }
``` ```
--- ---
#### Periodic flush #### Periodic flush
```c++ ```c++
// periodically flush all *registered* loggers every 3 seconds: // periodically flush all *registered* loggers every 3 seconds:
// warning: only use if all your loggers are thread safe! // warning: only use if all your loggers are thread safe!
spdlog::flush_every(std::chrono::seconds(3)); spdlog::flush_every(std::chrono::seconds(3));
``` ```
--- ---
#### Binary logging #### Binary logging
```c++ ```c++
// log binary data as hex. // log binary data as hex.
// many types of std::container<char> types can be used. // many types of std::container<char> types can be used.
// ranges are supported too. // ranges are supported too.
// format flags: // format flags:
// {:X} - print in uppercase. // {:X} - print in uppercase.
// {:s} - don't separate each byte with space. // {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start. // {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines. // {:n} - don't split the output to lines.
#include "spdlog/fmt/bin_to_hex.h" #include "spdlog/fmt/bin_to_hex.h"
void binary_example() void binary_example()
{ {
auto console = spdlog::get("console"); auto console = spdlog::get("console");
std::array<char, 80> buf; std::array<char, 80> buf;
console->info("Binary example: {}", spdlog::to_hex(buf)); console->info("Binary example: {}", spdlog::to_hex(buf));
console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10)); console->info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
// more examples: // more examples:
// logger->info("uppercase: {:X}", spdlog::to_hex(buf)); // logger->info("uppercase: {:X}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf)); // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
// logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf)); // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
} }
``` ```
--- ---
#### Logger with multi sinks - each with different format and log level #### Logger with multi sinks - each with different format and log level
```c++ ```c++
// create logger with 2 targets with different log levels and formats. // create logger with 2 targets with different log levels and formats.
// the console will show only warnings or errors, while the file will log all. // the console will show only warnings or errors, while the file will log all.
void multi_sink_example() void multi_sink_example()
{ {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_level(spdlog::level::warn); console_sink->set_level(spdlog::level::warn);
console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v"); console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true); auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
file_sink->set_level(spdlog::level::trace); file_sink->set_level(spdlog::level::trace);
spdlog::logger logger("multi_sink", {console_sink, file_sink}); spdlog::logger logger("multi_sink", {console_sink, file_sink});
logger.set_level(spdlog::level::debug); logger.set_level(spdlog::level::debug);
logger.warn("this should appear in both console and file"); logger.warn("this should appear in both console and file");
logger.info("this message should not appear in the console, only in the file"); logger.info("this message should not appear in the console, only in the file");
} }
``` ```
--- ---
#### Asynchronous logging #### Asynchronous logging
```c++ ```c++
#include "spdlog/async.h" #include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/basic_file_sink.h"
void async_example() void async_example()
{ {
// default thread pool settings can be modified *before* creating the async logger: // default thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(8192, 1); // queue with 8k items and 1 backing thread. // spdlog::init_thread_pool(8192, 1); // queue with 8k items and 1 backing thread.
auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt"); auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
// alternatively: // alternatively:
// auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt"); // auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
} }
``` ```
--- ---
#### Asynchronous logger with multi sinks #### Asynchronous logger with multi sinks
```c++ ```c++
#include "spdlog/sinks/stdout_color_sinks.h" #include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/sinks/rotating_file_sink.h" #include "spdlog/sinks/rotating_file_sink.h"
void multi_sink_example2() void multi_sink_example2()
{ {
spdlog::init_thread_pool(8192, 1); spdlog::init_thread_pool(8192, 1);
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >(); auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt >();
auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3); auto rotating_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("mylog.txt", 1024*1024*10, 3);
std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink}; std::vector<spdlog::sink_ptr> sinks {stdout_sink, rotating_sink};
auto logger = std::make_shared<spdlog::async_logger>("loggername", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block); auto logger = std::make_shared<spdlog::async_logger>("loggername", sinks.begin(), sinks.end(), spdlog::thread_pool(), spdlog::async_overflow_policy::block);
spdlog::register_logger(logger); spdlog::register_logger(logger);
} }
``` ```
--- ---
#### User defined types #### User defined types
```c++ ```c++
// user defined types logging by implementing operator<< // user defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included #include "spdlog/fmt/ostr.h" // must be included
struct my_type struct my_type
{ {
int i; int i;
template<typename OStream> template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c) friend OStream &operator<<(OStream &os, const my_type &c)
{ {
return os << "[my_type i=" << c.i << "]"; return os << "[my_type i=" << c.i << "]";
} }
}; };
void user_defined_example() void user_defined_example()
{ {
spdlog::get("console")->info("user defined type: {}", my_type{14}); spdlog::get("console")->info("user defined type: {}", my_type{14});
} }
``` ```
--- ---
#### Custom error handler #### Custom error handler
```c++ ```c++
void err_handler_example() void err_handler_example()
{ {
// can be set globally or per logger(logger->set_error_handler(..)) // can be set globally or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** LOGGER ERROR ***: {}", msg); }); spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** LOGGER ERROR ***: {}", msg); });
spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3); spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
} }
``` ```
--- ---
#### syslog #### syslog
```c++ ```c++
#include "spdlog/sinks/syslog_sink.h" #include "spdlog/sinks/syslog_sink.h"
void syslog_example() void syslog_example()
{ {
std::string ident = "spdlog-example"; std::string ident = "spdlog-example";
auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID); auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog."); syslog_logger->warn("This is warning that will end up in syslog.");
} }
``` ```
--- ---
#### Android example #### Android example
```c++ ```c++
#include "spdlog/sinks/android_sink.h" #include "spdlog/sinks/android_sink.h"
void android_example() void android_example()
{ {
std::string tag = "spdlog-android"; std::string tag = "spdlog-android";
auto android_logger = spdlog::android_logger("android", tag); auto android_logger = spdlog::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message."); android_logger->critical("Use \"adb shell logcat\" to view this message.");
} }
``` ```
## Documentation ## Documentation
Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki/1.-QuickStart) pages. Documentation can be found in the [wiki](https://github.com/gabime/spdlog/wiki/1.-QuickStart) pages.

View File

@ -713,7 +713,7 @@ typedef basic_format_args<wprintf_context> wprintf_args;
/** /**
\rst \rst
Constructs an `~fmt::format_arg_store` object that contains references to Constructs an `~fmt::format_arg_store` object that contains references to
arguments and can be implicitly converted to `~fmt::printf_args`. arguments and can be implicitly converted to `~fmt::printf_args`.
\endrst \endrst
*/ */
template<typename... Args> template<typename... Args>
@ -723,7 +723,7 @@ inline format_arg_store<printf_context, Args...>
/** /**
\rst \rst
Constructs an `~fmt::format_arg_store` object that contains references to Constructs an `~fmt::format_arg_store` object that contains references to
arguments and can be implicitly converted to `~fmt::wprintf_args`. arguments and can be implicitly converted to `~fmt::wprintf_args`.
\endrst \endrst
*/ */
template<typename... Args> template<typename... Args>

View File

@ -159,7 +159,7 @@ void for_each(index_sequence<Is...>, Tuple &&tup, F &&f) FMT_NOEXCEPT {
} }
template <class T> template <class T>
FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value>
get_indexes(T const &) { return {}; } get_indexes(T const &) { return {}; }
template <class Tuple, class F> template <class Tuple, class F>
@ -169,14 +169,14 @@ void for_each(Tuple &&tup, F &&f) {
} }
template<typename Arg> template<typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&, FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
typename std::enable_if< typename std::enable_if<
!is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) { !is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
return add_space ? " {}" : "{}"; return add_space ? " {}" : "{}";
} }
template<typename Arg> template<typename Arg>
FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&, FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&,
typename std::enable_if< typename std::enable_if<
is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) { is_like_std_string<typename std::decay<Arg>::type>::value>::type* = nullptr) {
return add_space ? " \"{}\"" : "\"{}\""; return add_space ? " \"{}\"" : "\"{}\"";
@ -205,7 +205,7 @@ struct is_tuple_like {
}; };
template <typename TupleT, typename Char> template <typename TupleT, typename Char>
struct formatter<TupleT, Char, struct formatter<TupleT, Char,
typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> { typename std::enable_if<fmt::is_tuple_like<TupleT>::value>::type> {
private: private:
// C++11 generic lambda for format() // C++11 generic lambda for format()

View File

@ -142,4 +142,4 @@
// Defaults to __FUNCTION__ (should work on all compilers) if not defined. // Defaults to __FUNCTION__ (should work on all compilers) if not defined.
// //
// #define SPDLOG_FUNCTION __PRETTY_FUNCTION__ // #define SPDLOG_FUNCTION __PRETTY_FUNCTION__
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@ -1,2 +1,2 @@
#define CATCH_CONFIG_MAIN #define CATCH_CONFIG_MAIN
#include "catch.hpp" #include "catch.hpp"

View File

@ -104,4 +104,4 @@ TEST_CASE("full_queue", "[mpmc_blocking_q]")
int item = -1; int item = -1;
q.dequeue_for(item, milliseconds(0)); q.dequeue_for(item, milliseconds(0));
REQUIRE(item == 123456); REQUIRE(item == 123456);
} }

View File

@ -13,4 +13,4 @@ std::size_t count_lines(const std::string &filename);
std::size_t get_filesize(const std::string &filename); std::size_t get_filesize(const std::string &filename);
bool ends_with(std::string const &value, std::string const &ending); bool ends_with(std::string const &value, std::string const &ending);

View File

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