Compare commits
88 Commits
feature/vc
...
v5.2.0
Author | SHA1 | Date | |
---|---|---|---|
cae23c764f | |||
f25b2af6eb | |||
508d372df1 | |||
12c3275c36 | |||
98189c23dc | |||
ec55b4a82a | |||
5d58982f77 | |||
57665ca825 | |||
deaa753657 | |||
7c7c877621 | |||
afa71a6b4b | |||
172cd39702 | |||
82213fd3a5 | |||
a32bf885ba | |||
61eb662e5f | |||
2887370666 | |||
8826d62075 | |||
fae284e2e1 | |||
2408617ed9 | |||
cc10b7f998 | |||
3c97d5f668 | |||
0accf24320 | |||
8ec2ef345c | |||
10dbe2d44d | |||
6b2cdb6b54 | |||
06bc795133 | |||
239a08ff9b | |||
41dd8d2184 | |||
57b4b13b65 | |||
a66b116aad | |||
5c4102c0be | |||
ebb7318895 | |||
b11876096b | |||
d603a74c6f | |||
95d633e71e | |||
217d0650f4 | |||
45d7bb34d7 | |||
2e32319236 | |||
8eb0d0b7c3 | |||
f18f04c0ee | |||
193da820b2 | |||
c6198305d4 | |||
c77d6ae3f5 | |||
c72b2dbd6b | |||
835523f77b | |||
ec8a35b587 | |||
aca18995d1 | |||
f9178f58aa | |||
2477946e68 | |||
7c4d040384 | |||
197cf8ed36 | |||
dd0d7c268f | |||
b2bfccac0a | |||
8b8b352e61 | |||
0403dd354b | |||
b78b453504 | |||
f8fef833b8 | |||
fc4068f2e5 | |||
c300866dcc | |||
18485a74e5 | |||
4dd5950406 | |||
98de54106d | |||
4d64272a1a | |||
0ccece908b | |||
64cd725060 | |||
cc2fa55608 | |||
4fb268585c | |||
3a2495c456 | |||
1d4d058ed0 | |||
15a1347531 | |||
4cbfa71338 | |||
705625af0a | |||
01bc6654cb | |||
eea42bff66 | |||
06b4762c19 | |||
1ee9479009 | |||
73e94ed03a | |||
1883519e82 | |||
6f6c1f85ef | |||
c55ff3cb1b | |||
08006ddd97 | |||
fa4aee6ddc | |||
691502d7ad | |||
43deaba547 | |||
2d02ae0f0c | |||
a8879da4fc | |||
5f4a430845 | |||
b9231be305 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
build
|
||||
*.pyc
|
||||
venv
|
||||
|
12
.pre-commit-config.yaml
Normal file
12
.pre-commit-config.yaml
Normal file
@ -0,0 +1,12 @@
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
|
||||
- repo: https://github.com/pocc/pre-commit-hooks
|
||||
rev: ''
|
||||
hooks:
|
||||
- id: clang-format
|
33
.travis.yml
33
.travis.yml
@ -7,14 +7,19 @@ matrix:
|
||||
include:
|
||||
# macOS
|
||||
- os: osx
|
||||
env:
|
||||
- HOMEBREW_NO_AUTO_UPDATE=1
|
||||
compiler: clang
|
||||
script:
|
||||
- brew install mbedtls
|
||||
- python test/run.py
|
||||
- make ws
|
||||
|
||||
# Linux
|
||||
- os: linux
|
||||
dist: xenial
|
||||
dist: bionic
|
||||
before_install:
|
||||
- sudo apt-get install -y libmbedtls-dev
|
||||
script:
|
||||
- python test/run.py
|
||||
- make ws
|
||||
@ -31,11 +36,21 @@ matrix:
|
||||
# - CXX=clang++
|
||||
|
||||
# Windows
|
||||
- os: windows
|
||||
env:
|
||||
- CMAKE_PATH="/c/Program Files/CMake/bin"
|
||||
script:
|
||||
- export PATH=$CMAKE_PATH:$PATH
|
||||
- cmake -DUSE_TLS=1 -DUSE_WS=1 -DUSE_MBED_TLS=1 -DUSE_VENDORED_THIRD_PARTY=1 .
|
||||
- cmake --build --parallel .
|
||||
- python test/run.py
|
||||
# - os: windows
|
||||
# env:
|
||||
# - CMAKE_PATH="/c/Program Files/CMake/bin"
|
||||
# script:
|
||||
# - cd third_party/zlib
|
||||
# - cmake .
|
||||
# - cmake --build . --target install
|
||||
# - cd ../..
|
||||
# # - cd third_party/mbedtls
|
||||
# # - cmake .
|
||||
# # - cmake --build . --target install
|
||||
# # - cd ../..
|
||||
# - export PATH=$CMAKE_PATH:$PATH
|
||||
# - cd test
|
||||
# - cmake .
|
||||
# - cmake --build --parallel .
|
||||
# - ixwebsocket_unittest.exe
|
||||
# # - python test/run.py
|
||||
|
31
CHANGELOG.md
31
CHANGELOG.md
@ -1,31 +0,0 @@
|
||||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [unreleased] - 2019-06-09
|
||||
### Changed
|
||||
- mbedtls and zlib are searched with find_package, and we use the vendored version if nothing is found
|
||||
- travis CI uses g++ on Linux
|
||||
|
||||
## [4.0.0] - 2019-06-09
|
||||
### Changed
|
||||
- WebSocket::send() sends message in TEXT mode by default
|
||||
- WebSocketMessage sets a new binary field, which tells whether the received incoming message is binary or text
|
||||
- WebSocket::send takes a third arg, binary which default to true (can be text too)
|
||||
- WebSocket callback only take one object, a const ix::WebSocketMessagePtr& msg
|
||||
- Add explicit WebSocket::sendBinary method
|
||||
- New headers + WebSocketMessage class to hold message data, still not used across the board
|
||||
- Add test/compatibility folder with small servers and clients written in different languages and different libraries to test compatibility.
|
||||
- ws echo_server has a -g option to print a greeting message on connect
|
||||
- IXSocketMbedTLS: better error handling in close and connect
|
||||
|
||||
## [3.1.2] - 2019-06-06
|
||||
### Added
|
||||
- ws connect has a -x option to disable per message deflate
|
||||
- Add WebSocket::disablePerMessageDeflate() option.
|
||||
|
||||
## [3.0.0] - 2019-06-xx
|
||||
### Changed
|
||||
- TLS, aka SSL works on Windows (websocket and http clients)
|
||||
- ws command line tool build on Windows
|
||||
- Async API for HttpClient
|
||||
- HttpClient API changed to use shared_ptr for response and request
|
@ -25,7 +25,10 @@ set( IXWEBSOCKET_SOURCES
|
||||
ixwebsocket/IXCancellationRequest.cpp
|
||||
ixwebsocket/IXConnectionState.cpp
|
||||
ixwebsocket/IXDNSLookup.cpp
|
||||
ixwebsocket/IXExponentialBackoff.cpp
|
||||
ixwebsocket/IXHttp.cpp
|
||||
ixwebsocket/IXHttpClient.cpp
|
||||
ixwebsocket/IXHttpServer.cpp
|
||||
ixwebsocket/IXNetSystem.cpp
|
||||
ixwebsocket/IXSelectInterrupt.cpp
|
||||
ixwebsocket/IXSelectInterruptFactory.cpp
|
||||
@ -34,6 +37,7 @@ set( IXWEBSOCKET_SOURCES
|
||||
ixwebsocket/IXSocketFactory.cpp
|
||||
ixwebsocket/IXSocketServer.cpp
|
||||
ixwebsocket/IXUrlParser.cpp
|
||||
ixwebsocket/IXUserAgent.cpp
|
||||
ixwebsocket/IXWebSocket.cpp
|
||||
ixwebsocket/IXWebSocketCloseConstants.cpp
|
||||
ixwebsocket/IXWebSocketHandshake.cpp
|
||||
@ -51,7 +55,10 @@ set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXCancellationRequest.h
|
||||
ixwebsocket/IXConnectionState.h
|
||||
ixwebsocket/IXDNSLookup.h
|
||||
ixwebsocket/IXExponentialBackoff.h
|
||||
ixwebsocket/IXHttp.h
|
||||
ixwebsocket/IXHttpClient.h
|
||||
ixwebsocket/IXHttpServer.h
|
||||
ixwebsocket/IXNetSystem.h
|
||||
ixwebsocket/IXProgressCallback.h
|
||||
ixwebsocket/IXSelectInterrupt.h
|
||||
@ -62,6 +69,8 @@ set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXSocketFactory.h
|
||||
ixwebsocket/IXSocketServer.h
|
||||
ixwebsocket/IXUrlParser.h
|
||||
ixwebsocket/IXUtf8Validator.h
|
||||
ixwebsocket/IXUserAgent.h
|
||||
ixwebsocket/IXWebSocket.h
|
||||
ixwebsocket/IXWebSocketCloseConstants.h
|
||||
ixwebsocket/IXWebSocketCloseInfo.h
|
||||
@ -78,6 +87,7 @@ set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXWebSocketSendInfo.h
|
||||
ixwebsocket/IXWebSocketServer.h
|
||||
ixwebsocket/IXWebSocketTransport.h
|
||||
ixwebsocket/IXWebSocketVersion.h
|
||||
ixwebsocket/LUrlParser.h
|
||||
ixwebsocket/libwshandshake.hpp
|
||||
)
|
||||
@ -134,7 +144,17 @@ if (APPLE AND USE_TLS AND NOT USE_MBED_TLS)
|
||||
target_link_libraries(ixwebsocket "-framework foundation" "-framework security")
|
||||
endif()
|
||||
|
||||
if (USE_OPEN_SSL)
|
||||
if (WIN32)
|
||||
target_link_libraries(ixwebsocket wsock32 ws2_32)
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
|
||||
if (UNIX)
|
||||
find_package(Threads)
|
||||
target_link_libraries(ixwebsocket ${CMAKE_THREAD_LIBS_INIT})
|
||||
endif()
|
||||
|
||||
if (USE_TLS AND USE_OPEN_SSL)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
add_definitions(${OPENSSL_DEFINITIONS})
|
||||
message(STATUS "OpenSSL: " ${OPENSSL_VERSION})
|
||||
@ -142,7 +162,7 @@ if (USE_OPEN_SSL)
|
||||
target_link_libraries(ixwebsocket ${OPENSSL_LIBRARIES})
|
||||
endif()
|
||||
|
||||
if (USE_MBED_TLS)
|
||||
if (USE_TLS AND USE_MBED_TLS)
|
||||
if (USE_VENDORED_THIRD_PARTY)
|
||||
set (ENABLE_PROGRAMS OFF)
|
||||
add_subdirectory(third_party/mbedtls)
|
||||
@ -156,15 +176,14 @@ if (USE_MBED_TLS)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
find_package(ZLIB REQUIRED)
|
||||
find_package(ZLIB)
|
||||
if (ZLIB_FOUND)
|
||||
include_directories(${ZLIB_INCLUDE_DIRS})
|
||||
target_link_libraries(ixwebsocket ${ZLIB_LIBRARIES})
|
||||
else()
|
||||
add_subdirectory(third_party/zlib)
|
||||
include_directories(third_party/zlib ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib)
|
||||
target_link_libraries(ixwebsocket zlibstatic wsock32 ws2_32)
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
|
||||
target_link_libraries(ixwebsocket zlibstatic)
|
||||
endif()
|
||||
|
||||
set( IXWEBSOCKET_INCLUDE_DIRS
|
||||
|
@ -1 +1 @@
|
||||
4.0.0
|
||||
5.2.0
|
||||
|
422
README.md
422
README.md
@ -1,421 +1,13 @@
|
||||
# General
|
||||
## Hello world
|
||||
|
||||

|
||||

|
||||
|
||||
## Introduction
|
||||
IXWebSocket is a C++ library for WebSocket client and server development. It has minimal dependencies (no boost), is very simple to use and support everything you'll likely need for websocket dev (SSL, deflate compression, compiles on most platforms, etc...). HTTP client and server code is also available, but it hasn't received as much testing.
|
||||
|
||||
[*WebSocket*](https://en.wikipedia.org/wiki/WebSocket) is a computer communications protocol, providing full-duplex and bi-directionnal communication channels over a single TCP connection. *IXWebSocket* is a C++ library for client and server Websocket communication, and for client HTTP communication. The code is derived from [easywsclient](https://github.com/dhbaird/easywsclient) and from the [Satori C SDK](https://github.com/satori-com/satori-rtm-sdk-c). It has been tested on the following platforms.
|
||||
It is been used on big mobile video game titles sending and receiving tons of messages since 2017 (iOS and Android).
|
||||
|
||||
* macOS
|
||||
* iOS
|
||||
* Linux
|
||||
* Android
|
||||
* Windows
|
||||
Interested ? Go read the [docs](https://bsergean.github.io/IXWebSocket/site/) ! If things don't work as expected, please create an issue in github, or even better a pull request if you know how to fix your problem.
|
||||
|
||||
## Examples
|
||||
IXWebSocket is actively being developed, check out the [changelog](CHANGELOG.md) to know what's cooking. If you are looking for a real time messaging service (the chat-like 'server' your websocket code will talk to) with many features such as history, backed by Redis, look at [cobra](https://github.com/machinezone/cobra).
|
||||
|
||||
The [*ws*](https://github.com/machinezone/IXWebSocket/tree/master/ws) folder countains many interactive programs for chat, [file transfers](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_send.cpp), [curl like](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_http_client.cpp) http clients, demonstrating client and server usage.
|
||||
|
||||
Here is what the client API looks like.
|
||||
|
||||
```
|
||||
ix::WebSocket webSocket;
|
||||
|
||||
std::string url("ws://localhost:8080/");
|
||||
webSocket.setUrl(url);
|
||||
|
||||
// Optional heart beat, sent every 45 seconds when there is not any traffic
|
||||
// to make sure that load balancers do not kill an idle connection.
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
|
||||
// Per message deflate connection is enabled by default. You can tweak its parameters or disable it
|
||||
webSocket.disablePerMessageDeflate();
|
||||
|
||||
// Setup a callback to be fired when a message or an event (open, close, error) is received
|
||||
webSocket.setOnMessageCallback(
|
||||
[](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
std::cout << msg->str << std::endl;
|
||||
}
|
||||
});
|
||||
|
||||
// Now that our callback is setup, we can start our background thread and receive messages
|
||||
webSocket.start();
|
||||
|
||||
// Send a message to the server (default to TEXT mode)
|
||||
webSocket.send("hello world");
|
||||
|
||||
// The message can be sent in BINARY mode (useful if you send MsgPack data for example)
|
||||
webSocket.sendBinary("some serialized binary data");
|
||||
|
||||
// ... finally ...
|
||||
|
||||
// Stop the connection
|
||||
webSocket.stop()
|
||||
```
|
||||
|
||||
Here is what the server API looks like. Note that server support is very recent and subject to changes.
|
||||
|
||||
```
|
||||
// Run a server on localhost at a given port.
|
||||
// Bound host name, max connections and listen backlog can also be passed in as parameters.
|
||||
ix::WebSocketServer server(port);
|
||||
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cerr << "New connection" << std::endl;
|
||||
|
||||
// A connection state object is available, and has a default id
|
||||
// You can subclass ConnectionState and pass an alternate factory
|
||||
// to override it. It is useful if you want to store custom
|
||||
// attributes per connection (authenticated bool flag, attributes, etc...)
|
||||
std::cerr << "id: " << connectionState->getId() << std::endl;
|
||||
|
||||
// The uri the client did connect to.
|
||||
std::cerr << "Uri: " << msg->openInfo.uri << std::endl;
|
||||
|
||||
std::cerr << "Headers:" << std::endl;
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
std::cerr << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// For an echo server, we just send back to the client whatever was received by the server
|
||||
// All connected clients are available in an std::set. See the broadcast cpp example.
|
||||
// Second parameter tells whether we are sending the message in binary or text mode.
|
||||
// Here we send it in the same mode as it was received.
|
||||
webSocket->send(msg->str, msg->binary);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
// Error handling
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Run the server in the background. Server can be stoped by calling server.stop()
|
||||
server.start();
|
||||
|
||||
// Block until server.stop() is called.
|
||||
server.wait();
|
||||
|
||||
```
|
||||
|
||||
Here is what the HTTP client API looks like. Note that HTTP client support is very recent and subject to changes.
|
||||
|
||||
```
|
||||
//
|
||||
// Preparation
|
||||
//
|
||||
HttpClient httpClient;
|
||||
HttpRequestArgsPtr args = httpClient.createRequest();
|
||||
|
||||
// Custom headers can be set
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["Foo"] = "bar";
|
||||
args->extraHeaders = headers;
|
||||
|
||||
// Timeout options
|
||||
args->connectTimeout = connectTimeout;
|
||||
args->transferTimeout = transferTimeout;
|
||||
|
||||
// Redirect options
|
||||
args->followRedirects = followRedirects;
|
||||
args->maxRedirects = maxRedirects;
|
||||
|
||||
// Misc
|
||||
args->compress = compress; // Enable gzip compression
|
||||
args->verbose = verbose;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
|
||||
//
|
||||
// Synchronous Request
|
||||
//
|
||||
HttpResponsePtr out;
|
||||
std::string url = "https://www.google.com";
|
||||
|
||||
// HEAD request
|
||||
out = httpClient.head(url, args);
|
||||
|
||||
// GET request
|
||||
out = httpClient.get(url, args);
|
||||
|
||||
// POST request with parameters
|
||||
HttpParameters httpParameters;
|
||||
httpParameters["foo"] = "bar";
|
||||
out = httpClient.post(url, httpParameters, args);
|
||||
|
||||
// POST request with a body
|
||||
out = httpClient.post(url, std::string("foo=bar"), args);
|
||||
|
||||
//
|
||||
// Result
|
||||
//
|
||||
auto errorCode = response->errorCode; // Can be HttpErrorCode::Ok, HttpErrorCode::UrlMalformed, etc...
|
||||
auto errorCode = response->errorCode; // 200, 404, etc...
|
||||
auto responseHeaders = response->headers; // All the headers in a special case-insensitive unordered_map of (string, string)
|
||||
auto payload = response->payload; // All the bytes from the response as an std::string
|
||||
auto errorMsg = response->errorMsg; // Descriptive error message in case of failure
|
||||
auto uploadSize = response->uploadSize; // Byte count of uploaded data
|
||||
auto downloadSize = response->downloadSize; // Byte count of downloaded data
|
||||
|
||||
//
|
||||
// Asynchronous Request
|
||||
//
|
||||
bool async = true;
|
||||
HttpClient httpClient(async);
|
||||
auto args = httpClient.createRequest(url, HttpClient::kGet);
|
||||
|
||||
// Push the request to a queue,
|
||||
bool ok = httpClient.performRequest(args, [](const HttpResponsePtr& response)
|
||||
{
|
||||
// This callback execute in a background thread. Make sure you uses appropriate protection such as mutex
|
||||
auto statusCode = response->statusCode; // acess results
|
||||
}
|
||||
);
|
||||
|
||||
// ok will be false if your httpClient is not async
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
CMakefiles for the library and the examples are available. This library has few dependencies, so it is possible to just add the source files into your project. Otherwise the usual way will suffice.
|
||||
|
||||
```
|
||||
mkdir build # make a build dir so that you can build out of tree.
|
||||
cd build
|
||||
cmake ..
|
||||
make -j
|
||||
make install # will install to /usr/local on Unix, on macOS it is a good idea to sudo chown -R `whoami`:staff /usr/local
|
||||
```
|
||||
|
||||
Headers and a static library will be installed to the target dir.
|
||||
|
||||
A [conan](https://conan.io/) file is available at [conan-IXWebSocket](https://github.com/Zinnion/conan-IXWebSocket).
|
||||
|
||||
There is a unittest which can be executed by typing `make test`.
|
||||
|
||||
There is a Dockerfile for running some code on Linux. To use docker-compose you must make a docker container first.
|
||||
|
||||
```
|
||||
$ make docker
|
||||
...
|
||||
$ docker compose up &
|
||||
...
|
||||
$ docker exec -it ixwebsocket_ws_1 bash
|
||||
app@ca2340eb9106:~$ ws --help
|
||||
ws is a websocket tool
|
||||
...
|
||||
```
|
||||
|
||||
Finally you can build and install the `ws command line tool` with Homebrew. The homebrew version might be slightly out of date.
|
||||
|
||||
```
|
||||
brew tap bsergean/IXWebSocket
|
||||
brew install IXWebSocket
|
||||
```
|
||||
|
||||
## Implementation details
|
||||
|
||||
### Per Message Deflate compression.
|
||||
|
||||
The per message deflate compression option is supported. It can lead to very nice bandbwith savings (20x !) if your messages are similar, which is often the case for example for chat applications. All features of the spec should be supported.
|
||||
|
||||
### TLS/SSL
|
||||
|
||||
Connections can be optionally secured and encrypted with TLS/SSL when using a wss:// endpoint, or using normal un-encrypted socket with ws:// endpoints. AppleSSL is used on iOS and macOS, OpenSSL is used on Android and Linux, mbedTLS is used on Windows.
|
||||
|
||||
### Polling and background thread work
|
||||
|
||||
No manual polling to fetch data is required. Data is sent and received instantly by using a background thread for receiving data and the select [system](http://man7.org/linux/man-pages/man2/select.2.html) call to be notified by the OS of incoming data. No timeout is used for select so that the background thread is only woken up when data is available, to optimize battery life. This is also the recommended way of using select according to the select tutorial, section [select law](https://linux.die.net/man/2/select_tut). Read and Writes to the socket are non blocking. Data is sent right away and not enqueued by writing directly to the socket, which is [possible](https://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid) since system socket implementations allow concurrent read/writes. However concurrent writes need to be protected with mutex.
|
||||
|
||||
### Automatic reconnection
|
||||
|
||||
If the remote end (server) breaks the connection, the code will try to perpetually reconnect, by using an exponential backoff strategy, capped at one retry every 10 seconds. This behavior can be disabled.
|
||||
|
||||
### Large messages
|
||||
|
||||
Large frames are broken up into smaller chunks or messages to avoid filling up the os tcp buffers, which is permitted thanks to WebSocket [fragmentation](https://tools.ietf.org/html/rfc6455#section-5.4). Messages up to 1G were sent and received succesfully.
|
||||
|
||||
## Limitations
|
||||
|
||||
* On Windows TLS is not setup yet to validate certificates.
|
||||
* There is no convenient way to embed a ca cert.
|
||||
* No utf-8 validation is made when sending TEXT message with sendText()
|
||||
* Automatic reconnection works at the TCP socket level, and will detect remote end disconnects. However, if the device/computer network become unreachable (by turning off wifi), it is quite hard to reliably and timely detect it at the socket level using `recv` and `send` error codes. [Here](https://stackoverflow.com/questions/14782143/linux-socket-how-to-detect-disconnected-network-in-a-client-program) is a good discussion on the subject. This behavior is consistent with other runtimes such as node.js. One way to detect a disconnected device with low level C code is to do a name resolution with DNS but this can be expensive. Mobile devices have good and reliable API to do that.
|
||||
* The server code is using select to detect incoming data, and creates one OS thread per connection. This is not as scalable as strategies using epoll or kqueue.
|
||||
|
||||
## C++ code organization
|
||||
|
||||
Here is a simplistic diagram which explains how the code is structured in term of class/modules.
|
||||
|
||||
```
|
||||
+-----------------------+ --- Public
|
||||
| | Start the receiving Background thread. Auto reconnection. Simple websocket Ping.
|
||||
| IXWebSocket | Interface used by C++ test clients. No IX dependencies.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocketServer | Run a server and give each connections its own WebSocket object.
|
||||
| | Each connection is handled in a new OS thread.
|
||||
| |
|
||||
+-----------------------+ --- Private
|
||||
| |
|
||||
| IXWebSocketTransport | Low level websocket code, framing, managing raw socket. Adapted from easywsclient.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocketHandshake | Establish the connection between client and server.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocket | ws:// Unencrypted Socket handler
|
||||
| IXWebSocketAppleSSL | wss:// TLS encrypted Socket AppleSSL handler. Used on iOS and macOS
|
||||
| IXWebSocketOpenSSL | wss:// TLS encrypted Socket OpenSSL handler. Used on Android and Linux
|
||||
| | Can be used on macOS too.
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXSocketConnect | Connect to the remote host (client).
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXDNSLookup | Does DNS resolution asynchronously so that it can be interrupted.
|
||||
| |
|
||||
+-----------------------+
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### Sending messages
|
||||
|
||||
`websocket.send("foo")` will send a message.
|
||||
|
||||
If the connection was closed and sending failed, the return value will be set to false.
|
||||
|
||||
### ReadyState
|
||||
|
||||
`getReadyState()` returns the state of the connection. There are 4 possible states.
|
||||
|
||||
1. ReadyState::Connecting - The connection is not yet open.
|
||||
2. ReadyState::Open - The connection is open and ready to communicate.
|
||||
3. ReadyState::Closing - The connection is in the process of closing.
|
||||
4. ReadyState::Closed - The connection is closed or could not be opened.
|
||||
|
||||
### Open and Close notifications
|
||||
|
||||
The onMessage event will be fired when the connection is opened or closed. This is similar to the [Javascript browser API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), which has `open` and `close` events notification that can be registered with the browser `addEventListener`.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback(
|
||||
[](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cout << "send greetings" << std::endl;
|
||||
|
||||
// Headers can be inspected (pairs of string/string)
|
||||
std::cout << "Handshake Headers:" << std::endl;
|
||||
for (auto it : msg->headers)
|
||||
{
|
||||
std::cout << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::cout << "disconnected" << std::endl;
|
||||
|
||||
// The server can send an explicit code and reason for closing.
|
||||
// This data can be accessed through the closeInfo object.
|
||||
std::cout << msg->closeInfo.code << std::endl;
|
||||
std::cout << msg->closeInfo.reason << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Error notification
|
||||
|
||||
A message will be fired when there is an error with the connection. The message type will be `ix::WebSocketMessageType::Error`. Multiple fields will be available on the event to describe the error.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback(
|
||||
[](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Error: " << msg->errorInfo.reason << std::endl;
|
||||
ss << "#retries: " << msg->eventInfo.retries << std::endl;
|
||||
ss << "Wait time(ms): " << msg->eventInfo.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << msg->eventInfo.http_status << std::endl;
|
||||
std::cout << ss.str() << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### start, stop
|
||||
|
||||
1. `websocket.start()` connect to the remote server and starts the message receiving background thread.
|
||||
2. `websocket.stop()` disconnect from the remote server and closes the background thread.
|
||||
|
||||
### Configuring the remote url
|
||||
|
||||
The url can be set and queried after a websocket object has been created. You will have to call `stop` and `start` if you want to disconnect and connect to that new url.
|
||||
|
||||
```
|
||||
std::string url("wss://example.com");
|
||||
websocket.configure(url);
|
||||
```
|
||||
|
||||
### Ping/Pong support
|
||||
|
||||
Ping/pong messages are used to implement keep-alive. 2 message types exists to identify ping and pong messages. Note that when a ping message is received, a pong is instantly send back as requested by the WebSocket spec.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback(
|
||||
[](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Ping ||
|
||||
msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
std::cout << "pong data: " << msg->str << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
A ping message can be sent to the server, with an optional data string.
|
||||
|
||||
```
|
||||
websocket.ping("ping data, optional (empty string is ok): limited to 125 bytes long");
|
||||
```
|
||||
|
||||
### Heartbeat.
|
||||
|
||||
You can configure an optional heart beat / keep-alive, sent every 45 seconds
|
||||
when there is no any traffic to make sure that load balancers do not kill an
|
||||
idle connection.
|
||||
|
||||
```
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
```
|
||||
IXWebSocket is not yet autobahn compliant, but we are working on changing this. See the current compliance [test results](https://bsergean.github.io/IXWebSocket/autobahn/index.html). The only tests that are still failing are the Websocket Compression ones (see section 12 and 13).
|
||||
|
23
docker/Dockerfile.ubuntu_disco
Normal file
23
docker/Dockerfile.ubuntu_disco
Normal file
@ -0,0 +1,23 @@
|
||||
# Build time
|
||||
FROM ubuntu:disco as build
|
||||
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt-get update
|
||||
RUN apt-get -y install wget
|
||||
RUN mkdir -p /tmp/cmake
|
||||
WORKDIR /tmp/cmake
|
||||
RUN wget https://github.com/Kitware/CMake/releases/download/v3.14.0/cmake-3.14.0-Linux-x86_64.tar.gz
|
||||
RUN tar zxf cmake-3.14.0-Linux-x86_64.tar.gz
|
||||
|
||||
RUN apt-get -y install g++
|
||||
RUN apt-get -y install libssl-dev
|
||||
RUN apt-get -y install libz-dev
|
||||
RUN apt-get -y install make
|
||||
RUN apt-get -y install python
|
||||
|
||||
COPY . .
|
||||
|
||||
ARG CMAKE_BIN_PATH=/tmp/cmake/cmake-3.14.0-Linux-x86_64/bin
|
||||
ENV PATH="${CMAKE_BIN_PATH}:${PATH}"
|
||||
|
||||
RUN ["make", "test"]
|
130
docs/CHANGELOG.md
Normal file
130
docs/CHANGELOG.md
Normal file
@ -0,0 +1,130 @@
|
||||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [5.2.0] - 2019-09-04
|
||||
|
||||
- Fragmentation: for sent messages which are compressed, the continuation fragments should not have the rsv1 bit set (fix all autobahn tests for zlib compression 12.X)
|
||||
- Websocket Server / do a case insensitive string search when looking for an Upgrade header whose value is websocket. (some client use WebSocket with some upper-case characters)
|
||||
|
||||
## [5.1.9] - 2019-09-03
|
||||
|
||||
- ws autobahn / report progress with spdlog::info to get timing info
|
||||
- ws autobahn / use condition variables for stopping test case + add more logging on errors
|
||||
|
||||
## [5.1.8] - 2019-09-03
|
||||
|
||||
- Per message deflate/compression: handle fragmented messages (fix autobahn test: 12.1.X and probably others)
|
||||
|
||||
## [5.1.7] - 2019-09-03
|
||||
|
||||
- Receiving invalid UTF-8 TEXT message should fail and close the connection (fix remaining autobahn test: 6.X UTF-8 Handling)
|
||||
|
||||
## [5.1.6] - 2019-09-03
|
||||
|
||||
- Sending invalid UTF-8 TEXT message should fail and close the connection (fix remaining autobahn test: 6.X UTF-8 Handling)
|
||||
- Fix failing unittest which was sending binary data in text mode with WebSocket::send to call properly call WebSocket::sendBinary instead.
|
||||
- Validate that the reason is proper utf-8. (fix autobahn test 7.5.1)
|
||||
- Validate close codes. Autobahn 7.9.*
|
||||
|
||||
## [5.1.5] - 2019-09-03
|
||||
|
||||
Framentation: data and continuation blocks received out of order (fix autobahn test: 5.9 through 5.20 Fragmentation)
|
||||
|
||||
## [5.1.4] - 2019-09-03
|
||||
|
||||
Sending invalid UTF-8 TEXT message should fail and close the connection (fix **tons** of autobahn test: 6.X UTF-8 Handling)
|
||||
|
||||
## [5.1.3] - 2019-09-03
|
||||
|
||||
Message type (TEXT or BINARY) is invalid for received fragmented messages (fix autobahn test: 5.3 through 5.8 Fragmentation)
|
||||
|
||||
## [5.1.2] - 2019-09-02
|
||||
|
||||
Ping and Pong messages cannot be fragmented (fix autobahn test: 5.1 and 5.2 Fragmentation)
|
||||
|
||||
## [5.1.1] - 2019-09-01
|
||||
|
||||
Close connections when reserved bits are used (fix autobahn test: 3.X Reserved Bits)
|
||||
|
||||
## [5.1.0] - 2019-08-31
|
||||
|
||||
- ws autobahn / Add code to test websocket client compliance with the autobahn test-suite
|
||||
- add utf-8 validation code, not hooked up properly yet
|
||||
- Ping received with a payload too large (> 125 bytes) trigger a connection closure
|
||||
- cobra / add tracking about published messages
|
||||
- cobra / publish returns a message id, that can be used when
|
||||
- cobra / new message type in the message received handler when publish/ok is received (can be used to implement an ack system).
|
||||
|
||||
## [5.0.9] - 2019-08-30
|
||||
|
||||
- User-Agent header is set when not specified.
|
||||
- New option to cap the max wait between reconnection attempts. Still default to 10s. (setMaxWaitBetweenReconnectionRetries).
|
||||
|
||||
```
|
||||
ws connect --max_wait 5000 ws://example.com # will only wait 5 seconds max between reconnection attempts
|
||||
```
|
||||
|
||||
## [5.0.7] - 2019-08-23
|
||||
- WebSocket: add new option to pass in extra HTTP headers when connecting.
|
||||
- `ws connect` add new option (-H, works like [curl](https://stackoverflow.com/questions/356705/how-to-send-a-header-using-a-http-request-through-a-curl-call)) to pass in extra HTTP headers when connecting
|
||||
|
||||
If you run against `ws echo_server` you will see the headers being received printed in the terminal.
|
||||
```
|
||||
ws connect -H "foo: bar" -H "baz: buz" ws://127.0.0.1:8008
|
||||
```
|
||||
|
||||
- CobraConnection: sets a unique id field for all messages sent to [cobra](https://github.com/machinezone/cobra).
|
||||
- CobraConnection: sets a counter as a field for each event published.
|
||||
|
||||
## [5.0.6] - 2019-08-22
|
||||
- Windows: silly compile error (poll should be in the global namespace)
|
||||
|
||||
## [5.0.5] - 2019-08-22
|
||||
- Windows: use select instead of WSAPoll, through a poll wrapper
|
||||
|
||||
## [5.0.4] - 2019-08-20
|
||||
- Windows build fixes (there was a problem with the use of ::poll that has a different name on Windows (WSAPoll))
|
||||
|
||||
## [5.0.3] - 2019-08-14
|
||||
- CobraMetricThreadedPublisher _enable flag is an atomic, and CobraMetricsPublisher is enabled by default
|
||||
|
||||
## [5.0.2] - 2019-08-01
|
||||
- ws cobra_subscribe has a new -q (quiet) option
|
||||
- ws cobra_subscribe knows to and display msg stats (count and # of messages received per second)
|
||||
- ws cobra_subscribe, cobra_to_statsd and cobra_to_sentry commands have a new option, --filter to restrict the events they want to receive
|
||||
|
||||
## [5.0.1] - 2019-07-25
|
||||
- ws connect command has a new option to send in binary mode (still default to text)
|
||||
- ws connect command has readline history thanks to libnoise-cpp. Now ws connect one can use using arrows to lookup previous sent messages and edit them
|
||||
|
||||
## [5.0.0] - 2019-06-23
|
||||
### Changed
|
||||
- New HTTP server / still very early. ws gained a new command, httpd can run a simple webserver serving local files.
|
||||
- IXDNSLookup. Uses weak pointer + smart_ptr + shared_from_this instead of static sets + mutex to handle object going away before dns lookup has resolved
|
||||
- cobra_to_sentry / backtraces are reversed and line number is not extracted correctly
|
||||
- mbedtls and zlib are searched with find_package, and we use the vendored version if nothing is found
|
||||
- travis CI uses g++ on Linux
|
||||
|
||||
## [4.0.0] - 2019-06-09
|
||||
### Changed
|
||||
- WebSocket::send() sends message in TEXT mode by default
|
||||
- WebSocketMessage sets a new binary field, which tells whether the received incoming message is binary or text
|
||||
- WebSocket::send takes a third arg, binary which default to true (can be text too)
|
||||
- WebSocket callback only take one object, a const ix::WebSocketMessagePtr& msg
|
||||
- Add explicit WebSocket::sendBinary method
|
||||
- New headers + WebSocketMessage class to hold message data, still not used across the board
|
||||
- Add test/compatibility folder with small servers and clients written in different languages and different libraries to test compatibility.
|
||||
- ws echo_server has a -g option to print a greeting message on connect
|
||||
- IXSocketMbedTLS: better error handling in close and connect
|
||||
|
||||
## [3.1.2] - 2019-06-06
|
||||
### Added
|
||||
- ws connect has a -x option to disable per message deflate
|
||||
- Add WebSocket::disablePerMessageDeflate() option.
|
||||
|
||||
## [3.0.0] - 2019-06-xx
|
||||
### Changed
|
||||
- TLS, aka SSL works on Windows (websocket and http clients)
|
||||
- ws command line tool build on Windows
|
||||
- Async API for HttpClient
|
||||
- HttpClient API changed to use shared_ptr for response and request
|
62
docs/build.md
Normal file
62
docs/build.md
Normal file
@ -0,0 +1,62 @@
|
||||
## Build
|
||||
|
||||
### CMake
|
||||
|
||||
CMakefiles for the library and the examples are available. This library has few dependencies, so it is possible to just add the source files into your project. Otherwise the usual way will suffice.
|
||||
|
||||
```
|
||||
mkdir build # make a build dir so that you can build out of tree.
|
||||
cd build
|
||||
cmake -DUSE_TLS=1 ..
|
||||
make -j
|
||||
make install # will install to /usr/local on Unix, on macOS it is a good idea to sudo chown -R `whoami`:staff /usr/local
|
||||
```
|
||||
|
||||
Headers and a static library will be installed to the target dir.
|
||||
There is a unittest which can be executed by typing `make test`.
|
||||
|
||||
Options for building:
|
||||
|
||||
* `-DUSE_TLS=1` will enable TLS support
|
||||
* `-DUSE_MBED_TLS=1` will use [mbedlts](https://tls.mbed.org/) for the TLS support (default on Windows)
|
||||
* `-DUSE_WS=1` will build the ws interactive command line tool
|
||||
|
||||
### vcpkg
|
||||
|
||||
It is possible to get IXWebSocket through Microsoft [vcpkg](https://github.com/microsoft/vcpkg).
|
||||
|
||||
```
|
||||
vcpkg install ixwebsocket
|
||||
```
|
||||
|
||||
### Conan
|
||||
|
||||
Support for building with conan was contributed by Olivia Zoe (thanks !). The package name to reference is `IXWebSocket/5.0.0@LunarWatcher/stable`. The package is in the process to be published to the official conan package repo, but in the meantime, it can be accessed by adding a new remote
|
||||
|
||||
```
|
||||
conan remote add remote_name_here https://api.bintray.com/conan/oliviazoe0/conan-packages
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
There is a Dockerfile for running the unittest on Linux, and to run the `ws` tool. It is also available on the docker registry.
|
||||
|
||||
```
|
||||
docker run bsergean/ws
|
||||
```
|
||||
|
||||
To use docker-compose you must make a docker container first.
|
||||
|
||||
```
|
||||
$ make docker
|
||||
...
|
||||
$ docker compose up &
|
||||
...
|
||||
$ docker exec -it ixwebsocket_ws_1 bash
|
||||
app@ca2340eb9106:~$ ws --help
|
||||
ws is a websocket tool
|
||||
...
|
||||
```
|
||||
|
||||
|
||||
|
77
docs/design.md
Normal file
77
docs/design.md
Normal file
@ -0,0 +1,77 @@
|
||||
## Implementation details
|
||||
|
||||
### Per Message Deflate compression.
|
||||
|
||||
The per message deflate compression option is supported. It can lead to very nice bandbwith savings (20x !) if your messages are similar, which is often the case for example for chat applications. All features of the spec should be supported.
|
||||
|
||||
### TLS/SSL
|
||||
|
||||
Connections can be optionally secured and encrypted with TLS/SSL when using a wss:// endpoint, or using normal un-encrypted socket with ws:// endpoints. AppleSSL is used on iOS and macOS, OpenSSL is used on Android and Linux, mbedTLS is used on Windows.
|
||||
|
||||
### Polling and background thread work
|
||||
|
||||
No manual polling to fetch data is required. Data is sent and received instantly by using a background thread for receiving data and the select [system](http://man7.org/linux/man-pages/man2/select.2.html) call to be notified by the OS of incoming data. No timeout is used for select so that the background thread is only woken up when data is available, to optimize battery life. This is also the recommended way of using select according to the select tutorial, section [select law](https://linux.die.net/man/2/select_tut). Read and Writes to the socket are non blocking. Data is sent right away and not enqueued by writing directly to the socket, which is [possible](https://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid) since system socket implementations allow concurrent read/writes. However concurrent writes need to be protected with mutex.
|
||||
|
||||
### Automatic reconnection
|
||||
|
||||
If the remote end (server) breaks the connection, the code will try to perpetually reconnect, by using an exponential backoff strategy, capped at one retry every 10 seconds. This behavior can be disabled.
|
||||
|
||||
### Large messages
|
||||
|
||||
Large frames are broken up into smaller chunks or messages to avoid filling up the os tcp buffers, which is permitted thanks to WebSocket [fragmentation](https://tools.ietf.org/html/rfc6455#section-5.4). Messages up to 1G were sent and received succesfully.
|
||||
|
||||
### Testing
|
||||
|
||||
The library has an interactive tool which is handy for testing compatibility ith other libraries. We have tested our client against Python, Erlang, Node.js, and C++ websocket server libraries.
|
||||
|
||||
The unittest tries to be comprehensive, and has been running on multiple platoform, with different sanitizers such as thread sanitizer to catch data races or the undefined behavior sanitizer.
|
||||
|
||||
The regression test is running after each commit on travis.
|
||||
|
||||
## Limitations
|
||||
|
||||
* On Windows TLS is not setup yet to validate certificates.
|
||||
* There is no convenient way to embed a ca cert.
|
||||
* Automatic reconnection works at the TCP socket level, and will detect remote end disconnects. However, if the device/computer network become unreachable (by turning off wifi), it is quite hard to reliably and timely detect it at the socket level using `recv` and `send` error codes. [Here](https://stackoverflow.com/questions/14782143/linux-socket-how-to-detect-disconnected-network-in-a-client-program) is a good discussion on the subject. This behavior is consistent with other runtimes such as node.js. One way to detect a disconnected device with low level C code is to do a name resolution with DNS but this can be expensive. Mobile devices have good and reliable API to do that.
|
||||
* The server code is using select to detect incoming data, and creates one OS thread per connection. This is not as scalable as strategies using epoll or kqueue.
|
||||
|
||||
## C++ code organization
|
||||
|
||||
Here is a simplistic diagram which explains how the code is structured in term of class/modules.
|
||||
|
||||
```
|
||||
+-----------------------+ --- Public
|
||||
| | Start the receiving Background thread. Auto reconnection. Simple websocket Ping.
|
||||
| IXWebSocket | Interface used by C++ test clients. No IX dependencies.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocketServer | Run a server and give each connections its own WebSocket object.
|
||||
| | Each connection is handled in a new OS thread.
|
||||
| |
|
||||
+-----------------------+ --- Private
|
||||
| |
|
||||
| IXWebSocketTransport | Low level websocket code, framing, managing raw socket. Adapted from easywsclient.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocketHandshake | Establish the connection between client and server.
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXWebSocket | ws:// Unencrypted Socket handler
|
||||
| IXWebSocketAppleSSL | wss:// TLS encrypted Socket AppleSSL handler. Used on iOS and macOS
|
||||
| IXWebSocketOpenSSL | wss:// TLS encrypted Socket OpenSSL handler. Used on Android and Linux
|
||||
| | Can be used on macOS too.
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXSocketConnect | Connect to the remote host (client).
|
||||
| |
|
||||
+-----------------------+
|
||||
| |
|
||||
| IXDNSLookup | Does DNS resolution asynchronously so that it can be interrupted.
|
||||
| |
|
||||
+-----------------------+
|
||||
```
|
||||
|
||||
|
46
docs/index.md
Normal file
46
docs/index.md
Normal file
@ -0,0 +1,46 @@
|
||||

|
||||
|
||||
## Introduction
|
||||
|
||||
[*WebSocket*](https://en.wikipedia.org/wiki/WebSocket) is a computer communications protocol, providing full-duplex and bi-directionnal communication channels over a single TCP connection. *IXWebSocket* is a C++ library for client and server Websocket communication, and for client and server HTTP communication. *TLS* aka *SSL* is supported. The code is derived from [easywsclient](https://github.com/dhbaird/easywsclient) and from the [Satori C SDK](https://github.com/satori-com/satori-rtm-sdk-c). It has been tested on the following platforms.
|
||||
|
||||
* macOS
|
||||
* iOS
|
||||
* Linux
|
||||
* Android
|
||||
* Windows
|
||||
|
||||
## Example code
|
||||
|
||||
```
|
||||
# Required on Windows
|
||||
ix::initNetSystem();
|
||||
|
||||
# Our websocket object
|
||||
ix::WebSocket webSocket;
|
||||
|
||||
std::string url("ws://localhost:8080/");
|
||||
webSocket.setUrl(url);
|
||||
|
||||
// Setup a callback to be fired when a message or an event (open, close, error) is received
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
std::cout << msg->str << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Now that our callback is setup, we can start our background thread and receive messages
|
||||
webSocket.start();
|
||||
|
||||
// Send a message to the server (default to TEXT mode)
|
||||
webSocket.send("hello world");
|
||||
```
|
||||
|
||||
## Why another library ?
|
||||
|
||||
There are 2 main reasons that explain why IXWebSocket got written. First, we needed a C++ cross-platform client library, which should have few dependencies. What looked like the most solid one, [websocketpp](https://github.com/zaphoyd/websocketpp) did depend on boost and this was not an option for us. Secondly, there were other available libraries with fewer dependencies (C ones), but they required calling an explicit poll routine periodically to know if a client had received data from a server, which was not elegant.
|
||||
|
||||
We started by solving those 2 problems, then we added server websocket code, then an HTTP client, and finally a very simple HTTP server.
|
418
docs/usage.md
Normal file
418
docs/usage.md
Normal file
@ -0,0 +1,418 @@
|
||||
# Examples
|
||||
|
||||
The [*ws*](https://github.com/machinezone/IXWebSocket/tree/master/ws) folder countains many interactive programs for chat, [file transfers](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_send.cpp), [curl like](https://github.com/machinezone/IXWebSocket/blob/master/ws/ws_http_client.cpp) http clients, demonstrating client and server usage.
|
||||
|
||||
## Windows note
|
||||
|
||||
To use the network system on Windows, you need to initialize it once with *WSAStartup()* and clean it up with *WSACleanup()*. We have helpers for that which you can use, see below. This init would typically take place in your main function.
|
||||
|
||||
```
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
ix::initNetSystem();
|
||||
|
||||
...
|
||||
|
||||
ix::uninitNetSystem();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## WebSocket client API
|
||||
|
||||
```
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
|
||||
...
|
||||
|
||||
# Our websocket object
|
||||
ix::WebSocket webSocket;
|
||||
|
||||
std::string url("ws://localhost:8080/");
|
||||
webSocket.setUrl(url);
|
||||
|
||||
// Optional heart beat, sent every 45 seconds when there is not any traffic
|
||||
// to make sure that load balancers do not kill an idle connection.
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
|
||||
// Per message deflate connection is enabled by default. You can tweak its parameters or disable it
|
||||
webSocket.disablePerMessageDeflate();
|
||||
|
||||
// Setup a callback to be fired when a message or an event (open, close, error) is received
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
std::cout << msg->str << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Now that our callback is setup, we can start our background thread and receive messages
|
||||
webSocket.start();
|
||||
|
||||
// Send a message to the server (default to TEXT mode)
|
||||
webSocket.send("hello world");
|
||||
|
||||
// The message can be sent in BINARY mode (useful if you send MsgPack data for example)
|
||||
webSocket.sendBinary("some serialized binary data");
|
||||
|
||||
// ... finally ...
|
||||
|
||||
// Stop the connection
|
||||
webSocket.stop()
|
||||
```
|
||||
|
||||
### Sending messages
|
||||
|
||||
`websocket.send("foo")` will send a message.
|
||||
|
||||
If the connection was closed and sending failed, the return value will be set to false.
|
||||
|
||||
### ReadyState
|
||||
|
||||
`getReadyState()` returns the state of the connection. There are 4 possible states.
|
||||
|
||||
1. ReadyState::Connecting - The connection is not yet open.
|
||||
2. ReadyState::Open - The connection is open and ready to communicate.
|
||||
3. ReadyState::Closing - The connection is in the process of closing.
|
||||
4. ReadyState::Closed - The connection is closed or could not be opened.
|
||||
|
||||
### Open and Close notifications
|
||||
|
||||
The onMessage event will be fired when the connection is opened or closed. This is similar to the [Javascript browser API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket), which has `open` and `close` events notification that can be registered with the browser `addEventListener`.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cout << "send greetings" << std::endl;
|
||||
|
||||
// Headers can be inspected (pairs of string/string)
|
||||
std::cout << "Handshake Headers:" << std::endl;
|
||||
for (auto it : msg->headers)
|
||||
{
|
||||
std::cout << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::cout << "disconnected" << std::endl;
|
||||
|
||||
// The server can send an explicit code and reason for closing.
|
||||
// This data can be accessed through the closeInfo object.
|
||||
std::cout << msg->closeInfo.code << std::endl;
|
||||
std::cout << msg->closeInfo.reason << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Error notification
|
||||
|
||||
A message will be fired when there is an error with the connection. The message type will be `ix::WebSocketMessageType::Error`. Multiple fields will be available on the event to describe the error.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Error: " << msg->errorInfo.reason << std::endl;
|
||||
ss << "#retries: " << msg->eventInfo.retries << std::endl;
|
||||
ss << "Wait time(ms): " << msg->eventInfo.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << msg->eventInfo.http_status << std::endl;
|
||||
std::cout << ss.str() << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### start, stop
|
||||
|
||||
1. `websocket.start()` connect to the remote server and starts the message receiving background thread.
|
||||
2. `websocket.stop()` disconnect from the remote server and closes the background thread.
|
||||
|
||||
### Configuring the remote url
|
||||
|
||||
The url can be set and queried after a websocket object has been created. You will have to call `stop` and `start` if you want to disconnect and connect to that new url.
|
||||
|
||||
```
|
||||
std::string url("wss://example.com");
|
||||
websocket.configure(url);
|
||||
```
|
||||
|
||||
### Ping/Pong support
|
||||
|
||||
Ping/pong messages are used to implement keep-alive. 2 message types exists to identify ping and pong messages. Note that when a ping message is received, a pong is instantly send back as requested by the WebSocket spec.
|
||||
|
||||
```
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Ping ||
|
||||
msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
std::cout << "pong data: " << msg->str << std::endl;
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
A ping message can be sent to the server, with an optional data string.
|
||||
|
||||
```
|
||||
websocket.ping("ping data, optional (empty string is ok): limited to 125 bytes long");
|
||||
```
|
||||
|
||||
### Heartbeat.
|
||||
|
||||
You can configure an optional heart beat / keep-alive, sent every 45 seconds
|
||||
when there is no any traffic to make sure that load balancers do not kill an
|
||||
idle connection.
|
||||
|
||||
```
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
```
|
||||
|
||||
### Supply extra HTTP headers.
|
||||
|
||||
You can set extra HTTP headers to be sent during the WebSocket handshake.
|
||||
|
||||
```
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["foo"] = "bar";
|
||||
webSocket.setExtraHeaders(headers);
|
||||
```
|
||||
|
||||
### Automatic reconnection
|
||||
|
||||
Automatic reconnection kicks in when the connection is disconnected without the user consent. This feature is on by default and can be turned off.
|
||||
|
||||
```
|
||||
webSocket.enableAutomaticReconnection(); // turn on
|
||||
webSocket.disableAutomaticReconnection(); // turn off
|
||||
bool enabled = webSocket.isAutomaticReconnectionEnabled(); // query state
|
||||
```
|
||||
|
||||
The technique to calculate wait time is called [exponential
|
||||
backoff](https://docs.aws.amazon.com/general/latest/gr/api-retries.html). Here
|
||||
are the default waiting times between attempts (from connecting with `ws connect ws://foo.com`)
|
||||
|
||||
```
|
||||
> Connection error: Got bad status connecting to foo.com, status: 301, HTTP Status line: HTTP/1.1 301 Moved Permanently
|
||||
|
||||
#retries: 1
|
||||
Wait time(ms): 100
|
||||
#retries: 2
|
||||
Wait time(ms): 200
|
||||
#retries: 3
|
||||
Wait time(ms): 400
|
||||
#retries: 4
|
||||
Wait time(ms): 800
|
||||
#retries: 5
|
||||
Wait time(ms): 1600
|
||||
#retries: 6
|
||||
Wait time(ms): 3200
|
||||
#retries: 7
|
||||
Wait time(ms): 6400
|
||||
#retries: 8
|
||||
Wait time(ms): 10000
|
||||
```
|
||||
|
||||
The waiting time is capped by default at 10s between 2 attempts, but that value can be changed and queried.
|
||||
|
||||
```
|
||||
webSocket.setMaxWaitBetweenReconnectionRetries(5 * 1000); // 5000ms = 5s
|
||||
uint32_t m = webSocket.getMaxWaitBetweenReconnectionRetries();
|
||||
```
|
||||
|
||||
## WebSocket server API
|
||||
|
||||
```
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
|
||||
...
|
||||
|
||||
// Run a server on localhost at a given port.
|
||||
// Bound host name, max connections and listen backlog can also be passed in as parameters.
|
||||
ix::WebSocketServer server(port);
|
||||
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](const ix::WebSocketMessagePtr msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cerr << "New connection" << std::endl;
|
||||
|
||||
// A connection state object is available, and has a default id
|
||||
// You can subclass ConnectionState and pass an alternate factory
|
||||
// to override it. It is useful if you want to store custom
|
||||
// attributes per connection (authenticated bool flag, attributes, etc...)
|
||||
std::cerr << "id: " << connectionState->getId() << std::endl;
|
||||
|
||||
// The uri the client did connect to.
|
||||
std::cerr << "Uri: " << msg->openInfo.uri << std::endl;
|
||||
|
||||
std::cerr << "Headers:" << std::endl;
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
std::cerr << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// For an echo server, we just send back to the client whatever was received by the server
|
||||
// All connected clients are available in an std::set. See the broadcast cpp example.
|
||||
// Second parameter tells whether we are sending the message in binary or text mode.
|
||||
// Here we send it in the same mode as it was received.
|
||||
webSocket->send(msg->str, msg->binary);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
// Error handling
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Run the server in the background. Server can be stoped by calling server.stop()
|
||||
server.start();
|
||||
|
||||
// Block until server.stop() is called.
|
||||
server.wait();
|
||||
|
||||
```
|
||||
|
||||
## HTTP client API
|
||||
|
||||
```
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
|
||||
...
|
||||
|
||||
//
|
||||
// Preparation
|
||||
//
|
||||
HttpClient httpClient;
|
||||
HttpRequestArgsPtr args = httpClient.createRequest();
|
||||
|
||||
// Custom headers can be set
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["Foo"] = "bar";
|
||||
args->extraHeaders = headers;
|
||||
|
||||
// Timeout options
|
||||
args->connectTimeout = connectTimeout;
|
||||
args->transferTimeout = transferTimeout;
|
||||
|
||||
// Redirect options
|
||||
args->followRedirects = followRedirects;
|
||||
args->maxRedirects = maxRedirects;
|
||||
|
||||
// Misc
|
||||
args->compress = compress; // Enable gzip compression
|
||||
args->verbose = verbose;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
|
||||
//
|
||||
// Synchronous Request
|
||||
//
|
||||
HttpResponsePtr out;
|
||||
std::string url = "https://www.google.com";
|
||||
|
||||
// HEAD request
|
||||
out = httpClient.head(url, args);
|
||||
|
||||
// GET request
|
||||
out = httpClient.get(url, args);
|
||||
|
||||
// POST request with parameters
|
||||
HttpParameters httpParameters;
|
||||
httpParameters["foo"] = "bar";
|
||||
out = httpClient.post(url, httpParameters, args);
|
||||
|
||||
// POST request with a body
|
||||
out = httpClient.post(url, std::string("foo=bar"), args);
|
||||
|
||||
//
|
||||
// Result
|
||||
//
|
||||
auto statusCode = response->statusCode; // Can be HttpErrorCode::Ok, HttpErrorCode::UrlMalformed, etc...
|
||||
auto errorCode = response->errorCode; // 200, 404, etc...
|
||||
auto responseHeaders = response->headers; // All the headers in a special case-insensitive unordered_map of (string, string)
|
||||
auto payload = response->payload; // All the bytes from the response as an std::string
|
||||
auto errorMsg = response->errorMsg; // Descriptive error message in case of failure
|
||||
auto uploadSize = response->uploadSize; // Byte count of uploaded data
|
||||
auto downloadSize = response->downloadSize; // Byte count of downloaded data
|
||||
|
||||
//
|
||||
// Asynchronous Request
|
||||
//
|
||||
bool async = true;
|
||||
HttpClient httpClient(async);
|
||||
auto args = httpClient.createRequest(url, HttpClient::kGet);
|
||||
|
||||
// Push the request to a queue,
|
||||
bool ok = httpClient.performRequest(args, [](const HttpResponsePtr& response)
|
||||
{
|
||||
// This callback execute in a background thread. Make sure you uses appropriate protection such as mutex
|
||||
auto statusCode = response->statusCode; // acess results
|
||||
}
|
||||
);
|
||||
|
||||
// ok will be false if your httpClient is not async
|
||||
```
|
||||
|
||||
## HTTP server API
|
||||
|
||||
```
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
|
||||
ix::HttpServer server(port, hostname);
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
std::cerr << res.second << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
server.start();
|
||||
server.wait();
|
||||
```
|
||||
|
||||
If you want to handle how requests are processed, implement the setOnConnectionCallback callback, which takes an HttpRequestPtr as input, and returns an HttpResponsePtr. You can look at HttpServer::setDefaultConnectionCallback for a slightly more advanced callback example.
|
||||
|
||||
```
|
||||
setOnConnectionCallback(
|
||||
[this](HttpRequestPtr request,
|
||||
std::shared_ptr<ConnectionState> /*connectionState*/) -> HttpResponsePtr
|
||||
{
|
||||
// Build a string for the response
|
||||
std::stringstream ss;
|
||||
ss << request->method
|
||||
<< " "
|
||||
<< request->uri;
|
||||
|
||||
std::string content = ss.str();
|
||||
|
||||
return std::make_shared<HttpResponse>(200, "OK",
|
||||
HttpErrorCode::Ok,
|
||||
WebSocketHttpHeaders(),
|
||||
content);
|
||||
}
|
||||
```
|
73
docs/ws.md
Normal file
73
docs/ws.md
Normal file
@ -0,0 +1,73 @@
|
||||
## General
|
||||
|
||||
ws is a command line tool that should exercise most of the IXWebSocket code, and provide example code.
|
||||
|
||||
```
|
||||
ws is a websocket tool
|
||||
Usage: ws [OPTIONS] SUBCOMMAND
|
||||
|
||||
Options:
|
||||
-h,--help Print this help message and exit
|
||||
|
||||
Subcommands:
|
||||
send Send a file
|
||||
receive Receive a file
|
||||
transfer Broadcasting server
|
||||
connect Connect to a remote server
|
||||
chat Group chat
|
||||
echo_server Echo server
|
||||
broadcast_server Broadcasting server
|
||||
ping Ping pong
|
||||
curl HTTP Client
|
||||
redis_publish Redis publisher
|
||||
redis_subscribe Redis subscriber
|
||||
cobra_subscribe Cobra subscriber
|
||||
cobra_publish Cobra publisher
|
||||
cobra_to_statsd Cobra to statsd
|
||||
cobra_to_sentry Cobra to sentry
|
||||
snake Snake server
|
||||
httpd HTTP server
|
||||
```
|
||||
|
||||
## File transfer
|
||||
|
||||
```
|
||||
# Start transfer server, which is just a broadcast server at this point
|
||||
ws transfer # running on port 8080.
|
||||
|
||||
# Start receiver first
|
||||
ws receive ws://localhost:8080
|
||||
|
||||
# Then send a file. File will be received and written to disk by the receiver process
|
||||
ws send ws://localhost:8080 /file/to/path
|
||||
```
|
||||
|
||||
## HTTP Client
|
||||
|
||||
```
|
||||
$ ws curl --help
|
||||
HTTP Client
|
||||
Usage: ws curl [OPTIONS] url
|
||||
|
||||
Positionals:
|
||||
url TEXT REQUIRED Connection url
|
||||
|
||||
Options:
|
||||
-h,--help Print this help message and exit
|
||||
-d TEXT Form data
|
||||
-F TEXT Form data
|
||||
-H TEXT Header
|
||||
--output TEXT Output file
|
||||
-I Send a HEAD request
|
||||
-L Follow redirects
|
||||
--max-redirects INT Max Redirects
|
||||
-v Verbose
|
||||
-O Save output to disk
|
||||
--compress Enable gzip compression
|
||||
--connect-timeout INT Connection timeout
|
||||
--transfer-timeout INT Transfer timeout
|
||||
```
|
||||
|
||||
## Cobra Client
|
||||
|
||||
[cobra](https://github.com/machinezone/cobra) is a real time messenging server. ws has sub-command to interacti with cobra.
|
@ -9,30 +9,20 @@
|
||||
|
||||
#include <string.h>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
const int64_t DNSLookup::kDefaultWait = 10; // ms
|
||||
|
||||
std::atomic<uint64_t> DNSLookup::_nextId(0);
|
||||
std::set<uint64_t> DNSLookup::_activeJobs;
|
||||
std::mutex DNSLookup::_activeJobsMutex;
|
||||
const int64_t DNSLookup::kDefaultWait = 1; // ms
|
||||
|
||||
DNSLookup::DNSLookup(const std::string& hostname, int port, int64_t wait) :
|
||||
_hostname(hostname),
|
||||
_port(port),
|
||||
_wait(wait),
|
||||
_res(nullptr),
|
||||
_done(false),
|
||||
_id(_nextId++)
|
||||
_done(false)
|
||||
{
|
||||
setHostname(hostname);
|
||||
}
|
||||
|
||||
DNSLookup::~DNSLookup()
|
||||
{
|
||||
// Remove this job from the active jobs list
|
||||
std::lock_guard<std::mutex> lock(_activeJobsMutex);
|
||||
_activeJobs.erase(_id);
|
||||
;
|
||||
}
|
||||
|
||||
struct addrinfo* DNSLookup::getAddrInfo(const std::string& hostname,
|
||||
@ -60,14 +50,14 @@ namespace ix
|
||||
|
||||
struct addrinfo* DNSLookup::resolve(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested,
|
||||
bool blocking)
|
||||
bool cancellable)
|
||||
{
|
||||
return blocking ? resolveBlocking(errMsg, isCancellationRequested)
|
||||
: resolveAsync(errMsg, isCancellationRequested);
|
||||
return cancellable ? resolveCancellable(errMsg, isCancellationRequested)
|
||||
: resolveUnCancellable(errMsg, isCancellationRequested);
|
||||
}
|
||||
|
||||
struct addrinfo* DNSLookup::resolveBlocking(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
struct addrinfo* DNSLookup::resolveUnCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
errMsg = "no error";
|
||||
|
||||
@ -78,11 +68,11 @@ namespace ix
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return getAddrInfo(getHostname(), _port, errMsg);
|
||||
return getAddrInfo(_hostname, _port, errMsg);
|
||||
}
|
||||
|
||||
struct addrinfo* DNSLookup::resolveAsync(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
struct addrinfo* DNSLookup::resolveCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
errMsg = "no error";
|
||||
|
||||
@ -94,30 +84,28 @@ namespace ix
|
||||
// if you need a second lookup.
|
||||
}
|
||||
|
||||
// Record job in the active Job set
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_activeJobsMutex);
|
||||
_activeJobs.insert(_id);
|
||||
}
|
||||
|
||||
//
|
||||
// Good resource on thread forced termination
|
||||
// https://www.bo-yang.net/2017/11/19/cpp-kill-detached-thread
|
||||
//
|
||||
_thread = std::thread(&DNSLookup::run, this, _id, getHostname(), _port);
|
||||
_thread.detach();
|
||||
auto ptr = shared_from_this();
|
||||
std::weak_ptr<DNSLookup> self(ptr);
|
||||
|
||||
std::unique_lock<std::mutex> lock(_conditionVariableMutex);
|
||||
int port = _port;
|
||||
std::string hostname(_hostname);
|
||||
|
||||
// We make the background thread doing the work a shared pointer
|
||||
// instead of a member variable, because it can keep running when
|
||||
// this object goes out of scope, in case of cancellation
|
||||
auto t = std::make_shared<std::thread>(&DNSLookup::run, this, self, hostname, port);
|
||||
t->detach();
|
||||
|
||||
while (!_done)
|
||||
{
|
||||
// Wait for 10 milliseconds on the condition variable, to see
|
||||
// if the bg thread has terminated.
|
||||
if (_condition.wait_for(lock, std::chrono::milliseconds(_wait)) == std::cv_status::no_timeout)
|
||||
{
|
||||
// Background thread has terminated, so we can break of this loop
|
||||
break;
|
||||
}
|
||||
// Wait for 1 milliseconds, to see if the bg thread has terminated.
|
||||
// We do not use a condition variable to wait, as destroying this one
|
||||
// if the bg thread is alive can cause undefined behavior.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(_wait));
|
||||
|
||||
// Were we cancelled ?
|
||||
if (isCancellationRequested && isCancellationRequested())
|
||||
@ -138,7 +126,7 @@ namespace ix
|
||||
return getRes();
|
||||
}
|
||||
|
||||
void DNSLookup::run(uint64_t id, const std::string& hostname, int port) // thread runner
|
||||
void DNSLookup::run(std::weak_ptr<DNSLookup> self, std::string hostname, int port) // thread runner
|
||||
{
|
||||
// We don't want to read or write into members variables of an object that could be
|
||||
// gone, so we use temporary variables (res) or we pass in by copy everything that
|
||||
@ -146,33 +134,14 @@ namespace ix
|
||||
std::string errMsg;
|
||||
struct addrinfo* res = getAddrInfo(hostname, port, errMsg);
|
||||
|
||||
// if this isn't an active job, and the control thread is gone
|
||||
// there is nothing to do, and we don't want to touch the defunct
|
||||
// object data structure such as _errMsg or _condition
|
||||
std::lock_guard<std::mutex> lock(_activeJobsMutex);
|
||||
if (_activeJobs.count(id) == 0)
|
||||
if (self.lock())
|
||||
{
|
||||
return;
|
||||
// Copy result into the member variables
|
||||
setRes(res);
|
||||
setErrMsg(errMsg);
|
||||
|
||||
_done = true;
|
||||
}
|
||||
|
||||
// Copy result into the member variables
|
||||
setRes(res);
|
||||
setErrMsg(errMsg);
|
||||
|
||||
_condition.notify_one();
|
||||
_done = true;
|
||||
}
|
||||
|
||||
void DNSLookup::setHostname(const std::string& hostname)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_hostnameMutex);
|
||||
_hostname = hostname;
|
||||
}
|
||||
|
||||
const std::string& DNSLookup::getHostname()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_hostnameMutex);
|
||||
return _hostname;
|
||||
}
|
||||
|
||||
void DNSLookup::setErrMsg(const std::string& errMsg)
|
||||
|
@ -12,39 +12,36 @@
|
||||
|
||||
#include "IXCancellationRequest.h"
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
struct addrinfo;
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class DNSLookup
|
||||
class DNSLookup : public std::enable_shared_from_this<DNSLookup>
|
||||
{
|
||||
public:
|
||||
DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
|
||||
~DNSLookup();
|
||||
~DNSLookup() = default;
|
||||
|
||||
struct addrinfo* resolve(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested,
|
||||
bool blocking = false);
|
||||
bool cancellable = true);
|
||||
|
||||
private:
|
||||
struct addrinfo* resolveAsync(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveBlocking(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveUnCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
|
||||
static struct addrinfo* getAddrInfo(const std::string& hostname,
|
||||
int port,
|
||||
std::string& errMsg);
|
||||
|
||||
void run(uint64_t id, const std::string& hostname, int port); // thread runner
|
||||
|
||||
void setHostname(const std::string& hostname);
|
||||
const std::string& getHostname();
|
||||
void run(std::weak_ptr<DNSLookup> self, std::string hostname, int port); // thread runner
|
||||
|
||||
void setErrMsg(const std::string& errMsg);
|
||||
const std::string& getErrMsg();
|
||||
@ -53,10 +50,9 @@ namespace ix
|
||||
struct addrinfo* getRes();
|
||||
|
||||
std::string _hostname;
|
||||
std::mutex _hostnameMutex;
|
||||
int _port;
|
||||
|
||||
int64_t _wait;
|
||||
const static int64_t kDefaultWait;
|
||||
|
||||
struct addrinfo* _res;
|
||||
std::mutex _resMutex;
|
||||
@ -65,15 +61,5 @@ namespace ix
|
||||
std::mutex _errMsgMutex;
|
||||
|
||||
std::atomic<bool> _done;
|
||||
std::thread _thread;
|
||||
std::condition_variable _condition;
|
||||
std::mutex _conditionVariableMutex;
|
||||
|
||||
uint64_t _id;
|
||||
static std::atomic<uint64_t> _nextId;
|
||||
static std::set<uint64_t> _activeJobs;
|
||||
static std::mutex _activeJobsMutex;
|
||||
|
||||
const static int64_t kDefaultWait;
|
||||
};
|
||||
} // namespace ix
|
||||
|
26
ixwebsocket/IXExponentialBackoff.cpp
Normal file
26
ixwebsocket/IXExponentialBackoff.cpp
Normal file
@ -0,0 +1,26 @@
|
||||
/*
|
||||
* IXExponentialBackoff.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXExponentialBackoff.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
uint32_t calculateRetryWaitMilliseconds(
|
||||
uint32_t retry_count,
|
||||
uint32_t maxWaitBetweenReconnectionRetries)
|
||||
{
|
||||
uint32_t wait_time = std::pow(2, retry_count) * 100;
|
||||
|
||||
if (wait_time > maxWaitBetweenReconnectionRetries || wait_time == 0)
|
||||
{
|
||||
wait_time = maxWaitBetweenReconnectionRetries;
|
||||
}
|
||||
|
||||
return wait_time;
|
||||
}
|
||||
}
|
16
ixwebsocket/IXExponentialBackoff.h
Normal file
16
ixwebsocket/IXExponentialBackoff.h
Normal file
@ -0,0 +1,16 @@
|
||||
/*
|
||||
* IXExponentialBackoff.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
uint32_t calculateRetryWaitMilliseconds(
|
||||
uint32_t retry_count,
|
||||
uint32_t maxWaitBetweenReconnectionRetries);
|
||||
} // namespace ix
|
138
ixwebsocket/IXHttp.cpp
Normal file
138
ixwebsocket/IXHttp.cpp
Normal file
@ -0,0 +1,138 @@
|
||||
/*
|
||||
* IXHttp.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXHttp.h"
|
||||
#include "IXCancellationRequest.h"
|
||||
#include "IXSocket.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::string Http::trim(const std::string& str)
|
||||
{
|
||||
std::string out;
|
||||
for (auto c : str)
|
||||
{
|
||||
if (c != ' ' && c != '\n' && c != '\r')
|
||||
{
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
std::tuple<std::string, std::string, std::string> Http::parseRequestLine(const std::string& line)
|
||||
{
|
||||
// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
|
||||
std::string token;
|
||||
std::stringstream tokenStream(line);
|
||||
std::vector<std::string> tokens;
|
||||
|
||||
// Split by ' '
|
||||
while (std::getline(tokenStream, token, ' '))
|
||||
{
|
||||
tokens.push_back(token);
|
||||
}
|
||||
|
||||
std::string method;
|
||||
if (tokens.size() >= 1)
|
||||
{
|
||||
method = trim(tokens[0]);
|
||||
}
|
||||
|
||||
std::string requestUri;
|
||||
if (tokens.size() >= 2)
|
||||
{
|
||||
requestUri = trim(tokens[1]);
|
||||
}
|
||||
|
||||
std::string httpVersion;
|
||||
if (tokens.size() >= 3)
|
||||
{
|
||||
httpVersion = trim(tokens[2]);
|
||||
}
|
||||
|
||||
return std::make_tuple(method, requestUri, httpVersion);
|
||||
}
|
||||
|
||||
std::tuple<bool, std::string, HttpRequestPtr> Http::parseRequest(std::shared_ptr<Socket> socket)
|
||||
{
|
||||
HttpRequestPtr httpRequest;
|
||||
|
||||
std::atomic<bool> requestInitCancellation(false);
|
||||
|
||||
int timeoutSecs = 5; // FIXME
|
||||
|
||||
auto isCancellationRequested =
|
||||
makeCancellationRequestWithTimeout(timeoutSecs, requestInitCancellation);
|
||||
|
||||
// Read first line
|
||||
auto lineResult = socket->readLine(isCancellationRequested);
|
||||
auto lineValid = lineResult.first;
|
||||
auto line = lineResult.second;
|
||||
|
||||
if (!lineValid)
|
||||
{
|
||||
return std::make_tuple(false, "Error reading HTTP request line", httpRequest);
|
||||
}
|
||||
|
||||
// Parse request line (GET /foo HTTP/1.1\r\n)
|
||||
auto requestLine = Http::parseRequestLine(line);
|
||||
auto method = std::get<0>(requestLine);
|
||||
auto uri = std::get<1>(requestLine);
|
||||
auto httpVersion = std::get<2>(requestLine);
|
||||
|
||||
// Retrieve and validate HTTP headers
|
||||
auto result = parseHttpHeaders(socket, isCancellationRequested);
|
||||
auto headersValid = result.first;
|
||||
auto headers = result.second;
|
||||
|
||||
if (!headersValid)
|
||||
{
|
||||
return std::make_tuple(false, "Error parsing HTTP headers", httpRequest);
|
||||
}
|
||||
|
||||
httpRequest = std::make_shared<HttpRequest>(uri, method, httpVersion, headers);
|
||||
return std::make_tuple(true, "", httpRequest);
|
||||
}
|
||||
|
||||
bool Http::sendResponse(HttpResponsePtr response, std::shared_ptr<Socket> socket)
|
||||
{
|
||||
// Write the response to the socket
|
||||
std::stringstream ss;
|
||||
ss << "HTTP/1.1 ";
|
||||
ss << response->statusCode;
|
||||
ss << " ";
|
||||
ss << response->description;
|
||||
ss << "\r\n";
|
||||
|
||||
if (!socket->writeBytes(ss.str(), nullptr))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Write headers
|
||||
ss.str("");
|
||||
ss << "Content-Length: " << response->payload.size() << "\r\n";
|
||||
for (auto&& it : response->headers)
|
||||
{
|
||||
ss << it.first << ": " << it.second << "\r\n";
|
||||
}
|
||||
ss << "\r\n";
|
||||
|
||||
if (!socket->writeBytes(ss.str(), nullptr))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return response->payload.empty()
|
||||
? true
|
||||
: socket->writeBytes(response->payload, nullptr);
|
||||
}
|
||||
}
|
122
ixwebsocket/IXHttp.h
Normal file
122
ixwebsocket/IXHttp.h
Normal file
@ -0,0 +1,122 @@
|
||||
/*
|
||||
* IXHttp.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXProgressCallback.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include <tuple>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
enum class HttpErrorCode : int
|
||||
{
|
||||
Ok = 0,
|
||||
CannotConnect = 1,
|
||||
Timeout = 2,
|
||||
Gzip = 3,
|
||||
UrlMalformed = 4,
|
||||
CannotCreateSocket = 5,
|
||||
SendError = 6,
|
||||
ReadError = 7,
|
||||
CannotReadStatusLine = 8,
|
||||
MissingStatus = 9,
|
||||
HeaderParsingError = 10,
|
||||
MissingLocation = 11,
|
||||
TooManyRedirects = 12,
|
||||
ChunkReadError = 13,
|
||||
CannotReadBody = 14,
|
||||
Invalid = 100
|
||||
};
|
||||
|
||||
struct HttpResponse
|
||||
{
|
||||
int statusCode;
|
||||
std::string description;
|
||||
HttpErrorCode errorCode;
|
||||
WebSocketHttpHeaders headers;
|
||||
std::string payload;
|
||||
std::string errorMsg;
|
||||
uint64_t uploadSize;
|
||||
uint64_t downloadSize;
|
||||
|
||||
HttpResponse(int s = 0,
|
||||
const std::string& des = std::string(),
|
||||
const HttpErrorCode& c = HttpErrorCode::Ok,
|
||||
const WebSocketHttpHeaders& h = WebSocketHttpHeaders(),
|
||||
const std::string& p = std::string(),
|
||||
const std::string& e = std::string(),
|
||||
uint64_t u = 0,
|
||||
uint64_t d = 0)
|
||||
: statusCode(s)
|
||||
, description(des)
|
||||
, errorCode(c)
|
||||
, headers(h)
|
||||
, payload(p)
|
||||
, errorMsg(e)
|
||||
, uploadSize(u)
|
||||
, downloadSize(d)
|
||||
{
|
||||
;
|
||||
}
|
||||
};
|
||||
|
||||
using HttpResponsePtr = std::shared_ptr<HttpResponse>;
|
||||
using HttpParameters = std::map<std::string, std::string>;
|
||||
using Logger = std::function<void(const std::string&)>;
|
||||
using OnResponseCallback = std::function<void(const HttpResponsePtr&)>;
|
||||
|
||||
struct HttpRequestArgs
|
||||
{
|
||||
std::string url;
|
||||
std::string verb;
|
||||
WebSocketHttpHeaders extraHeaders;
|
||||
std::string body;
|
||||
int connectTimeout;
|
||||
int transferTimeout;
|
||||
bool followRedirects;
|
||||
int maxRedirects;
|
||||
bool verbose;
|
||||
bool compress;
|
||||
Logger logger;
|
||||
OnProgressCallback onProgressCallback;
|
||||
};
|
||||
|
||||
using HttpRequestArgsPtr = std::shared_ptr<HttpRequestArgs>;
|
||||
|
||||
struct HttpRequest
|
||||
{
|
||||
std::string uri;
|
||||
std::string method;
|
||||
std::string version;
|
||||
WebSocketHttpHeaders headers;
|
||||
|
||||
HttpRequest(const std::string& u,
|
||||
const std::string& m,
|
||||
const std::string& v,
|
||||
const WebSocketHttpHeaders& h = WebSocketHttpHeaders())
|
||||
: uri(u)
|
||||
, method(m)
|
||||
, version(v)
|
||||
, headers(h)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
using HttpRequestPtr = std::shared_ptr<HttpRequest>;
|
||||
|
||||
class Http
|
||||
{
|
||||
public:
|
||||
static std::tuple<bool, std::string, HttpRequestPtr> parseRequest(
|
||||
std::shared_ptr<Socket> socket);
|
||||
static bool sendResponse(HttpResponsePtr response, std::shared_ptr<Socket> socket);
|
||||
|
||||
static std::tuple<std::string, std::string, std::string> parseRequestLine(
|
||||
const std::string& line);
|
||||
static std::string trim(const std::string& str);
|
||||
};
|
||||
} // namespace ix
|
@ -6,6 +6,7 @@
|
||||
|
||||
#include "IXHttpClient.h"
|
||||
#include "IXUrlParser.h"
|
||||
#include "IXUserAgent.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include "IXSocketFactory.h"
|
||||
|
||||
@ -14,6 +15,7 @@
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
#include <assert.h>
|
||||
#include <zlib.h>
|
||||
|
||||
namespace ix
|
||||
@ -52,6 +54,8 @@ namespace ix
|
||||
bool HttpClient::performRequest(HttpRequestArgsPtr args,
|
||||
const OnResponseCallback& onResponseCallback)
|
||||
{
|
||||
assert(_async && "HttpClient needs its async parameter set to true "
|
||||
"in order to call performRequest");
|
||||
if (!_async) return false;
|
||||
|
||||
// Enqueue the task
|
||||
@ -118,6 +122,7 @@ namespace ix
|
||||
int code = 0;
|
||||
WebSocketHttpHeaders headers;
|
||||
std::string payload;
|
||||
std::string description;
|
||||
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
@ -126,9 +131,9 @@ namespace ix
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Cannot parse url: " << url;
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::UrlMalformed,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::UrlMalformed,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
bool tls = protocol == "https";
|
||||
@ -137,9 +142,9 @@ namespace ix
|
||||
|
||||
if (!_socket)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::CannotCreateSocket,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::CannotCreateSocket,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Build request string
|
||||
@ -167,7 +172,7 @@ namespace ix
|
||||
// Set a default User agent if none is present
|
||||
if (headers.find("User-Agent") == headers.end())
|
||||
{
|
||||
ss << "User-Agent: ixwebsocket" << "\r\n";
|
||||
ss << "User-Agent: " << userAgent() << "\r\n";
|
||||
}
|
||||
|
||||
if (verb == kPost || verb == kPut)
|
||||
@ -200,7 +205,7 @@ namespace ix
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Cannot connect to url: " << url << " / error : " << errMsg;
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::CannotConnect,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::CannotConnect,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -226,7 +231,7 @@ namespace ix
|
||||
if (!_socket->writeBytes(req, isCancellationRequested))
|
||||
{
|
||||
std::string errorMsg("Cannot send request");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::SendError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::SendError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -240,7 +245,7 @@ namespace ix
|
||||
if (!lineValid)
|
||||
{
|
||||
std::string errorMsg("Cannot retrieve status line");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::CannotReadStatusLine,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::CannotReadStatusLine,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -255,7 +260,7 @@ namespace ix
|
||||
if (sscanf(line.c_str(), "HTTP/1.1 %d", &code) != 1)
|
||||
{
|
||||
std::string errorMsg("Cannot parse response code from status line");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::MissingStatus,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::MissingStatus,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -267,7 +272,7 @@ namespace ix
|
||||
if (!headersValid)
|
||||
{
|
||||
std::string errorMsg("Cannot parse http headers");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::HeaderParsingError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::HeaderParsingError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -278,7 +283,7 @@ namespace ix
|
||||
if (headers.find("Location") == headers.end())
|
||||
{
|
||||
std::string errorMsg("Missing location header for redirect");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::MissingLocation,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::MissingLocation,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -287,7 +292,7 @@ namespace ix
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Too many redirects: " << redirects;
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::TooManyRedirects,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::TooManyRedirects,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -299,7 +304,7 @@ namespace ix
|
||||
|
||||
if (verb == "HEAD")
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::Ok,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::Ok,
|
||||
headers, payload, std::string(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -320,7 +325,7 @@ namespace ix
|
||||
if (!chunkResult.first)
|
||||
{
|
||||
errorMsg = "Cannot read chunk";
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::ChunkReadError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -338,7 +343,7 @@ namespace ix
|
||||
|
||||
if (!lineResult.first)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::ChunkReadError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -365,7 +370,7 @@ namespace ix
|
||||
if (!chunkResult.first)
|
||||
{
|
||||
errorMsg = "Cannot read chunk";
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::ChunkReadError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -376,7 +381,7 @@ namespace ix
|
||||
|
||||
if (!lineResult.first)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::ChunkReadError,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -391,7 +396,7 @@ namespace ix
|
||||
else
|
||||
{
|
||||
std::string errorMsg("Cannot read http body");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::CannotReadBody,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::CannotReadBody,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
@ -405,14 +410,14 @@ namespace ix
|
||||
if (!gzipInflate(payload, decompressedPayload))
|
||||
{
|
||||
std::string errorMsg("Error decompressing payload");
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::Gzip,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::Gzip,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
payload = decompressedPayload;
|
||||
}
|
||||
|
||||
return std::make_shared<HttpResponse>(code, HttpErrorCode::Ok,
|
||||
return std::make_shared<HttpResponse>(code, description, HttpErrorCode::Ok,
|
||||
headers, payload, std::string(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
@ -6,6 +6,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXHttp.h"
|
||||
#include "IXSocket.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include <algorithm>
|
||||
@ -20,78 +21,6 @@
|
||||
|
||||
namespace ix
|
||||
{
|
||||
enum class HttpErrorCode : int
|
||||
{
|
||||
Ok = 0,
|
||||
CannotConnect = 1,
|
||||
Timeout = 2,
|
||||
Gzip = 3,
|
||||
UrlMalformed = 4,
|
||||
CannotCreateSocket = 5,
|
||||
SendError = 6,
|
||||
ReadError = 7,
|
||||
CannotReadStatusLine = 8,
|
||||
MissingStatus = 9,
|
||||
HeaderParsingError = 10,
|
||||
MissingLocation = 11,
|
||||
TooManyRedirects = 12,
|
||||
ChunkReadError = 13,
|
||||
CannotReadBody = 14,
|
||||
Invalid = 100
|
||||
};
|
||||
|
||||
struct HttpResponse
|
||||
{
|
||||
int statusCode;
|
||||
HttpErrorCode errorCode;
|
||||
WebSocketHttpHeaders headers;
|
||||
std::string payload;
|
||||
std::string errorMsg;
|
||||
uint64_t uploadSize;
|
||||
uint64_t downloadSize;
|
||||
|
||||
HttpResponse(int s = 0,
|
||||
const HttpErrorCode& c = HttpErrorCode::Ok,
|
||||
const WebSocketHttpHeaders& h = WebSocketHttpHeaders(),
|
||||
const std::string& p = std::string(),
|
||||
const std::string& e = std::string(),
|
||||
uint64_t u = 0,
|
||||
uint64_t d = 0)
|
||||
: statusCode(s)
|
||||
, errorCode(c)
|
||||
, headers(h)
|
||||
, payload(p)
|
||||
, errorMsg(e)
|
||||
, uploadSize(u)
|
||||
, downloadSize(d)
|
||||
{
|
||||
;
|
||||
}
|
||||
};
|
||||
|
||||
using HttpResponsePtr = std::shared_ptr<HttpResponse>;
|
||||
using HttpParameters = std::map<std::string, std::string>;
|
||||
using Logger = std::function<void(const std::string&)>;
|
||||
using OnResponseCallback = std::function<void(const HttpResponsePtr&)>;
|
||||
|
||||
struct HttpRequestArgs
|
||||
{
|
||||
std::string url;
|
||||
std::string verb;
|
||||
WebSocketHttpHeaders extraHeaders;
|
||||
std::string body;
|
||||
int connectTimeout;
|
||||
int transferTimeout;
|
||||
bool followRedirects;
|
||||
int maxRedirects;
|
||||
bool verbose;
|
||||
bool compress;
|
||||
Logger logger;
|
||||
OnProgressCallback onProgressCallback;
|
||||
};
|
||||
|
||||
using HttpRequestArgsPtr = std::shared_ptr<HttpRequestArgs>;
|
||||
|
||||
class HttpClient
|
||||
{
|
||||
public:
|
||||
|
160
ixwebsocket/IXHttpServer.cpp
Normal file
160
ixwebsocket/IXHttpServer.cpp
Normal file
@ -0,0 +1,160 @@
|
||||
/*
|
||||
* IXHttpServer.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXHttpServer.h"
|
||||
#include "IXSocketConnect.h"
|
||||
#include "IXSocketFactory.h"
|
||||
#include "IXNetSystem.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
std::pair<bool, std::vector<uint8_t>> load(const std::string& path)
|
||||
{
|
||||
std::vector<uint8_t> memblock;
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) return std::make_pair(false, memblock);
|
||||
|
||||
file.seekg(0, file.end);
|
||||
std::streamoff size = file.tellg();
|
||||
file.seekg(0, file.beg);
|
||||
|
||||
memblock.resize((size_t) size);
|
||||
file.read((char*)&memblock.front(), static_cast<std::streamsize>(size));
|
||||
|
||||
return std::make_pair(true, memblock);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> readAsString(const std::string& path)
|
||||
{
|
||||
auto res = load(path);
|
||||
auto vec = res.second;
|
||||
return std::make_pair(res.first, std::string(vec.begin(), vec.end()));
|
||||
}
|
||||
}
|
||||
|
||||
namespace ix
|
||||
{
|
||||
HttpServer::HttpServer(int port,
|
||||
const std::string& host,
|
||||
int backlog,
|
||||
size_t maxConnections) : SocketServer(port, host, backlog, maxConnections),
|
||||
_connectedClientsCount(0)
|
||||
{
|
||||
setDefaultConnectionCallback();
|
||||
}
|
||||
|
||||
HttpServer::~HttpServer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void HttpServer::stop()
|
||||
{
|
||||
stopAcceptingConnections();
|
||||
|
||||
// FIXME: cancelling / closing active clients ...
|
||||
|
||||
SocketServer::stop();
|
||||
}
|
||||
|
||||
void HttpServer::setOnConnectionCallback(const OnConnectionCallback& callback)
|
||||
{
|
||||
_onConnectionCallback = callback;
|
||||
}
|
||||
|
||||
void HttpServer::handleConnection(
|
||||
int fd,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
_connectedClientsCount++;
|
||||
|
||||
std::string errorMsg;
|
||||
auto socket = createSocket(fd, errorMsg);
|
||||
|
||||
// Set the socket to non blocking mode + other tweaks
|
||||
SocketConnect::configure(fd);
|
||||
|
||||
auto ret = Http::parseRequest(socket);
|
||||
// FIXME: handle errors in parseRequest
|
||||
|
||||
if (std::get<0>(ret))
|
||||
{
|
||||
auto response = _onConnectionCallback(std::get<2>(ret), connectionState);
|
||||
if (!Http::sendResponse(response, socket))
|
||||
{
|
||||
logError("Cannot send response");
|
||||
}
|
||||
}
|
||||
connectionState->setTerminated();
|
||||
|
||||
_connectedClientsCount--;
|
||||
}
|
||||
|
||||
size_t HttpServer::getConnectedClientsCount()
|
||||
{
|
||||
return _connectedClientsCount;
|
||||
}
|
||||
|
||||
void HttpServer::setDefaultConnectionCallback()
|
||||
{
|
||||
setOnConnectionCallback(
|
||||
[this](HttpRequestPtr request,
|
||||
std::shared_ptr<ConnectionState> /*connectionState*/) -> HttpResponsePtr
|
||||
{
|
||||
std::string uri(request->uri);
|
||||
if (uri.empty() || uri == "/")
|
||||
{
|
||||
uri = "/index.html";
|
||||
}
|
||||
|
||||
std::string path("." + uri);
|
||||
auto res = readAsString(path);
|
||||
bool found = res.first;
|
||||
if (!found)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(404, "Not Found",
|
||||
HttpErrorCode::Ok,
|
||||
WebSocketHttpHeaders(),
|
||||
std::string());
|
||||
}
|
||||
|
||||
std::string content = res.second;
|
||||
|
||||
// Log request
|
||||
std::stringstream ss;
|
||||
ss << request->method
|
||||
<< " "
|
||||
<< request->headers["User-Agent"]
|
||||
<< " "
|
||||
<< request->uri
|
||||
<< " "
|
||||
<< content.size();
|
||||
logInfo(ss.str());
|
||||
|
||||
WebSocketHttpHeaders headers;
|
||||
// FIXME: check extensions to set the content type
|
||||
// headers["Content-Type"] = "application/octet-stream";
|
||||
headers["Accept-Ranges"] = "none";
|
||||
|
||||
for (auto&& it : request->headers)
|
||||
{
|
||||
headers[it.first] = it.second;
|
||||
}
|
||||
|
||||
return std::make_shared<HttpResponse>(200, "OK",
|
||||
HttpErrorCode::Ok,
|
||||
headers,
|
||||
content);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
49
ixwebsocket/IXHttpServer.h
Normal file
49
ixwebsocket/IXHttpServer.h
Normal file
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* IXHttpServer.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXHttp.h"
|
||||
#include "IXSocketServer.h"
|
||||
#include "IXWebSocket.h"
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility> // pair
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class HttpServer final : public SocketServer
|
||||
{
|
||||
public:
|
||||
using OnConnectionCallback =
|
||||
std::function<HttpResponsePtr(HttpRequestPtr, std::shared_ptr<ConnectionState>)>;
|
||||
|
||||
HttpServer(int port = SocketServer::kDefaultPort,
|
||||
const std::string& host = SocketServer::kDefaultHost,
|
||||
int backlog = SocketServer::kDefaultTcpBacklog,
|
||||
size_t maxConnections = SocketServer::kDefaultMaxConnections);
|
||||
virtual ~HttpServer();
|
||||
virtual void stop() final;
|
||||
|
||||
void setOnConnectionCallback(const OnConnectionCallback& callback);
|
||||
|
||||
private:
|
||||
// Member variables
|
||||
OnConnectionCallback _onConnectionCallback;
|
||||
std::atomic<int> _connectedClientsCount;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(int fd,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
|
||||
void setDefaultConnectionCallback();
|
||||
};
|
||||
} // namespace ix
|
@ -15,9 +15,8 @@ namespace ix
|
||||
WSADATA wsaData;
|
||||
int err;
|
||||
|
||||
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
|
||||
// Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h
|
||||
wVersionRequested = MAKEWORD(2, 2);
|
||||
|
||||
err = WSAStartup(wVersionRequested, &wsaData);
|
||||
|
||||
return err == 0;
|
||||
@ -30,10 +29,83 @@ namespace ix
|
||||
{
|
||||
#ifdef _WIN32
|
||||
int err = WSACleanup();
|
||||
|
||||
return err == 0;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// This function should be in the global namespace
|
||||
#ifdef _WIN32
|
||||
//
|
||||
// That function could 'return WSAPoll(pfd, nfds, timeout);'
|
||||
// but WSAPoll is said to have weird behaviors on the internet
|
||||
// (the curl folks have had problems with it).
|
||||
//
|
||||
// So we make it a select wrapper
|
||||
//
|
||||
int poll(struct pollfd *fds, nfds_t nfds, int timeout)
|
||||
{
|
||||
int maxfd = 0;
|
||||
fd_set readfds, writefds, errorfds;
|
||||
FD_ZERO(&readfds);
|
||||
FD_ZERO(&writefds);
|
||||
FD_ZERO(&errorfds);
|
||||
|
||||
for (nfds_t i = 0; i < nfds; ++i)
|
||||
{
|
||||
struct pollfd *fd = &fds[i];
|
||||
|
||||
if (fd->fd > maxfd)
|
||||
{
|
||||
maxfd = fd->fd;
|
||||
}
|
||||
if ((fd->events & POLLIN))
|
||||
{
|
||||
FD_SET(fd->fd, &readfds);
|
||||
}
|
||||
if ((fd->events & POLLOUT))
|
||||
{
|
||||
FD_SET(fd->fd, &writefds);
|
||||
}
|
||||
if ((fd->events & POLLERR))
|
||||
{
|
||||
FD_SET(fd->fd, &errorfds);
|
||||
}
|
||||
}
|
||||
|
||||
struct timeval tv;
|
||||
tv.tv_sec = timeout / 1000;
|
||||
tv.tv_usec = (timeout % 1000) * 1000;
|
||||
|
||||
int ret = select(maxfd + 1, &readfds, &writefds, &errorfds,
|
||||
timeout != -1 ? &tv : NULL);
|
||||
|
||||
if (ret < 0)
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
|
||||
for (nfds_t i = 0; i < nfds; ++i)
|
||||
{
|
||||
struct pollfd *fd = &fds[i];
|
||||
fd->revents = 0;
|
||||
|
||||
if (FD_ISSET(fd->fd, &readfds))
|
||||
{
|
||||
fd->revents |= POLLIN;
|
||||
}
|
||||
if (FD_ISSET(fd->fd, &writefds))
|
||||
{
|
||||
fd->revents |= POLLOUT;
|
||||
}
|
||||
if (FD_ISSET(fd->fd, &errorfds))
|
||||
{
|
||||
fd->revents |= POLLERR;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
#endif
|
||||
|
@ -12,11 +12,18 @@
|
||||
#include <basetsd.h>
|
||||
#include <io.h>
|
||||
#include <ws2def.h>
|
||||
|
||||
// Define our own poll on Windows
|
||||
typedef unsigned long int nfds_t;
|
||||
|
||||
int poll(struct pollfd* fds, nfds_t nfds, int timeout);
|
||||
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <poll.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
|
@ -44,41 +44,42 @@ namespace ix
|
||||
close();
|
||||
}
|
||||
|
||||
PollResultType Socket::poll(int timeoutMs)
|
||||
PollResultType Socket::poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
std::shared_ptr<SelectInterrupt> selectInterrupt)
|
||||
{
|
||||
return isReadyToRead(timeoutMs);
|
||||
}
|
||||
//
|
||||
// We used to use ::select to poll but on Android 9 we get large fds out of ::connect
|
||||
// which crash in FD_SET as they are larger than FD_SETSIZE.
|
||||
// Switching to ::poll does fix that.
|
||||
//
|
||||
// However poll isn't as portable as select and has bugs on Windows, so we should write a
|
||||
// shim to fallback to select on those platforms.
|
||||
// See https://github.com/mpv-player/mpv/pull/5203/files for such a select wrapper.
|
||||
//
|
||||
nfds_t nfds = 1;
|
||||
struct pollfd fds[2];
|
||||
|
||||
PollResultType Socket::select(bool readyToRead, int timeoutMs)
|
||||
{
|
||||
fd_set rfds;
|
||||
fd_set wfds;
|
||||
FD_ZERO(&rfds);
|
||||
FD_ZERO(&wfds);
|
||||
|
||||
fd_set* fds = (readyToRead) ? &rfds : & wfds;
|
||||
if (_sockfd != -1)
|
||||
{
|
||||
FD_SET(_sockfd, fds);
|
||||
}
|
||||
fds[0].fd = sockfd;
|
||||
fds[0].events = (readyToRead) ? POLLIN : POLLOUT;
|
||||
fds[0].events |= POLLERR;
|
||||
|
||||
// File descriptor used to interrupt select when needed
|
||||
int interruptFd = _selectInterrupt->getFd();
|
||||
if (interruptFd != -1)
|
||||
int interruptFd = -1;
|
||||
if (selectInterrupt)
|
||||
{
|
||||
FD_SET(interruptFd, fds);
|
||||
interruptFd = selectInterrupt->getFd();
|
||||
|
||||
if (interruptFd != -1)
|
||||
{
|
||||
nfds = 2;
|
||||
fds[1].fd = interruptFd;
|
||||
fds[1].events = POLLIN;
|
||||
}
|
||||
}
|
||||
|
||||
struct timeval timeout;
|
||||
timeout.tv_sec = timeoutMs / 1000;
|
||||
timeout.tv_usec = 1000 * (timeoutMs % 1000);
|
||||
|
||||
// Compute the highest fd.
|
||||
int sockfd = _sockfd;
|
||||
int nfds = (std::max)(sockfd, interruptFd);
|
||||
|
||||
int ret = ::select(nfds + 1, &rfds, &wfds, nullptr,
|
||||
(timeoutMs < 0) ? nullptr : &timeout);
|
||||
int ret = ::poll(fds, nfds, timeoutMs);
|
||||
|
||||
PollResultType pollResult = PollResultType::ReadyForRead;
|
||||
if (ret < 0)
|
||||
@ -89,9 +90,9 @@ namespace ix
|
||||
{
|
||||
pollResult = PollResultType::Timeout;
|
||||
}
|
||||
else if (interruptFd != -1 && FD_ISSET(interruptFd, &rfds))
|
||||
else if (interruptFd != -1 && fds[1].revents & POLLIN)
|
||||
{
|
||||
uint64_t value = _selectInterrupt->read();
|
||||
uint64_t value = selectInterrupt->read();
|
||||
|
||||
if (value == kSendRequest)
|
||||
{
|
||||
@ -102,13 +103,36 @@ namespace ix
|
||||
pollResult = PollResultType::CloseRequest;
|
||||
}
|
||||
}
|
||||
else if (sockfd != -1 && readyToRead && FD_ISSET(sockfd, &rfds))
|
||||
else if (sockfd != -1 && readyToRead && fds[0].revents & POLLIN)
|
||||
{
|
||||
pollResult = PollResultType::ReadyForRead;
|
||||
}
|
||||
else if (sockfd != -1 && !readyToRead && FD_ISSET(sockfd, &wfds))
|
||||
else if (sockfd != -1 && !readyToRead && fds[0].revents & POLLOUT)
|
||||
{
|
||||
pollResult = PollResultType::ReadyForWrite;
|
||||
|
||||
#ifdef _WIN32
|
||||
// On connect error, in async mode, windows will write to the exceptions fds
|
||||
if (fds[0].revents & POLLERR)
|
||||
{
|
||||
pollResult = PollResultType::Error;
|
||||
}
|
||||
#else
|
||||
int optval = -1;
|
||||
socklen_t optlen = sizeof(optval);
|
||||
|
||||
// getsockopt() puts the errno value for connect into optval so 0
|
||||
// means no-error.
|
||||
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1 ||
|
||||
optval != 0)
|
||||
{
|
||||
pollResult = PollResultType::Error;
|
||||
|
||||
// set errno to optval so that external callers can have an
|
||||
// appropriate error description when calling strerror
|
||||
errno = optval;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
return pollResult;
|
||||
@ -122,7 +146,7 @@ namespace ix
|
||||
}
|
||||
|
||||
bool readyToRead = true;
|
||||
return select(readyToRead, timeoutMs);
|
||||
return poll(readyToRead, timeoutMs, _sockfd, _selectInterrupt);
|
||||
}
|
||||
|
||||
PollResultType Socket::isReadyToWrite(int timeoutMs)
|
||||
@ -133,7 +157,7 @@ namespace ix
|
||||
}
|
||||
|
||||
bool readyToRead = false;
|
||||
return select(readyToRead, timeoutMs);
|
||||
return poll(readyToRead, timeoutMs, _sockfd, _selectInterrupt);
|
||||
}
|
||||
|
||||
// Wake up from poll/select by writing to the pipe which is watched by select
|
||||
@ -232,19 +256,28 @@ namespace ix
|
||||
bool Socket::writeBytes(const std::string& str,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
int offset = 0;
|
||||
int len = (int) str.size();
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (isCancellationRequested && isCancellationRequested()) return false;
|
||||
|
||||
char* buffer = const_cast<char*>(str.c_str());
|
||||
int len = (int) str.size();
|
||||
|
||||
ssize_t ret = send(buffer, len);
|
||||
ssize_t ret = send((char*)&str[offset], len);
|
||||
|
||||
// We wrote some bytes, as needed, all good.
|
||||
if (ret > 0)
|
||||
{
|
||||
return ret == len;
|
||||
if (ret == len)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
offset += ret;
|
||||
len -= ret;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// There is possibly something to be writen, try again
|
||||
else if (ret < 0 && Socket::isWaitNeeded())
|
||||
|
@ -88,6 +88,12 @@ namespace ix
|
||||
static bool isWaitNeeded();
|
||||
static void closeSocket(int fd);
|
||||
|
||||
static PollResultType poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
std::shared_ptr<SelectInterrupt> selectInterrupt = nullptr);
|
||||
|
||||
|
||||
// Used as special codes for pipe communication
|
||||
static const uint64_t kSendRequest;
|
||||
static const uint64_t kCloseRequest;
|
||||
@ -97,8 +103,6 @@ namespace ix
|
||||
std::mutex _socketMutex;
|
||||
|
||||
private:
|
||||
PollResultType select(bool readyToRead, int timeoutMs);
|
||||
|
||||
static const int kDefaultPollTimeout;
|
||||
static const int kDefaultPollNoTimeout;
|
||||
|
||||
|
@ -63,55 +63,31 @@ namespace ix
|
||||
return -1;
|
||||
}
|
||||
|
||||
// On Linux the timeout needs to be re-initialized everytime
|
||||
// http://man7.org/linux/man-pages/man2/select.2.html
|
||||
struct timeval timeout;
|
||||
timeout.tv_sec = 0;
|
||||
timeout.tv_usec = 10 * 1000; // 10ms timeout
|
||||
int timeoutMs = 10;
|
||||
bool readyToRead = false;
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, fd);
|
||||
|
||||
fd_set wfds;
|
||||
fd_set efds;
|
||||
|
||||
FD_ZERO(&wfds);
|
||||
FD_SET(fd, &wfds);
|
||||
FD_ZERO(&efds);
|
||||
FD_SET(fd, &efds);
|
||||
|
||||
// Use select to check the status of the new connection
|
||||
res = select(fd + 1, nullptr, &wfds, &efds, &timeout);
|
||||
|
||||
if (res < 0 && (Socket::getErrno() == EBADF || Socket::getErrno() == EINVAL))
|
||||
if (pollResult == PollResultType::Timeout)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
else if (pollResult == PollResultType::Error)
|
||||
{
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = std::string("Connect error, select error: ") + strerror(Socket::getErrno());
|
||||
errMsg = std::string("Connect error: ") +
|
||||
strerror(Socket::getErrno());
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Nothing was written to the socket, wait again.
|
||||
if (!FD_ISSET(fd, &wfds)) continue;
|
||||
|
||||
// Something was written to the socket. Check for errors.
|
||||
int optval = -1;
|
||||
socklen_t optlen = sizeof(optval);
|
||||
|
||||
#ifdef _WIN32
|
||||
// On connect error, in async mode, windows will write to the exceptions fds
|
||||
if (FD_ISSET(fd, &efds))
|
||||
#else
|
||||
// getsockopt() puts the errno value for connect into optval so 0
|
||||
// means no-error.
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1 ||
|
||||
optval != 0)
|
||||
#endif
|
||||
else if (pollResult == PollResultType::ReadyForWrite)
|
||||
{
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = strerror(optval);
|
||||
return -1;
|
||||
return fd;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Success !
|
||||
return fd;
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = std::string("Connect error: ") +
|
||||
strerror(Socket::getErrno());
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
@ -128,8 +104,8 @@ namespace ix
|
||||
//
|
||||
// First do DNS resolution
|
||||
//
|
||||
DNSLookup dnsLookup(hostname, port);
|
||||
struct addrinfo *res = dnsLookup.resolve(errMsg, isCancellationRequested);
|
||||
auto dnsLookup = std::make_shared<DNSLookup>(hostname, port);
|
||||
struct addrinfo *res = dnsLookup->resolve(errMsg, isCancellationRequested);
|
||||
if (res == nullptr)
|
||||
{
|
||||
return -1;
|
||||
|
@ -11,7 +11,6 @@
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <future>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
@ -214,17 +213,12 @@ namespace ix
|
||||
{
|
||||
if (_stop) return;
|
||||
|
||||
// Use select to check whether a new connection is in progress
|
||||
fd_set rfds;
|
||||
struct timeval timeout;
|
||||
timeout.tv_sec = 0;
|
||||
timeout.tv_usec = 10 * 1000; // 10ms timeout
|
||||
// Use poll to check whether a new connection is in progress
|
||||
int timeoutMs = 10;
|
||||
bool readyToRead = true;
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, _serverFd);
|
||||
|
||||
FD_ZERO(&rfds);
|
||||
FD_SET(_serverFd, &rfds);
|
||||
|
||||
if (select(_serverFd + 1, &rfds, nullptr, nullptr, &timeout) < 0 &&
|
||||
(errno == EBADF || errno == EINVAL))
|
||||
if (pollResult == PollResultType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "SocketServer::run() error in select: "
|
||||
@ -233,9 +227,8 @@ namespace ix
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!FD_ISSET(_serverFd, &rfds))
|
||||
if (pollResult != PollResultType::ReadyForRead)
|
||||
{
|
||||
// We reached the select timeout, and no new connections are pending
|
||||
continue;
|
||||
}
|
||||
|
||||
|
83
ixwebsocket/IXUserAgent.cpp
Normal file
83
ixwebsocket/IXUserAgent.cpp
Normal file
@ -0,0 +1,83 @@
|
||||
/*
|
||||
* IXUserAgent.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXUserAgent.h"
|
||||
#include "IXWebSocketVersion.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <zlib.h>
|
||||
|
||||
// Platform name
|
||||
#if defined(_WIN32)
|
||||
#define PLATFORM_NAME "windows" // Windows
|
||||
#elif defined(_WIN64)
|
||||
#define PLATFORM_NAME "windows" // Windows
|
||||
#elif defined(__CYGWIN__) && !defined(_WIN32)
|
||||
#define PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)
|
||||
#elif defined(__ANDROID__)
|
||||
#define PLATFORM_NAME "android" // Android (implies Linux, so it must come first)
|
||||
#elif defined(__linux__)
|
||||
#define PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other
|
||||
#elif defined(__unix__) || !defined(__APPLE__) && defined(__MACH__)
|
||||
#include <sys/param.h>
|
||||
#if defined(BSD)
|
||||
#define PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
|
||||
#endif
|
||||
#elif defined(__hpux)
|
||||
#define PLATFORM_NAME "hp-ux" // HP-UX
|
||||
#elif defined(_AIX)
|
||||
#define PLATFORM_NAME "aix" // IBM AIX
|
||||
#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
|
||||
#include <TargetConditionals.h>
|
||||
#if TARGET_IPHONE_SIMULATOR == 1
|
||||
#define PLATFORM_NAME "ios" // Apple iOS
|
||||
#elif TARGET_OS_IPHONE == 1
|
||||
#define PLATFORM_NAME "ios" // Apple iOS
|
||||
#elif TARGET_OS_MAC == 1
|
||||
#define PLATFORM_NAME "macos" // Apple OSX
|
||||
#endif
|
||||
#elif defined(__sun) && defined(__SVR4)
|
||||
#define PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana
|
||||
#else
|
||||
#define PLATFORM_NAME "unknown platform"
|
||||
#endif
|
||||
|
||||
// SSL
|
||||
#if defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
#include <openssl/opensslv.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::string userAgent()
|
||||
{
|
||||
std::stringstream ss;
|
||||
|
||||
// IXWebSocket Version
|
||||
ss << "ixwebsocket/" << IX_WEBSOCKET_VERSION;
|
||||
|
||||
// Platform
|
||||
ss << " " << PLATFORM_NAME;
|
||||
|
||||
// TLS
|
||||
#ifdef IXWEBSOCKET_USE_TLS
|
||||
#ifdef IXWEBSOCKET_USE_MBED_TLS
|
||||
ss << " ssl/mbedtls";
|
||||
#elif __APPLE__
|
||||
ss << " ssl/DarwinSSL";
|
||||
#elif defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
ss << " ssl/OpenSSL " << OPENSSL_VERSION_TEXT;
|
||||
#endif
|
||||
#else
|
||||
ss << " nossl";
|
||||
#endif
|
||||
|
||||
// Zlib version
|
||||
ss << " zlib " << ZLIB_VERSION;
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
}
|
14
ixwebsocket/IXUserAgent.h
Normal file
14
ixwebsocket/IXUserAgent.h
Normal file
@ -0,0 +1,14 @@
|
||||
/*
|
||||
* IXUserAgent.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::string userAgent();
|
||||
} // namespace ix
|
167
ixwebsocket/IXUtf8Validator.h
Normal file
167
ixwebsocket/IXUtf8Validator.h
Normal file
@ -0,0 +1,167 @@
|
||||
/*
|
||||
* The following code is adapted from code originally written by Bjoern
|
||||
* Hoehrmann <bjoern@hoehrmann.de>. See
|
||||
* http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
|
||||
*
|
||||
* The original license:
|
||||
*
|
||||
* Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* IXUtf8Validator.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*
|
||||
* From websocketpp. Tiny modifications made for code style, function names etc...
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
/// State that represents a valid utf8 input sequence
|
||||
static unsigned int const utf8_accept = 0;
|
||||
/// State that represents an invalid utf8 input sequence
|
||||
static unsigned int const utf8_reject = 1;
|
||||
|
||||
/// Lookup table for the UTF8 decode state machine
|
||||
static uint8_t const utf8d[] = {
|
||||
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
|
||||
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
|
||||
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
|
||||
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
|
||||
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
|
||||
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
|
||||
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
|
||||
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
|
||||
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
|
||||
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
|
||||
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
|
||||
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
|
||||
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
|
||||
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
|
||||
};
|
||||
|
||||
/// Decode the next byte of a UTF8 sequence
|
||||
/**
|
||||
* @param [out] state The decoder state to advance
|
||||
* @param [out] codep The codepoint to fill in
|
||||
* @param [in] byte The byte to input
|
||||
* @return The ending state of the decode operation
|
||||
*/
|
||||
inline uint32_t decodeNextByte(uint32_t * state, uint32_t * codep, uint8_t byte)
|
||||
{
|
||||
uint32_t type = utf8d[byte];
|
||||
|
||||
*codep = (*state != utf8_accept) ?
|
||||
(byte & 0x3fu) | (*codep << 6) :
|
||||
(0xff >> type) & (byte);
|
||||
|
||||
*state = utf8d[256 + *state*16 + type];
|
||||
return *state;
|
||||
}
|
||||
|
||||
/// Provides streaming UTF8 validation functionality
|
||||
class Utf8Validator
|
||||
{
|
||||
public:
|
||||
/// Construct and initialize the validator
|
||||
Utf8Validator() : m_state(utf8_accept),m_codepoint(0) {}
|
||||
|
||||
/// Advance the state of the validator with the next input byte
|
||||
/**
|
||||
* @param byte The byte to advance the validation state with
|
||||
* @return Whether or not the byte resulted in a validation error.
|
||||
*/
|
||||
bool consume(uint8_t byte)
|
||||
{
|
||||
if (decodeNextByte(&m_state,&m_codepoint,byte) == utf8_reject)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Advance Validator state with input from an iterator pair
|
||||
/**
|
||||
* @param begin Input iterator to the start of the input range
|
||||
* @param end Input iterator to the end of the input range
|
||||
* @return Whether or not decoding the bytes resulted in a validation error.
|
||||
*/
|
||||
template <typename iterator_type>
|
||||
bool decode(iterator_type begin, iterator_type end)
|
||||
{
|
||||
for (iterator_type it = begin; it != end; ++it)
|
||||
{
|
||||
unsigned int result = decodeNextByte(
|
||||
&m_state,
|
||||
&m_codepoint,
|
||||
static_cast<uint8_t>(*it)
|
||||
);
|
||||
|
||||
if (result == utf8_reject)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Return whether the input sequence ended on a valid utf8 codepoint
|
||||
/**
|
||||
* @return Whether or not the input sequence ended on a valid codepoint.
|
||||
*/
|
||||
bool complete()
|
||||
{
|
||||
return m_state == utf8_accept;
|
||||
}
|
||||
|
||||
/// Reset the Validator to decode another message
|
||||
void reset()
|
||||
{
|
||||
m_state = utf8_accept;
|
||||
m_codepoint = 0;
|
||||
}
|
||||
private:
|
||||
uint32_t m_state;
|
||||
uint32_t m_codepoint;
|
||||
};
|
||||
|
||||
/// Validate a UTF8 string
|
||||
/**
|
||||
* convenience function that creates a Validator, validates a complete string
|
||||
* and returns the result.
|
||||
*/
|
||||
inline bool validateUtf8(std::string const & s)
|
||||
{
|
||||
Utf8Validator v;
|
||||
if (!v.decode(s.begin(),s.end()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return v.complete();
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -7,29 +7,13 @@
|
||||
#include "IXWebSocket.h"
|
||||
#include "IXSetThreadName.h"
|
||||
#include "IXWebSocketHandshake.h"
|
||||
#include "IXExponentialBackoff.h"
|
||||
#include "IXUtf8Validator.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
namespace
|
||||
{
|
||||
uint64_t calculateRetryWaitMilliseconds(uint32_t retry_count)
|
||||
{
|
||||
uint64_t wait_time;
|
||||
|
||||
if (retry_count <= 6)
|
||||
{
|
||||
// max wait_time is 6400 ms (2 ^ 6 = 64)
|
||||
wait_time = ((uint64_t)std::pow(2, retry_count) * 100L);
|
||||
}
|
||||
else
|
||||
{
|
||||
wait_time = 10 * 1000; // 10 sec
|
||||
}
|
||||
|
||||
return wait_time;
|
||||
}
|
||||
}
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -38,11 +22,13 @@ namespace ix
|
||||
const int WebSocket::kDefaultPingIntervalSecs(-1);
|
||||
const int WebSocket::kDefaultPingTimeoutSecs(-1);
|
||||
const bool WebSocket::kDefaultEnablePong(true);
|
||||
const uint32_t WebSocket::kDefaultMaxWaitBetweenReconnectionRetries(10 * 1000); // 10s
|
||||
|
||||
WebSocket::WebSocket() :
|
||||
_onMessageCallback(OnMessageCallback()),
|
||||
_stop(false),
|
||||
_automaticReconnection(true),
|
||||
_maxWaitBetweenReconnectionRetries(kDefaultMaxWaitBetweenReconnectionRetries),
|
||||
_handshakeTimeoutSecs(kDefaultHandShakeTimeoutSecs),
|
||||
_enablePong(kDefaultEnablePong),
|
||||
_pingIntervalSecs(kDefaultPingIntervalSecs),
|
||||
@ -70,6 +56,11 @@ namespace ix
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_url = url;
|
||||
}
|
||||
void WebSocket::setExtraHeaders(const WebSocketHttpHeaders& headers)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_extraHeaders = headers;
|
||||
}
|
||||
|
||||
const std::string& WebSocket::getUrl() const
|
||||
{
|
||||
@ -144,6 +135,18 @@ namespace ix
|
||||
_perMessageDeflateOptions = perMessageDeflateOptions;
|
||||
}
|
||||
|
||||
void WebSocket::setMaxWaitBetweenReconnectionRetries(uint32_t maxWaitBetweenReconnectionRetries)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_maxWaitBetweenReconnectionRetries = maxWaitBetweenReconnectionRetries;
|
||||
}
|
||||
|
||||
uint32_t WebSocket::getMaxWaitBetweenReconnectionRetries() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
return _maxWaitBetweenReconnectionRetries;
|
||||
}
|
||||
|
||||
void WebSocket::start()
|
||||
{
|
||||
if (_thread.joinable()) return; // we've already been started
|
||||
@ -176,7 +179,7 @@ namespace ix
|
||||
_pingTimeoutSecs);
|
||||
}
|
||||
|
||||
WebSocketInitResult status = _ws.connectToUrl(_url, timeoutSecs);
|
||||
WebSocketInitResult status = _ws.connectToUrl(_url, _extraHeaders, timeoutSecs);
|
||||
if (!status.success)
|
||||
{
|
||||
return status;
|
||||
@ -271,7 +274,7 @@ namespace ix
|
||||
|
||||
if (_automaticReconnection)
|
||||
{
|
||||
duration = millis(calculateRetryWaitMilliseconds(retries++));
|
||||
duration = millis(calculateRetryWaitMilliseconds(retries++, _maxWaitBetweenReconnectionRetries));
|
||||
|
||||
connectErr.wait_time = duration.count();
|
||||
connectErr.retries = retries;
|
||||
@ -390,9 +393,7 @@ namespace ix
|
||||
bool binary,
|
||||
const OnProgressCallback& onProgressCallback)
|
||||
{
|
||||
return sendMessage(data,
|
||||
(binary) ? SendMessageKind::Binary: SendMessageKind::Text,
|
||||
onProgressCallback);
|
||||
return (binary) ? sendBinary(data, onProgressCallback) : sendText(data, onProgressCallback);
|
||||
}
|
||||
|
||||
WebSocketSendInfo WebSocket::sendBinary(const std::string& text,
|
||||
@ -404,6 +405,12 @@ namespace ix
|
||||
WebSocketSendInfo WebSocket::sendText(const std::string& text,
|
||||
const OnProgressCallback& onProgressCallback)
|
||||
{
|
||||
if (!validateUtf8(text))
|
||||
{
|
||||
close(WebSocketCloseConstants::kInvalidFramePayloadData,
|
||||
WebSocketCloseConstants::kInvalidFramePayloadDataMessage);
|
||||
return false;
|
||||
}
|
||||
return sendMessage(text, SendMessageKind::Text, onProgressCallback);
|
||||
}
|
||||
|
||||
|
@ -44,6 +44,9 @@ namespace ix
|
||||
~WebSocket();
|
||||
|
||||
void setUrl(const std::string& url);
|
||||
|
||||
// send extra headers in client handshake request
|
||||
void setExtraHeaders(const WebSocketHttpHeaders& headers);
|
||||
void setPerMessageDeflateOptions(
|
||||
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
|
||||
void setHeartBeatPeriod(int heartBeatPeriodSecs);
|
||||
@ -94,6 +97,8 @@ namespace ix
|
||||
void enableAutomaticReconnection();
|
||||
void disableAutomaticReconnection();
|
||||
bool isAutomaticReconnectionEnabled() const;
|
||||
void setMaxWaitBetweenReconnectionRetries(uint32_t maxWaitBetweenReconnectionRetries);
|
||||
uint32_t getMaxWaitBetweenReconnectionRetries() const;
|
||||
|
||||
private:
|
||||
WebSocketSendInfo sendMessage(const std::string& text,
|
||||
@ -111,6 +116,8 @@ namespace ix
|
||||
WebSocketTransport _ws;
|
||||
|
||||
std::string _url;
|
||||
WebSocketHttpHeaders _extraHeaders;
|
||||
|
||||
WebSocketPerMessageDeflateOptions _perMessageDeflateOptions;
|
||||
mutable std::mutex _configMutex; // protect all config variables access
|
||||
|
||||
@ -118,10 +125,14 @@ namespace ix
|
||||
static OnTrafficTrackerCallback _onTrafficTrackerCallback;
|
||||
|
||||
std::atomic<bool> _stop;
|
||||
std::atomic<bool> _automaticReconnection;
|
||||
std::thread _thread;
|
||||
std::mutex _writeMutex;
|
||||
|
||||
// Automatic reconnection
|
||||
std::atomic<bool> _automaticReconnection;
|
||||
static const uint32_t kDefaultMaxWaitBetweenReconnectionRetries;
|
||||
uint32_t _maxWaitBetweenReconnectionRetries;
|
||||
|
||||
std::atomic<int> _handshakeTimeoutSecs;
|
||||
static const int kDefaultHandShakeTimeoutSecs;
|
||||
|
||||
|
@ -11,6 +11,7 @@ namespace ix
|
||||
const uint16_t WebSocketCloseConstants::kNormalClosureCode(1000);
|
||||
const uint16_t WebSocketCloseConstants::kInternalErrorCode(1011);
|
||||
const uint16_t WebSocketCloseConstants::kAbnormalCloseCode(1006);
|
||||
const uint16_t WebSocketCloseConstants::kInvalidFramePayloadData(1007);
|
||||
const uint16_t WebSocketCloseConstants::kProtocolErrorCode(1002);
|
||||
const uint16_t WebSocketCloseConstants::kNoStatusCodeErrorCode(1005);
|
||||
|
||||
@ -20,4 +21,11 @@ namespace ix
|
||||
const std::string WebSocketCloseConstants::kPingTimeoutMessage("Ping timeout");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorMessage("Protocol error");
|
||||
const std::string WebSocketCloseConstants::kNoStatusCodeErrorMessage("No status code");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorReservedBitUsed("Reserved bit used");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorPingPayloadOversized("Ping reason control frame with payload length > 125 octets");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorCodeControlMessageFragmented("Control message fragmented");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorCodeDataOpcodeOutOfSequence("Fragmentation: data message out of sequence");
|
||||
const std::string WebSocketCloseConstants::kProtocolErrorCodeContinuationOpCodeOutOfSequence("Fragmentation: continuation opcode out of sequence");
|
||||
const std::string WebSocketCloseConstants::kInvalidFramePayloadDataMessage("Invalid frame payload data");
|
||||
const std::string WebSocketCloseConstants::kInvalidCloseCodeMessage("Invalid close code");
|
||||
}
|
||||
|
@ -18,6 +18,7 @@ namespace ix
|
||||
static const uint16_t kAbnormalCloseCode;
|
||||
static const uint16_t kProtocolErrorCode;
|
||||
static const uint16_t kNoStatusCodeErrorCode;
|
||||
static const uint16_t kInvalidFramePayloadData;
|
||||
|
||||
static const std::string kNormalClosureMessage;
|
||||
static const std::string kInternalErrorMessage;
|
||||
@ -25,5 +26,12 @@ namespace ix
|
||||
static const std::string kPingTimeoutMessage;
|
||||
static const std::string kProtocolErrorMessage;
|
||||
static const std::string kNoStatusCodeErrorMessage;
|
||||
static const std::string kProtocolErrorReservedBitUsed;
|
||||
static const std::string kProtocolErrorPingPayloadOversized;
|
||||
static const std::string kProtocolErrorCodeControlMessageFragmented;
|
||||
static const std::string kProtocolErrorCodeDataOpcodeOutOfSequence;
|
||||
static const std::string kProtocolErrorCodeContinuationOpCodeOutOfSequence;
|
||||
static const std::string kInvalidFramePayloadDataMessage;
|
||||
static const std::string kInvalidCloseCodeMessage;
|
||||
};
|
||||
} // namespace ix
|
||||
|
@ -7,6 +7,8 @@
|
||||
#include "IXWebSocketHandshake.h"
|
||||
#include "IXSocketConnect.h"
|
||||
#include "IXUrlParser.h"
|
||||
#include "IXHttp.h"
|
||||
#include "IXUserAgent.h"
|
||||
|
||||
#include "libwshandshake.hpp"
|
||||
|
||||
@ -31,15 +33,6 @@ namespace ix
|
||||
|
||||
}
|
||||
|
||||
std::string WebSocketHandshake::trim(const std::string& str)
|
||||
{
|
||||
std::string out(str);
|
||||
out.erase(std::remove(out.begin(), out.end(), ' '), out.end());
|
||||
out.erase(std::remove(out.begin(), out.end(), '\r'), out.end());
|
||||
out.erase(std::remove(out.begin(), out.end(), '\n'), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
bool WebSocketHandshake::insensitiveStringCompare(const std::string& a, const std::string& b)
|
||||
{
|
||||
return std::equal(a.begin(), a.end(),
|
||||
@ -50,40 +43,6 @@ namespace ix
|
||||
});
|
||||
}
|
||||
|
||||
std::tuple<std::string, std::string, std::string> WebSocketHandshake::parseRequestLine(const std::string& line)
|
||||
{
|
||||
// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
|
||||
std::string token;
|
||||
std::stringstream tokenStream(line);
|
||||
std::vector<std::string> tokens;
|
||||
|
||||
// Split by ' '
|
||||
while (std::getline(tokenStream, token, ' '))
|
||||
{
|
||||
tokens.push_back(token);
|
||||
}
|
||||
|
||||
std::string method;
|
||||
if (tokens.size() >= 1)
|
||||
{
|
||||
method = trim(tokens[0]);
|
||||
}
|
||||
|
||||
std::string requestUri;
|
||||
if (tokens.size() >= 2)
|
||||
{
|
||||
requestUri = trim(tokens[1]);
|
||||
}
|
||||
|
||||
std::string httpVersion;
|
||||
if (tokens.size() >= 3)
|
||||
{
|
||||
httpVersion = trim(tokens[2]);
|
||||
}
|
||||
|
||||
return std::make_tuple(method, requestUri, httpVersion);
|
||||
}
|
||||
|
||||
std::string WebSocketHandshake::genRandomString(const int len)
|
||||
{
|
||||
std::string alphanum =
|
||||
@ -130,6 +89,7 @@ namespace ix
|
||||
}
|
||||
|
||||
WebSocketInitResult WebSocketHandshake::clientHandshake(const std::string& url,
|
||||
const WebSocketHttpHeaders& extraHeaders,
|
||||
const std::string& host,
|
||||
const std::string& path,
|
||||
int port,
|
||||
@ -169,6 +129,17 @@ namespace ix
|
||||
ss << "Sec-WebSocket-Version: 13\r\n";
|
||||
ss << "Sec-WebSocket-Key: " << secWebSocketKey << "\r\n";
|
||||
|
||||
// User-Agent can be customized by users
|
||||
if (extraHeaders.find("User-Agent") == extraHeaders.end())
|
||||
{
|
||||
ss << "User-Agent: " << userAgent() << "\r\n";
|
||||
}
|
||||
|
||||
for (auto& it : extraHeaders)
|
||||
{
|
||||
ss << it.first << ":" << it.second << "\r\n";
|
||||
}
|
||||
|
||||
if (_enablePerMessageDeflate)
|
||||
{
|
||||
ss << _perMessageDeflateOptions.generateHeader();
|
||||
@ -264,7 +235,7 @@ namespace ix
|
||||
else if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions))
|
||||
{
|
||||
return WebSocketInitResult(
|
||||
false, 0,"Failed to initialize per message deflate engine");
|
||||
false, 0, "Failed to initialize per message deflate engine");
|
||||
}
|
||||
}
|
||||
|
||||
@ -294,7 +265,7 @@ namespace ix
|
||||
}
|
||||
|
||||
// Validate request line (GET /foo HTTP/1.1\r\n)
|
||||
auto requestLine = parseRequestLine(line);
|
||||
auto requestLine = Http::parseRequestLine(line);
|
||||
auto method = std::get<0>(requestLine);
|
||||
auto uri = std::get<1>(requestLine);
|
||||
auto httpVersion = std::get<2>(requestLine);
|
||||
@ -324,7 +295,7 @@ namespace ix
|
||||
return sendErrorResponse(400, "Missing Sec-WebSocket-Key value");
|
||||
}
|
||||
|
||||
if (headers["upgrade"] != "websocket")
|
||||
if (!insensitiveStringCompare(headers["upgrade"], "WebSocket"))
|
||||
{
|
||||
return sendErrorResponse(400, "Invalid or missing Upgrade header");
|
||||
}
|
||||
@ -355,6 +326,7 @@ namespace ix
|
||||
ss << "Sec-WebSocket-Accept: " << std::string(output) << "\r\n";
|
||||
ss << "Upgrade: websocket\r\n";
|
||||
ss << "Connection: Upgrade\r\n";
|
||||
ss << "Server: " << userAgent() << "\r\n";
|
||||
|
||||
// Parse the client headers. Does it support deflate ?
|
||||
std::string header = headers["sec-websocket-extensions"];
|
||||
|
@ -15,7 +15,6 @@
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -50,11 +49,13 @@ namespace ix
|
||||
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
|
||||
std::atomic<bool>& enablePerMessageDeflate);
|
||||
|
||||
WebSocketInitResult clientHandshake(const std::string& url,
|
||||
const std::string& host,
|
||||
const std::string& path,
|
||||
int port,
|
||||
int timeoutSecs);
|
||||
WebSocketInitResult clientHandshake(
|
||||
const std::string& url,
|
||||
const WebSocketHttpHeaders& extraHeaders,
|
||||
const std::string& host,
|
||||
const std::string& path,
|
||||
int port,
|
||||
int timeoutSecs);
|
||||
|
||||
WebSocketInitResult serverHandshake(int fd, int timeoutSecs);
|
||||
|
||||
@ -64,8 +65,6 @@ namespace ix
|
||||
// Parse HTTP headers
|
||||
WebSocketInitResult sendErrorResponse(int code, const std::string& reason);
|
||||
|
||||
std::tuple<std::string, std::string, std::string> parseRequestLine(const std::string& line);
|
||||
std::string trim(const std::string& str);
|
||||
bool insensitiveStringCompare(const std::string& a, const std::string& b);
|
||||
|
||||
std::atomic<bool>& _requestInitCancellation;
|
||||
|
@ -19,12 +19,12 @@
|
||||
|
||||
namespace ix
|
||||
{
|
||||
using OnConnectionCallback =
|
||||
std::function<void(std::shared_ptr<WebSocket>, std::shared_ptr<ConnectionState>)>;
|
||||
|
||||
class WebSocketServer final : public SocketServer
|
||||
{
|
||||
public:
|
||||
using OnConnectionCallback =
|
||||
std::function<void(std::shared_ptr<WebSocket>, std::shared_ptr<ConnectionState>)>;
|
||||
|
||||
WebSocketServer(int port = SocketServer::kDefaultPort,
|
||||
const std::string& host = SocketServer::kDefaultHost,
|
||||
int backlog = SocketServer::kDefaultTcpBacklog,
|
||||
|
@ -37,6 +37,7 @@
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include "IXUrlParser.h"
|
||||
#include "IXSocketFactory.h"
|
||||
#include "IXUtf8Validator.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
@ -76,6 +77,7 @@ namespace ix
|
||||
|
||||
WebSocketTransport::WebSocketTransport() :
|
||||
_useMask(true),
|
||||
_compressedMessage(false),
|
||||
_readyState(ReadyState::CLOSED),
|
||||
_closeCode(WebSocketCloseConstants::kInternalErrorCode),
|
||||
_closeReason(WebSocketCloseConstants::kInternalErrorMessage),
|
||||
@ -127,8 +129,10 @@ namespace ix
|
||||
}
|
||||
|
||||
// Client
|
||||
WebSocketInitResult WebSocketTransport::connectToUrl(const std::string& url,
|
||||
int timeoutSecs)
|
||||
WebSocketInitResult WebSocketTransport::connectToUrl(
|
||||
const std::string& url,
|
||||
const WebSocketHttpHeaders& headers,
|
||||
int timeoutSecs)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_socketMutex);
|
||||
|
||||
@ -156,8 +160,8 @@ namespace ix
|
||||
_perMessageDeflateOptions,
|
||||
_enablePerMessageDeflate);
|
||||
|
||||
auto result = webSocketHandshake.clientHandshake(url, host, path, port,
|
||||
timeoutSecs);
|
||||
auto result = webSocketHandshake.clientHandshake(url, headers, host, path,
|
||||
port, timeoutSecs);
|
||||
if (result.success)
|
||||
{
|
||||
setReadyState(ReadyState::OPEN);
|
||||
@ -330,7 +334,7 @@ namespace ix
|
||||
}
|
||||
|
||||
// poll the socket
|
||||
PollResultType pollResult = _socket->poll(lastingTimeoutDelayInMs);
|
||||
PollResultType pollResult = _socket->isReadyToRead(lastingTimeoutDelayInMs);
|
||||
|
||||
// Make sure we send all the buffered data
|
||||
// there can be a lot of it for large messages.
|
||||
@ -470,12 +474,22 @@ namespace ix
|
||||
const uint8_t * data = (uint8_t *) &_rxbuf[0]; // peek, but don't consume
|
||||
ws.fin = (data[0] & 0x80) == 0x80;
|
||||
ws.rsv1 = (data[0] & 0x40) == 0x40;
|
||||
ws.rsv2 = (data[0] & 0x20) == 0x20;
|
||||
ws.rsv3 = (data[0] & 0x10) == 0x10;
|
||||
ws.opcode = (wsheader_type::opcode_type) (data[0] & 0x0f);
|
||||
ws.mask = (data[1] & 0x80) == 0x80;
|
||||
ws.N0 = (data[1] & 0x7f);
|
||||
ws.header_size = 2 + (ws.N0 == 126? 2 : 0) + (ws.N0 == 127? 8 : 0) + (ws.mask? 4 : 0);
|
||||
if (_rxbuf.size() < ws.header_size) break; /* Need: ws.header_size - _rxbuf.size() */
|
||||
|
||||
if ((ws.rsv1 && !_enablePerMessageDeflate) || ws.rsv2 || ws.rsv3)
|
||||
{
|
||||
close(WebSocketCloseConstants::kProtocolErrorCode,
|
||||
WebSocketCloseConstants::kProtocolErrorReservedBitUsed,
|
||||
_rxbuf.size());
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Calculate payload length:
|
||||
// 0-125 mean the payload is that long.
|
||||
@ -534,29 +548,62 @@ namespace ix
|
||||
return; /* Need: ws.header_size+ws.N - _rxbuf.size() */
|
||||
}
|
||||
|
||||
if (!ws.fin && (
|
||||
ws.opcode == wsheader_type::PING
|
||||
|| ws.opcode == wsheader_type::PONG
|
||||
|| ws.opcode == wsheader_type::CLOSE
|
||||
)){
|
||||
// Control messages should not be fragmented
|
||||
close(WebSocketCloseConstants::kProtocolErrorCode,
|
||||
WebSocketCloseConstants::kProtocolErrorCodeControlMessageFragmented);
|
||||
return;
|
||||
}
|
||||
|
||||
unmaskReceiveBuffer(ws);
|
||||
std::string frameData(_rxbuf.begin()+ws.header_size,
|
||||
_rxbuf.begin()+ws.header_size+(size_t) ws.N);
|
||||
|
||||
// We got a whole message, now do something with it:
|
||||
if (
|
||||
ws.opcode == wsheader_type::TEXT_FRAME
|
||||
|| ws.opcode == wsheader_type::BINARY_FRAME
|
||||
|| ws.opcode == wsheader_type::CONTINUATION
|
||||
) {
|
||||
unmaskReceiveBuffer(ws);
|
||||
|
||||
MessageKind messageKind =
|
||||
(ws.opcode == wsheader_type::TEXT_FRAME)
|
||||
? MessageKind::MSG_TEXT
|
||||
: MessageKind::MSG_BINARY;
|
||||
if (ws.opcode != wsheader_type::CONTINUATION)
|
||||
{
|
||||
_fragmentedMessageKind =
|
||||
(ws.opcode == wsheader_type::TEXT_FRAME)
|
||||
? MessageKind::MSG_TEXT
|
||||
: MessageKind::MSG_BINARY;
|
||||
|
||||
_compressedMessage = _enablePerMessageDeflate && ws.rsv1;
|
||||
|
||||
// Continuation message needs to follow a non-fin TEXT or BINARY message
|
||||
if (!_chunks.empty())
|
||||
{
|
||||
close(WebSocketCloseConstants::kProtocolErrorCode,
|
||||
WebSocketCloseConstants::kProtocolErrorCodeDataOpcodeOutOfSequence);
|
||||
}
|
||||
}
|
||||
else if (_chunks.empty())
|
||||
{
|
||||
// Continuation message need to follow a non-fin TEXT or BINARY message
|
||||
close(WebSocketCloseConstants::kProtocolErrorCode,
|
||||
WebSocketCloseConstants::kProtocolErrorCodeContinuationOpCodeOutOfSequence);
|
||||
}
|
||||
|
||||
//
|
||||
// Usual case. Small unfragmented messages
|
||||
//
|
||||
if (ws.fin && _chunks.empty())
|
||||
{
|
||||
emitMessage(messageKind,
|
||||
std::string(_rxbuf.begin()+ws.header_size,
|
||||
_rxbuf.begin()+ws.header_size+(size_t) ws.N),
|
||||
ws,
|
||||
emitMessage(_fragmentedMessageKind,
|
||||
frameData,
|
||||
_compressedMessage,
|
||||
onMessageCallback);
|
||||
|
||||
_compressedMessage = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -567,54 +614,54 @@ namespace ix
|
||||
// the internal buffer which is slow and can let the internal OS
|
||||
// receive buffer fill out.
|
||||
//
|
||||
_chunks.emplace_back(
|
||||
std::vector<uint8_t>(_rxbuf.begin()+ws.header_size,
|
||||
_rxbuf.begin()+ws.header_size+(size_t)ws.N));
|
||||
_chunks.emplace_back(frameData);
|
||||
|
||||
if (ws.fin)
|
||||
{
|
||||
emitMessage(messageKind, getMergedChunks(), ws, onMessageCallback);
|
||||
emitMessage(_fragmentedMessageKind, getMergedChunks(),
|
||||
_compressedMessage, onMessageCallback);
|
||||
|
||||
_chunks.clear();
|
||||
_compressedMessage = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
emitMessage(MessageKind::FRAGMENT, std::string(), ws, onMessageCallback);
|
||||
emitMessage(MessageKind::FRAGMENT, std::string(), false, onMessageCallback);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ws.opcode == wsheader_type::PING)
|
||||
{
|
||||
unmaskReceiveBuffer(ws);
|
||||
|
||||
std::string pingData(_rxbuf.begin()+ws.header_size,
|
||||
_rxbuf.begin()+ws.header_size + (size_t) ws.N);
|
||||
// too large
|
||||
if (frameData.size() > 125)
|
||||
{
|
||||
// Unexpected frame type
|
||||
close(WebSocketCloseConstants::kProtocolErrorCode,
|
||||
WebSocketCloseConstants::kProtocolErrorPingPayloadOversized);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_enablePong)
|
||||
{
|
||||
// Reply back right away
|
||||
bool compress = false;
|
||||
sendData(wsheader_type::PONG, pingData, compress);
|
||||
sendData(wsheader_type::PONG, frameData, compress);
|
||||
}
|
||||
|
||||
emitMessage(MessageKind::PING, pingData, ws, onMessageCallback);
|
||||
emitMessage(MessageKind::PING, frameData, false, onMessageCallback);
|
||||
}
|
||||
else if (ws.opcode == wsheader_type::PONG)
|
||||
{
|
||||
unmaskReceiveBuffer(ws);
|
||||
std::string pongData(_rxbuf.begin()+ws.header_size,
|
||||
_rxbuf.begin()+ws.header_size + (size_t) ws.N);
|
||||
|
||||
std::lock_guard<std::mutex> lck(_lastReceivePongTimePointMutex);
|
||||
_lastReceivePongTimePoint = std::chrono::steady_clock::now();
|
||||
|
||||
emitMessage(MessageKind::PONG, pongData, ws, onMessageCallback);
|
||||
emitMessage(MessageKind::PONG, frameData, false, onMessageCallback);
|
||||
}
|
||||
else if (ws.opcode == wsheader_type::CLOSE)
|
||||
{
|
||||
std::string reason;
|
||||
uint16_t code = 0;
|
||||
|
||||
unmaskReceiveBuffer(ws);
|
||||
|
||||
if (ws.N >= 2)
|
||||
{
|
||||
// Extract the close code first, available as the first 2 bytes
|
||||
@ -624,8 +671,28 @@ namespace ix
|
||||
// Get the reason.
|
||||
if (ws.N > 2)
|
||||
{
|
||||
reason.assign(_rxbuf.begin()+ws.header_size + 2,
|
||||
_rxbuf.begin()+ws.header_size + (size_t) ws.N);
|
||||
reason = frameData.substr(2, frameData.size());
|
||||
}
|
||||
|
||||
// Validate that the reason is proper utf-8. Autobahn 7.5.1
|
||||
if (!validateUtf8(reason))
|
||||
{
|
||||
code = WebSocketCloseConstants::kInvalidFramePayloadData;
|
||||
reason = WebSocketCloseConstants::kInvalidFramePayloadDataMessage;
|
||||
}
|
||||
|
||||
// Validate close codes. Autobahn 7.9.*
|
||||
// 1014, 1015 are debattable. The firefox MSDN has a description for them
|
||||
if (code < 1000 || code == 1004 || code == 1006 ||
|
||||
(code > 1013 && code < 3000))
|
||||
{
|
||||
// build up an error message containing the bad error code
|
||||
std::stringstream ss;
|
||||
ss << WebSocketCloseConstants::kInvalidCloseCodeMessage
|
||||
<< ": " << code;
|
||||
reason = ss.str();
|
||||
|
||||
code = WebSocketCloseConstants::kProtocolErrorCode;
|
||||
}
|
||||
}
|
||||
else
|
||||
@ -711,8 +778,7 @@ namespace ix
|
||||
|
||||
for (auto&& chunk : _chunks)
|
||||
{
|
||||
std::string str(chunk.begin(), chunk.end());
|
||||
msg += str;
|
||||
msg += chunk;
|
||||
}
|
||||
|
||||
return msg;
|
||||
@ -720,21 +786,38 @@ namespace ix
|
||||
|
||||
void WebSocketTransport::emitMessage(MessageKind messageKind,
|
||||
const std::string& message,
|
||||
const wsheader_type& ws,
|
||||
bool compressedMessage,
|
||||
const OnMessageCallback& onMessageCallback)
|
||||
{
|
||||
size_t wireSize = message.size();
|
||||
|
||||
// When the RSV1 bit is 1 it means the message is compressed
|
||||
if (_enablePerMessageDeflate && ws.rsv1 && messageKind != MessageKind::FRAGMENT)
|
||||
if (compressedMessage && messageKind != MessageKind::FRAGMENT)
|
||||
{
|
||||
std::string decompressedMessage;
|
||||
bool success = _perMessageDeflate.decompress(message, decompressedMessage);
|
||||
onMessageCallback(decompressedMessage, wireSize, !success, messageKind);
|
||||
|
||||
if (messageKind == MessageKind::MSG_TEXT && !validateUtf8(decompressedMessage))
|
||||
{
|
||||
close(WebSocketCloseConstants::kInvalidFramePayloadData,
|
||||
WebSocketCloseConstants::kInvalidFramePayloadDataMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
onMessageCallback(decompressedMessage, wireSize, !success, messageKind);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
onMessageCallback(message, wireSize, false, messageKind);
|
||||
if (messageKind == MessageKind::MSG_TEXT && !validateUtf8(message))
|
||||
{
|
||||
close(WebSocketCloseConstants::kInvalidFramePayloadData,
|
||||
WebSocketCloseConstants::kInvalidFramePayloadDataMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
onMessageCallback(message, wireSize, false, messageKind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -755,7 +838,7 @@ namespace ix
|
||||
{
|
||||
if (_readyState != ReadyState::OPEN && _readyState != ReadyState::CLOSING)
|
||||
{
|
||||
return WebSocketSendInfo();
|
||||
return WebSocketSendInfo(false);
|
||||
}
|
||||
|
||||
size_t payloadSize = message.size();
|
||||
@ -783,6 +866,8 @@ namespace ix
|
||||
message_end = compressedMessage.end();
|
||||
}
|
||||
|
||||
_txbuf.reserve(wireSize);
|
||||
|
||||
// Common case for most message. No fragmentation required.
|
||||
if (wireSize < kChunkSize)
|
||||
{
|
||||
@ -870,8 +955,9 @@ namespace ix
|
||||
header[0] |= 0x80;
|
||||
}
|
||||
|
||||
// This bit indicate that the frame is compressed
|
||||
if (compress)
|
||||
// The rsv1 bit indicate that the frame is compressed
|
||||
// continuation opcodes should not set it. Autobahn 12.2.10 and others 12.X
|
||||
if (compress && type != wsheader_type::CONTINUATION)
|
||||
{
|
||||
header[0] |= 0x40;
|
||||
}
|
||||
@ -1047,6 +1133,11 @@ namespace ix
|
||||
|
||||
if (_readyState == ReadyState::CLOSING || _readyState == ReadyState::CLOSED) return;
|
||||
|
||||
if (closeWireSize == 0)
|
||||
{
|
||||
closeWireSize = reason.size();
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_closeDataMutex);
|
||||
_closeCode = code;
|
||||
|
@ -24,6 +24,7 @@
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
@ -75,8 +76,10 @@ namespace ix
|
||||
int pingIntervalSecs,
|
||||
int pingTimeoutSecs);
|
||||
|
||||
WebSocketInitResult connectToUrl(const std::string& url, // Client
|
||||
int timeoutSecs);
|
||||
WebSocketInitResult connectToUrl( // Client
|
||||
const std::string& url,
|
||||
const WebSocketHttpHeaders& headers,
|
||||
int timeoutSecs);
|
||||
WebSocketInitResult connectToSocket(int fd, // Server
|
||||
int timeoutSecs);
|
||||
|
||||
@ -109,6 +112,8 @@ namespace ix
|
||||
unsigned header_size;
|
||||
bool fin;
|
||||
bool rsv1;
|
||||
bool rsv2;
|
||||
bool rsv3;
|
||||
bool mask;
|
||||
enum opcode_type
|
||||
{
|
||||
@ -144,7 +149,15 @@ namespace ix
|
||||
// messages (tested messages up to 700M) and we cannot put them in a single
|
||||
// buffer that is resized, as this operation can be slow when a buffer has its
|
||||
// size increased 2 fold, while appending to a list has a fixed cost.
|
||||
std::list<std::vector<uint8_t>> _chunks;
|
||||
std::list<std::string> _chunks;
|
||||
|
||||
// Record the message kind (will be TEXT or BINARY) for a fragmented
|
||||
// message, present in the first chunk, since the final chunk will be a
|
||||
// CONTINUATION opcode and doesn't tell the full message kind
|
||||
MessageKind _fragmentedMessageKind;
|
||||
|
||||
// Ditto for whether a message is compressed
|
||||
bool _compressedMessage;
|
||||
|
||||
// Fragments are 32K long
|
||||
static constexpr size_t kChunkSize = 1 << 15;
|
||||
@ -234,7 +247,7 @@ namespace ix
|
||||
|
||||
void emitMessage(MessageKind messageKind,
|
||||
const std::string& message,
|
||||
const wsheader_type& ws,
|
||||
bool compressedMessage,
|
||||
const OnMessageCallback& onMessageCallback);
|
||||
|
||||
bool isSendBufferEmpty() const;
|
||||
|
9
ixwebsocket/IXWebSocketVersion.h
Normal file
9
ixwebsocket/IXWebSocketVersion.h
Normal file
@ -0,0 +1,9 @@
|
||||
/*
|
||||
* IXWebSocketVersion.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#define IX_WEBSOCKET_VERSION "5.2.0"
|
16
makefile
16
makefile
@ -9,14 +9,17 @@ 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)
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j install)
|
||||
|
||||
ws:
|
||||
mkdir -p build && (cd build ; cmake -DUSE_TLS=1 -DUSE_WS=1 -DUSE_MBED_TLS=1 -DUSE_VENDORED_THIRD_PARTY=1 .. ; make -j)
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_MBED_TLS=1 .. ; make -j)
|
||||
|
||||
uninstall:
|
||||
xargs rm -fv < build/install_manifest.txt
|
||||
|
||||
tag:
|
||||
git tag v"`cat DOCKER_VERSION`"
|
||||
|
||||
.PHONY: docker
|
||||
|
||||
NAME := bsergean/ws
|
||||
@ -60,6 +63,9 @@ test:
|
||||
ws_test: ws
|
||||
(cd ws ; env DEBUG=1 PATH=../ws/build:$$PATH bash test_ws.sh)
|
||||
|
||||
autobahn_report:
|
||||
cp -rvf ~/sandbox/reports/clients/* ../bsergean.github.io/IXWebSocket/autobahn/
|
||||
|
||||
# For the fork that is configured with appveyor
|
||||
rebase_upstream:
|
||||
git fetch upstream
|
||||
@ -71,6 +77,12 @@ install_cmake_for_linux:
|
||||
mkdir -p /tmp/cmake
|
||||
(cd /tmp/cmake ; curl -L -O https://github.com/Kitware/CMake/releases/download/v3.14.0/cmake-3.14.0-Linux-x86_64.tar.gz ; tar zxf cmake-3.14.0-Linux-x86_64.tar.gz)
|
||||
|
||||
# python -m venv venv
|
||||
# source venv/bin/activate
|
||||
# pip install mkdocs
|
||||
doc:
|
||||
./venv/bin/mkdocs build -d ../bsergean.github.io/IXWebSocket/site
|
||||
|
||||
.PHONY: test
|
||||
.PHONY: build
|
||||
.PHONY: ws
|
||||
|
1
mkdocs.yml
Normal file
1
mkdocs.yml
Normal file
@ -0,0 +1 @@
|
||||
site_name: IXWebSocket
|
@ -7,7 +7,7 @@ project (ixwebsocket_unittest)
|
||||
|
||||
set (CMAKE_CXX_STANDARD 14)
|
||||
|
||||
if (NOT WIN32)
|
||||
if (MAC)
|
||||
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")
|
||||
@ -28,6 +28,7 @@ include_directories(
|
||||
set (SOURCES
|
||||
test_runner.cpp
|
||||
IXTest.cpp
|
||||
IXGetFreePort.cpp
|
||||
../third_party/msgpack11/msgpack11.cpp
|
||||
../ws/ixcore/utils/IXCoreLogger.cpp
|
||||
|
||||
@ -38,6 +39,8 @@ set (SOURCES
|
||||
IXUrlParserTest.cpp
|
||||
IXWebSocketServerTest.cpp
|
||||
IXHttpClientTest.cpp
|
||||
IXHttpServerTest.cpp
|
||||
IXUnityBuildsTest.cpp
|
||||
)
|
||||
|
||||
# Some unittest don't work on windows yet
|
||||
@ -64,7 +67,7 @@ endif()
|
||||
|
||||
add_executable(ixwebsocket_unittest ${SOURCES})
|
||||
|
||||
if (NOT WIN32)
|
||||
if (MAC)
|
||||
add_sanitizers(ixwebsocket_unittest)
|
||||
endif()
|
||||
|
||||
|
@ -17,33 +17,33 @@ TEST_CASE("dns", "[net]")
|
||||
{
|
||||
SECTION("Test resolving a known hostname")
|
||||
{
|
||||
DNSLookup dnsLookup("www.google.com", 80);
|
||||
auto dnsLookup = std::make_shared<DNSLookup>("www.google.com", 80);
|
||||
|
||||
std::string errMsg;
|
||||
struct addrinfo* res;
|
||||
|
||||
res = dnsLookup.resolve(errMsg, [] { return false; });
|
||||
res = dnsLookup->resolve(errMsg, [] { return false; });
|
||||
std::cerr << "Error message: " << errMsg << std::endl;
|
||||
REQUIRE(res != nullptr);
|
||||
}
|
||||
|
||||
SECTION("Test resolving a non-existing hostname")
|
||||
{
|
||||
DNSLookup dnsLookup("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", 80);
|
||||
auto dnsLookup = std::make_shared<DNSLookup>("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww", 80);
|
||||
|
||||
std::string errMsg;
|
||||
struct addrinfo* res = dnsLookup.resolve(errMsg, [] { return false; });
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg, [] { return false; });
|
||||
std::cerr << "Error message: " << errMsg << std::endl;
|
||||
REQUIRE(res == nullptr);
|
||||
}
|
||||
|
||||
SECTION("Test resolving a good hostname, with cancellation")
|
||||
{
|
||||
DNSLookup dnsLookup("www.google.com", 80, 1);
|
||||
auto dnsLookup = std::make_shared<DNSLookup>("www.google.com", 80, 1);
|
||||
|
||||
std::string errMsg;
|
||||
// The callback returning true means we are requesting cancellation
|
||||
struct addrinfo* res = dnsLookup.resolve(errMsg, [] { return true; });
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg, [] { return true; });
|
||||
std::cerr << "Error message: " << errMsg << std::endl;
|
||||
REQUIRE(res == nullptr);
|
||||
}
|
||||
|
93
test/IXGetFreePort.cpp
Normal file
93
test/IXGetFreePort.cpp
Normal file
@ -0,0 +1,93 @@
|
||||
/*
|
||||
* IXGetFreePort.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXGetFreePort.h"
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
#include <string>
|
||||
#include <random>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int getAnyFreePortRandom()
|
||||
{
|
||||
std::random_device rd;
|
||||
std::uniform_int_distribution<int> dist(1024 + 1, 65535);
|
||||
|
||||
return dist(rd);
|
||||
}
|
||||
|
||||
int getAnyFreePort()
|
||||
{
|
||||
int defaultPort = 8090;
|
||||
int sockfd;
|
||||
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
|
||||
{
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
int enable = 1;
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
|
||||
(char*) &enable, sizeof(enable)) < 0)
|
||||
{
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
// Bind to port 0. This is the standard way to get a free port.
|
||||
struct sockaddr_in server; // server address information
|
||||
server.sin_family = AF_INET;
|
||||
server.sin_port = htons(0);
|
||||
server.sin_addr.s_addr = inet_addr("127.0.0.1");
|
||||
|
||||
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
|
||||
{
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
struct sockaddr_in sa; // server address information
|
||||
socklen_t len = sizeof(sa);
|
||||
if (getsockname(sockfd, (struct sockaddr *) &sa, &len) < 0)
|
||||
{
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
int port = ntohs(sa.sin_port);
|
||||
Socket::closeSocket(sockfd);
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
int getFreePort()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(address_sanitizer)
|
||||
int port = getAnyFreePortRandom();
|
||||
# else
|
||||
int port = getAnyFreePort();
|
||||
# endif
|
||||
#else
|
||||
int port = getAnyFreePort();
|
||||
#endif
|
||||
//
|
||||
// Only port above 1024 can be used by non root users, but for some
|
||||
// reason I got port 7 returned with macOS when binding on port 0...
|
||||
//
|
||||
if (port > 1024)
|
||||
{
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
} // namespace ix
|
||||
|
||||
|
12
test/IXGetFreePort.h
Normal file
12
test/IXGetFreePort.h
Normal file
@ -0,0 +1,12 @@
|
||||
/*
|
||||
* IXGetFreePort.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int getFreePort();
|
||||
} // namespace ix
|
70
test/IXHttpServerTest.cpp
Normal file
70
test/IXHttpServerTest.cpp
Normal file
@ -0,0 +1,70 @@
|
||||
/*
|
||||
* IXSocketTest.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
#include "IXGetFreePort.h"
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
TEST_CASE("http server", "[httpd]")
|
||||
{
|
||||
SECTION("Connect to a local HTTP server")
|
||||
{
|
||||
int port = getFreePort();
|
||||
ix::HttpServer server(port, "127.0.0.1");
|
||||
|
||||
auto res = server.listen();
|
||||
REQUIRE(res.first);
|
||||
server.start();
|
||||
|
||||
HttpClient httpClient;
|
||||
WebSocketHttpHeaders headers;
|
||||
|
||||
std::string url("http://127.0.0.1:");
|
||||
url += std::to_string(port);
|
||||
url += "/data/foo.txt";
|
||||
auto args = httpClient.createRequest(url);
|
||||
|
||||
args->extraHeaders = headers;
|
||||
args->connectTimeout = 60;
|
||||
args->transferTimeout = 60;
|
||||
args->followRedirects = true;
|
||||
args->maxRedirects = 10;
|
||||
args->verbose = true;
|
||||
args->compress = true;
|
||||
args->logger = [](const std::string& msg)
|
||||
{
|
||||
std::cout << msg;
|
||||
};
|
||||
args->onProgressCallback = [](int current, int total) -> bool
|
||||
{
|
||||
std::cerr << "\r" << "Downloaded "
|
||||
<< current << " bytes out of " << total;
|
||||
return true;
|
||||
};
|
||||
|
||||
auto response = httpClient.get(url, args);
|
||||
|
||||
for (auto it : response->headers)
|
||||
{
|
||||
std::cerr << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
|
||||
std::cerr << "Upload size: " << response->uploadSize << std::endl;
|
||||
std::cerr << "Download size: " << response->downloadSize << std::endl;
|
||||
std::cerr << "Status: " << response->statusCode << std::endl;
|
||||
std::cerr << "Error message: " << response->errorMsg << std::endl;
|
||||
|
||||
REQUIRE(response->errorCode == HttpErrorCode::Ok);
|
||||
REQUIRE(response->statusCode == 200);
|
||||
|
||||
server.stop();
|
||||
}
|
||||
}
|
@ -72,88 +72,6 @@ namespace ix
|
||||
Logger() << msg;
|
||||
}
|
||||
|
||||
int getAnyFreePortRandom()
|
||||
{
|
||||
std::random_device rd;
|
||||
std::uniform_int_distribution<int> dist(1024 + 1, 65535);
|
||||
|
||||
return dist(rd);
|
||||
}
|
||||
|
||||
int getAnyFreePort()
|
||||
{
|
||||
int defaultPort = 8090;
|
||||
int sockfd;
|
||||
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
|
||||
{
|
||||
log("Cannot compute a free port. socket error.");
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
int enable = 1;
|
||||
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
|
||||
(char*) &enable, sizeof(enable)) < 0)
|
||||
{
|
||||
log("Cannot compute a free port. setsockopt error.");
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
// Bind to port 0. This is the standard way to get a free port.
|
||||
struct sockaddr_in server; // server address information
|
||||
server.sin_family = AF_INET;
|
||||
server.sin_port = htons(0);
|
||||
server.sin_addr.s_addr = inet_addr("127.0.0.1");
|
||||
|
||||
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
|
||||
{
|
||||
log("Cannot compute a free port. bind error.");
|
||||
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
struct sockaddr_in sa; // server address information
|
||||
socklen_t len = sizeof(sa);
|
||||
if (getsockname(sockfd, (struct sockaddr *) &sa, &len) < 0)
|
||||
{
|
||||
log("Cannot compute a free port. getsockname error.");
|
||||
|
||||
Socket::closeSocket(sockfd);
|
||||
return getAnyFreePortRandom();
|
||||
}
|
||||
|
||||
int port = ntohs(sa.sin_port);
|
||||
Socket::closeSocket(sockfd);
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
int getFreePort()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
#if defined(__has_feature)
|
||||
# if __has_feature(address_sanitizer)
|
||||
int port = getAnyFreePortRandom();
|
||||
# else
|
||||
int port = getAnyFreePort();
|
||||
# endif
|
||||
#else
|
||||
int port = getAnyFreePort();
|
||||
#endif
|
||||
//
|
||||
// Only port above 1024 can be used by non root users, but for some
|
||||
// reason I got port 7 returned with macOS when binding on port 0...
|
||||
//
|
||||
if (port > 1024)
|
||||
{
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void hexDump(const std::string& prefix,
|
||||
const std::string& s)
|
||||
{
|
||||
|
@ -6,6 +6,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXGetFreePort.h"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <mutex>
|
||||
@ -46,7 +47,5 @@ namespace ix
|
||||
|
||||
void log(const std::string& msg);
|
||||
|
||||
int getFreePort();
|
||||
|
||||
bool startWebSocketEchoServer(ix::WebSocketServer& server);
|
||||
} // namespace ix
|
||||
|
52
test/IXUnityBuildsTest.cpp
Normal file
52
test/IXUnityBuildsTest.cpp
Normal file
@ -0,0 +1,52 @@
|
||||
/*
|
||||
* IXUnityBuildsTest.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
#include <ixwebsocket/IXConnectionState.h>
|
||||
#include <ixwebsocket/IXDNSLookup.h>
|
||||
#include <ixwebsocket/IXHttp.h>
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixwebsocket/IXProgressCallback.h>
|
||||
#include <ixwebsocket/IXSelectInterrupt.h>
|
||||
#include <ixwebsocket/IXSelectInterruptFactory.h>
|
||||
#include <ixwebsocket/IXSetThreadName.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketConnect.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <ixwebsocket/IXSocketServer.h>
|
||||
#include <ixwebsocket/IXUrlParser.h>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketCloseConstants.h>
|
||||
#include <ixwebsocket/IXWebSocketCloseInfo.h>
|
||||
#include <ixwebsocket/IXWebSocketErrorInfo.h>
|
||||
#include <ixwebsocket/IXWebSocketHandshake.h>
|
||||
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
|
||||
#include <ixwebsocket/IXWebSocketMessage.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageQueue.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageType.h>
|
||||
#include <ixwebsocket/IXWebSocketOpenInfo.h>
|
||||
#include <ixwebsocket/IXWebSocketPerMessageDeflate.h>
|
||||
#include <ixwebsocket/IXWebSocketPerMessageDeflateCodec.h>
|
||||
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
|
||||
#include <ixwebsocket/IXWebSocketSendInfo.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <ixwebsocket/IXWebSocketTransport.h>
|
||||
#include <ixwebsocket/LUrlParser.h>
|
||||
#include <ixwebsocket/libwshandshake.hpp>
|
||||
|
||||
#include "catch.hpp"
|
||||
|
||||
using namespace ix;
|
||||
|
||||
TEST_CASE("unity build", "[unity_build]")
|
||||
{
|
||||
SECTION("dummy test")
|
||||
{
|
||||
REQUIRE(true);
|
||||
}
|
||||
}
|
@ -34,6 +34,8 @@ namespace
|
||||
const std::string& getCloseReason();
|
||||
bool getCloseRemote();
|
||||
|
||||
bool hasConnectionError() const;
|
||||
|
||||
private:
|
||||
ix::WebSocket _webSocket;
|
||||
int _port;
|
||||
@ -42,6 +44,7 @@ namespace
|
||||
uint16_t _closeCode;
|
||||
std::string _closeReason;
|
||||
bool _closeRemote;
|
||||
std::atomic<bool> _connectionError;
|
||||
};
|
||||
|
||||
WebSocketClient::WebSocketClient(int port)
|
||||
@ -49,10 +52,16 @@ namespace
|
||||
, _closeCode(0)
|
||||
, _closeReason(std::string(""))
|
||||
, _closeRemote(false)
|
||||
, _connectionError(false)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
bool WebSocketClient::hasConnectionError() const
|
||||
{
|
||||
return _connectionError;
|
||||
}
|
||||
|
||||
bool WebSocketClient::isReady() const
|
||||
{
|
||||
return _webSocket.getReadyState() == ix::ReadyState::Open;
|
||||
@ -133,6 +142,7 @@ namespace
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
_connectionError = true;
|
||||
ss << "Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
@ -248,6 +258,7 @@ TEST_CASE("Websocket_client_close_default", "[close]")
|
||||
// Wait for all chat instance to be ready
|
||||
while (true)
|
||||
{
|
||||
REQUIRE(!webSocketClient.hasConnectionError());
|
||||
if (webSocketClient.isReady()) break;
|
||||
ix::msleep(10);
|
||||
}
|
||||
|
@ -206,7 +206,7 @@ namespace
|
||||
|
||||
void WebSocketChat::sendMessage(const std::string& text)
|
||||
{
|
||||
_webSocket.send(encodeMessage(text));
|
||||
_webSocket.sendBinary(encodeMessage(text));
|
||||
}
|
||||
|
||||
bool startServer(ix::WebSocketServer& server)
|
||||
@ -239,7 +239,7 @@ namespace
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->send(msg->str);
|
||||
client->sendBinary(msg->str);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
1
test/data/foo.txt
Normal file
1
test/data/foo.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello world
|
@ -99,8 +99,10 @@ def runCMake(sanitizer, buildDir):
|
||||
#generator = '"NMake Makefiles"'
|
||||
#generator = '"Visual Studio 16 2019"'
|
||||
generator = '"Visual Studio 15 2017"'
|
||||
USE_VENDORED_THIRD_PARTY = 'ON'
|
||||
else:
|
||||
generator = '"Unix Makefiles"'
|
||||
USE_VENDORED_THIRD_PARTY = 'ON'
|
||||
|
||||
CMAKE_BUILD_TYPE = BUILD_TYPE
|
||||
|
||||
@ -110,6 +112,7 @@ def runCMake(sanitizer, buildDir):
|
||||
-DCMAKE_BUILD_TYPE={CMAKE_BUILD_TYPE} \
|
||||
-DUSE_TLS=1 \
|
||||
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
|
||||
-DUSE_VENDORED_THIRD_PARTY={USE_VENDORED_THIRD_PARTY} \
|
||||
-G{generator}'
|
||||
|
||||
cmakeCmd = fmt.format(**locals())
|
||||
|
44
third_party/cpp-linenoise/.gitignore
vendored
Normal file
44
third_party/cpp-linenoise/.gitignore
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
# Others
|
||||
*.dSYM
|
||||
*.swp
|
||||
Debug
|
||||
Release
|
||||
*.suo
|
||||
*.sdf
|
||||
*.user
|
||||
xcuserdata
|
||||
*.xcworkspace
|
||||
Makefile
|
||||
CMakeFiles
|
||||
CMakeCache.txt
|
||||
*.cmake
|
||||
history.txt
|
22
third_party/cpp-linenoise/LICENSE
vendored
Normal file
22
third_party/cpp-linenoise/LICENSE
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
Copyright (c) 2015 yhirose
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
95
third_party/cpp-linenoise/README.md
vendored
Normal file
95
third_party/cpp-linenoise/README.md
vendored
Normal file
@ -0,0 +1,95 @@
|
||||
cpp-linenoise
|
||||
=============
|
||||
|
||||
Multi-platfrom (Unix, Windows) C++ header-only linenoise-based readline library.
|
||||
|
||||
This library gathered code from following excellent libraries, clean it up, and put it into a C++ header file for convenience.
|
||||
|
||||
* `linenoise.h` and `linenose.c` ([antirez/linenoise](https://github.com/antirez/linenoise))
|
||||
* `ANSI.c` ([adoxa/ansicon](https://github.com/adoxa/ansicon))
|
||||
* `Win32_ANSI.h` and `Win32_ANSI.c` ([MSOpenTech/redis](https://github.com/MSOpenTech/redis))
|
||||
|
||||
The licenses for the libraries are included in `linenoise.hpp`.
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
```c++
|
||||
#include "linenoise.hpp"
|
||||
|
||||
...
|
||||
|
||||
const auto path = "history.txt";
|
||||
|
||||
// Setup completion words every time when a user types
|
||||
linenoise::SetCompletionCallback([](const char* editBuffer, std::vector<std::string>& completions) {
|
||||
if (editBuffer[0] == 'h') {
|
||||
completions.push_back("hello");
|
||||
completions.push_back("hello there");
|
||||
}
|
||||
});
|
||||
|
||||
// Enable the multi-line mode
|
||||
linenoise::SetMultiLine(true);
|
||||
|
||||
// Set max length of the history
|
||||
linenoise::SetHistoryMaxLen(4);
|
||||
|
||||
// Load history
|
||||
linenoise::LoadHistory(path);
|
||||
|
||||
while (true) {
|
||||
// Read line
|
||||
std::string line;
|
||||
auto quit = linenoise::Readline("hello> ", line);
|
||||
|
||||
if (quit) {
|
||||
break;
|
||||
}
|
||||
|
||||
cout << "echo: '" << line << "'" << endl;
|
||||
|
||||
// Add text to history
|
||||
linenoise::AddHistory(line.c_str());
|
||||
}
|
||||
|
||||
// Save history
|
||||
linenoise::SaveHistory(path);
|
||||
```
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
```c++
|
||||
namespace linenoise;
|
||||
|
||||
std::string Readline(const char* prompt);
|
||||
|
||||
void SetMultiLine(bool multiLineMode);
|
||||
|
||||
typedef std::function<void (const char* editBuffer, std::vector<std::string>& completions)> CompletionCallback;
|
||||
|
||||
void SetCompletionCallback(CompletionCallback fn);
|
||||
|
||||
bool SetHistoryMaxLen(size_t len);
|
||||
|
||||
bool LoadHistory(const char* path);
|
||||
|
||||
bool SaveHistory(const char* path);
|
||||
|
||||
bool AddHistory(const char* line);
|
||||
|
||||
const std::vector<std::string>& GetHistory();
|
||||
```
|
||||
|
||||
Tested compilers
|
||||
----------------
|
||||
|
||||
* Visual Studio 2015
|
||||
* Clang 3.5
|
||||
* GCC 6.3.1
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
BSD license (© 2015 Yuji Hirose)
|
5
third_party/cpp-linenoise/example/CMakeLists.txt
vendored
Normal file
5
third_party/cpp-linenoise/example/CMakeLists.txt
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.0)
|
||||
include_directories(.)
|
||||
add_definitions("-std=c++1y")
|
||||
|
||||
add_executable(example example.cpp)
|
54
third_party/cpp-linenoise/example/example.cpp
vendored
Normal file
54
third_party/cpp-linenoise/example/example.cpp
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
#include <iostream>
|
||||
#include "../linenoise.hpp"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(int argc, const char** argv)
|
||||
{
|
||||
const auto path = "history.txt";
|
||||
|
||||
// Enable the multi-line mode
|
||||
linenoise::SetMultiLine(true);
|
||||
|
||||
// Set max length of the history
|
||||
linenoise::SetHistoryMaxLen(4);
|
||||
|
||||
// Setup completion words every time when a user types
|
||||
linenoise::SetCompletionCallback([](const char* editBuffer, std::vector<std::string>& completions) {
|
||||
if (editBuffer[0] == 'h') {
|
||||
#ifdef _WIN32
|
||||
completions.push_back("hello こんにちは");
|
||||
completions.push_back("hello こんにちは there");
|
||||
#else
|
||||
completions.push_back("hello");
|
||||
completions.push_back("hello there");
|
||||
#endif
|
||||
}
|
||||
});
|
||||
|
||||
// Load history
|
||||
linenoise::LoadHistory(path);
|
||||
|
||||
while (true) {
|
||||
std::string line;
|
||||
#ifdef _WIN32
|
||||
auto quit = linenoise::Readline("hello> ", line);
|
||||
#else
|
||||
auto quit = linenoise::Readline("\033[32mこんにちは\x1b[0m> ", line);
|
||||
#endif
|
||||
|
||||
if (quit) {
|
||||
break;
|
||||
}
|
||||
|
||||
cout << "echo: '" << line << "'" << endl;
|
||||
|
||||
// Add line to history
|
||||
linenoise::AddHistory(line.c_str());
|
||||
|
||||
// Save history
|
||||
linenoise::SaveHistory(path);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
28
third_party/cpp-linenoise/example/example.sln
vendored
Normal file
28
third_party/cpp-linenoise/example/example.sln
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
VisualStudioVersion = 14.0.23107.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example", "example.vcxproj", "{563BF990-4217-439F-92A4-F8A285052772}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Debug|x64.Build.0 = Debug|x64
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Debug|x86.Build.0 = Debug|Win32
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Release|x64.ActiveCfg = Release|x64
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Release|x64.Build.0 = Release|x64
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Release|x86.ActiveCfg = Release|Win32
|
||||
{563BF990-4217-439F-92A4-F8A285052772}.Release|x86.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
153
third_party/cpp-linenoise/example/example.vcxproj
vendored
Normal file
153
third_party/cpp-linenoise/example/example.vcxproj
vendored
Normal file
@ -0,0 +1,153 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{563BF990-4217-439F-92A4-F8A285052772}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<RootNamespace>example</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="example.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\linenoise.hpp" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
2421
third_party/cpp-linenoise/linenoise.hpp
vendored
Normal file
2421
third_party/cpp-linenoise/linenoise.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@ -23,6 +23,7 @@ include_directories(ws ..)
|
||||
include_directories(ws ../third_party)
|
||||
include_directories(ws ../third_party/statsd-client-cpp/src)
|
||||
include_directories(ws ../third_party/spdlog/include)
|
||||
include_directories(ws ../third_party/cpp-linenoise)
|
||||
include_directories(ws snake)
|
||||
|
||||
if (UNIX)
|
||||
@ -68,6 +69,8 @@ add_executable(ws
|
||||
ws_cobra_to_statsd.cpp
|
||||
ws_cobra_to_sentry.cpp
|
||||
ws_snake.cpp
|
||||
ws_httpd.cpp
|
||||
ws_autobahn.cpp
|
||||
ws.cpp)
|
||||
|
||||
target_link_libraries(ws ixwebsocket)
|
||||
|
@ -72,7 +72,6 @@ namespace ix
|
||||
std::string line;
|
||||
std::stringstream tokenStream(stack);
|
||||
|
||||
std::stringstream ss;
|
||||
std::smatch group;
|
||||
|
||||
while (std::getline(tokenStream, line))
|
||||
@ -84,6 +83,7 @@ namespace ix
|
||||
const auto linenoStr = group.str(2);
|
||||
const auto function = group.str(3);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << linenoStr;
|
||||
uint64_t lineno;
|
||||
ss >> lineno;
|
||||
@ -97,6 +97,8 @@ namespace ix
|
||||
}
|
||||
}
|
||||
|
||||
std::reverse(frames.begin(), frames.end());
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
|
@ -18,13 +18,15 @@
|
||||
namespace ix
|
||||
{
|
||||
TrafficTrackerCallback CobraConnection::_trafficTrackerCallback = nullptr;
|
||||
PublishTrackerCallback CobraConnection::_publishTrackerCallback = nullptr;
|
||||
constexpr size_t CobraConnection::kQueueMaxSize;
|
||||
|
||||
CobraConnection::CobraConnection() :
|
||||
_webSocket(new WebSocket()),
|
||||
_publishMode(CobraConnection_PublishMode_Immediate),
|
||||
_authenticated(false),
|
||||
_eventCallback(nullptr)
|
||||
_eventCallback(nullptr),
|
||||
_id(0)
|
||||
{
|
||||
_pdu["action"] = "rtm/publish";
|
||||
|
||||
@ -55,6 +57,24 @@ namespace ix
|
||||
}
|
||||
}
|
||||
|
||||
void CobraConnection::setPublishTrackerCallback(const PublishTrackerCallback& callback)
|
||||
{
|
||||
_publishTrackerCallback = callback;
|
||||
}
|
||||
|
||||
void CobraConnection::resetPublishTrackerCallback()
|
||||
{
|
||||
setPublishTrackerCallback(nullptr);
|
||||
}
|
||||
|
||||
void CobraConnection::invokePublishTrackerCallback(bool sent, bool acked)
|
||||
{
|
||||
if (_publishTrackerCallback)
|
||||
{
|
||||
_publishTrackerCallback(sent, acked);
|
||||
}
|
||||
}
|
||||
|
||||
void CobraConnection::setEventCallback(const EventCallback& eventCallback)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_eventCallbackMutex);
|
||||
@ -62,19 +82,20 @@ namespace ix
|
||||
}
|
||||
|
||||
void CobraConnection::invokeEventCallback(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errorMsg,
|
||||
const WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId)
|
||||
const std::string& errorMsg,
|
||||
const WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_eventCallbackMutex);
|
||||
if (_eventCallback)
|
||||
{
|
||||
_eventCallback(eventType, errorMsg, headers, subscriptionId);
|
||||
_eventCallback(eventType, errorMsg, headers, subscriptionId, msgId);
|
||||
}
|
||||
}
|
||||
|
||||
void CobraConnection::invokeErrorCallback(const std::string& errorMsg,
|
||||
const std::string& serializedPdu)
|
||||
const std::string& serializedPdu)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << errorMsg << " : received pdu => " << serializedPdu;
|
||||
@ -177,6 +198,17 @@ namespace ix
|
||||
{
|
||||
invokeErrorCallback("Unsubscription error", msg->str);
|
||||
}
|
||||
else if (action == "rtm/publish/ok")
|
||||
{
|
||||
if (!handlePublishResponse(data))
|
||||
{
|
||||
invokeErrorCallback("Error processing publish response", msg->str);
|
||||
}
|
||||
}
|
||||
else if (action == "rtm/publish/error")
|
||||
{
|
||||
invokeErrorCallback("Publish error", msg->str);
|
||||
}
|
||||
else
|
||||
{
|
||||
invokeErrorCallback("Un-handled message type", msg->str);
|
||||
@ -244,6 +276,7 @@ namespace ix
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "auth/handshake";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
std::string serializedJson = serializeJson(pdu);
|
||||
CobraConnection::invokeTrafficTrackerCallback(serializedJson.size(), false);
|
||||
@ -306,6 +339,7 @@ namespace ix
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "auth/authenticate";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
std::string serializedJson = serializeJson(pdu);
|
||||
CobraConnection::invokeTrafficTrackerCallback(serializedJson.size(), false);
|
||||
@ -371,6 +405,24 @@ namespace ix
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::handlePublishResponse(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isMember("id")) return false;
|
||||
Json::Value id = pdu["id"];
|
||||
|
||||
if (!id.isUInt64()) return false;
|
||||
|
||||
uint64_t msgId = id.asUInt64();
|
||||
|
||||
invokeEventCallback(ix::CobraConnection_EventType_Published,
|
||||
std::string(), WebSocketHttpHeaders(),
|
||||
std::string(), msgId);
|
||||
|
||||
invokePublishTrackerCallback(false, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::connect()
|
||||
{
|
||||
_webSocket->start();
|
||||
@ -396,19 +448,22 @@ namespace ix
|
||||
//
|
||||
// publish is not thread safe as we are trying to reuse some Json objects.
|
||||
//
|
||||
bool CobraConnection::publish(const Json::Value& channels,
|
||||
const Json::Value& msg)
|
||||
CobraConnection::MsgId CobraConnection::publish(const Json::Value& channels,
|
||||
const Json::Value& msg)
|
||||
{
|
||||
invokePublishTrackerCallback(true, false);
|
||||
|
||||
_body["channels"] = channels;
|
||||
_body["message"] = msg;
|
||||
_pdu["body"] = _body;
|
||||
_pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
std::string serializedJson = serializeJson(_pdu);
|
||||
|
||||
if (_publishMode == CobraConnection_PublishMode_Batch)
|
||||
{
|
||||
enqueue(serializedJson);
|
||||
return true;
|
||||
return _id - 1;
|
||||
}
|
||||
|
||||
//
|
||||
@ -417,27 +472,34 @@ namespace ix
|
||||
//
|
||||
if (_authenticated && publishMessage(serializedJson))
|
||||
{
|
||||
return true;
|
||||
return _id - 1;
|
||||
}
|
||||
else // Or else we enqueue
|
||||
// Slow code path is when we haven't connected yet (startup),
|
||||
// or when the connection drops for some reason.
|
||||
{
|
||||
enqueue(serializedJson);
|
||||
return false;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void CobraConnection::subscribe(const std::string& channel,
|
||||
SubscriptionCallback cb)
|
||||
const std::string& filter,
|
||||
SubscriptionCallback cb)
|
||||
{
|
||||
// Create and send a subscribe pdu
|
||||
Json::Value body;
|
||||
body["channel"] = channel;
|
||||
|
||||
if (!filter.empty())
|
||||
{
|
||||
body["filter"] = filter;
|
||||
}
|
||||
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "rtm/subscribe";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
_webSocket->send(pdu.toStyledString());
|
||||
|
||||
@ -463,6 +525,7 @@ namespace ix
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "rtm/unsubscribe";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
_webSocket->send(pdu.toStyledString());
|
||||
}
|
||||
@ -516,7 +579,7 @@ namespace ix
|
||||
{
|
||||
auto webSocketSendInfo = _webSocket->send(serializedJson);
|
||||
CobraConnection::invokeTrafficTrackerCallback(webSocketSendInfo.wireSize,
|
||||
false);
|
||||
false);
|
||||
return webSocketSendInfo.success;
|
||||
}
|
||||
|
||||
|
@ -15,6 +15,7 @@
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <limits>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -27,7 +28,8 @@ namespace ix
|
||||
CobraConnection_EventType_Open = 2,
|
||||
CobraConnection_EventType_Closed = 3,
|
||||
CobraConnection_EventType_Subscribed = 4,
|
||||
CobraConnection_EventType_UnSubscribed = 5
|
||||
CobraConnection_EventType_UnSubscribed = 5,
|
||||
CobraConnection_EventType_Published = 6
|
||||
};
|
||||
|
||||
enum CobraConnectionPublishMode
|
||||
@ -40,12 +42,17 @@ namespace ix
|
||||
using EventCallback = std::function<void(CobraConnectionEventType,
|
||||
const std::string&,
|
||||
const WebSocketHttpHeaders&,
|
||||
const std::string&)>;
|
||||
const std::string&,
|
||||
uint64_t msgId)>;
|
||||
|
||||
using TrafficTrackerCallback = std::function<void(size_t size, bool incoming)>;
|
||||
using PublishTrackerCallback = std::function<void(bool sent, bool acked)>;
|
||||
|
||||
class CobraConnection
|
||||
{
|
||||
public:
|
||||
using MsgId = uint64_t;
|
||||
|
||||
CobraConnection();
|
||||
~CobraConnection();
|
||||
|
||||
@ -57,11 +64,18 @@ namespace ix
|
||||
const std::string& rolesecret,
|
||||
const WebSocketPerMessageDeflateOptions& webSocketPerMessageDeflateOptions);
|
||||
|
||||
/// Set the traffic tracker callback
|
||||
static void setTrafficTrackerCallback(const TrafficTrackerCallback& callback);
|
||||
|
||||
/// Reset the traffic tracker callback to an no-op one.
|
||||
static void resetTrafficTrackerCallback();
|
||||
|
||||
/// Set the publish tracker callback
|
||||
static void setPublishTrackerCallback(const PublishTrackerCallback& callback);
|
||||
|
||||
/// Reset the publish tracker callback to an no-op one.
|
||||
static void resetPublishTrackerCallback();
|
||||
|
||||
/// Set the closed callback
|
||||
void setEventCallback(const EventCallback& eventCallback);
|
||||
|
||||
@ -71,11 +85,13 @@ namespace ix
|
||||
/// Publish a message to a channel
|
||||
///
|
||||
/// No-op if the connection is not established
|
||||
bool publish(const Json::Value& channels, const Json::Value& msg);
|
||||
MsgId publish(const Json::Value& channels, const Json::Value& msg);
|
||||
|
||||
// Subscribe to a channel, and execute a callback when an incoming
|
||||
// message arrives.
|
||||
void subscribe(const std::string& channel, SubscriptionCallback cb);
|
||||
void subscribe(const std::string& channel,
|
||||
const std::string& filter = std::string(),
|
||||
SubscriptionCallback cb = nullptr);
|
||||
|
||||
/// Unsubscribe from a channel
|
||||
void unsubscribe(const std::string& channel);
|
||||
@ -109,6 +125,7 @@ namespace ix
|
||||
bool handleSubscriptionData(const Json::Value& pdu);
|
||||
bool handleSubscriptionResponse(const Json::Value& pdu);
|
||||
bool handleUnsubscriptionResponse(const Json::Value& pdu);
|
||||
bool handlePublishResponse(const Json::Value& pdu);
|
||||
|
||||
void initWebSocketOnMessageCallback();
|
||||
|
||||
@ -119,11 +136,15 @@ namespace ix
|
||||
/// Invoke the traffic tracker callback
|
||||
static void invokeTrafficTrackerCallback(size_t size, bool incoming);
|
||||
|
||||
/// Invoke the publish tracker callback
|
||||
static void invokePublishTrackerCallback(bool sent, bool acked);
|
||||
|
||||
/// Invoke event callbacks
|
||||
void invokeEventCallback(CobraConnectionEventType eventType,
|
||||
const std::string& errorMsg = std::string(),
|
||||
const WebSocketHttpHeaders& headers = WebSocketHttpHeaders(),
|
||||
const std::string& subscriptionId = std::string());
|
||||
const std::string& subscriptionId = std::string(),
|
||||
uint64_t msgId = std::numeric_limits<uint64_t>::max());
|
||||
void invokeErrorCallback(const std::string& errorMsg, const std::string& serializedPdu);
|
||||
|
||||
///
|
||||
@ -148,6 +169,9 @@ namespace ix
|
||||
/// Traffic tracker callback
|
||||
static TrafficTrackerCallback _trafficTrackerCallback;
|
||||
|
||||
/// Publish tracker callback
|
||||
static PublishTrackerCallback _publishTrackerCallback;
|
||||
|
||||
/// Cobra events callbacks
|
||||
EventCallback _eventCallback;
|
||||
mutable std::mutex _eventCallbackMutex;
|
||||
@ -166,6 +190,9 @@ namespace ix
|
||||
|
||||
// Cap the queue size (100 elems so far -> ~100k)
|
||||
static constexpr size_t kQueueMaxSize = 256;
|
||||
|
||||
// Each pdu sent should have an incremental unique id
|
||||
std::atomic<uint64_t> _id;
|
||||
};
|
||||
|
||||
} // namespace ix
|
||||
|
@ -17,7 +17,7 @@ namespace ix
|
||||
const std::string CobraMetricsPublisher::kSetBlacklistId = "sms_set_blacklist_id";
|
||||
|
||||
CobraMetricsPublisher::CobraMetricsPublisher() :
|
||||
_enabled(false)
|
||||
_enabled(true)
|
||||
{
|
||||
}
|
||||
|
||||
@ -191,6 +191,19 @@ namespace ix
|
||||
msg["device"] = _device;
|
||||
}
|
||||
|
||||
{
|
||||
//
|
||||
// Bump a counter for each id
|
||||
// This is used to make sure that we are not
|
||||
// dropping messages, by checking that all the ids is the list of
|
||||
// all natural numbers until the last value sent (0, 1, 2, ..., N)
|
||||
//
|
||||
std::lock_guard<std::mutex> lock(_device_mutex);
|
||||
auto it = _counters.emplace(id, 0);
|
||||
msg["per_id_counter"] = it.first->second;
|
||||
it.first->second += 1;
|
||||
}
|
||||
|
||||
// Now actually enqueue the task
|
||||
_cobra_metrics_theaded_publisher.push(msg);
|
||||
}
|
||||
|
@ -7,6 +7,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "IXCobraMetricsThreadedPublisher.h"
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <jsoncpp/json/json.h>
|
||||
#include <string>
|
||||
@ -132,8 +133,8 @@ namespace ix
|
||||
CobraMetricsThreadedPublisher _cobra_metrics_theaded_publisher;
|
||||
|
||||
/// A boolean to enable or disable this system
|
||||
/// push becomes a no-op when _enabled is true
|
||||
bool _enabled;
|
||||
/// push becomes a no-op when _enabled is false
|
||||
std::atomic<bool> _enabled;
|
||||
|
||||
/// A uuid used to uniquely identify a session
|
||||
std::string _session;
|
||||
@ -150,6 +151,10 @@ namespace ix
|
||||
_last_update;
|
||||
mutable std::mutex _last_update_mutex; // protect access to _last_update
|
||||
|
||||
/// Bump a counter for each metric type
|
||||
std::unordered_map<std::string, int> _counters;
|
||||
mutable std::mutex _counters_mutex; // protect access to _counters
|
||||
|
||||
// const strings for internal ids
|
||||
static const std::string kSetRateControlId;
|
||||
static const std::string kSetBlacklistId;
|
||||
|
@ -25,7 +25,8 @@ namespace ix
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId)
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
std::stringstream ss;
|
||||
|
||||
@ -58,6 +59,10 @@ namespace ix
|
||||
{
|
||||
ss << "Unsubscribed through subscription id: " << subscriptionId;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
ss << "Published message " << msgId << " acked";
|
||||
}
|
||||
|
||||
ix::IXCoreLogger::Log(ss.str().c_str());
|
||||
});
|
||||
|
43
ws/ws.cpp
43
ws/ws.cpp
@ -9,15 +9,10 @@
|
||||
//
|
||||
#include "ws.h"
|
||||
|
||||
//
|
||||
// Main drive for websocket utilities
|
||||
//
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
// #include <unistd.h>
|
||||
|
||||
#include <cli11/CLI11.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
@ -60,6 +55,7 @@ int main(int argc, char** argv)
|
||||
std::string hostname("127.0.0.1");
|
||||
std::string pidfile;
|
||||
std::string channel;
|
||||
std::string filter;
|
||||
std::string message;
|
||||
std::string password;
|
||||
std::string appkey;
|
||||
@ -76,12 +72,14 @@ int main(int argc, char** argv)
|
||||
bool followRedirects = false;
|
||||
bool verbose = false;
|
||||
bool save = false;
|
||||
bool quiet = false;
|
||||
bool compress = false;
|
||||
bool strict = false;
|
||||
bool stress = false;
|
||||
bool disableAutomaticReconnection = false;
|
||||
bool disablePerMessageDeflate = false;
|
||||
bool greetings = false;
|
||||
bool binaryMode = false;
|
||||
int port = 8008;
|
||||
int redisPort = 6379;
|
||||
int statsdPort = 8125;
|
||||
@ -91,6 +89,7 @@ int main(int argc, char** argv)
|
||||
int delayMs = -1;
|
||||
int count = 1;
|
||||
int jobs = 4;
|
||||
uint32_t maxWaitBetweenReconnectionRetries;
|
||||
|
||||
CLI::App* sendApp = app.add_subcommand("send", "Send a file");
|
||||
sendApp->add_option("url", url, "Connection url")->required();
|
||||
@ -111,8 +110,11 @@ int main(int argc, char** argv)
|
||||
|
||||
CLI::App* connectApp = app.add_subcommand("connect", "Connect to a remote server");
|
||||
connectApp->add_option("url", url, "Connection url")->required();
|
||||
connectApp->add_option("-H", headers, "Header")->join();
|
||||
connectApp->add_flag("-d", disableAutomaticReconnection, "Disable Automatic Reconnection");
|
||||
connectApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate");
|
||||
connectApp->add_flag("-b", binaryMode, "Send in binary mode");
|
||||
connectApp->add_option("--max_wait", maxWaitBetweenReconnectionRetries, "Max Wait Time between reconnection retries");
|
||||
|
||||
CLI::App* chatApp = app.add_subcommand("chat", "Group chat");
|
||||
chatApp->add_option("url", url, "Connection url")->required();
|
||||
@ -168,6 +170,8 @@ int main(int argc, char** argv)
|
||||
cobraSubscribeApp->add_option("--rolesecret", rolesecret, "Role secret");
|
||||
cobraSubscribeApp->add_option("channel", channel, "Channel")->required();
|
||||
cobraSubscribeApp->add_option("--pidfile", pidfile, "Pid file");
|
||||
cobraSubscribeApp->add_option("--filter", filter, "Stream SQL Filter");
|
||||
cobraSubscribeApp->add_flag("-q", quiet, "Quiet / only display stats");
|
||||
|
||||
CLI::App* cobraPublish = app.add_subcommand("cobra_publish", "Cobra publisher");
|
||||
cobraPublish->add_option("--appkey", appkey, "Appkey");
|
||||
@ -192,6 +196,7 @@ int main(int argc, char** argv)
|
||||
cobra2statsd->add_option("channel", channel, "Channel")->required();
|
||||
cobra2statsd->add_flag("-v", verbose, "Verbose");
|
||||
cobra2statsd->add_option("--pidfile", pidfile, "Pid file");
|
||||
cobra2statsd->add_option("--filter", filter, "Stream SQL Filter");
|
||||
|
||||
CLI::App* cobra2sentry = app.add_subcommand("cobra_to_sentry", "Cobra to sentry");
|
||||
cobra2sentry->add_option("--appkey", appkey, "Appkey");
|
||||
@ -204,6 +209,7 @@ int main(int argc, char** argv)
|
||||
cobra2sentry->add_flag("-v", verbose, "Verbose");
|
||||
cobra2sentry->add_flag("-s", strict, "Strict mode. Error out when sending to sentry fails");
|
||||
cobra2sentry->add_option("--pidfile", pidfile, "Pid file");
|
||||
cobra2sentry->add_option("--filter", filter, "Stream SQL Filter");
|
||||
|
||||
CLI::App* runApp = app.add_subcommand("snake", "Snake server");
|
||||
runApp->add_option("--port", port, "Connection url");
|
||||
@ -216,6 +222,14 @@ int main(int argc, char** argv)
|
||||
->check(CLI::ExistingPath);
|
||||
runApp->add_flag("-v", verbose, "Verbose");
|
||||
|
||||
CLI::App* httpServerApp = app.add_subcommand("httpd", "HTTP server");
|
||||
httpServerApp->add_option("--port", port, "Port");
|
||||
httpServerApp->add_option("--host", hostname, "Hostname");
|
||||
|
||||
CLI::App* autobahnApp = app.add_subcommand("autobahn", "Test client Autobahn compliance");
|
||||
autobahnApp->add_option("--url", url, "url");
|
||||
autobahnApp->add_flag("-q", quiet, "Quiet");
|
||||
|
||||
CLI11_PARSE(app, argc, argv);
|
||||
|
||||
// pid file handling
|
||||
@ -245,8 +259,9 @@ int main(int argc, char** argv)
|
||||
}
|
||||
else if (app.got_subcommand("connect"))
|
||||
{
|
||||
ret = ix::ws_connect_main(url, disableAutomaticReconnection,
|
||||
disablePerMessageDeflate);
|
||||
ret = ix::ws_connect_main(url, headers, disableAutomaticReconnection,
|
||||
disablePerMessageDeflate, binaryMode,
|
||||
maxWaitBetweenReconnectionRetries);
|
||||
}
|
||||
else if (app.got_subcommand("chat"))
|
||||
{
|
||||
@ -284,7 +299,7 @@ int main(int argc, char** argv)
|
||||
{
|
||||
ret = ix::ws_cobra_subscribe_main(appkey, endpoint,
|
||||
rolename, rolesecret,
|
||||
channel);
|
||||
channel, filter, quiet);
|
||||
}
|
||||
else if (app.got_subcommand("cobra_publish"))
|
||||
{
|
||||
@ -296,14 +311,14 @@ int main(int argc, char** argv)
|
||||
{
|
||||
ret = ix::ws_cobra_to_statsd_main(appkey, endpoint,
|
||||
rolename, rolesecret,
|
||||
channel, hostname, statsdPort,
|
||||
channel, filter, hostname, statsdPort,
|
||||
prefix, fields, verbose);
|
||||
}
|
||||
else if (app.got_subcommand("cobra_to_sentry"))
|
||||
{
|
||||
ret = ix::ws_cobra_to_sentry_main(appkey, endpoint,
|
||||
rolename, rolesecret,
|
||||
channel, dsn,
|
||||
channel, filter, dsn,
|
||||
verbose, strict, jobs);
|
||||
}
|
||||
else if (app.got_subcommand("snake"))
|
||||
@ -313,6 +328,14 @@ int main(int argc, char** argv)
|
||||
redisPassword, verbose,
|
||||
appsConfigPath);
|
||||
}
|
||||
else if (app.got_subcommand("httpd"))
|
||||
{
|
||||
ret = ix::ws_httpd_main(port, hostname);
|
||||
}
|
||||
else if (app.got_subcommand("autobahn"))
|
||||
{
|
||||
ret = ix::ws_autobahn_main(url, quiet);
|
||||
}
|
||||
|
||||
ix::uninitNetSystem();
|
||||
return ret;
|
||||
|
15
ws/ws.h
15
ws/ws.h
@ -31,8 +31,11 @@ namespace ix
|
||||
int ws_chat_main(const std::string& url, const std::string& user);
|
||||
|
||||
int ws_connect_main(const std::string& url,
|
||||
const std::string& headers,
|
||||
bool disableAutomaticReconnection,
|
||||
bool disablePerMessageDeflate);
|
||||
bool disablePerMessageDeflate,
|
||||
bool binaryMode,
|
||||
uint32_t maxWaitBetweenReconnectionRetries);
|
||||
|
||||
int ws_receive_main(const std::string& url, bool enablePerMessageDeflate, int delayMs);
|
||||
|
||||
@ -55,7 +58,9 @@ namespace ix
|
||||
const std::string& endpoint,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel);
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
bool quiet);
|
||||
|
||||
int ws_cobra_publish_main(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
@ -70,6 +75,7 @@ namespace ix
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& host,
|
||||
int port,
|
||||
const std::string& prefix,
|
||||
@ -81,6 +87,7 @@ namespace ix
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& dsn,
|
||||
bool verbose,
|
||||
bool strict,
|
||||
@ -93,4 +100,8 @@ namespace ix
|
||||
const std::string& redisPassword,
|
||||
bool verbose,
|
||||
const std::string& appsConfigPath);
|
||||
|
||||
int ws_httpd_main(int port, const std::string& hostname);
|
||||
|
||||
int ws_autobahn_main(const std::string& url, bool quiet);
|
||||
} // namespace ix
|
||||
|
318
ws/ws_autobahn.cpp
Normal file
318
ws/ws_autobahn.cpp
Normal file
@ -0,0 +1,318 @@
|
||||
/*
|
||||
* ws_autobahn.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
//
|
||||
// 1. First you need to generate a config file in a config folder,
|
||||
// which can use a white list of test to execute (with globbing),
|
||||
// or a black list of tests to ignore
|
||||
//
|
||||
// config/fuzzingserver.json
|
||||
// {
|
||||
// "url": "ws://127.0.0.1:9001",
|
||||
// "outdir": "./reports/clients",
|
||||
// "cases": ["2.*"],
|
||||
// "exclude-cases": [
|
||||
// ],
|
||||
// "exclude-agent-cases": {}
|
||||
// }
|
||||
//
|
||||
//
|
||||
// 2 Run the test server (using docker)
|
||||
// docker run -it --rm \
|
||||
// -v "${PWD}/config:/config" \
|
||||
// -v "${PWD}/reports:/reports" \
|
||||
// -p 9001:9001 \
|
||||
// --name fuzzingserver \
|
||||
// crossbario/autobahn-testsuite
|
||||
//
|
||||
// 3. Run this command
|
||||
// ws autobahn -q --url ws://localhost:9001
|
||||
//
|
||||
// 4. A HTML report will be generated, you can inspect it to see if you are compliant or not
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string truncate(const std::string& str, size_t n)
|
||||
{
|
||||
if (str.size() < n)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
else
|
||||
{
|
||||
return str.substr(0, n) + "...";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class AutobahnTestCase
|
||||
{
|
||||
public:
|
||||
AutobahnTestCase(const std::string& _url, bool quiet);
|
||||
void run();
|
||||
|
||||
private:
|
||||
void log(const std::string& msg);
|
||||
|
||||
std::string _url;
|
||||
ix::WebSocket _webSocket;
|
||||
|
||||
bool _quiet;
|
||||
|
||||
std::mutex _mutex;
|
||||
std::condition_variable _condition;
|
||||
};
|
||||
|
||||
AutobahnTestCase::AutobahnTestCase(const std::string& url, bool quiet) :
|
||||
_url(url),
|
||||
_quiet(quiet)
|
||||
{
|
||||
_webSocket.disableAutomaticReconnection();
|
||||
|
||||
// FIXME: this should be on by default
|
||||
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions(
|
||||
true, false, false, 15, 15);
|
||||
_webSocket.setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions);
|
||||
}
|
||||
|
||||
void AutobahnTestCase::log(const std::string& msg)
|
||||
{
|
||||
if (!_quiet)
|
||||
{
|
||||
std::cerr << msg;
|
||||
}
|
||||
}
|
||||
|
||||
void AutobahnTestCase::run()
|
||||
{
|
||||
_webSocket.setUrl(_url);
|
||||
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + _url);
|
||||
|
||||
_webSocket.setOnMessageCallback(
|
||||
[this](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
log("autobahn: connected");
|
||||
ss << "Uri: " << msg->openInfo.uri << std::endl;
|
||||
ss << "Handshake Headers:" << std::endl;
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
ss << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
ss << "autobahn: connection closed:";
|
||||
ss << " code " << msg->closeInfo.code;
|
||||
ss << " reason " << msg->closeInfo.reason << std::endl;
|
||||
|
||||
_condition.notify_one();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received " << msg->wireSize << " bytes" << std::endl;
|
||||
|
||||
ss << "autobahn: received message: "
|
||||
<< truncate(msg->str, 40)
|
||||
<< std::endl;
|
||||
|
||||
_webSocket.send(msg->str, msg->binary);
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Connection error: " << msg->errorInfo.reason << std::endl;
|
||||
ss << "#retries: " << msg->errorInfo.retries << std::endl;
|
||||
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl;
|
||||
|
||||
// And error can happen, in which case the test-case is marked done
|
||||
_condition.notify_one();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
ss << "Received message fragment" << std::endl;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping" << std::endl;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong" << std::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid ix::WebSocketMessageType" << std::endl;
|
||||
}
|
||||
|
||||
log(ss.str());
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
|
||||
log("Waiting for test completion ...");
|
||||
std::unique_lock<std::mutex> lock(_mutex);
|
||||
_condition.wait(lock);
|
||||
|
||||
_webSocket.stop();
|
||||
}
|
||||
|
||||
bool generateReport(const std::string& url)
|
||||
{
|
||||
ix::WebSocket webSocket;
|
||||
std::string reportUrl(url);
|
||||
reportUrl += "/updateReports?agent=ixwebsocket";
|
||||
webSocket.setUrl(reportUrl);
|
||||
webSocket.disableAutomaticReconnection();
|
||||
|
||||
std::atomic<bool> success(true);
|
||||
std::condition_variable condition;
|
||||
|
||||
webSocket.setOnMessageCallback(
|
||||
[&condition, &success](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
std::cerr << "Report generated" << std::endl;
|
||||
condition.notify_one();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Connection error: " << msg->errorInfo.reason << std::endl;
|
||||
ss << "#retries: " << msg->errorInfo.retries << std::endl;
|
||||
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl;
|
||||
std::cerr << ss.str() << std::endl;
|
||||
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
webSocket.start();
|
||||
std::mutex mutex;
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
condition.wait(lock);
|
||||
webSocket.stop();
|
||||
|
||||
if (!success)
|
||||
{
|
||||
spdlog::error("Cannot generate report at url {}", reportUrl);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
int getTestCaseCount(const std::string& url)
|
||||
{
|
||||
ix::WebSocket webSocket;
|
||||
std::string caseCountUrl(url);
|
||||
caseCountUrl += "/getCaseCount";
|
||||
webSocket.setUrl(caseCountUrl);
|
||||
webSocket.disableAutomaticReconnection();
|
||||
|
||||
int count = -1;
|
||||
std::condition_variable condition;
|
||||
|
||||
webSocket.setOnMessageCallback(
|
||||
[&condition, &count](const ix::WebSocketMessagePtr& msg)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
condition.notify_one();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Connection error: " << msg->errorInfo.reason << std::endl;
|
||||
ss << "#retries: " << msg->errorInfo.retries << std::endl;
|
||||
ss << "Wait time(ms): " << msg->errorInfo.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << msg->errorInfo.http_status << std::endl;
|
||||
std::cerr << ss.str() << std::endl;
|
||||
|
||||
condition.notify_one();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
// response is a string
|
||||
std::stringstream ss;
|
||||
ss << msg->str;
|
||||
ss >> count;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
webSocket.start();
|
||||
std::mutex mutex;
|
||||
std::unique_lock<std::mutex> lock(mutex);
|
||||
condition.wait(lock);
|
||||
webSocket.stop();
|
||||
|
||||
if (count == -1)
|
||||
{
|
||||
spdlog::error("Cannot retrieve test case count at url {}", caseCountUrl);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
//
|
||||
// make && bench ws autobahn --url ws://localhost:9001
|
||||
//
|
||||
int ws_autobahn_main(const std::string& url, bool quiet)
|
||||
{
|
||||
int testCasesCount = getTestCaseCount(url);
|
||||
std::cerr << "Test cases count: " << testCasesCount << std::endl;
|
||||
|
||||
if (testCasesCount == -1)
|
||||
{
|
||||
spdlog::error("Cannot retrieve test case count at url {}", url);
|
||||
return 1;
|
||||
}
|
||||
|
||||
testCasesCount++;
|
||||
|
||||
for (int i = 1 ; i < testCasesCount; ++i)
|
||||
{
|
||||
spdlog::info("Execute test case {}", i);
|
||||
|
||||
int caseNumber = i;
|
||||
|
||||
std::stringstream ss;
|
||||
ss << url
|
||||
<< "/runCase?case="
|
||||
<< caseNumber
|
||||
<< "&agent=ixwebsocket";
|
||||
|
||||
std::string url(ss.str());
|
||||
|
||||
AutobahnTestCase testCase(url, quiet);
|
||||
testCase.run();
|
||||
}
|
||||
|
||||
return generateReport(url) ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,7 @@
|
||||
#include <atomic>
|
||||
#include <jsoncpp/json/json.h>
|
||||
#include <ixcobra/IXCobraMetricsPublisher.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -23,6 +24,16 @@ namespace ix
|
||||
const std::string& path,
|
||||
bool stress)
|
||||
{
|
||||
std::atomic<int> sentMessages(0);
|
||||
std::atomic<int> ackedMessages(0);
|
||||
CobraConnection::setPublishTrackerCallback(
|
||||
[&sentMessages, &ackedMessages](bool sent, bool acked)
|
||||
{
|
||||
if (sent) sentMessages++;
|
||||
if (acked) ackedMessages++;
|
||||
}
|
||||
);
|
||||
|
||||
CobraMetricsPublisher cobraMetricsPublisher;
|
||||
cobraMetricsPublisher.enable(true);
|
||||
|
||||
@ -64,8 +75,11 @@ namespace ix
|
||||
|
||||
// Wait a bit for the message to get a chance to be sent
|
||||
// there isn't any ack on publish right now so it's the best we can do
|
||||
// FIXME: this comment is a lie now
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
|
||||
spdlog::info("Sent messages: {} Acked messages {}", sentMessages, ackedMessages);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
@ -11,13 +11,17 @@
|
||||
#include <atomic>
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int ws_cobra_subscribe_main(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel)
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
bool quiet)
|
||||
{
|
||||
|
||||
ix::CobraConnection conn;
|
||||
@ -28,42 +32,74 @@ namespace ix
|
||||
|
||||
Json::FastWriter jsonWriter;
|
||||
|
||||
// Display incoming messages
|
||||
std::atomic<int> msgPerSeconds(0);
|
||||
std::atomic<int> msgCount(0);
|
||||
|
||||
auto timer = [&msgPerSeconds, &msgCount]
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
std::cout << "#messages " << msgCount << " "
|
||||
<< "msg/s " << msgPerSeconds
|
||||
<< std::endl;
|
||||
|
||||
msgPerSeconds = 0;
|
||||
auto duration = std::chrono::seconds(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
}
|
||||
};
|
||||
|
||||
std::thread t(timer);
|
||||
|
||||
conn.setEventCallback(
|
||||
[&conn, &channel, &jsonWriter]
|
||||
[&conn, &channel, &jsonWriter, &filter, &msgCount, &msgPerSeconds, &quiet]
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId)
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
std::cout << "Subscriber: connected" << std::endl;
|
||||
spdlog::info("Subscriber connected");
|
||||
|
||||
for (auto it : headers)
|
||||
{
|
||||
std::cerr << it.first << ": " << it.second << std::endl;
|
||||
spdlog::info("{}: {}", it.first, it.second);
|
||||
}
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
std::cout << "Subscriber authenticated" << std::endl;
|
||||
conn.subscribe(channel,
|
||||
[&jsonWriter](const Json::Value& msg)
|
||||
spdlog::info("Subscriber authenticated");
|
||||
conn.subscribe(channel, filter,
|
||||
[&jsonWriter, &quiet,
|
||||
&msgPerSeconds, &msgCount](const Json::Value& msg)
|
||||
{
|
||||
std::cout << jsonWriter.write(msg) << std::endl;
|
||||
if (!quiet)
|
||||
{
|
||||
std::cout << jsonWriter.write(msg) << std::endl;
|
||||
}
|
||||
|
||||
msgPerSeconds++;
|
||||
msgCount++;
|
||||
});
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
{
|
||||
std::cout << "Subscriber: subscribed to channel " << subscriptionId << std::endl;
|
||||
spdlog::info("Subscriber: subscribed to channel {}", subscriptionId);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
{
|
||||
std::cout << "Subscriber: unsubscribed from channel " << subscriptionId << std::endl;
|
||||
spdlog::info("Subscriber: unsubscribed from channel {}", subscriptionId);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Error)
|
||||
{
|
||||
std::cout << "Subscriber: error" << errMsg << std::endl;
|
||||
spdlog::error("Subscriber: error {}", errMsg);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
spdlog::error("Published message hacked: {}", msgId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
@ -25,6 +25,7 @@ namespace ix
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& dsn,
|
||||
bool verbose,
|
||||
bool strict,
|
||||
@ -94,14 +95,15 @@ namespace ix
|
||||
}
|
||||
|
||||
conn.setEventCallback(
|
||||
[&conn, &channel, &jsonWriter,
|
||||
[&conn, &channel, &filter, &jsonWriter,
|
||||
verbose, &receivedCount, &sentCount,
|
||||
&condition, &conditionVariableMutex,
|
||||
&progressCondition, &queue]
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId)
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
@ -119,7 +121,7 @@ namespace ix
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
std::cerr << "Subscriber authenticated" << std::endl;
|
||||
conn.subscribe(channel,
|
||||
conn.subscribe(channel, filter,
|
||||
[&jsonWriter, verbose,
|
||||
&sentCount, &receivedCount,
|
||||
&condition, &conditionVariableMutex,
|
||||
@ -168,6 +170,10 @@ namespace ix
|
||||
{
|
||||
spdlog::error("Subscriber: error {}", errMsg);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
spdlog::error("Published message hacked: {}", msgId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
@ -63,6 +63,7 @@ namespace ix
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& host,
|
||||
int port,
|
||||
const std::string& prefix,
|
||||
@ -90,11 +91,12 @@ namespace ix
|
||||
uint64_t msgCount = 0;
|
||||
|
||||
conn.setEventCallback(
|
||||
[&conn, &channel, &jsonWriter, &statsdClient, verbose, &tokens, &prefix, &msgCount]
|
||||
[&conn, &channel, &filter, &jsonWriter, &statsdClient, verbose, &tokens, &prefix, &msgCount]
|
||||
(ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId)
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
@ -112,7 +114,7 @@ namespace ix
|
||||
else if (eventType == ix::CobraConnection_EventType_Authenticated)
|
||||
{
|
||||
spdlog::info("Subscriber authenticated");
|
||||
conn.subscribe(channel,
|
||||
conn.subscribe(channel, filter,
|
||||
[&jsonWriter, &statsdClient,
|
||||
verbose, &tokens, &prefix, &msgCount]
|
||||
(const Json::Value& msg)
|
||||
@ -148,6 +150,10 @@ namespace ix
|
||||
{
|
||||
spdlog::error("Subscriber: error {}", errMsg);
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Published)
|
||||
{
|
||||
spdlog::error("Published message hacked: {}", msgId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
@ -9,14 +9,20 @@
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
#include "linenoise.hpp"
|
||||
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class WebSocketConnect
|
||||
{
|
||||
public:
|
||||
WebSocketConnect(const std::string& _url,
|
||||
const std::string& headers,
|
||||
bool disableAutomaticReconnection,
|
||||
bool disablePerMessageDeflate);
|
||||
bool disablePerMessageDeflate,
|
||||
bool binaryMode,
|
||||
uint32_t maxWaitBetweenReconnectionRetries);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
@ -26,22 +32,32 @@ namespace ix
|
||||
|
||||
private:
|
||||
std::string _url;
|
||||
WebSocketHttpHeaders _headers;
|
||||
ix::WebSocket _webSocket;
|
||||
bool _disablePerMessageDeflate;
|
||||
bool _binaryMode;
|
||||
|
||||
void log(const std::string& msg);
|
||||
WebSocketHttpHeaders parseHeaders(const std::string& data);
|
||||
};
|
||||
|
||||
WebSocketConnect::WebSocketConnect(const std::string& url,
|
||||
const std::string& headers,
|
||||
bool disableAutomaticReconnection,
|
||||
bool disablePerMessageDeflate) :
|
||||
bool disablePerMessageDeflate,
|
||||
bool binaryMode,
|
||||
uint32_t maxWaitBetweenReconnectionRetries) :
|
||||
_url(url),
|
||||
_disablePerMessageDeflate(disablePerMessageDeflate)
|
||||
_disablePerMessageDeflate(disablePerMessageDeflate),
|
||||
_binaryMode(binaryMode)
|
||||
{
|
||||
if (disableAutomaticReconnection)
|
||||
{
|
||||
_webSocket.disableAutomaticReconnection();
|
||||
}
|
||||
_webSocket.setMaxWaitBetweenReconnectionRetries(maxWaitBetweenReconnectionRetries);
|
||||
|
||||
_headers = parseHeaders(headers);
|
||||
}
|
||||
|
||||
void WebSocketConnect::log(const std::string& msg)
|
||||
@ -49,6 +65,31 @@ namespace ix
|
||||
std::cout << msg << std::endl;
|
||||
}
|
||||
|
||||
WebSocketHttpHeaders WebSocketConnect::parseHeaders(const std::string& data)
|
||||
{
|
||||
WebSocketHttpHeaders headers;
|
||||
|
||||
// Split by \n
|
||||
std::string token;
|
||||
std::stringstream tokenStream(data);
|
||||
|
||||
while (std::getline(tokenStream, token))
|
||||
{
|
||||
std::size_t pos = token.rfind(':');
|
||||
|
||||
// Bail out if last '.' is found
|
||||
if (pos == std::string::npos) continue;
|
||||
|
||||
auto key = token.substr(0, pos);
|
||||
auto val = token.substr(pos+1);
|
||||
|
||||
std::cerr << key << ": " << val << std::endl;
|
||||
headers[key] = val;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
void WebSocketConnect::stop()
|
||||
{
|
||||
_webSocket.stop();
|
||||
@ -57,6 +98,7 @@ namespace ix
|
||||
void WebSocketConnect::start()
|
||||
{
|
||||
_webSocket.setUrl(_url);
|
||||
_webSocket.setExtraHeaders(_headers);
|
||||
|
||||
if (_disablePerMessageDeflate)
|
||||
{
|
||||
@ -133,45 +175,61 @@ namespace ix
|
||||
|
||||
void WebSocketConnect::sendMessage(const std::string& text)
|
||||
{
|
||||
_webSocket.sendText(text);
|
||||
if (_binaryMode)
|
||||
{
|
||||
_webSocket.sendBinary(text);
|
||||
}
|
||||
else
|
||||
{
|
||||
_webSocket.sendText(text);
|
||||
}
|
||||
}
|
||||
|
||||
int ws_connect_main(const std::string& url,
|
||||
const std::string& headers,
|
||||
bool disableAutomaticReconnection,
|
||||
bool disablePerMessageDeflate)
|
||||
bool disablePerMessageDeflate,
|
||||
bool binaryMode,
|
||||
uint32_t maxWaitBetweenReconnectionRetries)
|
||||
{
|
||||
std::cout << "Type Ctrl-D to exit prompt..." << std::endl;
|
||||
WebSocketConnect webSocketChat(url,
|
||||
headers,
|
||||
disableAutomaticReconnection,
|
||||
disablePerMessageDeflate);
|
||||
disablePerMessageDeflate,
|
||||
binaryMode,
|
||||
maxWaitBetweenReconnectionRetries);
|
||||
webSocketChat.start();
|
||||
|
||||
while (true)
|
||||
{
|
||||
std::string text;
|
||||
std::cout << "> " << std::flush;
|
||||
std::getline(std::cin, text);
|
||||
// Read line
|
||||
std::string line;
|
||||
auto quit = linenoise::Readline("> ", line);
|
||||
|
||||
if (text == "/stop")
|
||||
if (quit)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (line == "/stop")
|
||||
{
|
||||
std::cout << "Stopping connection..." << std::endl;
|
||||
webSocketChat.stop();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (text == "/start")
|
||||
if (line == "/start")
|
||||
{
|
||||
std::cout << "Starting connection..." << std::endl;
|
||||
webSocketChat.start();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!std::cin)
|
||||
{
|
||||
break;
|
||||
}
|
||||
webSocketChat.sendMessage(line);
|
||||
|
||||
webSocketChat.sendMessage(text);
|
||||
// Add text to history
|
||||
linenoise::AddHistory(line.c_str());
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
|
@ -44,7 +44,7 @@ namespace ix
|
||||
if (pos == std::string::npos) continue;
|
||||
|
||||
auto key = token.substr(0, pos);
|
||||
auto val = token.substr(pos+2);
|
||||
auto val = token.substr(pos+1);
|
||||
|
||||
std::cerr << key << ": " << val << std::endl;
|
||||
headers[key] = val;
|
||||
|
34
ws/ws_httpd.cpp
Normal file
34
ws/ws_httpd.cpp
Normal file
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* ws_httpd.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int ws_httpd_main(int port, const std::string& hostname)
|
||||
{
|
||||
spdlog::info("Listening on {}:{}", hostname, port);
|
||||
|
||||
ix::HttpServer server(port, hostname);
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
std::cerr << res.second << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
server.start();
|
||||
server.wait();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user