Compare commits
346 Commits
v9.6.1
...
feature/se
Author | SHA1 | Date | |
---|---|---|---|
1ac02fdc0e | |||
687956358d | |||
1a42c92325 | |||
6bb00b6788 | |||
12f6cd878d | |||
9aacebbbaf | |||
701c3745c2 | |||
156288b17b | |||
ed0e23e8a5 | |||
4c4f99606e | |||
a61586c846 | |||
d64d50c978 | |||
a64b7b0c4a | |||
0caeb81327 | |||
edac7a0171 | |||
abfadad2e9 | |||
2dc1547bbd | |||
5eb23c9764 | |||
9f4b2856b0 | |||
b5fc10326e | |||
8d3a47a873 | |||
4df58f3059 | |||
06b8cb8d3b | |||
ff81f5b496 | |||
c89f73006e | |||
c28951f049 | |||
dfaaaca223 | |||
c7f0bf3d64 | |||
234ce4c173 | |||
f60293b2e7 | |||
9441095637 | |||
f82d38f758 | |||
a7f42f35db | |||
cb1d1bfd85 | |||
28c3f2ea26 | |||
8dc132dbd3 | |||
98e2fbca6a | |||
fa7f0fadde | |||
2732dfd0f1 | |||
2e4c4b72b6 | |||
fc21ad519b | |||
c65cfd3d26 | |||
8955462f73 | |||
205c8c15bd | |||
78198a0147 | |||
d561e1141e | |||
753fc845ac | |||
5dbc00bbfe | |||
14ec8522ef | |||
0c2d1c22bc | |||
1d39a9c9a9 | |||
b588ed0fa1 | |||
d9f7a138b8 | |||
d3e04ff619 | |||
372dd24cc7 | |||
a9422cf34d | |||
c7e52e6fcd | |||
705e0823cb | |||
8e4cf74974 | |||
0a7157655b | |||
58d65926bb | |||
b178ba16af | |||
e4c09284b5 | |||
9367a1feff | |||
d37ed300e2 | |||
3207ce37b6 | |||
d036ad7138 | |||
4fe07579b9 | |||
f563d14134 | |||
f1b3ecc738 | |||
8387f89115 | |||
773f92347f | |||
8ff1339b80 | |||
c85d5da111 | |||
9ab7bc652a | |||
e5c724eb05 | |||
e0300903d9 | |||
1ef38afcf7 | |||
210d19c8a0 | |||
6d24cc44b2 | |||
768e8eb074 | |||
3dd902e1f9 | |||
f85c5002b7 | |||
d48bf9249b | |||
0dfc66f1c7 | |||
4564173b75 | |||
b60e5aaf1f | |||
da67f4cb9a | |||
b041042473 | |||
f83263d6a1 | |||
b0139c2217 | |||
0ba2e2ce96 | |||
4a91ad80c8 | |||
4cc715b13d | |||
0dfd7cd543 | |||
56f164ce2b | |||
65db8c9b00 | |||
4c4137d9f2 | |||
e433e8b5e9 | |||
bb442021cf | |||
91106b7456 | |||
309b5ee1b3 | |||
4eded01841 | |||
e3d0c899d3 | |||
d7595b0dd0 | |||
f0375e59fa | |||
c367435073 | |||
dc812c384e | |||
10b2d10dbd | |||
f96babc6a6 | |||
4e2e14fb22 | |||
bcf2fc1812 | |||
935e6791a3 | |||
fbb7c012a3 | |||
dac18fcabf | |||
d8e83caffc | |||
fbf80b9f50 | |||
c2a9139d41 | |||
6e3dff149a | |||
1bacbe38f4 | |||
2e9c610ac9 | |||
eb063ec60a | |||
37fb14646d | |||
ae543518d3 | |||
c865d64608 | |||
3004422cb6 | |||
0c46a17443 | |||
497373d976 | |||
91198aca0d | |||
b17a5e5f0b | |||
3f0ef59f65 | |||
1e96edc293 | |||
0afb77393b | |||
7614b642bb | |||
bc89580dfe | |||
358ae13a88 | |||
ccf9dcba70 | |||
94604fad61 | |||
5c4cc7c50d | |||
9ed961ec06 | |||
e6bd8cc8c4 | |||
ee25bd0f92 | |||
e77b9176f3 | |||
afe8b966ad | |||
310724c961 | |||
ceba8ae620 | |||
fead661ab7 | |||
9c8c17f577 | |||
a04f83930f | |||
c421d19800 | |||
521f02c90e | |||
c86b6074f2 | |||
d5d1a2c5f4 | |||
2a90e3f478 | |||
1d49ba41ea | |||
e1de1f6682 | |||
47ed5e4d4d | |||
d77f6f5659 | |||
05f0045d5d | |||
c4afb84f6e | |||
b0b2f9b6d2 | |||
ee37feb489 | |||
6b8337596f | |||
250665b92e | |||
86b83c889e | |||
c9c657c07b | |||
4f2babaf54 | |||
1b03bf4555 | |||
977b995af9 | |||
310ab990bd | |||
d6b49b54d4 | |||
f00cf39462 | |||
18550cf1cb | |||
168918f807 | |||
2750df8aa7 | |||
d6597d9f52 | |||
892ea375e3 | |||
03abe77b5f | |||
e46eb8aa49 | |||
2c4862e0f1 | |||
fd69efa45c | |||
e8aa15917f | |||
b3d77f8902 | |||
9c3b0b08ec | |||
fe7d94194c | |||
d6c26d6aa8 | |||
8a74ddcd13 | |||
18e7189a07 | |||
785dd42c84 | |||
0cff5065d9 | |||
e881b82511 | |||
d5551e5d68 | |||
e8583000b8 | |||
d642ef1a89 | |||
2df118022d | |||
95457c8f4c | |||
0a45b7787f | |||
b8c397e180 | |||
90105fa2b3 | |||
24859fef8a | |||
73d7280723 | |||
262de49c3c | |||
3a77e96a05 | |||
505dd6d50f | |||
3f8027b65c | |||
0f2c765f45 | |||
49077f8f44 | |||
6a23b8530f | |||
ae841af91a | |||
44f38849b2 | |||
ee12fbdb5f | |||
316c630830 | |||
1ea5db6110 | |||
986d9a00c0 | |||
7a05a11014 | |||
f09434263c | |||
335f594165 | |||
fa7ef06f4d | |||
3c9ec0aed0 | |||
c665d65cba | |||
5d4e897cc4 | |||
05033714bf | |||
a02bd3f25c | |||
fdbd213fa2 | |||
da64d349c8 | |||
17b01a8c66 | |||
79dd766fab | |||
8375b28747 | |||
e12551f309 | |||
6102f81710 | |||
9f678e5962 | |||
02a704a8c7 | |||
dd2360ed70 | |||
c4ab996470 | |||
6c54b07d92 | |||
7f9bef3b8d | |||
12d1c5d956 | |||
e9a4bd5617 | |||
f34ccbfdb5 | |||
1fa75d7fb2 | |||
39140ef98c | |||
e30ef4a87c | |||
9fc94f0487 | |||
121acdab6f | |||
6deaa03114 | |||
f4f30686c5 | |||
a21aae521f | |||
aed2356fc1 | |||
a478f734f6 | |||
98c579da03 | |||
e80def0cd0 | |||
cc8a9e883e | |||
4d587e35d8 | |||
50f4fd1115 | |||
06d2b68696 | |||
bf6f057777 | |||
b57c1d69f2 | |||
ff265d83f9 | |||
5b1c97b774 | |||
c8c81366f7 | |||
9a37fd56d1 | |||
7ecaff8c5d | |||
e4b0286a25 | |||
7ae6972306 | |||
59cea0372b | |||
78d88a8520 | |||
273af25d57 | |||
46d00360a8 | |||
3f5935a284 | |||
c236ff66e9 | |||
af3df5e519 | |||
d75753ec98 | |||
332bb87231 | |||
8adbcab441 | |||
9bc2e95196 | |||
30a0aa0a0f | |||
8622ea5cb2 | |||
ed3a50d9b5 | |||
df6a17dcc2 | |||
474985e784 | |||
cb904416c3 | |||
3e064ec63e | |||
b004769552 | |||
17270de621 | |||
239b5bc02c | |||
6bfabd5493 | |||
0b90f7df1b | |||
00ca7c8fb0 | |||
a11952fe22 | |||
06b9b2e649 | |||
dcfdcc3e1b | |||
b13fee16c1 | |||
9a7767ecb1 | |||
9b82a33aff | |||
70ef77a5d5 | |||
77903e9d90 | |||
de66a87a7c | |||
5ea2028c22 | |||
58a68ec0be | |||
a39278f7be | |||
f8373dc666 | |||
3febc2431d | |||
0bf736831a | |||
7710bf793f | |||
a6a43bd361 | |||
a39209a895 | |||
24c9e0abc3 | |||
9cc324d78d | |||
8574beceb1 | |||
0349b7f1c7 | |||
ce1ba20db5 | |||
395d823f41 | |||
6884f9f74f | |||
b34eccd749 | |||
50b638f7fd | |||
5bf1b91528 | |||
f77ececc92 | |||
58cccbdcf9 | |||
5710ffba6a | |||
ccd4522b8f | |||
28f29b7385 | |||
a7a422d6ed | |||
43fcf93584 | |||
32f4c8305e | |||
3cf44c8078 | |||
9e899fde2f | |||
ffd4f1d322 | |||
10dd13deb3 | |||
c1ed83a005 | |||
7117c74142 | |||
dd06a3fb25 | |||
45b579447e | |||
bb0b1836cd | |||
d5c8815438 | |||
ac500ed079 | |||
2bc38acbb1 | |||
977feae1d6 | |||
9c872fcc3e | |||
ec1ca3c55e | |||
16805759d3 | |||
88c2e1f6de | |||
1dc9b559e9 | |||
d31ecfc64e | |||
4813a40f2a | |||
ea81470f4a | |||
2a6b1d5f15 |
@ -1,47 +0,0 @@
|
||||
# https://releases.llvm.org/7.0.0/tools/clang/docs/ClangFormatStyleOptions.html
|
||||
|
||||
---
|
||||
Language: Cpp
|
||||
|
||||
BasedOnStyle: WebKit
|
||||
|
||||
AlignAfterOpenBracket: Align
|
||||
AlignOperands: true
|
||||
AlignTrailingComments: true
|
||||
AllowAllParametersOfDeclarationOnNextLine: true
|
||||
AllowShortBlocksOnASingleLine: false
|
||||
AllowShortCaseLabelsOnASingleLine: true
|
||||
AllowShortFunctionsOnASingleLine: false
|
||||
AllowShortIfStatementsOnASingleLine: true
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AlwaysBreakTemplateDeclarations: true
|
||||
BinPackArguments: false
|
||||
BinPackParameters: false
|
||||
BreakBeforeBinaryOperators: None
|
||||
BreakBeforeBraces: Allman
|
||||
BreakConstructorInitializersBeforeComma: true
|
||||
ColumnLimit: 100
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: false
|
||||
Cpp11BracedListStyle: true
|
||||
FixNamespaceComments: true
|
||||
IncludeBlocks: Regroup
|
||||
IncludeCategories:
|
||||
- Regex: '^["<](stdafx|pch)\.h[">]$'
|
||||
Priority: -1
|
||||
- Regex: '^<Windows\.h>$'
|
||||
Priority: 3
|
||||
- Regex: '^<(WinIoCtl|winhttp|Shellapi)\.h>$'
|
||||
Priority: 4
|
||||
- Regex: '.*'
|
||||
Priority: 2
|
||||
IndentCaseLabels: true
|
||||
IndentWidth: 4
|
||||
KeepEmptyLinesAtTheStartOfBlocks: false
|
||||
MaxEmptyLinesToKeep: 2
|
||||
NamespaceIndentation: All
|
||||
PenaltyReturnTypeOnItsOwnLine: 1000
|
||||
PointerAlignment: Left
|
||||
SpaceAfterTemplateKeyword: false
|
||||
SpaceAfterCStyleCast: true
|
||||
Standard: Cpp11
|
||||
UseTab: Never
|
@ -1,4 +1,3 @@
|
||||
build
|
||||
CMakeCache.txt
|
||||
ws/CMakeCache.txt
|
||||
test/build
|
||||
|
86
.github/workflows/ccpp.yml
vendored
86
.github/workflows/ccpp.yml
vendored
@ -1,86 +0,0 @@
|
||||
name: unittest
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: make test_make
|
||||
run: make test_make
|
||||
|
||||
mac_tsan_sectransport:
|
||||
runs-on: macOS-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: make test_tsan
|
||||
run: make test_tsan
|
||||
|
||||
mac_tsan_openssl:
|
||||
runs-on: macOS-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: install openssl
|
||||
run: brew install openssl@1.1
|
||||
- name: make test
|
||||
run: make test_tsan_openssl
|
||||
|
||||
mac_tsan_mbedtls:
|
||||
runs-on: macOS-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: install mbedtls
|
||||
run: brew install mbedtls
|
||||
- name: make test
|
||||
run: make test_tsan_mbedtls
|
||||
|
||||
windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: seanmiddleditch/gha-setup-vsdevenv@master
|
||||
- run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_CXX_COMPILER=cl.exe -DUSE_WS=1 -DUSE_TEST=1 ..
|
||||
- run: cmake --build build
|
||||
|
||||
# Running the unittest does not work, the binary cannot be found
|
||||
#- run: ../build/test/ixwebsocket_unittest.exe
|
||||
# working-directory: test
|
||||
|
||||
uwp:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: seanmiddleditch/gha-setup-vsdevenv@master
|
||||
- run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION="10.0" -DCMAKE_CXX_COMPILER=cl.exe -DUSE_TEST=1 ..
|
||||
- run: cmake --build build
|
||||
|
||||
#
|
||||
# Windows with OpenSSL is working but disabled as it takes 13 minutes (10 for openssl) to build with vcpkg
|
||||
#
|
||||
# windows_openssl:
|
||||
# runs-on: windows-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v1
|
||||
# - uses: seanmiddleditch/gha-setup-vsdevenv@master
|
||||
# - run: |
|
||||
# vcpkg install zlib:x64-windows
|
||||
# vcpkg install openssl:x64-windows
|
||||
# - run: |
|
||||
# mkdir build
|
||||
# cd build
|
||||
# cmake -DCMAKE_TOOLCHAIN_FILE=c:/vcpkg/scripts/buildsystems/vcpkg.cmake -DCMAKE_CXX_COMPILER=cl.exe -DUSE_OPEN_SSL=1 -DUSE_TLS=1 -DUSE_WS=1 -DUSE_TEST=1 ..
|
||||
# - run: cmake --build build
|
||||
#
|
||||
# # Running the unittest does not work, the binary cannot be found
|
||||
# #- run: ../build/test/ixwebsocket_unittest.exe
|
||||
# # working-directory: test
|
||||
|
25
.github/workflows/mkdocs.yml
vendored
25
.github/workflows/mkdocs.yml
vendored
@ -1,25 +0,0 @@
|
||||
name: mkdocs
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'docs/**'
|
||||
|
||||
jobs:
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Set up Python 3.8
|
||||
uses: actions/setup-python@v1
|
||||
with:
|
||||
python-version: 3.8
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install mkdocs
|
||||
pip install mkdocs-material
|
||||
pip install pygments
|
||||
- name: Build doc
|
||||
run: |
|
||||
git pull
|
||||
mkdocs gh-deploy
|
19
.github/workflows/stale.yml
vendored
19
.github/workflows/stale.yml
vendored
@ -1,19 +0,0 @@
|
||||
name: Mark stale issues and pull requests
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *"
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/stale@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: 'Stale issue message'
|
||||
stale-pr-message: 'Stale pull request message'
|
||||
stale-issue-label: 'no-issue-activity'
|
||||
stale-pr-label: 'no-pr-activity'
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,7 +1,2 @@
|
||||
build
|
||||
*.pyc
|
||||
venv
|
||||
ixsnake/ixsnake/.certs/
|
||||
site/
|
||||
ws/.certs/
|
||||
ws/.srl
|
||||
|
@ -1,12 +0,0 @@
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v2.5.0
|
||||
hooks:
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/pocc/pre-commit-hooks
|
||||
rev: v1.1.1
|
||||
hooks:
|
||||
- id: clang-format
|
||||
args: [-i, -style=file]
|
17
.travis.yml
Normal file
17
.travis.yml
Normal file
@ -0,0 +1,17 @@
|
||||
language: cpp
|
||||
dist: xenial
|
||||
|
||||
compiler:
|
||||
- gcc
|
||||
- clang
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
matrix:
|
||||
exclude:
|
||||
# GCC fails on recent Travis OSX images.
|
||||
- compiler: gcc
|
||||
os: osx
|
||||
|
||||
script: python test/run.py
|
@ -1,19 +0,0 @@
|
||||
# Find package structure taken from libcurl
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
|
||||
find_path(JSONCPP_INCLUDE_DIRS json/json.h)
|
||||
find_library(JSONCPP_LIBRARY jsoncpp)
|
||||
|
||||
find_package_handle_standard_args(JsonCpp
|
||||
FOUND_VAR
|
||||
JSONCPP_FOUND
|
||||
REQUIRED_VARS
|
||||
JSONCPP_LIBRARY
|
||||
JSONCPP_INCLUDE_DIRS
|
||||
FAIL_MESSAGE
|
||||
"Could NOT find jsoncpp"
|
||||
)
|
||||
|
||||
set(JSONCPP_INCLUDE_DIRS ${JSONCPP_INCLUDE_DIRS})
|
||||
set(JSONCPP_LIBRARIES ${JSONCPP_LIBRARY})
|
@ -1,13 +0,0 @@
|
||||
find_path(MBEDTLS_INCLUDE_DIRS mbedtls/ssl.h)
|
||||
|
||||
find_library(MBEDTLS_LIBRARY mbedtls)
|
||||
find_library(MBEDX509_LIBRARY mbedx509)
|
||||
find_library(MBEDCRYPTO_LIBRARY mbedcrypto)
|
||||
|
||||
set(MBEDTLS_LIBRARIES "${MBEDTLS_LIBRARY}" "${MBEDX509_LIBRARY}" "${MBEDCRYPTO_LIBRARY}")
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(MBEDTLS DEFAULT_MSG
|
||||
MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY)
|
||||
|
||||
mark_as_advanced(MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY)
|
@ -1,19 +0,0 @@
|
||||
# Find package structure taken from libcurl
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
|
||||
find_path(SPDLOG_INCLUDE_DIRS spdlog/spdlog.h)
|
||||
find_library(JSONCPP_LIBRARY spdlog)
|
||||
|
||||
find_package_handle_standard_args(SPDLOG
|
||||
FOUND_VAR
|
||||
SPDLOG_FOUND
|
||||
REQUIRED_VARS
|
||||
SPDLOG_LIBRARY
|
||||
SPDLOG_INCLUDE_DIRS
|
||||
FAIL_MESSAGE
|
||||
"Could NOT find spdlog"
|
||||
)
|
||||
|
||||
set(SPDLOG_INCLUDE_DIRS ${SPDLOG_INCLUDE_DIRS})
|
||||
set(SPDLOG_LIBRARIES ${SPDLOG_LIBRARY})
|
241
CMakeLists.txt
241
CMakeLists.txt
@ -4,19 +4,14 @@
|
||||
#
|
||||
|
||||
cmake_minimum_required(VERSION 3.4.1)
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}")
|
||||
|
||||
project(ixwebsocket C CXX)
|
||||
|
||||
set (CMAKE_CXX_STANDARD 14)
|
||||
set (CXX_STANDARD_REQUIRED ON)
|
||||
set (CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
endif()
|
||||
|
||||
if (UNIX)
|
||||
# -Wshorten-64-to-32 does not work with clang
|
||||
if (NOT WIN32)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic")
|
||||
endif()
|
||||
|
||||
@ -25,77 +20,56 @@ if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
endif()
|
||||
|
||||
set( IXWEBSOCKET_SOURCES
|
||||
ixwebsocket/IXBench.cpp
|
||||
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
|
||||
ixwebsocket/IXSocket.cpp
|
||||
ixwebsocket/IXSocketServer.cpp
|
||||
ixwebsocket/IXSocketConnect.cpp
|
||||
ixwebsocket/IXSocketFactory.cpp
|
||||
ixwebsocket/IXSocketServer.cpp
|
||||
ixwebsocket/IXSocketTLSOptions.cpp
|
||||
ixwebsocket/IXUdpSocket.cpp
|
||||
ixwebsocket/IXUrlParser.cpp
|
||||
ixwebsocket/IXUserAgent.cpp
|
||||
ixwebsocket/IXDNSLookup.cpp
|
||||
ixwebsocket/IXCancellationRequest.cpp
|
||||
ixwebsocket/IXNetSystem.cpp
|
||||
ixwebsocket/IXWebSocket.cpp
|
||||
ixwebsocket/IXWebSocketCloseConstants.cpp
|
||||
ixwebsocket/IXWebSocketServer.cpp
|
||||
ixwebsocket/IXWebSocketTransport.cpp
|
||||
ixwebsocket/IXWebSocketHandshake.cpp
|
||||
ixwebsocket/IXWebSocketHttpHeaders.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflate.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateCodec.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateOptions.cpp
|
||||
ixwebsocket/IXWebSocketServer.cpp
|
||||
ixwebsocket/IXWebSocketTransport.cpp
|
||||
ixwebsocket/IXWebSocketHttpHeaders.cpp
|
||||
ixwebsocket/IXHttpClient.cpp
|
||||
ixwebsocket/IXUrlParser.cpp
|
||||
ixwebsocket/LUrlParser.cpp
|
||||
ixwebsocket/IXSelectInterrupt.cpp
|
||||
ixwebsocket/IXSelectInterruptFactory.cpp
|
||||
ixwebsocket/IXConnectionState.cpp
|
||||
)
|
||||
|
||||
set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXBench.h
|
||||
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
|
||||
ixwebsocket/IXSelectInterruptFactory.h
|
||||
ixwebsocket/IXSetThreadName.h
|
||||
ixwebsocket/IXSocket.h
|
||||
ixwebsocket/IXSocketServer.h
|
||||
ixwebsocket/IXSocketConnect.h
|
||||
ixwebsocket/IXSocketFactory.h
|
||||
ixwebsocket/IXSocketServer.h
|
||||
ixwebsocket/IXSocketTLSOptions.h
|
||||
ixwebsocket/IXUdpSocket.h
|
||||
ixwebsocket/IXUrlParser.h
|
||||
ixwebsocket/IXUtf8Validator.h
|
||||
ixwebsocket/IXUserAgent.h
|
||||
ixwebsocket/IXSetThreadName.h
|
||||
ixwebsocket/IXDNSLookup.h
|
||||
ixwebsocket/IXCancellationRequest.h
|
||||
ixwebsocket/IXNetSystem.h
|
||||
ixwebsocket/IXProgressCallback.h
|
||||
ixwebsocket/IXWebSocket.h
|
||||
ixwebsocket/IXWebSocketCloseConstants.h
|
||||
ixwebsocket/IXWebSocketCloseInfo.h
|
||||
ixwebsocket/IXWebSocketErrorInfo.h
|
||||
ixwebsocket/IXWebSocketServer.h
|
||||
ixwebsocket/IXWebSocketTransport.h
|
||||
ixwebsocket/IXWebSocketHandshake.h
|
||||
ixwebsocket/IXWebSocketHandshakeKeyGen.h
|
||||
ixwebsocket/IXWebSocketHttpHeaders.h
|
||||
ixwebsocket/IXWebSocketInitResult.h
|
||||
ixwebsocket/IXWebSocketMessage.h
|
||||
ixwebsocket/IXWebSocketMessageType.h
|
||||
ixwebsocket/IXWebSocketOpenInfo.h
|
||||
ixwebsocket/IXWebSocketSendInfo.h
|
||||
ixwebsocket/IXWebSocketErrorInfo.h
|
||||
ixwebsocket/IXWebSocketPerMessageDeflate.h
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateCodec.h
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateOptions.h
|
||||
ixwebsocket/IXWebSocketSendInfo.h
|
||||
ixwebsocket/IXWebSocketServer.h
|
||||
ixwebsocket/IXWebSocketTransport.h
|
||||
ixwebsocket/IXWebSocketVersion.h
|
||||
ixwebsocket/IXWebSocketHttpHeaders.h
|
||||
ixwebsocket/libwshandshake.hpp
|
||||
ixwebsocket/IXHttpClient.h
|
||||
ixwebsocket/IXUrlParser.h
|
||||
ixwebsocket/LUrlParser.h
|
||||
ixwebsocket/IXSelectInterrupt.h
|
||||
ixwebsocket/IXSelectInterruptFactory.h
|
||||
ixwebsocket/IXConnectionState.h
|
||||
)
|
||||
|
||||
if (UNIX)
|
||||
@ -109,42 +83,26 @@ if (APPLE)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/apple/IXSetThreadName_apple.cpp)
|
||||
elseif (WIN32)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/windows/IXSetThreadName_windows.cpp)
|
||||
elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/freebsd/IXSetThreadName_freebsd.cpp)
|
||||
else()
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/linux/IXSetThreadName_linux.cpp)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSelectInterruptEventFd.cpp)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSelectInterruptEventFd.h)
|
||||
endif()
|
||||
|
||||
option(USE_TLS "Enable TLS support" FALSE)
|
||||
|
||||
set(USE_OPEN_SSL FALSE)
|
||||
if (USE_TLS)
|
||||
# default to securetranport on Apple if nothing is configured
|
||||
if (APPLE)
|
||||
if (NOT USE_MBED_TLS AND NOT USE_OPEN_SSL) # unless we want something else
|
||||
set(USE_SECURE_TRANSPORT ON)
|
||||
endif()
|
||||
# default to mbedtls on windows if nothing is configured
|
||||
elseif (WIN32)
|
||||
if (NOT USE_OPEN_SSL) # unless we want something else
|
||||
set(USE_MBED_TLS ON)
|
||||
endif()
|
||||
else() # default to OpenSSL on all other platforms
|
||||
if (NOT USE_MBED_TLS) # Unless mbedtls is requested
|
||||
set(USE_OPEN_SSL ON)
|
||||
endif()
|
||||
endif()
|
||||
add_definitions(-DIXWEBSOCKET_USE_TLS)
|
||||
|
||||
if (USE_MBED_TLS)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketMbedTLS.h)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketMbedTLS.cpp)
|
||||
elseif (USE_SECURE_TRANSPORT)
|
||||
if (APPLE)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketAppleSSL.h)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketAppleSSL.cpp)
|
||||
elseif (USE_OPEN_SSL)
|
||||
elseif (WIN32)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketSChannel.h)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketSChannel.cpp)
|
||||
else()
|
||||
set(USE_OPEN_SSL TRUE)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketOpenSSL.h)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketOpenSSL.cpp)
|
||||
else()
|
||||
message(FATAL_ERROR "TLS Configuration error: unknown backend")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
@ -153,84 +111,34 @@ add_library( ixwebsocket STATIC
|
||||
${IXWEBSOCKET_HEADERS}
|
||||
)
|
||||
|
||||
add_library ( ixwebsocket::ixwebsocket ALIAS ixwebsocket )
|
||||
|
||||
if (USE_TLS)
|
||||
target_compile_definitions(ixwebsocket PUBLIC IXWEBSOCKET_USE_TLS)
|
||||
if (USE_MBED_TLS)
|
||||
target_compile_definitions(ixwebsocket PUBLIC IXWEBSOCKET_USE_MBED_TLS)
|
||||
elseif (USE_OPEN_SSL)
|
||||
target_compile_definitions(ixwebsocket PUBLIC IXWEBSOCKET_USE_OPEN_SSL)
|
||||
elseif (USE_SECURE_TRANSPORT)
|
||||
target_compile_definitions(ixwebsocket PUBLIC IXWEBSOCKET_USE_SECURE_TRANSPORT)
|
||||
else()
|
||||
message(FATAL_ERROR "TLS Configuration error: unknown backend")
|
||||
endif()
|
||||
if (APPLE AND USE_TLS)
|
||||
target_link_libraries(ixwebsocket "-framework foundation" "-framework security")
|
||||
endif()
|
||||
|
||||
if (USE_TLS)
|
||||
if (USE_OPEN_SSL)
|
||||
message(STATUS "TLS configured to use openssl")
|
||||
|
||||
# Help finding Homebrew's OpenSSL on macOS
|
||||
if (APPLE)
|
||||
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} /usr/local/opt/openssl/lib)
|
||||
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} /usr/local/opt/openssl/include)
|
||||
|
||||
# This is for MacPort OpenSSL 1.0
|
||||
# set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} /opt/local/lib/openssl-1.0)
|
||||
# set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} /opt/local/include/openssl-1.0)
|
||||
endif()
|
||||
|
||||
# This OPENSSL_FOUND check is to help find a cmake manually configured OpenSSL
|
||||
if (NOT OPENSSL_FOUND)
|
||||
include(FindOpenSSL)
|
||||
endif()
|
||||
message(STATUS "OpenSSL: " ${OPENSSL_VERSION})
|
||||
|
||||
target_link_libraries(ixwebsocket PUBLIC OpenSSL::SSL OpenSSL::Crypto)
|
||||
elseif (USE_MBED_TLS)
|
||||
message(STATUS "TLS configured to use mbedtls")
|
||||
|
||||
find_package(MbedTLS REQUIRED)
|
||||
target_include_directories(ixwebsocket PUBLIC ${MBEDTLS_INCLUDE_DIRS})
|
||||
target_link_libraries(ixwebsocket PUBLIC ${MBEDTLS_LIBRARIES})
|
||||
elseif (USE_SECURE_TRANSPORT)
|
||||
message(STATUS "TLS configured to use secure transport")
|
||||
target_link_libraries(ixwebsocket PUBLIC "-framework foundation" "-framework security")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# This ZLIB_FOUND check is to help find a cmake manually configured zlib
|
||||
if (NOT ZLIB_FOUND)
|
||||
find_package(ZLIB)
|
||||
endif()
|
||||
if (ZLIB_FOUND)
|
||||
include_directories(${ZLIB_INCLUDE_DIRS})
|
||||
target_link_libraries(ixwebsocket PUBLIC ${ZLIB_LIBRARIES})
|
||||
else()
|
||||
include_directories(third_party/zlib ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib)
|
||||
add_subdirectory(third_party/zlib EXCLUDE_FROM_ALL)
|
||||
target_link_libraries(ixwebsocket PRIVATE $<LINK_ONLY:zlibstatic>)
|
||||
if (USE_OPEN_SSL)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
add_definitions(${OPENSSL_DEFINITIONS})
|
||||
message(STATUS "OpenSSL: " ${OPENSSL_VERSION})
|
||||
include_directories(${OPENSSL_INCLUDE_DIR})
|
||||
target_link_libraries(ixwebsocket ${OPENSSL_LIBRARIES})
|
||||
endif()
|
||||
|
||||
if (WIN32)
|
||||
target_link_libraries(ixwebsocket PUBLIC wsock32 ws2_32 shlwapi)
|
||||
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)
|
||||
|
||||
if (USE_TLS)
|
||||
target_link_libraries(ixwebsocket PUBLIC Crypt32)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if (UNIX)
|
||||
else()
|
||||
# gcc/Linux needs -pthread
|
||||
find_package(Threads)
|
||||
target_link_libraries(ixwebsocket PUBLIC ${CMAKE_THREAD_LIBS_INIT})
|
||||
endif()
|
||||
|
||||
target_link_libraries(ixwebsocket
|
||||
z ${CMAKE_THREAD_LIBS_INIT})
|
||||
endif()
|
||||
|
||||
set( IXWEBSOCKET_INCLUDE_DIRS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
.
|
||||
)
|
||||
|
||||
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
@ -238,32 +146,15 @@ if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
target_compile_options(ixwebsocket PRIVATE /MP)
|
||||
endif()
|
||||
|
||||
target_include_directories(ixwebsocket PUBLIC $<BUILD_INTERFACE:${IXWEBSOCKET_INCLUDE_DIRS}> $<INSTALL_INTERFACE:include/ixwebsocket>)
|
||||
target_include_directories( ixwebsocket PUBLIC ${IXWEBSOCKET_INCLUDE_DIRS} )
|
||||
|
||||
set_target_properties(ixwebsocket PROPERTIES PUBLIC_HEADER "${IXWEBSOCKET_HEADERS}")
|
||||
|
||||
install(TARGETS ixwebsocket EXPORT ixwebsocket
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/lib
|
||||
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_PREFIX}/include/ixwebsocket/
|
||||
install(TARGETS ixwebsocket
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/lib
|
||||
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_PREFIX}/include/ixwebsocket/
|
||||
)
|
||||
|
||||
install(EXPORT ixwebsocket NAMESPACE ixwebsocket:: DESTINATION lib/cmake/ixwebsocket)
|
||||
export(EXPORT ixwebsocket NAMESPACE ixwebsocket:: FILE ixwebsocketConfig.cmake)
|
||||
|
||||
if (USE_WS OR USE_TEST)
|
||||
add_subdirectory(ixcore)
|
||||
add_subdirectory(ixcrypto)
|
||||
add_subdirectory(ixcobra)
|
||||
add_subdirectory(ixsnake)
|
||||
add_subdirectory(ixsentry)
|
||||
add_subdirectory(ixbots)
|
||||
|
||||
add_subdirectory(third_party/spdlog spdlog)
|
||||
|
||||
if (USE_WS)
|
||||
add_subdirectory(ws)
|
||||
endif()
|
||||
if (USE_TEST)
|
||||
add_subdirectory(test)
|
||||
endif()
|
||||
if (NOT WIN32)
|
||||
add_subdirectory(ws)
|
||||
endif()
|
||||
|
1
DOCKER_VERSION
Normal file
1
DOCKER_VERSION
Normal file
@ -0,0 +1 @@
|
||||
2.0.0
|
@ -1 +1 @@
|
||||
docker/Dockerfile.alpine
|
||||
docker/Dockerfile.ubuntu_xenial
|
423
README.md
423
README.md
@ -1,51 +1,422 @@
|
||||
## Hello world
|
||||
# General
|
||||
|
||||

|
||||

|
||||
|
||||
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.
|
||||
## Introduction
|
||||
|
||||
It is been used on big mobile video game titles sending and receiving tons of messages since 2017 (iOS and Android). It was tested on macOS, iOS, Linux, Android, Windows and FreeBSD. Two important design goals are simplicity and correctness.
|
||||
[*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.
|
||||
|
||||
```cpp
|
||||
// Required on Windows
|
||||
ix::initNetSystem();
|
||||
* macOS
|
||||
* iOS
|
||||
* Linux
|
||||
* Android
|
||||
* Windows (no TLS)
|
||||
|
||||
// Our websocket object
|
||||
## 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.
|
||||
|
||||
Here is what the client API looks like.
|
||||
|
||||
```
|
||||
ix::WebSocket webSocket;
|
||||
|
||||
std::string url("ws://localhost:8080/");
|
||||
webSocket.setUrl(url);
|
||||
|
||||
// Setup a callback to be fired (in a background thread, watch out for race conditions !)
|
||||
// when a message or an event (open, close, error) is received
|
||||
webSocket.setOnMessageCallback([](const ix::WebSocketMessagePtr& msg)
|
||||
// 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);
|
||||
|
||||
// Setup a callback to be fired when a message or an event (open, close, error) is received
|
||||
webSocket.setOnMessageCallback(
|
||||
[](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
if (msg->type == ix::WebSocketMessageType::Message)
|
||||
if (messageType == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
std::cout << msg->str << std::endl;
|
||||
std::cout << 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)
|
||||
// Send a message to the server (default to BINARY mode)
|
||||
webSocket.send("hello world");
|
||||
|
||||
// The message can be sent in TEXT mode
|
||||
webSocket.sendText("hello again");
|
||||
|
||||
// ... finally ...
|
||||
|
||||
// Stop the connection
|
||||
webSocket.stop()
|
||||
```
|
||||
|
||||
Interested? Go read the [docs](https://machinezone.github.io/IXWebSocket/)! If things don't work as expected, please create an issue on GitHub, or even better a pull request if you know how to fix your problem.
|
||||
Here is what the server API looks like. Note that server support is very recent and subject to changes.
|
||||
|
||||
IXWebSocket is actively being developed, check out the [changelog](https://machinezone.github.io/IXWebSocket/CHANGELOG/) 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).
|
||||
```
|
||||
// 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);
|
||||
|
||||
IXWebSocket client code is autobahn compliant beginning with the 6.0.0 version. See the current [test results](https://bsergean.github.io/autobahn/reports/clients/index.html). Some tests are still failing in the server code.
|
||||
server.setOnConnectionCallback(
|
||||
[&server](std::shared_ptr<WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
webSocket->setOnMessageCallback(
|
||||
[webSocket, connectionState, &server](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cerr << "New connection" << std::endl;
|
||||
|
||||
## Users
|
||||
// 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;
|
||||
|
||||
If your company or project is using this library, feel free to open an issue or PR to amend this list.
|
||||
// The uri the client did connect to.
|
||||
std::cerr << "Uri: " << openInfo.uri << std::endl;
|
||||
|
||||
- [Machine Zone](https://www.mz.com)
|
||||
- [dis-light](https://gitlab.com/HCInk/dis-light), a discord library with a node frontend.
|
||||
- [libDiscordBot](https://github.com/tostc/libDiscordBot/tree/master), a work in progress discord library
|
||||
- [gwebsocket](https://github.com/norrbotten/gwebsocket), a websocket (lua) module for Garry's Mod
|
||||
- [DisCPP](https://github.com/DisCPP/DisCPP), a simple but feature rich Discord API wrapper
|
||||
std::cerr << "Headers:" << std::endl;
|
||||
for (auto it : openInfo.headers)
|
||||
{
|
||||
std::cerr << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (messageType == 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.
|
||||
webSocket->send(str);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
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;
|
||||
HttpRequestArgs args;
|
||||
|
||||
// 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;
|
||||
};
|
||||
|
||||
//
|
||||
// Request
|
||||
//
|
||||
HttpResponse 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 = std::get<0>(out);
|
||||
auto errorCode = std::get<1>(out);
|
||||
auto responseHeaders = std::get<2>(out);
|
||||
auto payload = std::get<3>(out);
|
||||
auto errorMsg = std::get<4>(out);
|
||||
auto uploadSize = std::get<5>(out);
|
||||
auto downloadSize = std::get<6>(out);
|
||||
```
|
||||
|
||||
## 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, and OpenSSL is used on Android and Linux.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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
|
||||
|
||||
* 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(
|
||||
[](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
if (messageType == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
std::cout << "send greetings" << std::endl;
|
||||
|
||||
// Headers can be inspected (pairs of string/string)
|
||||
std::cout << "Handshake Headers:" << std::endl;
|
||||
for (auto it : headers)
|
||||
{
|
||||
std::cout << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (messageType == 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 << closeInfo.code << std::endl;
|
||||
std::cout << 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(
|
||||
[](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
if (messageType == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Error: " << error.reason << std::endl;
|
||||
ss << "#retries: " << event.retries << std::endl;
|
||||
ss << "Wait time(ms): " << event.wait_time << std::endl;
|
||||
ss << "HTTP Status: " << event.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(
|
||||
[](ix::WebSocketMessageType messageType,
|
||||
const std::string& str,
|
||||
size_t wireSize,
|
||||
const ix::WebSocketErrorInfo& error,
|
||||
const ix::WebSocketOpenInfo& openInfo,
|
||||
const ix::WebSocketCloseInfo& closeInfo)
|
||||
{
|
||||
if (messageType == ix::WebSocketMessageType::Ping ||
|
||||
messageType == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
std::cout << "pong data: " << 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);
|
||||
```
|
||||
|
11
SECURITY.md
11
SECURITY.md
@ -1,11 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 7.x.x | :white_check_mark: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Users should send an email to bsergean@gmail.com to report a vulnerability.
|
16
appveyor.yml
16
appveyor.yml
@ -2,21 +2,13 @@ image:
|
||||
- Visual Studio 2017
|
||||
|
||||
install:
|
||||
- cd C:\Tools\vcpkg
|
||||
- git pull
|
||||
- .\bootstrap-vcpkg.bat
|
||||
- cd %APPVEYOR_BUILD_FOLDER%
|
||||
- ls -al
|
||||
- cmd: call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"
|
||||
- vcpkg install zlib:x64-windows
|
||||
- vcpkg install mbedtls:x64-windows
|
||||
- cd test
|
||||
- mkdir build
|
||||
- cd build
|
||||
- cmake -DCMAKE_TOOLCHAIN_FILE=c:/tools/vcpkg/scripts/buildsystems/vcpkg.cmake -DUSE_WS=1 -DUSE_TEST=1 -DUSE_TLS=1 -G"NMake Makefiles" ..
|
||||
- cmake -G"NMake Makefiles" ..
|
||||
- nmake
|
||||
- cd ..
|
||||
- cd test
|
||||
- ..\build\test\ixwebsocket_unittest.exe
|
||||
|
||||
cache: c:\tools\vcpkg\installed\
|
||||
- ixwebsocket_unittest.exe
|
||||
|
||||
build: off
|
||||
|
@ -1,67 +1,33 @@
|
||||
version: "3"
|
||||
services:
|
||||
# snake:
|
||||
# image: bsergean/ws:build
|
||||
# entrypoint: ws snake --port 8767 --host 0.0.0.0 --redis_hosts redis1
|
||||
# ports:
|
||||
# - "8767:8767"
|
||||
# networks:
|
||||
# - ws-net
|
||||
# depends_on:
|
||||
# - redis1
|
||||
snake:
|
||||
image: bsergean/ws:build
|
||||
entrypoint: ws snake --port 8765 --host 0.0.0.0 --redis_hosts redis1
|
||||
ports:
|
||||
- "8765:8765"
|
||||
networks:
|
||||
- ws-net
|
||||
depends_on:
|
||||
- redis1
|
||||
|
||||
# proxy:
|
||||
# image: bsergean/ws:build
|
||||
# entrypoint: strace ws proxy_server --remote_host 'wss://cobra.addsrv.com' --host 0.0.0.0 --port 8765 -v
|
||||
# ports:
|
||||
# - "8765:8765"
|
||||
# networks:
|
||||
# - ws-net
|
||||
|
||||
#pyproxy:
|
||||
# image: bsergean/ws_proxy:build
|
||||
# entrypoint: /usr/bin/ws_proxy.py --remote_url 'wss://cobra.addsrv.com' --host 0.0.0.0 --port 8765
|
||||
# ports:
|
||||
# - "8765:8765"
|
||||
# networks:
|
||||
# - ws-net
|
||||
|
||||
# # ws:
|
||||
# # security_opt:
|
||||
# # - seccomp:unconfined
|
||||
# # cap_add:
|
||||
# # - SYS_PTRACE
|
||||
# # stdin_open: true
|
||||
# # tty: true
|
||||
# # image: bsergean/ws:build
|
||||
# # entrypoint: sh
|
||||
# # networks:
|
||||
# # - ws-net
|
||||
# # depends_on:
|
||||
# # - redis1
|
||||
# #
|
||||
# # redis1:
|
||||
# # image: redis:alpine
|
||||
# # networks:
|
||||
# # - ws-net
|
||||
# #
|
||||
# # statsd:
|
||||
# # image: jaconel/statsd
|
||||
# # ports:
|
||||
# # - "8125:8125"
|
||||
# # environment:
|
||||
# # - STATSD_DUMP_MSG=true
|
||||
# # - GRAPHITE_HOST=127.0.0.1
|
||||
# # networks:
|
||||
# # - ws-net
|
||||
|
||||
compile:
|
||||
image: alpine
|
||||
entrypoint: sh
|
||||
ws:
|
||||
security_opt:
|
||||
- seccomp:unconfined
|
||||
cap_add:
|
||||
- SYS_PTRACE
|
||||
stdin_open: true
|
||||
tty: true
|
||||
volumes:
|
||||
- /Users/bsergeant/src/foss:/home/bsergean/src/foss
|
||||
image: bsergean/ws:build
|
||||
entrypoint: bash
|
||||
networks:
|
||||
- ws-net
|
||||
depends_on:
|
||||
- redis1
|
||||
|
||||
redis1:
|
||||
image: redis:alpine
|
||||
networks:
|
||||
- ws-net
|
||||
|
||||
networks:
|
||||
ws-net:
|
||||
|
@ -1,39 +0,0 @@
|
||||
FROM alpine:3.11 as build
|
||||
|
||||
RUN apk add --no-cache \
|
||||
gcc g++ musl-dev linux-headers \
|
||||
cmake mbedtls-dev make zlib-dev ninja
|
||||
|
||||
RUN addgroup -S app && \
|
||||
adduser -S -G app app && \
|
||||
chown -R app:app /opt && \
|
||||
chown -R app:app /usr/local
|
||||
|
||||
# There is a bug in CMake where we cannot build from the root top folder
|
||||
# So we build from /opt
|
||||
COPY --chown=app:app . /opt
|
||||
WORKDIR /opt
|
||||
|
||||
USER app
|
||||
RUN make ws_mbedtls_install && \
|
||||
sh tools/trim_repo_for_docker.sh
|
||||
|
||||
FROM alpine:3.11 as runtime
|
||||
|
||||
RUN apk add --no-cache libstdc++ mbedtls ca-certificates && \
|
||||
addgroup -S app && \
|
||||
adduser -S -G app app
|
||||
|
||||
COPY --chown=app:app --from=build /usr/local/bin/ws /usr/local/bin/ws
|
||||
|
||||
# COPY --chown=app:app --from=build /opt /opt
|
||||
|
||||
RUN chmod +x /usr/local/bin/ws && \
|
||||
ldd /usr/local/bin/ws
|
||||
|
||||
# Now run in usermode
|
||||
USER app
|
||||
WORKDIR /home/app
|
||||
|
||||
ENTRYPOINT ["ws"]
|
||||
EXPOSE 8008
|
@ -1,41 +0,0 @@
|
||||
FROM centos:8 as build
|
||||
|
||||
RUN yum install -y gcc-c++ make cmake zlib-devel openssl-devel redhat-rpm-config
|
||||
|
||||
RUN yum install -y epel-release
|
||||
RUN yum install -y mbedtls-devel
|
||||
|
||||
RUN groupadd app && useradd -g app app
|
||||
RUN chown -R app:app /opt
|
||||
RUN chown -R app:app /usr/local
|
||||
|
||||
# There is a bug in CMake where we cannot build from the root top folder
|
||||
# So we build from /opt
|
||||
COPY --chown=app:app . /opt
|
||||
WORKDIR /opt
|
||||
|
||||
USER app
|
||||
RUN [ "make", "ws_mbedtls_install" ]
|
||||
RUN [ "rm", "-rf", "build" ]
|
||||
|
||||
FROM centos:8 as runtime
|
||||
|
||||
RUN yum install -y gdb strace
|
||||
|
||||
RUN yum install -y epel-release
|
||||
RUN yum install -y mbedtls
|
||||
|
||||
RUN groupadd app && useradd -g app app
|
||||
COPY --chown=app:app --from=build /usr/local/bin/ws /usr/local/bin/ws
|
||||
RUN chmod +x /usr/local/bin/ws
|
||||
RUN ldd /usr/local/bin/ws
|
||||
|
||||
# Copy source code for gcc
|
||||
COPY --chown=app:app --from=build /opt /opt
|
||||
|
||||
# Now run in usermode
|
||||
USER app
|
||||
WORKDIR /home/app
|
||||
|
||||
ENTRYPOINT ["ws"]
|
||||
EXPOSE 8008
|
@ -2,14 +2,14 @@
|
||||
FROM debian:buster as build
|
||||
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt-get update
|
||||
RUN apt-get -y install wget
|
||||
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 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 g++
|
||||
RUN apt-get -y install libssl-dev
|
||||
RUN apt-get -y install libz-dev
|
||||
RUN apt-get -y install make
|
||||
@ -25,9 +25,9 @@ RUN ["make"]
|
||||
FROM debian:buster as runtime
|
||||
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt-get update
|
||||
# Runtime
|
||||
RUN apt-get install -y libssl1.1
|
||||
RUN apt-get update
|
||||
# Runtime
|
||||
RUN apt-get install -y libssl1.1
|
||||
RUN apt-get install -y ca-certificates
|
||||
RUN ["update-ca-certificates"]
|
||||
|
||||
|
@ -8,7 +8,7 @@ RUN yum install -y openssl-devel
|
||||
RUN yum install -y 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 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
|
||||
|
||||
ARG CMAKE_BIN_PATH=/tmp/cmake/cmake-3.14.0-Linux-x86_64/bin
|
||||
@ -16,7 +16,6 @@ ENV PATH="${CMAKE_BIN_PATH}:${PATH}"
|
||||
|
||||
RUN yum install -y python
|
||||
RUN yum install -y libtsan
|
||||
RUN yum install -y zlib-devel
|
||||
|
||||
COPY . .
|
||||
# RUN ["make", "test"]
|
||||
@ -27,7 +26,7 @@ FROM fedora:30 as runtime
|
||||
|
||||
RUN yum install -y libtsan
|
||||
|
||||
RUN groupadd app && useradd -g app app
|
||||
RUN groupadd app && useradd -g app app
|
||||
COPY --chown=app:app --from=build /usr/local/bin/ws /usr/local/bin/ws
|
||||
RUN chmod +x /usr/local/bin/ws
|
||||
RUN ldd /usr/local/bin/ws
|
||||
|
@ -1,23 +0,0 @@
|
||||
# Build time
|
||||
FROM ubuntu:bionic 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", "ws"]
|
@ -1,24 +0,0 @@
|
||||
# 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"]
|
||||
CMD ["sh"]
|
@ -2,14 +2,14 @@
|
||||
FROM ubuntu:xenial as build
|
||||
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt-get update
|
||||
RUN apt-get -y install wget
|
||||
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 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 g++
|
||||
RUN apt-get -y install libssl-dev
|
||||
RUN apt-get -y install libz-dev
|
||||
RUN apt-get -y install make
|
||||
|
@ -1,759 +0,0 @@
|
||||
# Changelog
|
||||
All changes to this project will be documented in this file.
|
||||
|
||||
## [9.6.1] - 2020-05-17
|
||||
|
||||
(windows + tls) mbedtls is the default windows tls backend + add ability to load system certificates with mbdetls on windows
|
||||
|
||||
## [9.6.0] - 2020-05-12
|
||||
|
||||
(ixbots) add options to limit how many messages per minute should be processed
|
||||
|
||||
## [9.5.9] - 2020-05-12
|
||||
|
||||
(ixbots) add new class to configure a bot to simplify passing options around
|
||||
|
||||
## [9.5.8] - 2020-05-08
|
||||
|
||||
(openssl tls) (openssl < 1.1) logic inversion - crypto locking callback are not registered properly
|
||||
|
||||
## [9.5.7] - 2020-05-08
|
||||
|
||||
(cmake) default TLS back to mbedtls on Windows Universal Platform
|
||||
|
||||
## [9.5.6] - 2020-05-06
|
||||
|
||||
(cobra bots) add a --heartbeat_timeout option to specify when the bot should terminate because no events are received
|
||||
|
||||
## [9.5.5] - 2020-05-06
|
||||
|
||||
(openssl tls) when OpenSSL is older than 1.1, register the crypto locking callback to be thread safe. Should fix lots of CI failures
|
||||
|
||||
## [9.5.4] - 2020-05-04
|
||||
|
||||
(cobra bots) do not use a queue to store messages pending processing, let the bot handle queuing
|
||||
|
||||
## [9.5.3] - 2020-04-29
|
||||
|
||||
(http client) better current request cancellation support when the HttpClient destructor is invoked (see #189)
|
||||
|
||||
## [9.5.2] - 2020-04-27
|
||||
|
||||
(cmake) fix cmake broken tls option parsing
|
||||
|
||||
## [9.5.1] - 2020-04-27
|
||||
|
||||
(http client) Set default values for most HttpRequestArgs struct members (fix #185)
|
||||
|
||||
## [9.5.0] - 2020-04-25
|
||||
|
||||
(ssl) Default to OpenSSL on Windows, since it can load the system certificates by default
|
||||
|
||||
## [9.4.1] - 2020-04-25
|
||||
|
||||
(header) Add a space between header name and header value since most http parsers expects it, although it it not required. Cf #184 and #155
|
||||
|
||||
## [9.4.0] - 2020-04-24
|
||||
|
||||
(ssl) Add support for supplying SSL CA from memory, for OpenSSL and MbedTLS backends
|
||||
|
||||
## [9.3.3] - 2020-04-17
|
||||
|
||||
(ixbots) display sent/receive message, per seconds as accumulated
|
||||
|
||||
## [9.3.2] - 2020-04-17
|
||||
|
||||
(ws) add a --logfile option to configure all logs to go to a file
|
||||
|
||||
## [9.3.1] - 2020-04-16
|
||||
|
||||
(cobra bots) add a utility class to factor out the common bots features (heartbeat) and move all bots to used it + convert cobra_subscribe to be a bot and add a unittest for it
|
||||
|
||||
## [9.3.0] - 2020-04-15
|
||||
|
||||
(websocket) add a positive number to the heartbeat message sent, incremented each time the heartbeat is sent
|
||||
|
||||
## [9.2.9] - 2020-04-15
|
||||
|
||||
(ixcobra) change cobra event callback to use a struct instead of several objects, which is more flexible/extensible
|
||||
|
||||
## [9.2.8] - 2020-04-15
|
||||
|
||||
(ixcobra) make CobraConnection_EventType an enum class (CobraEventType)
|
||||
|
||||
## [9.2.7] - 2020-04-14
|
||||
|
||||
(ixsentry) add a library method to upload a payload directly to sentry
|
||||
|
||||
## [9.2.6] - 2020-04-14
|
||||
|
||||
(ixcobra) snake server / handle invalid incoming json messages + cobra subscriber in fluentd mode insert a created_at timestamp entry
|
||||
|
||||
## [9.2.5] - 2020-04-13
|
||||
|
||||
(websocket) WebSocketMessagePtr is a unique_ptr instead of a shared_ptr
|
||||
|
||||
## [9.2.4] - 2020-04-13
|
||||
|
||||
(websocket) use persistent member variable as temp variables to encode/decode zlib messages in order to reduce transient allocations
|
||||
|
||||
## [9.2.3] - 2020-04-13
|
||||
|
||||
(ws) add a --runtime option to ws cobra_subscribe to optionally limit how much time it will run
|
||||
|
||||
## [9.2.2] - 2020-04-04
|
||||
|
||||
(third_party deps) fix #177, update bundled spdlog to 1.6.0
|
||||
|
||||
## [9.2.1] - 2020-04-04
|
||||
|
||||
(windows) when using OpenSSL, the system store is used to populate the cacert. No need to ship a cacert.pem file with your app.
|
||||
|
||||
## [9.2.0] - 2020-04-04
|
||||
|
||||
(windows) ci: windows build with TLS (mbedtls) + verify that we can be build with OpenSSL
|
||||
|
||||
## [9.1.9] - 2020-03-30
|
||||
|
||||
(cobra to statsd bot) add ability to extract a numerical value and send a timer event to statsd, with the --timer option
|
||||
|
||||
## [9.1.8] - 2020-03-29
|
||||
|
||||
(cobra to statsd bot) bot init was missing + capture socket error
|
||||
|
||||
## [9.1.7] - 2020-03-29
|
||||
|
||||
(cobra to statsd bot) add ability to extract a numerical value and send a gauge event to statsd, with the --gauge option
|
||||
|
||||
## [9.1.6] - 2020-03-29
|
||||
|
||||
(ws cobra subscriber) use a Json::StreamWriter to write to std::cout, and save one std::string allocation for each message printed
|
||||
|
||||
## [9.1.5] - 2020-03-29
|
||||
|
||||
(docker) trim down docker image (300M -> 12M) / binary built without symbol and size optimization, and source code not copied over
|
||||
|
||||
## [9.1.4] - 2020-03-28
|
||||
|
||||
(jsoncpp) update bundled copy to version 1.9.3 (at sha 3beb37ea14aec1bdce1a6d542dc464d00f4a6cec)
|
||||
|
||||
## [9.1.3] - 2020-03-27
|
||||
|
||||
(docker) alpine docker build with release with debug info, and bundle ca-certificates
|
||||
|
||||
## [9.1.2] - 2020-03-26
|
||||
|
||||
(mac ssl) rename DarwinSSL -> SecureTransport (see this too -> https://github.com/curl/curl/issues/3733)
|
||||
|
||||
## [9.1.1] - 2020-03-26
|
||||
|
||||
(websocket) fix data race accessing _socket object without mutex protection when calling wakeUpFromPoll in WebSocketTransport.cpp
|
||||
|
||||
## [9.1.0] - 2020-03-26
|
||||
|
||||
(ixcobra) add explicit event types for handshake, authentication and subscription failure, and handle those by exiting in ws_cobra_subcribe and friends
|
||||
|
||||
## [9.0.3] - 2020-03-24
|
||||
|
||||
(ws connect) display statistics about how much time it takes to stop the connection
|
||||
|
||||
## [9.0.2] - 2020-03-24
|
||||
|
||||
(socket) works with unique_ptr<Socket> instead of shared_ptr<Socket> in many places
|
||||
|
||||
## [9.0.1] - 2020-03-24
|
||||
|
||||
(socket) selectInterrupt member is an unique_ptr instead of being a shared_ptr
|
||||
|
||||
## [9.0.0] - 2020-03-23
|
||||
|
||||
(websocket) reset per-message deflate codec everytime we connect to a server/client
|
||||
|
||||
## [8.3.4] - 2020-03-23
|
||||
|
||||
(websocket) fix #167, a long standing issue with sending empty messages with per-message deflate extension (and hopefully other zlib bug)
|
||||
|
||||
## [8.3.3] - 2020-03-22
|
||||
|
||||
(cobra to statsd) port to windows and add a unittest
|
||||
|
||||
## [8.3.2] - 2020-03-20
|
||||
|
||||
(websocket+tls) fix hang in tls handshake which could lead to ANR, discovered through unittesting.
|
||||
|
||||
## [8.3.1] - 2020-03-20
|
||||
|
||||
(cobra) CobraMetricsPublisher can be configure with an ix::CobraConfig + more unittest use SSL in server + client
|
||||
|
||||
## [8.3.0] - 2020-03-18
|
||||
|
||||
(websocket) Simplify ping/pong based heartbeat implementation
|
||||
|
||||
## [8.2.7] - 2020-03-17
|
||||
|
||||
(ws) ws connect gains a new option to set the interval at which to send pings
|
||||
(ws) ws echo_server gains a new option (-p) to disable responding to pings with pongs
|
||||
|
||||
```
|
||||
IXWebSocket$ ws connect --ping_interval 2 wss://echo.websocket.org
|
||||
Type Ctrl-D to exit prompt...
|
||||
Connecting to url: wss://echo.websocket.org
|
||||
> ws_connect: connected
|
||||
[2020-03-17 23:53:02.726] [info] Uri: /
|
||||
[2020-03-17 23:53:02.726] [info] Headers:
|
||||
[2020-03-17 23:53:02.727] [info] Connection: Upgrade
|
||||
[2020-03-17 23:53:02.727] [info] Date: Wed, 18 Mar 2020 06:45:05 GMT
|
||||
[2020-03-17 23:53:02.727] [info] Sec-WebSocket-Accept: 0gtqbxW0aVL/QI/ICpLFnRaiKgA=
|
||||
[2020-03-17 23:53:02.727] [info] sec-websocket-extensions:
|
||||
[2020-03-17 23:53:02.727] [info] Server: Kaazing Gateway
|
||||
[2020-03-17 23:53:02.727] [info] Upgrade: websocket
|
||||
[2020-03-17 23:53:04.894] [info] Received pong
|
||||
[2020-03-17 23:53:06.859] [info] Received pong
|
||||
[2020-03-17 23:53:08.881] [info] Received pong
|
||||
[2020-03-17 23:53:10.848] [info] Received pong
|
||||
[2020-03-17 23:53:12.898] [info] Received pong
|
||||
[2020-03-17 23:53:14.865] [info] Received pong
|
||||
[2020-03-17 23:53:16.890] [info] Received pong
|
||||
[2020-03-17 23:53:18.853] [info] Received pong
|
||||
|
||||
[2020-03-17 23:53:19.388] [info]
|
||||
ws_connect: connection closed: code 1000 reason Normal closure
|
||||
|
||||
[2020-03-17 23:53:19.502] [info] Received 208 bytes
|
||||
[2020-03-17 23:53:19.502] [info] Sent 0 bytes
|
||||
```
|
||||
|
||||
## [8.2.6] - 2020-03-16
|
||||
|
||||
(cobra to sentry bot + docker) default docker file uses mbedtls + ws cobra_to_sentry pass tls options to sentryClient.
|
||||
|
||||
## [8.2.5] - 2020-03-13
|
||||
|
||||
(cobra client) ws cobra subscribe resubscribe at latest position after being disconnected
|
||||
|
||||
## [8.2.4] - 2020-03-13
|
||||
|
||||
(cobra client) can subscribe with a position
|
||||
|
||||
## [8.2.3] - 2020-03-13
|
||||
|
||||
(cobra client) pass the message position to the subscription data callback
|
||||
|
||||
## [8.2.2] - 2020-03-12
|
||||
|
||||
(openssl tls backend) Fix a hand in OpenSSL when using TLS v1.3 ... by disabling TLS v1.3
|
||||
|
||||
## [8.2.1] - 2020-03-11
|
||||
|
||||
(cobra) IXCobraConfig struct has tlsOptions and per message deflate options
|
||||
|
||||
## [8.2.0] - 2020-03-11
|
||||
|
||||
(cobra) add IXCobraConfig struct to pass cobra config around
|
||||
|
||||
## [8.1.9] - 2020-03-09
|
||||
|
||||
(ws cobra_subscribe) add a --fluentd option to wrap a message in an enveloppe so that fluentd can recognize it
|
||||
|
||||
## [8.1.8] - 2020-03-02
|
||||
|
||||
(websocket server) fix regression with disabling zlib extension on the server side. If a client does not support this extension the server will handle it fine. We still need to figure out how to disable the option.
|
||||
|
||||
## [8.1.7] - 2020-02-26
|
||||
|
||||
(websocket) traffic tracker received bytes is message size while it should be wire size
|
||||
|
||||
## [8.1.6] - 2020-02-26
|
||||
|
||||
(ws_connect) display sent/received bytes statistics on exit
|
||||
|
||||
## [8.1.5] - 2020-02-23
|
||||
|
||||
(server) give thread name to some usual worker threads / unittest is broken !!
|
||||
|
||||
## [8.1.4] - 2020-02-22
|
||||
|
||||
(websocket server) fix regression from 8.1.2, where per-deflate message compression was always disabled
|
||||
|
||||
## [8.1.3] - 2020-02-21
|
||||
|
||||
(client + server) Fix #155 / http header parser should treat the space(s) after the : delimiter as optional. Fixing this bug made us discover that websocket sub-protocols are not properly serialiazed, but start with a ,
|
||||
|
||||
## [8.1.2] - 2020-02-18
|
||||
|
||||
(WebSocketServer) add option to disable deflate compression, exposed with the -x option to ws echo_server
|
||||
|
||||
## [8.1.1] - 2020-02-18
|
||||
|
||||
(ws cobra to statsd and sentry sender) exit if no messages are received for one minute, which is a sign that something goes wrong on the server side. That should be changed to be configurable in the future
|
||||
|
||||
## [8.1.0] - 2020-02-13
|
||||
|
||||
(http client + sentry minidump upload) Multipart stream closing boundary is invalid + mark some options as mandatory in the command line tools
|
||||
|
||||
## [8.0.7] - 2020-02-12
|
||||
|
||||
(build) remove the unused subtree which was causing some way of installing to break
|
||||
|
||||
## [8.0.6] - 2020-01-31
|
||||
|
||||
(snake) add an option to disable answering pongs as response to pings, to test cobra client behavior with hanged connections
|
||||
|
||||
## [8.0.5] - 2020-01-31
|
||||
|
||||
(IXCobraConnection) set a ping timeout of 90 seconds. If no pong messages are received as responses to ping for a while, give up and close the connection
|
||||
|
||||
## [8.0.4] - 2020-01-31
|
||||
|
||||
(cobra to sentry) remove noisy logging
|
||||
|
||||
## [8.0.3] - 2020-01-30
|
||||
|
||||
(ixcobra) check if we are authenticated in publishNext before trying to publish a message
|
||||
|
||||
## [8.0.2] - 2020-01-28
|
||||
|
||||
Extract severity level when emitting messages to sentry
|
||||
|
||||
## [8.0.1] - 2020-01-28
|
||||
|
||||
Fix bug #151 - If a socket connection is interrupted, calling stop() on the IXWebSocket object blocks until the next retry
|
||||
|
||||
## [8.0.0] - 2020-01-26
|
||||
|
||||
(SocketServer) add ability to bind on an ipv6 address
|
||||
|
||||
## [7.9.6] - 2020-01-22
|
||||
|
||||
(ws) add a dnslookup sub-command, to get the ip address of a remote host
|
||||
|
||||
## [7.9.5] - 2020-01-14
|
||||
|
||||
(windows) fix #144, get rid of stubbed/un-implemented windows schannel ssl backend
|
||||
|
||||
## [7.9.4] - 2020-01-12
|
||||
|
||||
(openssl + mbedssl) fix #140, can send large files with ws send over ssl / still broken with apple ssl
|
||||
|
||||
## [7.9.3] - 2020-01-10
|
||||
|
||||
(apple ssl) model write method after the OpenSSL one for consistency
|
||||
|
||||
## [7.9.2] - 2020-01-06
|
||||
|
||||
(apple ssl) unify read and write ssl utility code
|
||||
|
||||
## [7.9.1] - 2020-01-06
|
||||
|
||||
(websocket client) better error propagation when errors are detected while sending data
|
||||
(ws send) detect failures to send big files, terminate in those cases and report error
|
||||
|
||||
## [7.9.0] - 2020-01-04
|
||||
|
||||
(ws send) add option (-x) to disable per message deflate compression
|
||||
|
||||
## [7.8.9] - 2020-01-04
|
||||
|
||||
(ws send + receive) handle all message types (ping + pong + fragment) / investigate #140
|
||||
|
||||
## [7.8.8] - 2019-12-28
|
||||
|
||||
(mbedtls) fix related to private key file parsing and initialization
|
||||
|
||||
## [7.8.6] - 2019-12-28
|
||||
|
||||
(ws cobra to sentry/statsd) fix for handling null events properly for empty queues + use queue to send data to statsd
|
||||
|
||||
## [7.8.5] - 2019-12-28
|
||||
|
||||
(ws cobra to sentry) handle null events for empty queues
|
||||
|
||||
## [7.8.4] - 2019-12-27
|
||||
|
||||
(ws cobra to sentry) game is picked in a fair manner, so that all games get the same share of sent events
|
||||
|
||||
## [7.8.3] - 2019-12-27
|
||||
|
||||
(ws cobra to sentry) refactor queue related code into a class
|
||||
|
||||
## [7.8.2] - 2019-12-25
|
||||
|
||||
(ws cobra to sentry) bound the queue size used to hold up cobra messages before they are sent to sentry. Default queue size is a 100 messages. Without such limit the program runs out of memory when a subscriber receive a lot of messages that cannot make it to sentry
|
||||
|
||||
## [7.8.1] - 2019-12-25
|
||||
|
||||
(ws client) use correct compilation defines so that spdlog is not used as a header only library (reduce binary size and increase compilation speed)
|
||||
|
||||
## [7.8.0] - 2019-12-24
|
||||
|
||||
(ws client) all commands use spdlog instead of std::cerr or std::cout for logging
|
||||
|
||||
## [7.6.5] - 2019-12-24
|
||||
|
||||
(cobra client) send a websocket ping every 30s to keep the connection opened
|
||||
|
||||
## [7.6.4] - 2019-12-22
|
||||
|
||||
(client) error handling, quote url in error case when failing to parse one
|
||||
(ws) ws_cobra_publish: register callbacks before connecting
|
||||
(doc) mention mbedtls in supported ssl server backend
|
||||
|
||||
## [7.6.3] - 2019-12-20
|
||||
|
||||
(tls) add a simple description of the TLS configuration routine for debugging
|
||||
|
||||
## [7.6.2] - 2019-12-20
|
||||
|
||||
(mbedtls) correct support for using own certificate and private key
|
||||
|
||||
## [7.6.1] - 2019-12-20
|
||||
|
||||
(ws commands) in websocket proxy, disable automatic reconnections + in Dockerfile, use alpine 3.11
|
||||
|
||||
## [7.6.0] - 2019-12-19
|
||||
|
||||
(cobra) Add TLS options to all cobra commands and classes. Add example to the doc.
|
||||
|
||||
## [7.5.8] - 2019-12-18
|
||||
|
||||
(cobra-to-sentry) capture application version from device field
|
||||
|
||||
## [7.5.7] - 2019-12-18
|
||||
|
||||
(tls) Experimental TLS server support with mbedtls (windows) + process cert tlsoption (client + server)
|
||||
|
||||
## [7.5.6] - 2019-12-18
|
||||
|
||||
(tls servers) Make it clear that apple ssl and mbedtls backends do not support SSL in server mode
|
||||
|
||||
## [7.5.5] - 2019-12-17
|
||||
|
||||
(tls options client) TLSOptions struct _validated member should be initialized to false
|
||||
|
||||
## [7.5.4] - 2019-12-16
|
||||
|
||||
(websocket client) improve the error message when connecting to a non websocket server
|
||||
|
||||
Before:
|
||||
|
||||
```
|
||||
Connection error: Got bad status connecting to example.com:443, status: 200, HTTP Status line: HTTP/1.1 200 OK
|
||||
```
|
||||
|
||||
After:
|
||||
|
||||
```
|
||||
Connection error: Expecting status 101 (Switching Protocol), got 200 status connecting to example.com:443, HTTP Status line: HTTP/1.1 200 OK
|
||||
```
|
||||
|
||||
## [7.5.3] - 2019-12-12
|
||||
|
||||
(server) attempt at fixing #131 by using blocking writes in server mode
|
||||
|
||||
## [7.5.2] - 2019-12-11
|
||||
|
||||
(ws) cobra to sentry - created events with sentry tags based on tags present in the cobra messages
|
||||
|
||||
## [7.5.1] - 2019-12-06
|
||||
|
||||
(mac) convert SSL errors to utf8
|
||||
|
||||
## [7.5.0] - 2019-12-05
|
||||
|
||||
- (ws) cobra to sentry. Handle Error 429 Too Many Requests and politely wait before sending more data to sentry.
|
||||
|
||||
In the example below sentry we are sending data too fast, sentry asks us to slow down which we do. Notice how the sent count stop increasing, while we are waiting for 41 seconds.
|
||||
|
||||
```
|
||||
[2019-12-05 15:50:33.759] [info] messages received 2449 sent 3
|
||||
[2019-12-05 15:50:34.759] [info] messages received 5533 sent 7
|
||||
[2019-12-05 15:50:35.759] [info] messages received 8612 sent 11
|
||||
[2019-12-05 15:50:36.759] [info] messages received 11562 sent 15
|
||||
[2019-12-05 15:50:37.759] [info] messages received 14410 sent 19
|
||||
[2019-12-05 15:50:38.759] [info] messages received 17236 sent 23
|
||||
[2019-12-05 15:50:39.282] [error] Error sending data to sentry: 429
|
||||
[2019-12-05 15:50:39.282] [error] Body: {"exception":[{"stacktrace":{"frames":[{"filename":"WorldScene.lua","function":"WorldScene.lua:1935","lineno":1958},{"filename":"WorldScene.lua","function":"onUpdate_WorldCam","lineno":1921},{"filename":"WorldMapTile.lua","function":"__index","lineno":239}]},"value":"noisytypes: Attempt to call nil(nil,2224139838)!"}],"platform":"python","sdk":{"name":"ws","version":"1.0.0"},"tags":[["game","niso"],["userid","107638363"],["environment","live"]],"timestamp":"2019-12-05T23:50:39Z"}
|
||||
|
||||
[2019-12-05 15:50:39.282] [error] Response: {"error_name":"rate_limit","error":"Creation of this event was denied due to rate limiting"}
|
||||
[2019-12-05 15:50:39.282] [warning] Error 429 - Too Many Requests. ws will sleep and retry after 41 seconds
|
||||
[2019-12-05 15:50:39.760] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:40.760] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:41.760] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:42.761] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:43.762] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:44.763] [info] messages received 18839 sent 25
|
||||
[2019-12-05 15:50:45.768] [info] messages received 18839 sent 25
|
||||
```
|
||||
|
||||
## [7.4.5] - 2019-12-03
|
||||
|
||||
- (ws) #125 / fix build problem when jsoncpp is not installed locally
|
||||
|
||||
## [7.4.4] - 2019-12-03
|
||||
|
||||
- (ws) #125 / cmake detects an already installed jsoncpp and will try to use this one if present
|
||||
|
||||
## [7.4.3] - 2019-12-03
|
||||
|
||||
- (http client) use std::unordered_map instead of std::map for HttpParameters and HttpFormDataParameters class aliases
|
||||
|
||||
## [7.4.2] - 2019-12-02
|
||||
|
||||
- (client) internal IXDNSLookup class requires a valid cancellation request function callback to be passed in
|
||||
|
||||
## [7.4.1] - 2019-12-02
|
||||
|
||||
- (client) fix an overflow in the exponential back off code
|
||||
|
||||
## [7.4.0] - 2019-11-25
|
||||
|
||||
- (http client) Add support for multipart HTTP POST upload
|
||||
- (ixsentry) Add support for uploading a minidump to sentry
|
||||
|
||||
## [7.3.5] - 2019-11-20
|
||||
|
||||
- On Darwin SSL, add ability to skip peer verification.
|
||||
|
||||
## [7.3.4] - 2019-11-20
|
||||
|
||||
- 32-bits compile fix, courtesy of @fcojavmc
|
||||
|
||||
## [7.3.1] - 2019-11-16
|
||||
|
||||
- ws proxy_server / remote server close not forwarded to the client
|
||||
|
||||
## [7.3.0] - 2019-11-15
|
||||
|
||||
- New ws command: `ws proxy_server`.
|
||||
|
||||
## [7.2.2] - 2019-11-01
|
||||
|
||||
- Tag a release + minor reformating.
|
||||
|
||||
## [7.2.1] - 2019-10-26
|
||||
|
||||
- Add unittest to IXSentryClient to lua backtrace parsing code
|
||||
|
||||
## [7.2.0] - 2019-10-24
|
||||
|
||||
- Add cobra_metrics_to_redis sub-command to create streams for each cobra metric event being received.
|
||||
|
||||
## [7.1.0] - 2019-10-13
|
||||
|
||||
- Add client support for websocket subprotocol. Look for the new addSubProtocol method for details.
|
||||
|
||||
## [7.0.0] - 2019-10-01
|
||||
|
||||
- TLS support in server code, only implemented for the OpenSSL SSL backend for now.
|
||||
|
||||
## [6.3.4] - 2019-09-30
|
||||
|
||||
- all ws subcommands propagate tls options to servers (unimplemented) or ws or http client (implemented) (contributed by Matt DeBoer)
|
||||
|
||||
## [6.3.3] - 2019-09-30
|
||||
|
||||
- ws has a --version option
|
||||
|
||||
## [6.3.2] - 2019-09-29
|
||||
|
||||
- (http + websocket clients) can specify cacert and some other tls options (not implemented on all backend). This makes it so that server certs can finally be validated on windows.
|
||||
|
||||
## [6.3.1] - 2019-09-29
|
||||
|
||||
- Add ability to use OpenSSL on apple platforms.
|
||||
|
||||
## [6.3.0] - 2019-09-28
|
||||
|
||||
- ixcobra / fix crash in CobraConnection::publishNext when the queue is empty + handle CobraConnection_PublishMode_Batch in CobraMetricsThreadedPublisher
|
||||
|
||||
## [6.2.9] - 2019-09-27
|
||||
|
||||
- mbedtls fixes / the unittest now pass on macOS, and hopefully will on Windows/AppVeyor as well.
|
||||
|
||||
## [6.2.8] - 2019-09-26
|
||||
|
||||
- Http server: add options to ws https to redirect all requests to a given url. POST requests will get a 200 and an empty response.
|
||||
|
||||
```
|
||||
ws httpd -L --redirect_url https://www.google.com
|
||||
```
|
||||
|
||||
## [6.2.7] - 2019-09-25
|
||||
|
||||
- Stop having ws send subcommand send a binary message in text mode, which would cause error in `make ws_test` shell script test.
|
||||
|
||||
## [6.2.6] - 2019-09-24
|
||||
|
||||
- Fix 2 race conditions detected with TSan, one in CobraMetricsPublisher::push and another one in WebSocketTransport::sendData (that one was bad).
|
||||
|
||||
## [6.2.5] - 2019-09-23
|
||||
|
||||
- Add simple Redis Server which is only capable of doing publish / subscribe. New ws redis_server sub-command to use it. The server is used in the unittest, so that we can run on CI in environment where redis isn not available like github actions env.
|
||||
|
||||
## [6.2.4] - 2019-09-22
|
||||
|
||||
- Add options to configure TLS ; contributed by Matt DeBoer. Only implemented for OpenSSL TLS backend for now.
|
||||
|
||||
## [6.2.3] - 2019-09-21
|
||||
|
||||
- Fix crash in the Linux unittest in the HTTP client code, in Socket::readBytes
|
||||
- Cobra Metrics Publisher code returns the message id of the message that got published, to be used to validated that it got sent properly when receiving an ack.
|
||||
|
||||
## [6.2.2] - 2019-09-19
|
||||
|
||||
- In DNS lookup code, make sure the weak pointer we use lives through the expected scope (if branch)
|
||||
|
||||
## [6.2.1] - 2019-09-17
|
||||
|
||||
- On error while doing a client handshake, additionally display port number next to the host name
|
||||
|
||||
## [6.2.0] - 2019-09-09
|
||||
|
||||
- websocket and http server: server does not close the bound client socket in many cases
|
||||
- improve some websocket error messages
|
||||
- add a utility function with unittest to parse status line and stop using scanf which triggers warnings on Windows
|
||||
- update ws CLI11 (our command line argument parsing library) to the latest, which fix a compiler bug about optional
|
||||
|
||||
## [6.1.0] - 2019-09-08
|
||||
|
||||
- move poll wrapper on top of select (only used on Windows) to the ix namespace
|
||||
|
||||
## [6.0.1] - 2019-09-05
|
||||
|
||||
- add cobra metrics publisher + server unittest
|
||||
- add cobra client + server unittest
|
||||
- ws snake (cobra simple server) add basic support for unsubscription + subscribe send the proper subscription data + redis client subscription can be cancelled
|
||||
- IXCobraConnection / pdu handlers can crash if they receive json data which is not an object
|
||||
|
||||
## [6.0.0] - 2019-09-04
|
||||
|
||||
- all client autobahn test should pass !
|
||||
- zlib/deflate has a bug with windowsbits == 8, so we silently upgrade it to 9/ (fix autobahn test 13.X which uses 8 for the windows size)
|
||||
|
||||
## [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
|
@ -1,78 +0,0 @@
|
||||
## 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_OPEN_SSL=1` will use [openssl](https://www.openssl.org/) for the TLS support (default on Linux and Windows)
|
||||
* `-DUSE_MBED_TLS=1` will use [mbedlts](https://tls.mbed.org/) for the TLS support
|
||||
* `-DUSE_WS=1` will build the ws interactive command line tool
|
||||
* `-DUSE_TEST=1` will build the unittest
|
||||
|
||||
If you are on Windows, look at the [appveyor](https://github.com/machinezone/IXWebSocket/blob/master/appveyor.yml) file (not maintained much though) or rather the [github actions](https://github.com/machinezone/IXWebSocket/blob/master/.github/workflows/ccpp.yml#L40) which have instructions for building dependencies.
|
||||
|
||||
It is also possible to externally include the project, so that everything is fetched over the wire when you build like so:
|
||||
|
||||
```
|
||||
ExternalProject_Add(
|
||||
IXWebSocket
|
||||
GIT_REPOSITORY https://github.com/machinezone/IXWebSocket.git
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### vcpkg
|
||||
|
||||
It is possible to get IXWebSocket through Microsoft [vcpkg](https://github.com/microsoft/vcpkg).
|
||||
|
||||
```
|
||||
vcpkg install ixwebsocket
|
||||
```
|
||||
|
||||
### Conan
|
||||
|
||||
[  ](https://bintray.com/conan/conan-center/ixwebsocket%3A_/_latestVersion)
|
||||
|
||||
Conan is currently supported through a recipe in [Conan Center](https://github.com/conan-io/conan-center-index/tree/master/recipes/ixwebsocket) ([Bintray entry](https://bintray.com/conan/conan-center/ixwebsocket%3A_)).
|
||||
|
||||
Package reference
|
||||
|
||||
* Conan 1.21.0 and up: `ixwebsocket/7.9.2`
|
||||
* Earlier versions: `ixwebsocket/7.9.2@_/_`
|
||||
|
||||
Note that the version listed here might not be the latest one. See Bintray or the recipe itself for the latest version. If you're migrating from the previous, custom Bintray remote, note that the package reference _has_ to be lower-case.
|
||||
|
||||
### Docker
|
||||
|
||||
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 docker.pkg.github.com/machinezone/ixwebsocket/ws:latest --help
|
||||
```
|
||||
|
||||
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
|
||||
...
|
||||
```
|
@ -1,81 +0,0 @@
|
||||
## General
|
||||
|
||||
[cobra](https://github.com/machinezone/cobra) is a real time messaging server. The `ws` utility can run a cobra server (named snake), and has client to publish and subscribe to a cobra server.
|
||||
|
||||
Bring up 3 terminals and run a server, a publisher and a subscriber in each one. As you publish data you should see it being received by the subscriber. You can run `redis-cli MONITOR` too to see how redis is being used.
|
||||
|
||||
### Server
|
||||
|
||||
You will need to have a redis server running locally. To run the server:
|
||||
|
||||
```bash
|
||||
$ cd <ixwebsocket-top-level-folder>/ixsnake/ixsnake
|
||||
$ ws snake
|
||||
{
|
||||
"apps": {
|
||||
"FC2F10139A2BAc53BB72D9db967b024f": {
|
||||
"roles": {
|
||||
"_sub": {
|
||||
"secret": "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba"
|
||||
},
|
||||
"_pub": {
|
||||
"secret": "1c04DB8fFe76A4EeFE3E318C72d771db"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redis host: 127.0.0.1
|
||||
redis password:
|
||||
redis port: 6379
|
||||
```
|
||||
|
||||
### Publisher
|
||||
|
||||
```bash
|
||||
$ cd <ixwebsocket-top-level-folder>/ws
|
||||
$ ws cobra_publish --appkey FC2F10139A2BAc53BB72D9db967b024f --endpoint ws://127.0.0.1:8008 --rolename _pub --rolesecret 1c04DB8fFe76A4EeFE3E318C72d771db test_channel cobraMetricsSample.json
|
||||
[2019-11-27 09:06:12.980] [info] Publisher connected
|
||||
[2019-11-27 09:06:12.980] [info] Connection: Upgrade
|
||||
[2019-11-27 09:06:12.980] [info] Sec-WebSocket-Accept: zTtQKMKbvwjdivURplYXwCVUCWM=
|
||||
[2019-11-27 09:06:12.980] [info] Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
[2019-11-27 09:06:12.980] [info] Server: ixwebsocket/7.4.0 macos ssl/DarwinSSL zlib 1.2.11
|
||||
[2019-11-27 09:06:12.980] [info] Upgrade: websocket
|
||||
[2019-11-27 09:06:12.982] [info] Publisher authenticated
|
||||
[2019-11-27 09:06:12.982] [info] Published msg 3
|
||||
[2019-11-27 09:06:12.982] [info] Published message id 3 acked
|
||||
```
|
||||
|
||||
### Subscriber
|
||||
|
||||
```bash
|
||||
$ ws cobra_subscribe --appkey FC2F10139A2BAc53BB72D9db967b024f --endpoint ws://127.0.0.1:8008 --rolename _pub --rolesecret 1c04DB8fFe76A4EeFE3E318C72d771db test_channel
|
||||
#messages 0 msg/s 0
|
||||
[2019-11-27 09:07:39.341] [info] Subscriber connected
|
||||
[2019-11-27 09:07:39.341] [info] Connection: Upgrade
|
||||
[2019-11-27 09:07:39.341] [info] Sec-WebSocket-Accept: 9vkQWofz49qMCUlTSptCCwHWm+Q=
|
||||
[2019-11-27 09:07:39.341] [info] Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
[2019-11-27 09:07:39.341] [info] Server: ixwebsocket/7.4.0 macos ssl/DarwinSSL zlib 1.2.11
|
||||
[2019-11-27 09:07:39.341] [info] Upgrade: websocket
|
||||
[2019-11-27 09:07:39.342] [info] Subscriber authenticated
|
||||
[2019-11-27 09:07:39.345] [info] Subscriber: subscribed to channel test_channel
|
||||
#messages 0 msg/s 0
|
||||
#messages 0 msg/s 0
|
||||
#messages 0 msg/s 0
|
||||
{"baz":123,"foo":"bar"}
|
||||
|
||||
#messages 1 msg/s 1
|
||||
#messages 1 msg/s 0
|
||||
#messages 1 msg/s 0
|
||||
{"baz":123,"foo":"bar"}
|
||||
|
||||
{"baz":123,"foo":"bar"}
|
||||
|
||||
#messages 3 msg/s 2
|
||||
#messages 3 msg/s 0
|
||||
{"baz":123,"foo":"bar"}
|
||||
|
||||
#messages 4 msg/s 1
|
||||
^C
|
||||
```
|
@ -1,82 +0,0 @@
|
||||
## 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 and mbedTLS can be used on Android, Linux and Windows.
|
||||
|
||||
If you are using OpenSSL, try to be on a version higher than 1.1.x as there there are thread safety problems with 1.0.x.
|
||||
|
||||
### 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 platforms, with different sanitizers such as a thread sanitizer to catch data races or the undefined behavior sanitizer.
|
||||
|
||||
The regression test is running after each commit on github actions for multiple configurations.
|
||||
|
||||
* Linux
|
||||
* macOS with thread sanitizer
|
||||
* macOS, with OpenSSL, with thread sanitizer
|
||||
* macOS, with MbedTLS, with thread sanitizer
|
||||
* Windows, with MbedTLS (the unittest is not run yet)
|
||||
|
||||
## Limitations
|
||||
|
||||
* On some configuration (mostly Android) certificate validation needs to be setup so that SocketTLSOptions.caFile point to a pem file, such as the one distributed by Firefox. Unless that setup is done connecting to a wss endpoint will display an error. With mbedtls the message will contain `error in handshake : X509 - Certificate verification failed, e.g. CRL, CA or signature check failed`.
|
||||
* 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.
|
||||
| |
|
||||
+-----------------------+
|
||||
```
|
@ -1,66 +0,0 @@
|
||||

|
||||
|
||||
## 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
|
||||
* FreeBSD
|
||||
|
||||
## Example code
|
||||
|
||||
```c++
|
||||
// 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. IXWebSocket comes with a command line utility named ws which is quite handy, and is now packaged with alpine linux. You can install it with `apk add ws`.
|
||||
|
||||
* Few dependencies (only zlib)
|
||||
* Simple to use ; uses std::string and std::function callbacks.
|
||||
* Complete support of the websocket protocol, and basic http support.
|
||||
* Client and Server
|
||||
* TLS support
|
||||
|
||||
## Alternative libraries
|
||||
|
||||
There are plenty of great websocket libraries out there, which might work for you. Here are a couple of serious ones.
|
||||
|
||||
* [websocketpp](https://github.com/zaphoyd/websocketpp) - C++
|
||||
* [beast](https://github.com/boostorg/beast) - C++
|
||||
* [libwebsockets](https://libwebsockets.org/) - C
|
||||
* [µWebSockets](https://github.com/uNetworking/uWebSockets) - C
|
||||
|
||||
## Contributing
|
||||
|
||||
IXWebSocket is developed on [GitHub](https://github.com/machinezone/IXWebSocket). We'd love to hear about how you use it; opening up an issue on GitHub is ok for that. If things don't work as expected, please create an issue on GitHub, or even better a pull request if you know how to fix your problem.
|
@ -1,94 +0,0 @@
|
||||
Notes on how we can update the different packages for ixwebsocket.
|
||||
|
||||
## VCPKG
|
||||
|
||||
Visit the [releases](https://github.com/machinezone/IXWebSocket/releases) page on Github. A tag must have been made first.
|
||||
|
||||
Download the latest entry.
|
||||
|
||||
```
|
||||
$ cd /tmp
|
||||
/tmp$ curl -s -O -L https://github.com/machinezone/IXWebSocket/archive/v9.1.9.tar.gz
|
||||
/tmp$
|
||||
/tmp$ openssl sha512 v9.1.9.tar.gz
|
||||
SHA512(v9.1.9.tar.gz)= f1fd731b5f6a9ce6d6d10bee22a5d9d9baaa8ea0564d6c4cd7eb91dcb88a45c49b2c7fdb75f8640a3589c1b30cee33ef5df8dcbb55920d013394d1e33ddd3c8e
|
||||
```
|
||||
|
||||
Now go punch those values in the vcpkg ixwebsocket port config files. Here is what the diff look like.
|
||||
|
||||
```
|
||||
vcpkg$ git diff
|
||||
diff --git a/ports/ixwebsocket/CONTROL b/ports/ixwebsocket/CONTROL
|
||||
index db9c2adc9..4acae5c3f 100644
|
||||
--- a/ports/ixwebsocket/CONTROL
|
||||
+++ b/ports/ixwebsocket/CONTROL
|
||||
@@ -1,5 +1,5 @@
|
||||
Source: ixwebsocket
|
||||
-Version: 8.0.5
|
||||
+Version: 9.1.9
|
||||
Build-Depends: zlib
|
||||
Homepage: https://github.com/machinezone/IXWebSocket
|
||||
Description: Lightweight WebSocket Client and Server + HTTP Client and Server
|
||||
diff --git a/ports/ixwebsocket/portfile.cmake b/ports/ixwebsocket/portfile.cmake
|
||||
index de082aece..68e523a05 100644
|
||||
--- a/ports/ixwebsocket/portfile.cmake
|
||||
+++ b/ports/ixwebsocket/portfile.cmake
|
||||
@@ -1,8 +1,8 @@
|
||||
vcpkg_from_github(
|
||||
OUT_SOURCE_PATH SOURCE_PATH
|
||||
REPO machinezone/IXWebSocket
|
||||
- REF v8.0.5
|
||||
- SHA512 9dcc20d9a0629b92c62a68a8bd7c8206f18dbd9e93289b0b687ec13c478ce9ad1f3563b38c399c8277b0d3812cc78ca725786ba1dedbc3445b9bdb9b689e8add
|
||||
+ REF v9.1.9
|
||||
+ SHA512 f1fd731b5f6a9ce6d6d10bee22a5d9d9baaa8ea0564d6c4cd7eb91dcb88a45c49b2c7fdb75f8640a3589c1b30cee33ef5df8dcbb55920d013394d1e33ddd3c8e
|
||||
)
|
||||
```
|
||||
|
||||
You will need a fork of the vcpkg repo to make a pull request.
|
||||
|
||||
```
|
||||
git fetch upstream
|
||||
git co master
|
||||
git reset --hard upstream/master
|
||||
git push origin master --force
|
||||
```
|
||||
|
||||
Make the pull request (I use a new branch to do that).
|
||||
|
||||
```
|
||||
vcpkg$ git co -b feature/ixwebsocket_9.1.9
|
||||
M ports/ixwebsocket/CONTROL
|
||||
M ports/ixwebsocket/portfile.cmake
|
||||
Switched to a new branch 'feature/ixwebsocket_9.1.9'
|
||||
vcpkg$
|
||||
vcpkg$
|
||||
vcpkg$ git commit -am 'ixwebsocket: update to 9.1.9'
|
||||
[feature/ixwebsocket_9.1.9 8587a4881] ixwebsocket: update to 9.1.9
|
||||
2 files changed, 3 insertions(+), 3 deletions(-)
|
||||
vcpkg$
|
||||
vcpkg$ git push
|
||||
fatal: The current branch feature/ixwebsocket_9.1.9 has no upstream branch.
|
||||
To push the current branch and set the remote as upstream, use
|
||||
|
||||
git push --set-upstream origin feature/ixwebsocket_9.1.9
|
||||
|
||||
vcpkg$ git push --set-upstream origin feature/ixwebsocket_9.1.9
|
||||
|
||||
Enumerating objects: 11, done.
|
||||
Counting objects: 100% (11/11), done.
|
||||
Delta compression using up to 8 threads
|
||||
Compressing objects: 100% (6/6), done.
|
||||
Writing objects: 100% (6/6), 621 bytes | 621.00 KiB/s, done.
|
||||
Total 6 (delta 4), reused 0 (delta 0)
|
||||
remote: Resolving deltas: 100% (4/4), completed with 4 local objects.
|
||||
remote:
|
||||
remote: Create a pull request for 'feature/ixwebsocket_9.1.9' on GitHub by visiting:
|
||||
remote: https://github.com/bsergean/vcpkg/pull/new/feature/ixwebsocket_9.1.9
|
||||
remote:
|
||||
To https://github.com/bsergean/vcpkg.git
|
||||
* [new branch] feature/ixwebsocket_9.1.9 -> feature/ixwebsocket_9.1.9
|
||||
Branch 'feature/ixwebsocket_9.1.9' set up to track remote branch 'feature/ixwebsocket_9.1.9' from 'origin' by rebasing.
|
||||
vcpkg$
|
||||
```
|
||||
|
||||
Just visit this url, https://github.com/bsergean/vcpkg/pull/new/feature/ixwebsocket_9.1.9, printed on the console, to make the pull request.
|
470
docs/usage.md
470
docs/usage.md
@ -1,470 +0,0 @@
|
||||
# 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.
|
||||
|
||||
```cpp
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
ix::initNetSystem();
|
||||
|
||||
...
|
||||
|
||||
ix::uninitNetSystem();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## WebSocket client API
|
||||
|
||||
```cpp
|
||||
#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.setPingInterval(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`.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
webSocket.setPingInterval(45);
|
||||
```
|
||||
|
||||
### Supply extra HTTP headers.
|
||||
|
||||
You can set extra HTTP headers to be sent during the WebSocket handshake.
|
||||
|
||||
```cpp
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["foo"] = "bar";
|
||||
webSocket.setExtraHeaders(headers);
|
||||
```
|
||||
|
||||
### Subprotocols
|
||||
|
||||
You can specify subprotocols to be set during the WebSocket handshake. For more info you can refer to [this doc](https://hpbn.co/websocket/#subprotocol-negotiation).
|
||||
|
||||
```cpp
|
||||
webSocket.addSubprotocol("appProtocol-v1");
|
||||
webSocket.addSubprotocol("appProtocol-v2");
|
||||
```
|
||||
|
||||
The protocol that the server did accept is available in the open info `protocol` field.
|
||||
|
||||
```cpp
|
||||
std::cout << "protocol: " << msg->openInfo.protocol << std::endl;
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```cpp
|
||||
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.
|
||||
|
||||
```cpp
|
||||
webSocket.setMaxWaitBetweenReconnectionRetries(5 * 1000); // 5000ms = 5s
|
||||
uint32_t m = webSocket.getMaxWaitBetweenReconnectionRetries();
|
||||
```
|
||||
|
||||
## WebSocket server API
|
||||
|
||||
```cpp
|
||||
#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
|
||||
|
||||
```cpp
|
||||
#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
|
||||
|
||||
```cpp
|
||||
#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.
|
||||
|
||||
```cpp
|
||||
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);
|
||||
}
|
||||
```
|
||||
|
||||
## TLS support and configuration
|
||||
|
||||
To leverage TLS features, the library must be compiled with the option `USE_TLS=1`.
|
||||
|
||||
If you are using OpenSSL, try to be on a version higher than 1.1.x as there there are thread safety problems with 1.0.x.
|
||||
|
||||
Then, secure sockets are automatically used when connecting to a `wss://*` url.
|
||||
|
||||
Additional TLS options can be configured by passing a `ix::SocketTLSOptions` instance to the
|
||||
`setTLSOptions` on `ix::WebSocket` (or `ix::WebSocketServer` or `ix::HttpServer`)
|
||||
|
||||
```cpp
|
||||
webSocket.setTLSOptions({
|
||||
.certFile = "path/to/cert/file.pem",
|
||||
.keyFile = "path/to/key/file.pem",
|
||||
.caFile = "path/to/trust/bundle/file.pem", // as a file, or in memory buffer in PEM format
|
||||
.tls = true // required in server mode
|
||||
});
|
||||
```
|
||||
|
||||
Specifying `certFile` and `keyFile` configures the certificate that will be used to communicate with TLS peers.
|
||||
|
||||
On a client, this is only necessary for connecting to servers that require a client certificate.
|
||||
|
||||
On a server, this is necessary for TLS support.
|
||||
|
||||
Specifying `caFile` configures the trusted roots bundle file (in PEM format) that will be used to verify peer certificates.
|
||||
- The special value of `SYSTEM` (the default) indicates that the system-configured trust bundle should be used; this is generally what you want when connecting to any publicly exposed API/server.
|
||||
- The special value of `NONE` can be used to disable peer verification; this is only recommended to rule out certificate verification when testing connectivity.
|
||||
- If the value contain the special value `-----BEGIN CERTIFICATE-----`, the value will be read from memory, and not from a file. This is convenient on platforms like Android where reading / writing to the file system can be challenging without proper permissions, or without knowing the location of a temp directory.
|
||||
|
||||
For a client, specifying `caFile` can be used if connecting to a server that uses a self-signed cert, or when using a custom CA in an internal environment.
|
||||
|
||||
For a server, specifying `caFile` implies that:
|
||||
1. You require clients to present a certificate
|
||||
1. It must be signed by one of the trusted roots in the file
|
369
docs/ws.md
369
docs/ws.md
@ -1,369 +0,0 @@
|
||||
## 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
|
||||
```
|
||||
|
||||
## curl
|
||||
|
||||
The curl subcommand try to be compatible with the curl syntax, to fetch http pages.
|
||||
|
||||
Making a HEAD request with the -I parameter.
|
||||
|
||||
```
|
||||
$ ws curl -I https://www.google.com/
|
||||
|
||||
Accept-Ranges: none
|
||||
Alt-Svc: quic=":443"; ma=2592000; v="46,43",h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000
|
||||
Cache-Control: private, max-age=0
|
||||
Content-Type: text/html; charset=ISO-8859-1
|
||||
Date: Tue, 08 Oct 2019 21:36:57 GMT
|
||||
Expires: -1
|
||||
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
|
||||
Server: gws
|
||||
Set-Cookie: NID=188=ASwfz8GrXQrHCLqAz-AndLOMLcz0rC9yecnf3h0yXZxRL3rTufTU_GDDwERp7qQL7LZ_EB8gCRyPXGERyOSAgaqgnrkoTmvWrwFemRLMaOZ896GrHobi5fV7VLklnSG2w48Gj8xMlwxfP7Z-bX-xR9UZxep1tHM6UmFQdD_GkBE; expires=Wed, 08-Apr-2020 21:36:57 GMT; path=/; domain=.google.com; HttpOnly
|
||||
Transfer-Encoding: chunked
|
||||
Vary: Accept-Encoding
|
||||
X-Frame-Options: SAMEORIGIN
|
||||
X-XSS-Protection: 0
|
||||
Upload size: 143
|
||||
Download size: 0
|
||||
Status: 200
|
||||
```
|
||||
|
||||
Making a POST request with the -F parameter.
|
||||
|
||||
```
|
||||
$ ws curl -F foo=bar https://httpbin.org/post
|
||||
foo: bar
|
||||
Downloaded 438 bytes out of 438
|
||||
Access-Control-Allow-Credentials: true
|
||||
Access-Control-Allow-Origin: *
|
||||
Connection: keep-alive
|
||||
Content-Encoding:
|
||||
Content-Length: 438
|
||||
Content-Type: application/json
|
||||
Date: Tue, 08 Oct 2019 21:47:54 GMT
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
Server: nginx
|
||||
X-Content-Type-Options: nosniff
|
||||
X-Frame-Options: DENY
|
||||
X-XSS-Protection: 1; mode=block
|
||||
Upload size: 219
|
||||
Download size: 438
|
||||
Status: 200
|
||||
payload: {
|
||||
"args": {},
|
||||
"data": "",
|
||||
"files": {},
|
||||
"form": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"headers": {
|
||||
"Accept": "*/*",
|
||||
"Content-Length": "7",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Host": "httpbin.org",
|
||||
"User-Agent": "ixwebsocket/7.0.0 macos ssl/OpenSSL OpenSSL 1.0.2q 20 Nov 2018 zlib 1.2.11"
|
||||
},
|
||||
"json": null,
|
||||
"origin": "155.94.127.118, 155.94.127.118",
|
||||
"url": "https://httpbin.org/post"
|
||||
}
|
||||
```
|
||||
|
||||
Passing in a custom header with -H.
|
||||
|
||||
```
|
||||
$ ws curl -F foo=bar -H 'my_custom_header: baz' https://httpbin.org/post
|
||||
my_custom_header: baz
|
||||
foo: bar
|
||||
Downloaded 470 bytes out of 470
|
||||
Access-Control-Allow-Credentials: true
|
||||
Access-Control-Allow-Origin: *
|
||||
Connection: keep-alive
|
||||
Content-Encoding:
|
||||
Content-Length: 470
|
||||
Content-Type: application/json
|
||||
Date: Tue, 08 Oct 2019 21:50:25 GMT
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
Server: nginx
|
||||
X-Content-Type-Options: nosniff
|
||||
X-Frame-Options: DENY
|
||||
X-XSS-Protection: 1; mode=block
|
||||
Upload size: 243
|
||||
Download size: 470
|
||||
Status: 200
|
||||
payload: {
|
||||
"args": {},
|
||||
"data": "",
|
||||
"files": {},
|
||||
"form": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"headers": {
|
||||
"Accept": "*/*",
|
||||
"Content-Length": "7",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Host": "httpbin.org",
|
||||
"My-Custom-Header": "baz",
|
||||
"User-Agent": "ixwebsocket/7.0.0 macos ssl/OpenSSL OpenSSL 1.0.2q 20 Nov 2018 zlib 1.2.11"
|
||||
},
|
||||
"json": null,
|
||||
"origin": "155.94.127.118, 155.94.127.118",
|
||||
"url": "https://httpbin.org/post"
|
||||
}
|
||||
```
|
||||
|
||||
## connect
|
||||
|
||||
The connect command connects to a websocket endpoint, and starts an interactive prompt. Line editing, such as using the direction keys to fetch the last thing you tried to type) is provided. That command is pretty useful to try to send random data to an endpoint and verify that the service handles it with grace (such as sending invalid json).
|
||||
|
||||
```
|
||||
ws connect wss://echo.websocket.org
|
||||
Type Ctrl-D to exit prompt...
|
||||
Connecting to url: wss://echo.websocket.org
|
||||
> ws_connect: connected
|
||||
Uri: /
|
||||
Handshake Headers:
|
||||
Connection: Upgrade
|
||||
Date: Tue, 08 Oct 2019 21:38:44 GMT
|
||||
Sec-WebSocket-Accept: 2j6LBScZveqrMx1W/GJkCWvZo3M=
|
||||
sec-websocket-extensions:
|
||||
Server: Kaazing Gateway
|
||||
Upgrade: websocket
|
||||
Received ping
|
||||
Received ping
|
||||
Received ping
|
||||
Hello world !
|
||||
> Received 13 bytes
|
||||
ws_connect: received message: Hello world !
|
||||
> Hello world !
|
||||
> Received 13 bytes
|
||||
ws_connect: received message: Hello world !
|
||||
```
|
||||
|
||||
```
|
||||
ws connect 'ws://jeanserge.com/v2?appkey=_pubsub'
|
||||
Type Ctrl-D to exit prompt...
|
||||
Connecting to url: ws://jeanserge.com/v2?appkey=_pubsub
|
||||
> ws_connect: connected
|
||||
Uri: /v2?appkey=_pubsub
|
||||
Handshake Headers:
|
||||
Connection: Upgrade
|
||||
Date: Tue, 08 Oct 2019 21:45:28 GMT
|
||||
Sec-WebSocket-Accept: LYHmjh9Gsu/Yw7aumQqyPObOEV4=
|
||||
Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
Server: Python/3.7 websockets/8.0.2
|
||||
Upgrade: websocket
|
||||
bababababababab
|
||||
> ws_connect: connection closed: code 1000 reason
|
||||
|
||||
ws_connect: connected
|
||||
Uri: /v2?appkey=_pubsub
|
||||
Handshake Headers:
|
||||
Connection: Upgrade
|
||||
Date: Tue, 08 Oct 2019 21:45:44 GMT
|
||||
Sec-WebSocket-Accept: I1rqxdLgTU+opPi5/zKPBTuXdLw=
|
||||
Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
Server: Python/3.7 websockets/8.0.2
|
||||
Upgrade: websocket
|
||||
```
|
||||
|
||||
## Websocket proxy
|
||||
|
||||
```
|
||||
ws proxy_server --remote_host ws://127.0.0.1:9000 -v
|
||||
Listening on 127.0.0.1:8008
|
||||
```
|
||||
|
||||
If you connect to ws://127.0.0.1:8008, the proxy will connect to ws://127.0.0.1:9000 and pass all traffic to this 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 and server
|
||||
|
||||
[cobra](https://github.com/machinezone/cobra) is a real time messenging server. ws has several sub-command to interact with cobra. There is also a minimal cobra compatible server named snake available.
|
||||
|
||||
Below are examples on running a snake server and clients with TLS enabled (the server only works with the OpenSSL and the Mbed TLS backend for now).
|
||||
|
||||
First, generate certificates.
|
||||
|
||||
```
|
||||
$ cd /path/to/IXWebSocket
|
||||
$ cd ixsnake/ixsnake
|
||||
$ bash ../../ws/generate_certs.sh
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
.....+++
|
||||
.................+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/trusted-ca-key.pem
|
||||
generated ./.certs/trusted-ca-crt.pem
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
..+++
|
||||
.......................................+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/trusted-server-key.pem
|
||||
Signature ok
|
||||
subject=/O=machinezone/O=IXWebSocket/CN=trusted-server
|
||||
Getting CA Private Key
|
||||
generated ./.certs/trusted-server-crt.pem
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
...................................+++
|
||||
..................................................+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/trusted-client-key.pem
|
||||
Signature ok
|
||||
subject=/O=machinezone/O=IXWebSocket/CN=trusted-client
|
||||
Getting CA Private Key
|
||||
generated ./.certs/trusted-client-crt.pem
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
..............+++
|
||||
.......................................+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/untrusted-ca-key.pem
|
||||
generated ./.certs/untrusted-ca-crt.pem
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
..........+++
|
||||
................................................+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/untrusted-client-key.pem
|
||||
Signature ok
|
||||
subject=/O=machinezone/O=IXWebSocket/CN=untrusted-client
|
||||
Getting CA Private Key
|
||||
generated ./.certs/untrusted-client-crt.pem
|
||||
Generating RSA private key, 2048 bit long modulus
|
||||
.....................................................................................+++
|
||||
...........+++
|
||||
e is 65537 (0x10001)
|
||||
generated ./.certs/selfsigned-client-key.pem
|
||||
Signature ok
|
||||
subject=/O=machinezone/O=IXWebSocket/CN=selfsigned-client
|
||||
Getting Private key
|
||||
generated ./.certs/selfsigned-client-crt.pem
|
||||
```
|
||||
|
||||
Now run the snake server.
|
||||
|
||||
```
|
||||
$ export certs=.certs
|
||||
$ ws snake --tls --port 8765 --cert-file ${certs}/trusted-server-crt.pem --key-file ${certs}/trusted-server-key.pem --ca-file ${certs}/trusted-ca-crt.pem
|
||||
{
|
||||
"apps": {
|
||||
"FC2F10139A2BAc53BB72D9db967b024f": {
|
||||
"roles": {
|
||||
"_sub": {
|
||||
"secret": "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba"
|
||||
},
|
||||
"_pub": {
|
||||
"secret": "1c04DB8fFe76A4EeFE3E318C72d771db"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redis host: 127.0.0.1
|
||||
redis password:
|
||||
redis port: 6379
|
||||
```
|
||||
|
||||
As a new connection comes in, such output should be printed
|
||||
|
||||
```
|
||||
[2019-12-19 20:27:19.724] [info] New connection
|
||||
id: 0
|
||||
Uri: /v2?appkey=_health
|
||||
Headers:
|
||||
Connection: Upgrade
|
||||
Host: 127.0.0.1:8765
|
||||
Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
Sec-WebSocket-Key: d747B0fE61Db73f7Eh47c0==
|
||||
Sec-WebSocket-Protocol: json
|
||||
Sec-WebSocket-Version: 13
|
||||
Upgrade: websocket
|
||||
User-Agent: ixwebsocket/7.5.8 macos ssl/OpenSSL OpenSSL 1.0.2q 20 Nov 2018 zlib 1.2.11
|
||||
```
|
||||
|
||||
To connect and publish a message, do:
|
||||
|
||||
```
|
||||
$ export certs=.certs
|
||||
$ cd /path/to/ws/folder
|
||||
$ ls cobraMetricsSample.json
|
||||
cobraMetricsSample.json
|
||||
$ ws cobra_publish --endpoint wss://127.0.0.1:8765 --appkey FC2F10139A2BAc53BB72D9db967b024f --rolename _pub --rolesecret 1c04DB8fFe76A4EeFE3E318C72d771db --channel foo --cert-file ${certs}/trusted-client-crt.pem --key-file ${certs}/trusted-client-key.pem --ca-file ${certs}/trusted-ca-crt.pem cobraMetricsSample.json
|
||||
[2019-12-19 20:46:42.656] [info] Publisher connected
|
||||
[2019-12-19 20:46:42.657] [info] Connection: Upgrade
|
||||
[2019-12-19 20:46:42.657] [info] Sec-WebSocket-Accept: rs99IFThoBrhSg+k8G4ixH9yaq4=
|
||||
[2019-12-19 20:46:42.657] [info] Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15; client_max_window_bits=15
|
||||
[2019-12-19 20:46:42.657] [info] Server: ixwebsocket/7.5.8 macos ssl/OpenSSL OpenSSL 1.0.2q 20 Nov 2018 zlib 1.2.11
|
||||
[2019-12-19 20:46:42.657] [info] Upgrade: websocket
|
||||
[2019-12-19 20:46:42.658] [info] Publisher authenticated
|
||||
[2019-12-19 20:46:42.658] [info] Published msg 3
|
||||
[2019-12-19 20:46:42.659] [info] Published message id 3 acked
|
||||
```
|
||||
|
||||
To use OpenSSL on macOS, compile with `make ws_openssl`. First you will have to install OpenSSL libraries, which can be done with Homebrew. Use `make ws_mbedtls` accordingly to use MbedTLS.
|
@ -1,43 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
|
||||
set (IXBOTS_SOURCES
|
||||
ixbots/IXCobraBot.cpp
|
||||
ixbots/IXCobraToSentryBot.cpp
|
||||
ixbots/IXCobraToStatsdBot.cpp
|
||||
ixbots/IXCobraToStdoutBot.cpp
|
||||
ixbots/IXStatsdClient.cpp
|
||||
)
|
||||
|
||||
set (IXBOTS_HEADERS
|
||||
ixbots/IXCobraBot.h
|
||||
ixbots/IXCobraBotConfig.h
|
||||
ixbots/IXCobraToSentryBot.h
|
||||
ixbots/IXCobraToStatsdBot.h
|
||||
ixbots/IXCobraToStdoutBot.h
|
||||
ixbots/IXStatsdClient.h
|
||||
)
|
||||
|
||||
add_library(ixbots STATIC
|
||||
${IXBOTS_SOURCES}
|
||||
${IXBOTS_HEADERS}
|
||||
)
|
||||
|
||||
find_package(JsonCpp)
|
||||
if (NOT JSONCPP_FOUND)
|
||||
set(JSONCPP_INCLUDE_DIRS ../third_party/jsoncpp)
|
||||
endif()
|
||||
|
||||
set(IXBOTS_INCLUDE_DIRS
|
||||
.
|
||||
..
|
||||
../ixcore
|
||||
../ixwebsocket
|
||||
../ixcobra
|
||||
../ixsentry
|
||||
${JSONCPP_INCLUDE_DIRS}
|
||||
${SPDLOG_INCLUDE_DIRS})
|
||||
|
||||
target_include_directories( ixbots PUBLIC ${IXBOTS_INCLUDE_DIRS} )
|
@ -1,268 +0,0 @@
|
||||
/*
|
||||
* IXCobraBot.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraBot.h"
|
||||
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int64_t CobraBot::run(const CobraBotConfig& botConfig)
|
||||
{
|
||||
auto config = botConfig.cobraConfig;
|
||||
auto channel = botConfig.channel;
|
||||
auto filter = botConfig.filter;
|
||||
auto position = botConfig.position;
|
||||
auto enableHeartbeat = botConfig.enableHeartbeat;
|
||||
auto heartBeatTimeout = botConfig.heartBeatTimeout;
|
||||
auto runtime = botConfig.runtime;
|
||||
auto maxEventsPerMinute = botConfig.maxEventsPerMinute;
|
||||
auto limitReceivedEvents = botConfig.limitReceivedEvents;
|
||||
|
||||
ix::CobraConnection conn;
|
||||
conn.configure(config);
|
||||
conn.connect();
|
||||
|
||||
std::atomic<uint64_t> sentCount(0);
|
||||
std::atomic<uint64_t> receivedCount(0);
|
||||
uint64_t sentCountTotal(0);
|
||||
uint64_t receivedCountTotal(0);
|
||||
uint64_t sentCountPerSecs(0);
|
||||
uint64_t receivedCountPerSecs(0);
|
||||
std::atomic<int> receivedCountPerMinutes(0);
|
||||
std::atomic<bool> stop(false);
|
||||
std::atomic<bool> throttled(false);
|
||||
std::atomic<bool> fatalCobraError(false);
|
||||
int minuteCounter = 0;
|
||||
|
||||
auto timer = [&sentCount,
|
||||
&receivedCount,
|
||||
&sentCountTotal,
|
||||
&receivedCountTotal,
|
||||
&sentCountPerSecs,
|
||||
&receivedCountPerSecs,
|
||||
&receivedCountPerMinutes,
|
||||
&minuteCounter,
|
||||
&stop] {
|
||||
while (!stop)
|
||||
{
|
||||
//
|
||||
// We cannot write to sentCount and receivedCount
|
||||
// as those are used externally, so we need to introduce
|
||||
// our own counters
|
||||
//
|
||||
std::stringstream ss;
|
||||
ss << "messages received "
|
||||
<< receivedCountPerSecs
|
||||
<< " "
|
||||
<< receivedCountTotal
|
||||
<< " sent "
|
||||
<< sentCountPerSecs
|
||||
<< " "
|
||||
<< sentCountTotal;
|
||||
CoreLogger::info(ss.str());
|
||||
|
||||
receivedCountPerSecs = receivedCount - receivedCountTotal;
|
||||
sentCountPerSecs = sentCount - sentCountTotal;
|
||||
|
||||
receivedCountTotal += receivedCountPerSecs;
|
||||
sentCountTotal += sentCountPerSecs;
|
||||
|
||||
auto duration = std::chrono::seconds(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
|
||||
if (minuteCounter++ == 60)
|
||||
{
|
||||
receivedCountPerMinutes = 0;
|
||||
minuteCounter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
CoreLogger::info("timer thread done");
|
||||
};
|
||||
|
||||
std::thread t1(timer);
|
||||
|
||||
auto heartbeat = [&sentCount, &receivedCount, &stop, &enableHeartbeat, &heartBeatTimeout, &fatalCobraError] {
|
||||
std::string state("na");
|
||||
|
||||
if (!enableHeartbeat) return;
|
||||
|
||||
while (!stop)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "messages received " << receivedCount;
|
||||
ss << "messages sent " << sentCount;
|
||||
|
||||
std::string currentState = ss.str();
|
||||
|
||||
if (currentState == state)
|
||||
{
|
||||
CoreLogger::error("no messages received or sent for 1 minute, exiting");
|
||||
fatalCobraError = true;
|
||||
break;
|
||||
}
|
||||
state = currentState;
|
||||
|
||||
auto duration = std::chrono::seconds(heartBeatTimeout);
|
||||
std::this_thread::sleep_for(duration);
|
||||
}
|
||||
|
||||
CoreLogger::info("heartbeat thread done");
|
||||
};
|
||||
|
||||
std::thread t2(heartbeat);
|
||||
|
||||
std::string subscriptionPosition(position);
|
||||
|
||||
conn.setEventCallback([this,
|
||||
&conn,
|
||||
&channel,
|
||||
&filter,
|
||||
&subscriptionPosition,
|
||||
&throttled,
|
||||
&receivedCount,
|
||||
&receivedCountPerMinutes,
|
||||
maxEventsPerMinute,
|
||||
limitReceivedEvents,
|
||||
&fatalCobraError,
|
||||
&sentCount](const CobraEventPtr& event) {
|
||||
if (event->type == ix::CobraEventType::Open)
|
||||
{
|
||||
CoreLogger::info("Subscriber connected");
|
||||
|
||||
for (auto&& it : event->headers)
|
||||
{
|
||||
CoreLogger::info(it.first + "::" + it.second);
|
||||
}
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Closed)
|
||||
{
|
||||
CoreLogger::info("Subscriber closed: {}" + event->errMsg);
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Authenticated)
|
||||
{
|
||||
CoreLogger::info("Subscriber authenticated");
|
||||
CoreLogger::info("Subscribing to " + channel);
|
||||
CoreLogger::info("Subscribing at position " + subscriptionPosition);
|
||||
CoreLogger::info("Subscribing with filter " + filter);
|
||||
conn.subscribe(channel, filter, subscriptionPosition,
|
||||
[&sentCount, &receivedCountPerMinutes,
|
||||
maxEventsPerMinute, limitReceivedEvents,
|
||||
&throttled, &receivedCount,
|
||||
&subscriptionPosition, &fatalCobraError,
|
||||
this](const Json::Value& msg, const std::string& position) {
|
||||
subscriptionPosition = position;
|
||||
++receivedCount;
|
||||
|
||||
++receivedCountPerMinutes;
|
||||
if (limitReceivedEvents)
|
||||
{
|
||||
if (receivedCountPerMinutes > maxEventsPerMinute)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If we cannot send to sentry fast enough, drop the message
|
||||
if (throttled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_onBotMessageCallback(
|
||||
msg, position, throttled,
|
||||
fatalCobraError, sentCount);
|
||||
});
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Subscribed)
|
||||
{
|
||||
CoreLogger::info("Subscriber: subscribed to channel " + event->subscriptionId);
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::UnSubscribed)
|
||||
{
|
||||
CoreLogger::info("Subscriber: unsubscribed from channel " + event->subscriptionId);
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Error)
|
||||
{
|
||||
CoreLogger::error("Subscriber: error " + event->errMsg);
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Published)
|
||||
{
|
||||
CoreLogger::error("Published message hacked: " + std::to_string(event->msgId));
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Pong)
|
||||
{
|
||||
CoreLogger::info("Received websocket pong: " + event->errMsg);
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::HandshakeError)
|
||||
{
|
||||
CoreLogger::error("Subscriber: Handshake error: " + event->errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::AuthenticationError)
|
||||
{
|
||||
CoreLogger::error("Subscriber: Authentication error: " + event->errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::SubscriptionError)
|
||||
{
|
||||
CoreLogger::error("Subscriber: Subscription error: " + event->errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Run forever
|
||||
if (runtime == -1)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
auto duration = std::chrono::seconds(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
|
||||
if (fatalCobraError) break;
|
||||
}
|
||||
}
|
||||
// Run for a duration, used by unittesting now
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < runtime; ++i)
|
||||
{
|
||||
auto duration = std::chrono::seconds(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
|
||||
if (fatalCobraError) break;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Cleanup.
|
||||
// join all the bg threads and stop them.
|
||||
//
|
||||
conn.disconnect();
|
||||
stop = true;
|
||||
|
||||
// progress thread
|
||||
t1.join();
|
||||
|
||||
// heartbeat thread
|
||||
if (t2.joinable()) t2.join();
|
||||
|
||||
return fatalCobraError ? -1 : (int64_t) sentCount;
|
||||
}
|
||||
|
||||
void CobraBot::setOnBotMessageCallback(const OnBotMessageCallback& callback)
|
||||
{
|
||||
_onBotMessageCallback = callback;
|
||||
}
|
||||
} // namespace ix
|
@ -1,34 +0,0 @@
|
||||
/*
|
||||
* IXCobraBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include "IXCobraBotConfig.h"
|
||||
#include <json/json.h>
|
||||
#include <stddef.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
using OnBotMessageCallback = std::function<void(const Json::Value&,
|
||||
const std::string&,
|
||||
std::atomic<bool>&,
|
||||
std::atomic<bool>&,
|
||||
std::atomic<uint64_t>&)>;
|
||||
|
||||
class CobraBot
|
||||
{
|
||||
public:
|
||||
CobraBot() = default;
|
||||
|
||||
int64_t run(const CobraBotConfig& botConfig);
|
||||
void setOnBotMessageCallback(const OnBotMessageCallback& callback);
|
||||
|
||||
private:
|
||||
OnBotMessageCallback _onBotMessageCallback;
|
||||
};
|
||||
} // namespace ix
|
@ -1,31 +0,0 @@
|
||||
/*
|
||||
* IXCobraBotConfig.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <limits>
|
||||
#include <ixcobra/IXCobraConfig.h>
|
||||
|
||||
#ifdef max
|
||||
#undef max
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
struct CobraBotConfig
|
||||
{
|
||||
CobraConfig cobraConfig;
|
||||
std::string channel;
|
||||
std::string filter;
|
||||
std::string position = std::string("$");
|
||||
bool enableHeartbeat = true;
|
||||
int heartBeatTimeout = 60;
|
||||
int runtime = -1;
|
||||
int maxEventsPerMinute = std::numeric_limits<int>::max();
|
||||
bool limitReceivedEvents = false;
|
||||
};
|
||||
} // namespace ix
|
@ -1,76 +0,0 @@
|
||||
/*
|
||||
* IXCobraToSentryBot.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraToSentryBot.h"
|
||||
|
||||
#include "IXCobraBot.h"
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int64_t cobra_to_sentry_bot(const CobraBotConfig& config,
|
||||
SentryClient& sentryClient,
|
||||
bool verbose)
|
||||
{
|
||||
CobraBot bot;
|
||||
bot.setOnBotMessageCallback([&sentryClient, &verbose](const Json::Value& msg,
|
||||
const std::string& /*position*/,
|
||||
std::atomic<bool>& throttled,
|
||||
std::atomic<bool>& /*fatalCobraError*/,
|
||||
std::atomic<uint64_t>& sentCount) -> void {
|
||||
sentryClient.send(msg, verbose,
|
||||
[&sentCount, &throttled](const HttpResponsePtr& response) {
|
||||
if (!response)
|
||||
{
|
||||
CoreLogger::warn("Null HTTP Response");
|
||||
return;
|
||||
}
|
||||
|
||||
if (response->statusCode == 200)
|
||||
{
|
||||
sentCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
CoreLogger::error("Error sending data to sentry: " + std::to_string(response->statusCode));
|
||||
CoreLogger::error("Response: " + response->payload);
|
||||
|
||||
// Error 429 Too Many Requests
|
||||
if (response->statusCode == 429)
|
||||
{
|
||||
auto retryAfter = response->headers["Retry-After"];
|
||||
std::stringstream ss;
|
||||
ss << retryAfter;
|
||||
int seconds;
|
||||
ss >> seconds;
|
||||
|
||||
if (!ss.eof() || ss.fail())
|
||||
{
|
||||
seconds = 30;
|
||||
CoreLogger::warn("Error parsing Retry-After header. "
|
||||
"Using " + retryAfter + " for the sleep duration");
|
||||
}
|
||||
|
||||
CoreLogger::warn("Error 429 - Too Many Requests. ws will sleep "
|
||||
"and retry after " + retryAfter + " seconds");
|
||||
|
||||
throttled = true;
|
||||
auto duration = std::chrono::seconds(seconds);
|
||||
std::this_thread::sleep_for(duration);
|
||||
throttled = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return bot.run(config);
|
||||
}
|
||||
} // namespace ix
|
@ -1,18 +0,0 @@
|
||||
/*
|
||||
* IXCobraToSentryBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include "IXCobraBotConfig.h"
|
||||
#include <ixsentry/IXSentryClient.h>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int64_t cobra_to_sentry_bot(const CobraBotConfig& config,
|
||||
SentryClient& sentryClient,
|
||||
bool verbose);
|
||||
} // namespace ix
|
@ -1,137 +0,0 @@
|
||||
/*
|
||||
* IXCobraToStatsdBot.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraToStatsdBot.h"
|
||||
|
||||
#include "IXCobraBot.h"
|
||||
#include "IXStatsdClient.h"
|
||||
#include <chrono>
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
// fields are command line argument that can be specified multiple times
|
||||
std::vector<std::string> parseFields(const std::string& fields)
|
||||
{
|
||||
std::vector<std::string> tokens;
|
||||
|
||||
// Split by \n
|
||||
std::string token;
|
||||
std::stringstream tokenStream(fields);
|
||||
|
||||
while (std::getline(tokenStream, token))
|
||||
{
|
||||
tokens.push_back(token);
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
//
|
||||
// Extract an attribute from a Json Value.
|
||||
// extractAttr("foo.bar", {"foo": {"bar": "baz"}}) => baz
|
||||
//
|
||||
Json::Value extractAttr(const std::string& attr, const Json::Value& jsonValue)
|
||||
{
|
||||
// Split by .
|
||||
std::string token;
|
||||
std::stringstream tokenStream(attr);
|
||||
|
||||
Json::Value val(jsonValue);
|
||||
|
||||
while (std::getline(tokenStream, token, '.'))
|
||||
{
|
||||
val = val[token];
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
int64_t cobra_to_statsd_bot(const ix::CobraBotConfig& config,
|
||||
StatsdClient& statsdClient,
|
||||
const std::string& fields,
|
||||
const std::string& gauge,
|
||||
const std::string& timer,
|
||||
bool verbose)
|
||||
{
|
||||
auto tokens = parseFields(fields);
|
||||
|
||||
CobraBot bot;
|
||||
bot.setOnBotMessageCallback(
|
||||
[&statsdClient, &tokens, &gauge, &timer, &verbose](const Json::Value& msg,
|
||||
const std::string& /*position*/,
|
||||
std::atomic<bool>& /*throttled*/,
|
||||
std::atomic<bool>& fatalCobraError,
|
||||
std::atomic<uint64_t>& sentCount) -> void {
|
||||
std::string id;
|
||||
for (auto&& attr : tokens)
|
||||
{
|
||||
id += ".";
|
||||
auto val = extractAttr(attr, msg);
|
||||
id += val.asString();
|
||||
}
|
||||
|
||||
if (gauge.empty() && timer.empty())
|
||||
{
|
||||
statsdClient.count(id, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string attrName = (!gauge.empty()) ? gauge : timer;
|
||||
auto val = extractAttr(attrName, msg);
|
||||
size_t x;
|
||||
|
||||
if (val.isInt())
|
||||
{
|
||||
x = (size_t) val.asInt();
|
||||
}
|
||||
else if (val.isInt64())
|
||||
{
|
||||
x = (size_t) val.asInt64();
|
||||
}
|
||||
else if (val.isUInt())
|
||||
{
|
||||
x = (size_t) val.asUInt();
|
||||
}
|
||||
else if (val.isUInt64())
|
||||
{
|
||||
x = (size_t) val.asUInt64();
|
||||
}
|
||||
else if (val.isDouble())
|
||||
{
|
||||
x = (size_t) val.asUInt64();
|
||||
}
|
||||
else
|
||||
{
|
||||
CoreLogger::error("Gauge " + gauge + " is not a numeric type");
|
||||
fatalCobraError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (verbose)
|
||||
{
|
||||
CoreLogger::info(id + " - " + attrName + " -> " + std::to_string(x));
|
||||
}
|
||||
|
||||
if (!gauge.empty())
|
||||
{
|
||||
statsdClient.gauge(id, x);
|
||||
}
|
||||
else
|
||||
{
|
||||
statsdClient.timing(id, x);
|
||||
}
|
||||
}
|
||||
|
||||
sentCount++;
|
||||
});
|
||||
|
||||
return bot.run(config);
|
||||
}
|
||||
} // namespace ix
|
@ -1,22 +0,0 @@
|
||||
/*
|
||||
* IXCobraToStatsdBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <ixbots/IXStatsdClient.h>
|
||||
#include "IXCobraBotConfig.h"
|
||||
#include <stddef.h>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int64_t cobra_to_statsd_bot(const ix::CobraBotConfig& config,
|
||||
StatsdClient& statsdClient,
|
||||
const std::string& fields,
|
||||
const std::string& gauge,
|
||||
const std::string& timer,
|
||||
bool verbose);
|
||||
} // namespace ix
|
@ -1,88 +0,0 @@
|
||||
/*
|
||||
* IXCobraToStdoutBot.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraToStdoutBot.h"
|
||||
|
||||
#include "IXCobraBot.h"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
using StreamWriterPtr = std::unique_ptr<Json::StreamWriter>;
|
||||
|
||||
StreamWriterPtr makeStreamWriter()
|
||||
{
|
||||
Json::StreamWriterBuilder builder;
|
||||
builder["commentStyle"] = "None";
|
||||
builder["indentation"] = ""; // will make the JSON object compact
|
||||
std::unique_ptr<Json::StreamWriter> jsonWriter(builder.newStreamWriter());
|
||||
return jsonWriter;
|
||||
}
|
||||
|
||||
std::string timeSinceEpoch()
|
||||
{
|
||||
std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
|
||||
std::chrono::system_clock::duration dtn = tp.time_since_epoch();
|
||||
|
||||
std::stringstream ss;
|
||||
ss << dtn.count() * std::chrono::system_clock::period::num /
|
||||
std::chrono::system_clock::period::den;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
void writeToStdout(bool fluentd,
|
||||
const StreamWriterPtr& jsonWriter,
|
||||
const Json::Value& msg,
|
||||
const std::string& position)
|
||||
{
|
||||
Json::Value enveloppe;
|
||||
if (fluentd)
|
||||
{
|
||||
enveloppe["producer"] = "cobra";
|
||||
enveloppe["consumer"] = "fluentd";
|
||||
|
||||
Json::Value nestedMessage(msg);
|
||||
nestedMessage["position"] = position;
|
||||
nestedMessage["created_at"] = timeSinceEpoch();
|
||||
enveloppe["message"] = nestedMessage;
|
||||
|
||||
jsonWriter->write(enveloppe, &std::cout);
|
||||
std::cout << std::endl; // add lf and flush
|
||||
}
|
||||
else
|
||||
{
|
||||
enveloppe = msg;
|
||||
std::cout << position << " ";
|
||||
jsonWriter->write(enveloppe, &std::cout);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
int64_t cobra_to_stdout_bot(const ix::CobraBotConfig& config,
|
||||
bool fluentd,
|
||||
bool quiet)
|
||||
{
|
||||
CobraBot bot;
|
||||
auto jsonWriter = makeStreamWriter();
|
||||
|
||||
bot.setOnBotMessageCallback(
|
||||
[&fluentd, &quiet, &jsonWriter](const Json::Value& msg,
|
||||
const std::string& position,
|
||||
std::atomic<bool>& /*throttled*/,
|
||||
std::atomic<bool>& /*fatalCobraError*/,
|
||||
std::atomic<uint64_t>& sentCount) -> void {
|
||||
if (!quiet)
|
||||
{
|
||||
writeToStdout(fluentd, jsonWriter, msg, position);
|
||||
}
|
||||
sentCount++;
|
||||
});
|
||||
|
||||
return bot.run(config);
|
||||
}
|
||||
} // namespace ix
|
@ -1,18 +0,0 @@
|
||||
/*
|
||||
* IXCobraToStdoutBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include "IXCobraBotConfig.h"
|
||||
#include <stddef.h>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
int64_t cobra_to_stdout_bot(const ix::CobraBotConfig& config,
|
||||
bool fluentd,
|
||||
bool quiet);
|
||||
} // namespace ix
|
@ -1,147 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, Rex
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * 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.
|
||||
*
|
||||
* * Neither the name of the {organization} nor the names of its
|
||||
* contributors may be used to endorse or promote products derived from
|
||||
* this software without specific prior written permission.
|
||||
*
|
||||
* 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 HOLDER 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* IXStatsdClient.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
// Adapted from statsd-client-cpp
|
||||
// test with netcat as a server: `nc -ul 8125`
|
||||
|
||||
#include "IXStatsdClient.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
StatsdClient::StatsdClient(const std::string& host, int port, const std::string& prefix)
|
||||
: _host(host)
|
||||
, _port(port)
|
||||
, _prefix(prefix)
|
||||
, _stop(false)
|
||||
{
|
||||
_thread = std::thread([this] {
|
||||
while (!_stop)
|
||||
{
|
||||
flushQueue();
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
StatsdClient::~StatsdClient()
|
||||
{
|
||||
_stop = true;
|
||||
if (_thread.joinable()) _thread.join();
|
||||
|
||||
_socket.close();
|
||||
}
|
||||
|
||||
bool StatsdClient::init(std::string& errMsg)
|
||||
{
|
||||
return _socket.init(_host, _port, errMsg);
|
||||
}
|
||||
|
||||
/* will change the original string */
|
||||
void StatsdClient::cleanup(std::string& key)
|
||||
{
|
||||
size_t pos = key.find_first_of(":|@");
|
||||
while (pos != std::string::npos)
|
||||
{
|
||||
key[pos] = '_';
|
||||
pos = key.find_first_of(":|@");
|
||||
}
|
||||
}
|
||||
|
||||
int StatsdClient::dec(const std::string& key)
|
||||
{
|
||||
return count(key, -1);
|
||||
}
|
||||
|
||||
int StatsdClient::inc(const std::string& key)
|
||||
{
|
||||
return count(key, 1);
|
||||
}
|
||||
|
||||
int StatsdClient::count(const std::string& key, size_t value)
|
||||
{
|
||||
return send(key, value, "c");
|
||||
}
|
||||
|
||||
int StatsdClient::gauge(const std::string& key, size_t value)
|
||||
{
|
||||
return send(key, value, "g");
|
||||
}
|
||||
|
||||
int StatsdClient::timing(const std::string& key, size_t ms)
|
||||
{
|
||||
return send(key, ms, "ms");
|
||||
}
|
||||
|
||||
int StatsdClient::send(std::string key, size_t value, const std::string& type)
|
||||
{
|
||||
cleanup(key);
|
||||
|
||||
char buf[256];
|
||||
snprintf(
|
||||
buf, sizeof(buf), "%s%s:%zd|%s\n", _prefix.c_str(), key.c_str(), value, type.c_str());
|
||||
|
||||
enqueue(buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void StatsdClient::enqueue(const std::string& message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
_queue.push_back(message);
|
||||
}
|
||||
|
||||
void StatsdClient::flushQueue()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
|
||||
while (!_queue.empty())
|
||||
{
|
||||
auto message = _queue.front();
|
||||
auto ret = _socket.sendto(message);
|
||||
if (ret != 0)
|
||||
{
|
||||
std::cerr << "error: " << strerror(UdpSocket::getErrno()) << std::endl;
|
||||
}
|
||||
_queue.pop_front();
|
||||
}
|
||||
}
|
||||
} // end namespace ix
|
@ -1,57 +0,0 @@
|
||||
/*
|
||||
* IXStatsdClient.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <ixwebsocket/IXUdpSocket.h>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class StatsdClient
|
||||
{
|
||||
public:
|
||||
StatsdClient(const std::string& host = "127.0.0.1",
|
||||
int port = 8125,
|
||||
const std::string& prefix = "");
|
||||
~StatsdClient();
|
||||
|
||||
bool init(std::string& errMsg);
|
||||
int inc(const std::string& key);
|
||||
int dec(const std::string& key);
|
||||
int count(const std::string& key, size_t value);
|
||||
int gauge(const std::string& key, size_t value);
|
||||
int timing(const std::string& key, size_t ms);
|
||||
|
||||
private:
|
||||
void enqueue(const std::string& message);
|
||||
|
||||
/* (Low Level Api) manually send a message
|
||||
* type = "c", "g" or "ms"
|
||||
*/
|
||||
int send(std::string key, size_t value, const std::string& type);
|
||||
|
||||
void cleanup(std::string& key);
|
||||
void flushQueue();
|
||||
|
||||
UdpSocket _socket;
|
||||
|
||||
std::string _host;
|
||||
int _port;
|
||||
std::string _prefix;
|
||||
|
||||
std::atomic<bool> _stop;
|
||||
std::thread _thread;
|
||||
std::mutex _mutex; // for the queue
|
||||
|
||||
std::deque<std::string> _queue;
|
||||
};
|
||||
|
||||
} // end namespace ix
|
@ -1,37 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
|
||||
set (IXCOBRA_SOURCES
|
||||
ixcobra/IXCobraConnection.cpp
|
||||
ixcobra/IXCobraMetricsThreadedPublisher.cpp
|
||||
ixcobra/IXCobraMetricsPublisher.cpp
|
||||
)
|
||||
|
||||
set (IXCOBRA_HEADERS
|
||||
ixcobra/IXCobraConnection.h
|
||||
ixcobra/IXCobraMetricsThreadedPublisher.h
|
||||
ixcobra/IXCobraMetricsPublisher.h
|
||||
ixcobra/IXCobraConfig.h
|
||||
ixcobra/IXCobraEventType.h
|
||||
)
|
||||
|
||||
add_library(ixcobra STATIC
|
||||
${IXCOBRA_SOURCES}
|
||||
${IXCOBRA_HEADERS}
|
||||
)
|
||||
|
||||
find_package(JsonCpp)
|
||||
if (NOT JSONCPP_FOUND)
|
||||
set(JSONCPP_INCLUDE_DIRS ../third_party/jsoncpp)
|
||||
endif()
|
||||
|
||||
set(IXCOBRA_INCLUDE_DIRS
|
||||
.
|
||||
..
|
||||
../ixcore
|
||||
../ixcrypto
|
||||
${JSONCPP_INCLUDE_DIRS})
|
||||
|
||||
target_include_directories( ixcobra PUBLIC ${IXCOBRA_INCLUDE_DIRS} )
|
@ -1,35 +0,0 @@
|
||||
/*
|
||||
* IXCobraConfig.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
struct CobraConfig
|
||||
{
|
||||
std::string appkey;
|
||||
std::string endpoint;
|
||||
std::string rolename;
|
||||
std::string rolesecret;
|
||||
WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions;
|
||||
SocketTLSOptions socketTLSOptions;
|
||||
|
||||
CobraConfig(const std::string& a = std::string(),
|
||||
const std::string& e = std::string(),
|
||||
const std::string& r = std::string(),
|
||||
const std::string& s = std::string())
|
||||
: appkey(a)
|
||||
, endpoint(e)
|
||||
, rolename(r)
|
||||
, rolesecret(s)
|
||||
{
|
||||
;
|
||||
}
|
||||
};
|
||||
} // namespace ix
|
@ -1,676 +0,0 @@
|
||||
/*
|
||||
* IXCobraConnection.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2018 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraConnection.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <ixcrypto/IXHMac.h>
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
namespace ix
|
||||
{
|
||||
TrafficTrackerCallback CobraConnection::_trafficTrackerCallback = nullptr;
|
||||
PublishTrackerCallback CobraConnection::_publishTrackerCallback = nullptr;
|
||||
constexpr size_t CobraConnection::kQueueMaxSize;
|
||||
constexpr CobraConnection::MsgId CobraConnection::kInvalidMsgId;
|
||||
constexpr int CobraConnection::kPingIntervalSecs;
|
||||
|
||||
CobraConnection::CobraConnection()
|
||||
: _webSocket(new WebSocket())
|
||||
, _publishMode(CobraConnection_PublishMode_Immediate)
|
||||
, _authenticated(false)
|
||||
, _eventCallback(nullptr)
|
||||
, _id(1)
|
||||
{
|
||||
_pdu["action"] = "rtm/publish";
|
||||
|
||||
_webSocket->addSubProtocol("json");
|
||||
initWebSocketOnMessageCallback();
|
||||
}
|
||||
|
||||
CobraConnection::~CobraConnection()
|
||||
{
|
||||
disconnect();
|
||||
setEventCallback(nullptr);
|
||||
}
|
||||
|
||||
void CobraConnection::setTrafficTrackerCallback(const TrafficTrackerCallback& callback)
|
||||
{
|
||||
_trafficTrackerCallback = callback;
|
||||
}
|
||||
|
||||
void CobraConnection::resetTrafficTrackerCallback()
|
||||
{
|
||||
setTrafficTrackerCallback(nullptr);
|
||||
}
|
||||
|
||||
void CobraConnection::invokeTrafficTrackerCallback(size_t size, bool incoming)
|
||||
{
|
||||
if (_trafficTrackerCallback)
|
||||
{
|
||||
_trafficTrackerCallback(size, incoming);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
_eventCallback = eventCallback;
|
||||
}
|
||||
|
||||
void CobraConnection::invokeEventCallback(ix::CobraEventType eventType,
|
||||
const std::string& errorMsg,
|
||||
const WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_eventCallbackMutex);
|
||||
if (_eventCallback)
|
||||
{
|
||||
_eventCallback(
|
||||
std::make_unique<CobraEvent>(eventType, errorMsg, headers, subscriptionId, msgId));
|
||||
}
|
||||
}
|
||||
|
||||
void CobraConnection::invokeErrorCallback(const std::string& errorMsg,
|
||||
const std::string& serializedPdu)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << errorMsg << " : received pdu => " << serializedPdu;
|
||||
invokeEventCallback(ix::CobraEventType::Error, ss.str());
|
||||
}
|
||||
|
||||
void CobraConnection::disconnect()
|
||||
{
|
||||
_authenticated = false;
|
||||
_webSocket->stop();
|
||||
}
|
||||
|
||||
void CobraConnection::initWebSocketOnMessageCallback()
|
||||
{
|
||||
_webSocket->setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) {
|
||||
CobraConnection::invokeTrafficTrackerCallback(msg->wireSize, true);
|
||||
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
invokeEventCallback(ix::CobraEventType::Open, std::string(), msg->openInfo.headers);
|
||||
sendHandshakeMessage();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
_authenticated = false;
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "Close code " << msg->closeInfo.code;
|
||||
ss << " reason " << msg->closeInfo.reason;
|
||||
invokeEventCallback(ix::CobraEventType::Closed, ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
Json::Value data;
|
||||
Json::Reader reader;
|
||||
if (!reader.parse(msg->str, data))
|
||||
{
|
||||
invokeErrorCallback("Invalid json", msg->str);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.isMember("action"))
|
||||
{
|
||||
invokeErrorCallback("Missing action", msg->str);
|
||||
return;
|
||||
}
|
||||
|
||||
auto action = data["action"].asString();
|
||||
|
||||
if (action == "auth/handshake/ok")
|
||||
{
|
||||
if (!handleHandshakeResponse(data))
|
||||
{
|
||||
invokeErrorCallback("Error extracting nonce from handshake response",
|
||||
msg->str);
|
||||
}
|
||||
}
|
||||
else if (action == "auth/handshake/error")
|
||||
{
|
||||
invokeEventCallback(ix::CobraEventType::HandshakeError, msg->str);
|
||||
}
|
||||
else if (action == "auth/authenticate/ok")
|
||||
{
|
||||
_authenticated = true;
|
||||
invokeEventCallback(ix::CobraEventType::Authenticated);
|
||||
flushQueue();
|
||||
}
|
||||
else if (action == "auth/authenticate/error")
|
||||
{
|
||||
invokeEventCallback(ix::CobraEventType::AuthenticationError, msg->str);
|
||||
}
|
||||
else if (action == "rtm/subscription/data")
|
||||
{
|
||||
handleSubscriptionData(data);
|
||||
}
|
||||
else if (action == "rtm/subscribe/ok")
|
||||
{
|
||||
if (!handleSubscriptionResponse(data))
|
||||
{
|
||||
invokeErrorCallback("Error processing subscribe response", msg->str);
|
||||
}
|
||||
}
|
||||
else if (action == "rtm/subscribe/error")
|
||||
{
|
||||
invokeEventCallback(ix::CobraEventType::SubscriptionError, msg->str);
|
||||
}
|
||||
else if (action == "rtm/unsubscribe/ok")
|
||||
{
|
||||
if (!handleUnsubscriptionResponse(data))
|
||||
{
|
||||
invokeErrorCallback("Error processing unsubscribe response", msg->str);
|
||||
}
|
||||
}
|
||||
else if (action == "rtm/unsubscribe/error")
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
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;
|
||||
invokeErrorCallback(ss.str(), std::string());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
invokeEventCallback(ix::CobraEventType::Pong, msg->str);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void CobraConnection::setPublishMode(CobraConnectionPublishMode publishMode)
|
||||
{
|
||||
_publishMode = publishMode;
|
||||
}
|
||||
|
||||
CobraConnectionPublishMode CobraConnection::getPublishMode()
|
||||
{
|
||||
return _publishMode;
|
||||
}
|
||||
|
||||
void CobraConnection::configure(
|
||||
const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
const WebSocketPerMessageDeflateOptions& webSocketPerMessageDeflateOptions,
|
||||
const SocketTLSOptions& socketTLSOptions)
|
||||
{
|
||||
_roleName = rolename;
|
||||
_roleSecret = rolesecret;
|
||||
|
||||
std::stringstream ss;
|
||||
ss << endpoint;
|
||||
ss << "/v2?appkey=";
|
||||
ss << appkey;
|
||||
|
||||
std::string url = ss.str();
|
||||
_webSocket->setUrl(url);
|
||||
_webSocket->setPerMessageDeflateOptions(webSocketPerMessageDeflateOptions);
|
||||
_webSocket->setTLSOptions(socketTLSOptions);
|
||||
|
||||
// Send a websocket ping every N seconds (N = 30) now
|
||||
// This should keep the connection open and prevent some load balancers such as
|
||||
// the Amazon one from shutting it down
|
||||
_webSocket->setPingInterval(kPingIntervalSecs);
|
||||
}
|
||||
|
||||
void CobraConnection::configure(const ix::CobraConfig& config)
|
||||
{
|
||||
configure(config.appkey,
|
||||
config.endpoint,
|
||||
config.rolename,
|
||||
config.rolesecret,
|
||||
config.webSocketPerMessageDeflateOptions,
|
||||
config.socketTLSOptions);
|
||||
}
|
||||
|
||||
//
|
||||
// Handshake message schema.
|
||||
//
|
||||
// handshake = {
|
||||
// "action": "auth/handshake",
|
||||
// "body": {
|
||||
// "data": {
|
||||
// "role": role
|
||||
// },
|
||||
// "method": "role_secret"
|
||||
// },
|
||||
// }
|
||||
//
|
||||
//
|
||||
bool CobraConnection::sendHandshakeMessage()
|
||||
{
|
||||
Json::Value data;
|
||||
data["role"] = _roleName;
|
||||
|
||||
Json::Value body;
|
||||
body["data"] = data;
|
||||
body["method"] = "role_secret";
|
||||
|
||||
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);
|
||||
|
||||
return _webSocket->send(serializedJson).success;
|
||||
}
|
||||
|
||||
//
|
||||
// Extract the nonce from the handshake response
|
||||
// use it to compute a hash during authentication
|
||||
//
|
||||
// {
|
||||
// "action": "auth/handshake/ok",
|
||||
// "body": {
|
||||
// "data": {
|
||||
// "nonce": "MTI0Njg4NTAyMjYxMzgxMzgzMg==",
|
||||
// "version": "0.0.24"
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
bool CobraConnection::handleHandshakeResponse(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isObject()) return false;
|
||||
|
||||
if (!pdu.isMember("body")) return false;
|
||||
Json::Value body = pdu["body"];
|
||||
|
||||
if (!body.isMember("data")) return false;
|
||||
Json::Value data = body["data"];
|
||||
|
||||
if (!data.isMember("nonce")) return false;
|
||||
Json::Value nonce = data["nonce"];
|
||||
|
||||
if (!nonce.isString()) return false;
|
||||
|
||||
return sendAuthMessage(nonce.asString());
|
||||
}
|
||||
|
||||
//
|
||||
// Authenticate message schema.
|
||||
//
|
||||
// challenge = {
|
||||
// "action": "auth/authenticate",
|
||||
// "body": {
|
||||
// "method": "role_secret",
|
||||
// "credentials": {
|
||||
// "hash": computeHash(secret, nonce)
|
||||
// }
|
||||
// },
|
||||
// }
|
||||
//
|
||||
bool CobraConnection::sendAuthMessage(const std::string& nonce)
|
||||
{
|
||||
Json::Value credentials;
|
||||
credentials["hash"] = hmac(nonce, _roleSecret);
|
||||
|
||||
Json::Value body;
|
||||
body["credentials"] = credentials;
|
||||
body["method"] = "role_secret";
|
||||
|
||||
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);
|
||||
|
||||
return _webSocket->send(serializedJson).success;
|
||||
}
|
||||
|
||||
bool CobraConnection::handleSubscriptionResponse(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isObject()) return false;
|
||||
|
||||
if (!pdu.isMember("body")) return false;
|
||||
Json::Value body = pdu["body"];
|
||||
|
||||
if (!body.isMember("subscription_id")) return false;
|
||||
Json::Value subscriptionId = body["subscription_id"];
|
||||
|
||||
if (!subscriptionId.isString()) return false;
|
||||
|
||||
invokeEventCallback(ix::CobraEventType::Subscribed,
|
||||
std::string(),
|
||||
WebSocketHttpHeaders(),
|
||||
subscriptionId.asString());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::handleUnsubscriptionResponse(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isObject()) return false;
|
||||
|
||||
if (!pdu.isMember("body")) return false;
|
||||
Json::Value body = pdu["body"];
|
||||
|
||||
if (!body.isMember("subscription_id")) return false;
|
||||
Json::Value subscriptionId = body["subscription_id"];
|
||||
|
||||
if (!subscriptionId.isString()) return false;
|
||||
|
||||
invokeEventCallback(ix::CobraEventType::UnSubscribed,
|
||||
std::string(),
|
||||
WebSocketHttpHeaders(),
|
||||
subscriptionId.asString());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::handleSubscriptionData(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isObject()) return false;
|
||||
|
||||
if (!pdu.isMember("body")) return false;
|
||||
Json::Value body = pdu["body"];
|
||||
|
||||
// Identify subscription_id, so that we can find
|
||||
// which callback to execute
|
||||
if (!body.isMember("subscription_id")) return false;
|
||||
Json::Value subscriptionId = body["subscription_id"];
|
||||
|
||||
std::lock_guard<std::mutex> lock(_cbsMutex);
|
||||
auto cb = _cbs.find(subscriptionId.asString());
|
||||
if (cb == _cbs.end()) return false; // cannot find callback
|
||||
|
||||
// Extract messages now
|
||||
if (!body.isMember("messages")) return false;
|
||||
Json::Value messages = body["messages"];
|
||||
|
||||
if (!body.isMember("position")) return false;
|
||||
std::string position = body["position"].asString();
|
||||
|
||||
for (auto&& msg : messages)
|
||||
{
|
||||
cb->second(msg, position);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::handlePublishResponse(const Json::Value& pdu)
|
||||
{
|
||||
if (!pdu.isObject()) return false;
|
||||
|
||||
if (!pdu.isMember("id")) return false;
|
||||
Json::Value id = pdu["id"];
|
||||
|
||||
if (!id.isUInt64()) return false;
|
||||
|
||||
uint64_t msgId = id.asUInt64();
|
||||
|
||||
invokeEventCallback(ix::CobraEventType::Published,
|
||||
std::string(),
|
||||
WebSocketHttpHeaders(),
|
||||
std::string(),
|
||||
msgId);
|
||||
|
||||
invokePublishTrackerCallback(false, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::connect()
|
||||
{
|
||||
_webSocket->start();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::isConnected() const
|
||||
{
|
||||
return _webSocket->getReadyState() == ix::ReadyState::Open;
|
||||
}
|
||||
|
||||
bool CobraConnection::isAuthenticated() const
|
||||
{
|
||||
return isConnected() && _authenticated;
|
||||
}
|
||||
|
||||
std::string CobraConnection::serializeJson(const Json::Value& value)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_jsonWriterMutex);
|
||||
return _jsonWriter.write(value);
|
||||
}
|
||||
|
||||
std::pair<CobraConnection::MsgId, std::string> CobraConnection::prePublish(
|
||||
const Json::Value& channels, const Json::Value& msg, bool addToQueue)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_prePublishMutex);
|
||||
|
||||
invokePublishTrackerCallback(true, false);
|
||||
|
||||
CobraConnection::MsgId msgId = _id;
|
||||
|
||||
_body["channels"] = channels;
|
||||
_body["message"] = msg;
|
||||
_pdu["body"] = _body;
|
||||
_pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
std::string serializedJson = serializeJson(_pdu);
|
||||
|
||||
if (addToQueue)
|
||||
{
|
||||
enqueue(serializedJson);
|
||||
}
|
||||
|
||||
return std::make_pair(msgId, serializedJson);
|
||||
}
|
||||
|
||||
bool CobraConnection::publishNext()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_queueMutex);
|
||||
|
||||
if (_messageQueue.empty()) return true;
|
||||
|
||||
auto&& msg = _messageQueue.back();
|
||||
if (!_authenticated || !publishMessage(msg))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_messageQueue.pop_back();
|
||||
return true;
|
||||
}
|
||||
|
||||
//
|
||||
// publish is not thread safe as we are trying to reuse some Json objects.
|
||||
//
|
||||
CobraConnection::MsgId CobraConnection::publish(const Json::Value& channels,
|
||||
const Json::Value& msg)
|
||||
{
|
||||
auto p = prePublish(channels, msg, false);
|
||||
auto msgId = p.first;
|
||||
auto serializedJson = p.second;
|
||||
|
||||
//
|
||||
// 1. When we use batch mode, we just enqueue and will do the flush explicitely
|
||||
// 2. When we aren't authenticated yet to the cobra server, we need to enqueue
|
||||
// and retry later
|
||||
// 3. If the network connection was droped (WebSocket::send will return false),
|
||||
// it means the message won't be sent so we need to enqueue as well.
|
||||
//
|
||||
// The order of the conditionals is important.
|
||||
//
|
||||
if (_publishMode == CobraConnection_PublishMode_Batch || !_authenticated ||
|
||||
!publishMessage(serializedJson))
|
||||
{
|
||||
enqueue(serializedJson);
|
||||
}
|
||||
|
||||
return msgId;
|
||||
}
|
||||
|
||||
void CobraConnection::subscribe(const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& position,
|
||||
SubscriptionCallback cb)
|
||||
{
|
||||
// Create and send a subscribe pdu
|
||||
Json::Value body;
|
||||
body["channel"] = channel;
|
||||
|
||||
if (!filter.empty())
|
||||
{
|
||||
body["filter"] = filter;
|
||||
}
|
||||
|
||||
if (!position.empty())
|
||||
{
|
||||
body["position"] = position;
|
||||
}
|
||||
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "rtm/subscribe";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
_webSocket->send(pdu.toStyledString());
|
||||
|
||||
// Set the callback
|
||||
std::lock_guard<std::mutex> lock(_cbsMutex);
|
||||
_cbs[channel] = cb;
|
||||
}
|
||||
|
||||
void CobraConnection::unsubscribe(const std::string& channel)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_cbsMutex);
|
||||
auto cb = _cbs.find(channel);
|
||||
if (cb == _cbs.end()) return;
|
||||
|
||||
_cbs.erase(cb);
|
||||
}
|
||||
|
||||
// Create and send an unsubscribe pdu
|
||||
Json::Value body;
|
||||
body["subscription_id"] = channel;
|
||||
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "rtm/unsubscribe";
|
||||
pdu["body"] = body;
|
||||
pdu["id"] = Json::UInt64(_id++);
|
||||
|
||||
_webSocket->send(pdu.toStyledString());
|
||||
}
|
||||
|
||||
//
|
||||
// Enqueue strategy drops old messages when we are at full capacity
|
||||
//
|
||||
// If we want to keep only 3 items max in the queue:
|
||||
//
|
||||
// enqueue(A) -> [A]
|
||||
// enqueue(B) -> [B, A]
|
||||
// enqueue(C) -> [C, B, A]
|
||||
// enqueue(D) -> [D, C, B] -- now we drop A, the oldest message,
|
||||
// -- and keep the 'fresh ones'
|
||||
//
|
||||
void CobraConnection::enqueue(const std::string& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_queueMutex);
|
||||
|
||||
if (_messageQueue.size() == CobraConnection::kQueueMaxSize)
|
||||
{
|
||||
_messageQueue.pop_back();
|
||||
}
|
||||
_messageQueue.push_front(msg);
|
||||
}
|
||||
|
||||
//
|
||||
// We process messages back (oldest) to front (newest) to respect ordering
|
||||
// when sending them. If we fail to send something, we put it back in the queue
|
||||
// at the end we picked it up originally (at the end).
|
||||
//
|
||||
bool CobraConnection::flushQueue()
|
||||
{
|
||||
while (!isQueueEmpty())
|
||||
{
|
||||
bool ok = publishNext();
|
||||
if (!ok) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CobraConnection::isQueueEmpty()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_queueMutex);
|
||||
return _messageQueue.empty();
|
||||
}
|
||||
|
||||
bool CobraConnection::publishMessage(const std::string& serializedJson)
|
||||
{
|
||||
auto webSocketSendInfo = _webSocket->send(serializedJson);
|
||||
CobraConnection::invokeTrafficTrackerCallback(webSocketSendInfo.wireSize, false);
|
||||
return webSocketSendInfo.success;
|
||||
}
|
||||
|
||||
void CobraConnection::suspend()
|
||||
{
|
||||
disconnect();
|
||||
}
|
||||
|
||||
void CobraConnection::resume()
|
||||
{
|
||||
connect();
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* IXCobraEvent.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXCobraEventType.h"
|
||||
#include <cstdint>
|
||||
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
struct CobraEvent
|
||||
{
|
||||
ix::CobraEventType type;
|
||||
const std::string& errMsg;
|
||||
const ix::WebSocketHttpHeaders& headers;
|
||||
const std::string& subscriptionId;
|
||||
uint64_t msgId; // CobraConnection::MsgId
|
||||
|
||||
CobraEvent(ix::CobraEventType t,
|
||||
const std::string& e,
|
||||
const ix::WebSocketHttpHeaders& h,
|
||||
const std::string& s,
|
||||
uint64_t m)
|
||||
: type(t)
|
||||
, errMsg(e)
|
||||
, headers(h)
|
||||
, subscriptionId(s)
|
||||
, msgId(m)
|
||||
{
|
||||
;
|
||||
}
|
||||
};
|
||||
|
||||
using CobraEventPtr = std::unique_ptr<CobraEvent>;
|
||||
} // namespace ix
|
@ -1,25 +0,0 @@
|
||||
/*
|
||||
* IXCobraEventType.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace ix
|
||||
{
|
||||
enum class CobraEventType
|
||||
{
|
||||
Authenticated = 0,
|
||||
Error = 1,
|
||||
Open = 2,
|
||||
Closed = 3,
|
||||
Subscribed = 4,
|
||||
UnSubscribed = 5,
|
||||
Published = 6,
|
||||
Pong = 7,
|
||||
HandshakeError = 8,
|
||||
AuthenticationError = 9,
|
||||
SubscriptionError = 10
|
||||
};
|
||||
}
|
@ -1,230 +0,0 @@
|
||||
/*
|
||||
* IXCobraMetricsThreadedPublisher.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXCobraMetricsThreadedPublisher.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
#include <ixwebsocket/IXSetThreadName.h>
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
namespace ix
|
||||
{
|
||||
CobraMetricsThreadedPublisher::CobraMetricsThreadedPublisher()
|
||||
: _stop(false)
|
||||
{
|
||||
_cobra_connection.setEventCallback([](const CobraEventPtr& event) {
|
||||
std::stringstream ss;
|
||||
|
||||
if (event->type == ix::CobraEventType::Open)
|
||||
{
|
||||
ss << "Handshake headers" << std::endl;
|
||||
|
||||
for (auto&& it : event->headers)
|
||||
{
|
||||
ss << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Authenticated)
|
||||
{
|
||||
ss << "Authenticated";
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Error)
|
||||
{
|
||||
ss << "Error: " << event->errMsg;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Closed)
|
||||
{
|
||||
ss << "Connection closed: " << event->errMsg;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Subscribed)
|
||||
{
|
||||
ss << "Subscribed through subscription id: " << event->subscriptionId;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::UnSubscribed)
|
||||
{
|
||||
ss << "Unsubscribed through subscription id: " << event->subscriptionId;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Published)
|
||||
{
|
||||
ss << "Published message " << event->msgId << " acked";
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::Pong)
|
||||
{
|
||||
ss << "Received websocket pong";
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::HandshakeError)
|
||||
{
|
||||
ss << "Handshake error: " << event->errMsg;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::AuthenticationError)
|
||||
{
|
||||
ss << "Authentication error: " << event->errMsg;
|
||||
}
|
||||
else if (event->type == ix::CobraEventType::SubscriptionError)
|
||||
{
|
||||
ss << "Subscription error: " << event->errMsg;
|
||||
}
|
||||
|
||||
CoreLogger::log(ss.str().c_str());
|
||||
});
|
||||
}
|
||||
|
||||
CobraMetricsThreadedPublisher::~CobraMetricsThreadedPublisher()
|
||||
{
|
||||
// The background thread won't be joinable if it was never
|
||||
// started by calling CobraMetricsThreadedPublisher::start
|
||||
if (!_thread.joinable()) return;
|
||||
|
||||
_stop = true;
|
||||
_condition.notify_one();
|
||||
_thread.join();
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::start()
|
||||
{
|
||||
if (_thread.joinable()) return; // we've already been started
|
||||
|
||||
_thread = std::thread(&CobraMetricsThreadedPublisher::run, this);
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::configure(const CobraConfig& config,
|
||||
const std::string& channel)
|
||||
{
|
||||
CoreLogger::log(config.socketTLSOptions.getDescription().c_str());
|
||||
|
||||
_channel = channel;
|
||||
_cobra_connection.configure(config);
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::pushMessage(MessageKind messageKind)
|
||||
{
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_queue_mutex);
|
||||
_queue.push(messageKind);
|
||||
}
|
||||
|
||||
// wake up one thread
|
||||
_condition.notify_one();
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::setPublishMode(CobraConnectionPublishMode publishMode)
|
||||
{
|
||||
_cobra_connection.setPublishMode(publishMode);
|
||||
}
|
||||
|
||||
bool CobraMetricsThreadedPublisher::flushQueue()
|
||||
{
|
||||
return _cobra_connection.flushQueue();
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::run()
|
||||
{
|
||||
setThreadName("CobraMetricsPublisher");
|
||||
|
||||
_cobra_connection.connect();
|
||||
|
||||
while (true)
|
||||
{
|
||||
Json::Value msg;
|
||||
MessageKind messageKind;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_queue_mutex);
|
||||
|
||||
while (!_stop && _queue.empty())
|
||||
{
|
||||
_condition.wait(lock);
|
||||
}
|
||||
if (_stop)
|
||||
{
|
||||
_cobra_connection.disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
messageKind = _queue.front();
|
||||
_queue.pop();
|
||||
}
|
||||
|
||||
switch (messageKind)
|
||||
{
|
||||
case MessageKind::Suspend:
|
||||
{
|
||||
_cobra_connection.suspend();
|
||||
continue;
|
||||
};
|
||||
break;
|
||||
|
||||
case MessageKind::Resume:
|
||||
{
|
||||
_cobra_connection.resume();
|
||||
continue;
|
||||
};
|
||||
break;
|
||||
|
||||
case MessageKind::Message:
|
||||
{
|
||||
if (_cobra_connection.getPublishMode() == CobraConnection_PublishMode_Immediate)
|
||||
{
|
||||
_cobra_connection.publishNext();
|
||||
}
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CobraConnection::MsgId CobraMetricsThreadedPublisher::push(const Json::Value& msg)
|
||||
{
|
||||
static const std::string messageIdKey("id");
|
||||
|
||||
//
|
||||
// Publish to multiple channels. This let the consumer side
|
||||
// easily subscribe to all message of a certain type, without having
|
||||
// to do manipulations on the messages on the server side.
|
||||
//
|
||||
Json::Value channels;
|
||||
|
||||
channels.append(_channel);
|
||||
if (msg.isMember(messageIdKey))
|
||||
{
|
||||
channels.append(msg[messageIdKey]);
|
||||
}
|
||||
auto res = _cobra_connection.prePublish(channels, msg, true);
|
||||
auto msgId = res.first;
|
||||
|
||||
pushMessage(MessageKind::Message);
|
||||
|
||||
return msgId;
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::suspend()
|
||||
{
|
||||
pushMessage(MessageKind::Suspend);
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::resume()
|
||||
{
|
||||
pushMessage(MessageKind::Resume);
|
||||
}
|
||||
|
||||
bool CobraMetricsThreadedPublisher::isConnected() const
|
||||
{
|
||||
return _cobra_connection.isConnected();
|
||||
}
|
||||
|
||||
bool CobraMetricsThreadedPublisher::isAuthenticated() const
|
||||
{
|
||||
return _cobra_connection.isAuthenticated();
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -1,19 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
|
||||
set (IXCORE_SOURCES
|
||||
ixcore/utils/IXCoreLogger.cpp
|
||||
)
|
||||
|
||||
set (IXCORE_HEADERS
|
||||
ixcore/utils/IXCoreLogger.h
|
||||
)
|
||||
|
||||
add_library(ixcore STATIC
|
||||
${IXCORE_SOURCES}
|
||||
${IXCORE_HEADERS}
|
||||
)
|
||||
|
||||
target_include_directories( ixcore PUBLIC . )
|
@ -1,44 +0,0 @@
|
||||
/*
|
||||
* IXCoreLogger.cpp
|
||||
* Author: Thomas Wells, Benjamin Sergeant
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "ixcore/utils/IXCoreLogger.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
// Default do a no-op logger
|
||||
CoreLogger::LogFunc CoreLogger::_currentLogger = [](const char*, LogLevel) {};
|
||||
|
||||
void CoreLogger::log(const char* msg, LogLevel level)
|
||||
{
|
||||
_currentLogger(msg, level);
|
||||
}
|
||||
|
||||
void CoreLogger::debug(const std::string& msg)
|
||||
{
|
||||
_currentLogger(msg.c_str(), LogLevel::Debug);
|
||||
}
|
||||
|
||||
void CoreLogger::info(const std::string& msg)
|
||||
{
|
||||
_currentLogger(msg.c_str(), LogLevel::Info);
|
||||
}
|
||||
|
||||
void CoreLogger::warn(const std::string& msg)
|
||||
{
|
||||
_currentLogger(msg.c_str(), LogLevel::Warning);
|
||||
}
|
||||
|
||||
void CoreLogger::error(const std::string& msg)
|
||||
{
|
||||
_currentLogger(msg.c_str(), LogLevel::Error);
|
||||
}
|
||||
|
||||
void CoreLogger::critical(const std::string& msg)
|
||||
{
|
||||
_currentLogger(msg.c_str(), LogLevel::Critical);
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -1,44 +0,0 @@
|
||||
/*
|
||||
* IXCoreLogger.h
|
||||
* Author: Thomas Wells, Benjamin Sergeant
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
enum class LogLevel
|
||||
{
|
||||
Debug = 0,
|
||||
Info = 1,
|
||||
Warning = 2,
|
||||
Error = 3,
|
||||
Critical = 4
|
||||
};
|
||||
|
||||
class CoreLogger
|
||||
{
|
||||
public:
|
||||
using LogFunc = std::function<void(const char*, LogLevel level)>;
|
||||
|
||||
static void log(const char* msg, LogLevel level = LogLevel::Debug);
|
||||
|
||||
static void debug(const std::string& msg);
|
||||
static void info(const std::string& msg);
|
||||
static void warn(const std::string& msg);
|
||||
static void error(const std::string& msg);
|
||||
static void critical(const std::string& msg);
|
||||
|
||||
static void setLogFunction(LogFunc& func)
|
||||
{
|
||||
_currentLogger = func;
|
||||
}
|
||||
|
||||
private:
|
||||
static LogFunc _currentLogger;
|
||||
};
|
||||
|
||||
} // namespace ix
|
@ -1,49 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../CMake;${CMAKE_MODULE_PATH}")
|
||||
|
||||
set (IXCRYPTO_SOURCES
|
||||
ixcrypto/IXHMac.cpp
|
||||
ixcrypto/IXBase64.cpp
|
||||
ixcrypto/IXUuid.cpp
|
||||
ixcrypto/IXHash.cpp
|
||||
)
|
||||
|
||||
set (IXCRYPTO_HEADERS
|
||||
ixcrypto/IXHMac.h
|
||||
ixcrypto/IXBase64.h
|
||||
ixcrypto/IXUuid.h
|
||||
ixcrypto/IXHash.h
|
||||
)
|
||||
|
||||
add_library(ixcrypto STATIC
|
||||
${IXCRYPTO_SOURCES}
|
||||
${IXCRYPTO_HEADERS}
|
||||
)
|
||||
|
||||
set(IXCRYPTO_INCLUDE_DIRS
|
||||
.
|
||||
../ixcore)
|
||||
|
||||
target_include_directories( ixcrypto PUBLIC ${IXCRYPTO_INCLUDE_DIRS} )
|
||||
|
||||
# hmac computation needs a crypto library
|
||||
|
||||
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_TLS)
|
||||
if (USE_MBED_TLS)
|
||||
find_package(MbedTLS REQUIRED)
|
||||
target_include_directories(ixcrypto PUBLIC ${MBEDTLS_INCLUDE_DIRS})
|
||||
target_link_libraries(ixcrypto ${MBEDTLS_LIBRARIES})
|
||||
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_MBED_TLS)
|
||||
elseif (APPLE)
|
||||
elseif (WIN32)
|
||||
else()
|
||||
find_package(OpenSSL REQUIRED)
|
||||
add_definitions(${OPENSSL_DEFINITIONS})
|
||||
message(STATUS "OpenSSL: " ${OPENSSL_VERSION})
|
||||
include_directories(${OPENSSL_INCLUDE_DIR})
|
||||
target_link_libraries(ixcrypto ${OPENSSL_LIBRARIES})
|
||||
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_OPEN_SSL)
|
||||
endif()
|
@ -1,53 +0,0 @@
|
||||
/*
|
||||
* IXHMac.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXHMac.h"
|
||||
|
||||
#include "IXBase64.h"
|
||||
|
||||
#if defined(IXCRYPTO_USE_MBED_TLS)
|
||||
#include <mbedtls/md.h>
|
||||
#elif defined(__APPLE__)
|
||||
#include <CommonCrypto/CommonHMAC.h>
|
||||
#elif defined(IXCRYPTO_USE_OPEN_SSL)
|
||||
#include <openssl/hmac.h>
|
||||
#else
|
||||
#include <assert.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::string hmac(const std::string& data, const std::string& key)
|
||||
{
|
||||
constexpr size_t hashSize = 16;
|
||||
unsigned char hash[hashSize];
|
||||
|
||||
#if defined(IXCRYPTO_USE_MBED_TLS)
|
||||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_MD5),
|
||||
(unsigned char*) key.c_str(),
|
||||
key.size(),
|
||||
(unsigned char*) data.c_str(),
|
||||
data.size(),
|
||||
(unsigned char*) &hash);
|
||||
#elif defined(__APPLE__)
|
||||
CCHmac(kCCHmacAlgMD5, key.c_str(), key.size(), data.c_str(), data.size(), &hash);
|
||||
#elif defined(IXCRYPTO_USE_OPEN_SSL)
|
||||
HMAC(EVP_md5(),
|
||||
key.c_str(),
|
||||
(int) key.size(),
|
||||
(unsigned char*) data.c_str(),
|
||||
(int) data.size(),
|
||||
(unsigned char*) hash,
|
||||
nullptr);
|
||||
#else
|
||||
assert(false && "hmac not implemented on this platform");
|
||||
#endif
|
||||
|
||||
std::string hashString(reinterpret_cast<char*>(hash), hashSize);
|
||||
|
||||
return base64_encode(hashString, (uint32_t) hashString.size());
|
||||
}
|
||||
} // namespace ix
|
@ -1,30 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
|
||||
set (IXSENTRY_SOURCES
|
||||
ixsentry/IXSentryClient.cpp
|
||||
)
|
||||
|
||||
set (IXSENTRY_HEADERS
|
||||
ixsentry/IXSentryClient.h
|
||||
)
|
||||
|
||||
add_library(ixsentry STATIC
|
||||
${IXSENTRY_SOURCES}
|
||||
${IXSENTRY_HEADERS}
|
||||
)
|
||||
|
||||
find_package(JsonCpp)
|
||||
if (NOT JSONCPP_FOUND)
|
||||
set(JSONCPP_INCLUDE_DIRS ../third_party/jsoncpp)
|
||||
endif()
|
||||
|
||||
set(IXSENTRY_INCLUDE_DIRS
|
||||
.
|
||||
..
|
||||
../ixcore
|
||||
${JSONCPP_INCLUDE_DIRS})
|
||||
|
||||
target_include_directories( ixsentry PUBLIC ${IXSENTRY_INCLUDE_DIRS} )
|
@ -1,310 +0,0 @@
|
||||
/*
|
||||
* IXSentryClient.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXSentryClient.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
|
||||
#include <ixwebsocket/IXWebSocketVersion.h>
|
||||
#include <sstream>
|
||||
|
||||
|
||||
namespace ix
|
||||
{
|
||||
SentryClient::SentryClient(const std::string& dsn)
|
||||
: _dsn(dsn)
|
||||
, _validDsn(false)
|
||||
, _luaFrameRegex("\t([^/]+):([0-9]+): in function ['<]([^/]+)['>]")
|
||||
, _httpClient(std::make_shared<HttpClient>(true))
|
||||
{
|
||||
const std::regex dsnRegex("(http[s]?)://([^:]+):([^@]+)@([^/]+)/([0-9]+)");
|
||||
std::smatch group;
|
||||
|
||||
if (std::regex_match(dsn, group, dsnRegex) && group.size() == 6)
|
||||
{
|
||||
_validDsn = true;
|
||||
|
||||
const auto scheme = group.str(1);
|
||||
const auto host = group.str(4);
|
||||
const auto project_id = group.str(5);
|
||||
_url = scheme + "://" + host + "/api/" + project_id + "/store/";
|
||||
|
||||
_publicKey = group.str(2);
|
||||
_secretKey = group.str(3);
|
||||
}
|
||||
}
|
||||
|
||||
void SentryClient::setTLSOptions(const SocketTLSOptions& tlsOptions)
|
||||
{
|
||||
_httpClient->setTLSOptions(tlsOptions);
|
||||
}
|
||||
|
||||
int64_t SentryClient::getTimestamp()
|
||||
{
|
||||
const auto tp = std::chrono::system_clock::now();
|
||||
const auto dur = tp.time_since_epoch();
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(dur).count();
|
||||
}
|
||||
|
||||
std::string SentryClient::getIso8601()
|
||||
{
|
||||
std::time_t now;
|
||||
std::time(&now);
|
||||
char buf[sizeof("2011-10-08T07:07:09Z")];
|
||||
std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", std::gmtime(&now));
|
||||
return buf;
|
||||
}
|
||||
|
||||
std::string SentryClient::computeAuthHeader()
|
||||
{
|
||||
std::string securityHeader("Sentry sentry_version=5");
|
||||
securityHeader += ",sentry_client=ws/";
|
||||
securityHeader += std::string(IX_WEBSOCKET_VERSION);
|
||||
securityHeader += ",sentry_timestamp=" + std::to_string(SentryClient::getTimestamp());
|
||||
securityHeader += ",sentry_key=" + _publicKey;
|
||||
securityHeader += ",sentry_secret=" + _secretKey;
|
||||
|
||||
return securityHeader;
|
||||
}
|
||||
|
||||
Json::Value SentryClient::parseLuaStackTrace(const std::string& stack)
|
||||
{
|
||||
Json::Value frames;
|
||||
|
||||
// Split by lines
|
||||
std::string line;
|
||||
std::stringstream tokenStream(stack);
|
||||
|
||||
std::smatch group;
|
||||
|
||||
while (std::getline(tokenStream, line))
|
||||
{
|
||||
// MapScene.lua:2169: in function 'singleCB'
|
||||
if (std::regex_match(line, group, _luaFrameRegex))
|
||||
{
|
||||
const auto fileName = group.str(1);
|
||||
const auto linenoStr = group.str(2);
|
||||
const auto function = group.str(3);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << linenoStr;
|
||||
uint64_t lineno;
|
||||
ss >> lineno;
|
||||
|
||||
Json::Value frame;
|
||||
frame["lineno"] = Json::UInt64(lineno);
|
||||
frame["filename"] = fileName;
|
||||
frame["function"] = function;
|
||||
|
||||
frames.append(frame);
|
||||
}
|
||||
}
|
||||
|
||||
std::reverse(frames.begin(), frames.end());
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
std::string parseExceptionName(const std::string& stack)
|
||||
{
|
||||
// Split by lines
|
||||
std::string line;
|
||||
std::stringstream tokenStream(stack);
|
||||
|
||||
// Extract the first line
|
||||
std::getline(tokenStream, line);
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
std::string SentryClient::computePayload(const Json::Value& msg)
|
||||
{
|
||||
Json::Value payload;
|
||||
|
||||
//
|
||||
// "tags": [
|
||||
// [
|
||||
// "a",
|
||||
// "b"
|
||||
// ],
|
||||
// ]
|
||||
//
|
||||
Json::Value tags(Json::arrayValue);
|
||||
|
||||
payload["platform"] = "python";
|
||||
payload["sdk"]["name"] = "ws";
|
||||
payload["sdk"]["version"] = IX_WEBSOCKET_VERSION;
|
||||
payload["timestamp"] = SentryClient::getIso8601();
|
||||
|
||||
bool isNoisyTypes = msg["id"].asString() == "game_noisytypes_id";
|
||||
|
||||
std::string stackTraceFieldName = isNoisyTypes ? "traceback" : "stack";
|
||||
std::string stack;
|
||||
std::string message;
|
||||
|
||||
if (isNoisyTypes)
|
||||
{
|
||||
stack = msg["data"][stackTraceFieldName].asString();
|
||||
message = parseExceptionName(stack);
|
||||
}
|
||||
else // logging
|
||||
{
|
||||
if (msg["data"].isMember("info"))
|
||||
{
|
||||
stack = msg["data"]["info"][stackTraceFieldName].asString();
|
||||
message = msg["data"]["info"]["message"].asString();
|
||||
|
||||
if (msg["data"].isMember("tags"))
|
||||
{
|
||||
auto members = msg["data"]["tags"].getMemberNames();
|
||||
|
||||
for (auto member : members)
|
||||
{
|
||||
Json::Value tag;
|
||||
tag.append(member);
|
||||
tag.append(msg["data"]["tags"][member]);
|
||||
tags.append(tag);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg["data"]["info"].isMember("level_str"))
|
||||
{
|
||||
// https://docs.sentry.io/enriching-error-data/context/?platform=python#setting-the-level
|
||||
std::string level = msg["data"]["info"]["level_str"].asString();
|
||||
if (level == "critical")
|
||||
{
|
||||
level = "fatal";
|
||||
}
|
||||
payload["level"] = level;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
stack = msg["data"][stackTraceFieldName].asString();
|
||||
message = msg["data"]["message"].asString();
|
||||
}
|
||||
}
|
||||
|
||||
Json::Value exception;
|
||||
exception["stacktrace"]["frames"] = parseLuaStackTrace(stack);
|
||||
exception["value"] = message;
|
||||
|
||||
payload["exception"].append(exception);
|
||||
|
||||
Json::Value extra;
|
||||
extra["cobra_event"] = msg;
|
||||
|
||||
// Builtin tags
|
||||
Json::Value gameTag;
|
||||
gameTag.append("game");
|
||||
gameTag.append(msg["device"]["game"]);
|
||||
tags.append(gameTag);
|
||||
|
||||
Json::Value userIdTag;
|
||||
userIdTag.append("userid");
|
||||
userIdTag.append(msg["device"]["user_id"]);
|
||||
tags.append(userIdTag);
|
||||
|
||||
Json::Value environmentTag;
|
||||
environmentTag.append("environment");
|
||||
environmentTag.append(msg["device"]["environment"]);
|
||||
tags.append(environmentTag);
|
||||
|
||||
Json::Value clientVersionTag;
|
||||
clientVersionTag.append("client_version");
|
||||
clientVersionTag.append(msg["device"]["app_version"]);
|
||||
tags.append(clientVersionTag);
|
||||
|
||||
payload["tags"] = tags;
|
||||
|
||||
return _jsonWriter.write(payload);
|
||||
}
|
||||
|
||||
void SentryClient::send(
|
||||
const Json::Value& msg,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback)
|
||||
{
|
||||
auto args = _httpClient->createRequest();
|
||||
args->url = _url;
|
||||
args->verb = HttpClient::kPost;
|
||||
args->extraHeaders["X-Sentry-Auth"] = SentryClient::computeAuthHeader();
|
||||
args->connectTimeout = 60;
|
||||
args->transferTimeout = 5 * 60;
|
||||
args->followRedirects = true;
|
||||
args->verbose = verbose;
|
||||
args->logger = [](const std::string& msg) { CoreLogger::log(msg.c_str()); };
|
||||
args->body = computePayload(msg);
|
||||
|
||||
_httpClient->performRequest(args, onResponseCallback);
|
||||
}
|
||||
|
||||
// https://sentry.io/api/12345/minidump?sentry_key=abcdefgh");
|
||||
std::string SentryClient::computeUrl(const std::string& project, const std::string& key)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "https://sentry.io/api/" << project << "/minidump?sentry_key=" << key;
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
//
|
||||
// curl -v -X POST -F upload_file_minidump=@ws/crash.dmp
|
||||
// 'https://sentry.io/api/123456/minidump?sentry_key=12344567890'
|
||||
//
|
||||
void SentryClient::uploadMinidump(const std::string& sentryMetadata,
|
||||
const std::string& minidumpBytes,
|
||||
const std::string& project,
|
||||
const std::string& key,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback)
|
||||
{
|
||||
std::string multipartBoundary = _httpClient->generateMultipartBoundary();
|
||||
|
||||
auto args = _httpClient->createRequest();
|
||||
args->verb = HttpClient::kPost;
|
||||
args->connectTimeout = 60;
|
||||
args->transferTimeout = 5 * 60;
|
||||
args->followRedirects = true;
|
||||
args->verbose = verbose;
|
||||
args->multipartBoundary = multipartBoundary;
|
||||
args->logger = [](const std::string& msg) { CoreLogger::log(msg.c_str()); };
|
||||
|
||||
HttpFormDataParameters httpFormDataParameters;
|
||||
httpFormDataParameters["upload_file_minidump"] = minidumpBytes;
|
||||
|
||||
HttpParameters httpParameters;
|
||||
httpParameters["sentry"] = sentryMetadata;
|
||||
|
||||
args->url = computeUrl(project, key);
|
||||
args->body = _httpClient->serializeHttpFormDataParameters(
|
||||
multipartBoundary, httpFormDataParameters, httpParameters);
|
||||
|
||||
_httpClient->performRequest(args, onResponseCallback);
|
||||
}
|
||||
|
||||
void SentryClient::uploadPayload(const Json::Value& payload,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback)
|
||||
{
|
||||
auto args = _httpClient->createRequest();
|
||||
args->extraHeaders["X-Sentry-Auth"] = SentryClient::computeAuthHeader();
|
||||
args->verb = HttpClient::kPost;
|
||||
args->connectTimeout = 60;
|
||||
args->transferTimeout = 5 * 60;
|
||||
args->followRedirects = true;
|
||||
args->verbose = verbose;
|
||||
args->logger = [](const std::string& msg) { CoreLogger::log(msg.c_str()); };
|
||||
|
||||
args->url = _url;
|
||||
args->body = _jsonWriter.write(payload);
|
||||
|
||||
_httpClient->performRequest(args, onResponseCallback);
|
||||
}
|
||||
} // namespace ix
|
@ -1,70 +0,0 @@
|
||||
/*
|
||||
* IXSentryClient.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <ixwebsocket/IXHttpClient.h>
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <json/json.h>
|
||||
#include <memory>
|
||||
#include <regex>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class SentryClient
|
||||
{
|
||||
public:
|
||||
SentryClient(const std::string& dsn);
|
||||
~SentryClient() = default;
|
||||
|
||||
void send(const Json::Value& msg,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback);
|
||||
|
||||
void uploadMinidump(const std::string& sentryMetadata,
|
||||
const std::string& minidumpBytes,
|
||||
const std::string& project,
|
||||
const std::string& key,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback);
|
||||
|
||||
void uploadPayload(const Json::Value& payload,
|
||||
bool verbose,
|
||||
const OnResponseCallback& onResponseCallback);
|
||||
|
||||
Json::Value parseLuaStackTrace(const std::string& stack);
|
||||
|
||||
// Mostly for testing
|
||||
void setTLSOptions(const SocketTLSOptions& tlsOptions);
|
||||
|
||||
|
||||
private:
|
||||
int64_t getTimestamp();
|
||||
std::string computeAuthHeader();
|
||||
std::string getIso8601();
|
||||
std::string computePayload(const Json::Value& msg);
|
||||
|
||||
std::string computeUrl(const std::string& project, const std::string& key);
|
||||
|
||||
void displayReponse(HttpResponsePtr response);
|
||||
|
||||
std::string _dsn;
|
||||
bool _validDsn;
|
||||
std::string _url;
|
||||
|
||||
// Used for authentication with a header
|
||||
std::string _publicKey;
|
||||
std::string _secretKey;
|
||||
|
||||
Json::FastWriter _jsonWriter;
|
||||
|
||||
std::regex _luaFrameRegex;
|
||||
|
||||
std::shared_ptr<HttpClient> _httpClient;
|
||||
};
|
||||
|
||||
} // namespace ix
|
@ -1,35 +0,0 @@
|
||||
#
|
||||
# Author: Benjamin Sergeant
|
||||
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
#
|
||||
|
||||
set (IXSNAKE_SOURCES
|
||||
ixsnake/IXSnakeServer.cpp
|
||||
ixsnake/IXSnakeProtocol.cpp
|
||||
ixsnake/IXAppConfig.cpp
|
||||
ixsnake/IXRedisClient.cpp
|
||||
ixsnake/IXRedisServer.cpp
|
||||
)
|
||||
|
||||
set (IXSNAKE_HEADERS
|
||||
ixsnake/IXSnakeServer.h
|
||||
ixsnake/IXSnakeProtocol.h
|
||||
ixsnake/IXAppConfig.h
|
||||
ixsnake/IXRedisClient.h
|
||||
ixsnake/IXRedisServer.h
|
||||
)
|
||||
|
||||
add_library(ixsnake STATIC
|
||||
${IXSNAKE_SOURCES}
|
||||
${IXSNAKE_HEADERS}
|
||||
)
|
||||
|
||||
set(IXSNAKE_INCLUDE_DIRS
|
||||
.
|
||||
..
|
||||
../ixcore
|
||||
../ixcrypto
|
||||
../ixwebsocket
|
||||
../third_party)
|
||||
|
||||
target_include_directories( ixsnake PUBLIC ${IXSNAKE_INCLUDE_DIRS} )
|
@ -1,59 +0,0 @@
|
||||
/*
|
||||
* IXRedisClient.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class RedisClient
|
||||
{
|
||||
public:
|
||||
using OnRedisSubscribeResponseCallback = std::function<void(const std::string&)>;
|
||||
using OnRedisSubscribeCallback = std::function<void(const std::string&)>;
|
||||
|
||||
RedisClient()
|
||||
: _stop(false)
|
||||
{
|
||||
}
|
||||
~RedisClient() = default;
|
||||
|
||||
bool connect(const std::string& hostname, int port);
|
||||
|
||||
bool auth(const std::string& password, std::string& response);
|
||||
|
||||
// Publish / Subscribe
|
||||
bool publish(const std::string& channel, const std::string& message, std::string& errMsg);
|
||||
|
||||
bool subscribe(const std::string& channel,
|
||||
const OnRedisSubscribeResponseCallback& responseCallback,
|
||||
const OnRedisSubscribeCallback& callback);
|
||||
|
||||
// XADD
|
||||
std::string xadd(const std::string& channel,
|
||||
const std::string& message,
|
||||
std::string& errMsg);
|
||||
|
||||
std::string prepareXaddCommand(const std::string& stream, const std::string& message);
|
||||
|
||||
std::string readXaddReply(std::string& errMsg);
|
||||
|
||||
bool sendCommand(const std::string& commands, int commandsCount, std::string& errMsg);
|
||||
|
||||
void stop();
|
||||
|
||||
private:
|
||||
std::string writeString(const std::string& str);
|
||||
|
||||
std::unique_ptr<Socket> _socket;
|
||||
std::atomic<bool> _stop;
|
||||
};
|
||||
} // namespace ix
|
@ -1,285 +0,0 @@
|
||||
/*
|
||||
* IXRedisServer.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXRedisServer.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
#include <ixwebsocket/IXNetSystem.h>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketConnect.h>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
RedisServer::RedisServer(
|
||||
int port, const std::string& host, int backlog, size_t maxConnections, int addressFamily)
|
||||
: SocketServer(port, host, backlog, maxConnections, addressFamily)
|
||||
, _connectedClientsCount(0)
|
||||
, _stopHandlingConnections(false)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
RedisServer::~RedisServer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void RedisServer::stop()
|
||||
{
|
||||
stopAcceptingConnections();
|
||||
|
||||
_stopHandlingConnections = true;
|
||||
while (_connectedClientsCount != 0)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
_stopHandlingConnections = false;
|
||||
|
||||
SocketServer::stop();
|
||||
}
|
||||
|
||||
void RedisServer::handleConnection(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
_connectedClientsCount++;
|
||||
|
||||
while (!_stopHandlingConnections)
|
||||
{
|
||||
std::vector<std::string> tokens;
|
||||
if (!parseRequest(socket, tokens))
|
||||
{
|
||||
if (_stopHandlingConnections)
|
||||
{
|
||||
logError("Cancellation requested");
|
||||
}
|
||||
else
|
||||
{
|
||||
logError("Error parsing request");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
bool success = false;
|
||||
|
||||
// publish
|
||||
if (tokens[0] == "COMMAND")
|
||||
{
|
||||
success = handleCommand(socket, tokens);
|
||||
}
|
||||
else if (tokens[0] == "PUBLISH")
|
||||
{
|
||||
success = handlePublish(socket, tokens);
|
||||
}
|
||||
else if (tokens[0] == "SUBSCRIBE")
|
||||
{
|
||||
success = handleSubscribe(socket, tokens);
|
||||
}
|
||||
|
||||
if (!success)
|
||||
{
|
||||
if (_stopHandlingConnections)
|
||||
{
|
||||
logError("Cancellation requested");
|
||||
}
|
||||
else
|
||||
{
|
||||
logError("Error processing request for command: " + tokens[0]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
cleanupSubscribers(socket);
|
||||
|
||||
logInfo("Connection closed for connection id " + connectionState->getId());
|
||||
connectionState->setTerminated();
|
||||
|
||||
_connectedClientsCount--;
|
||||
}
|
||||
|
||||
void RedisServer::cleanupSubscribers(std::unique_ptr<Socket>& socket)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
|
||||
for (auto&& it : _subscribers)
|
||||
{
|
||||
it.second.erase(socket.get());
|
||||
}
|
||||
|
||||
for (auto it : _subscribers)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Subscription id: " << it.first << " #subscribers: " << it.second.size();
|
||||
|
||||
logInfo(ss.str());
|
||||
}
|
||||
}
|
||||
|
||||
size_t RedisServer::getConnectedClientsCount()
|
||||
{
|
||||
return _connectedClientsCount;
|
||||
}
|
||||
|
||||
bool RedisServer::startsWith(const std::string& str, const std::string& start)
|
||||
{
|
||||
return str.compare(0, start.length(), start) == 0;
|
||||
}
|
||||
|
||||
std::string RedisServer::writeString(const std::string& str)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "$";
|
||||
ss << str.size();
|
||||
ss << "\r\n";
|
||||
ss << str;
|
||||
ss << "\r\n";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool RedisServer::parseRequest(std::unique_ptr<Socket>& socket,
|
||||
std::vector<std::string>& tokens)
|
||||
{
|
||||
// Parse first line
|
||||
auto cb = makeCancellationRequestWithTimeout(30, _stopHandlingConnections);
|
||||
auto lineResult = socket->readLine(cb);
|
||||
auto lineValid = lineResult.first;
|
||||
auto line = lineResult.second;
|
||||
|
||||
if (!lineValid) return false;
|
||||
|
||||
std::string str = line.substr(1);
|
||||
std::stringstream ss;
|
||||
ss << str;
|
||||
int count;
|
||||
ss >> count;
|
||||
|
||||
for (int i = 0; i < count; ++i)
|
||||
{
|
||||
auto lineResult = socket->readLine(cb);
|
||||
auto lineValid = lineResult.first;
|
||||
auto line = lineResult.second;
|
||||
|
||||
if (!lineValid) return false;
|
||||
|
||||
int stringSize;
|
||||
std::stringstream ss;
|
||||
ss << line.substr(1, line.size() - 1);
|
||||
ss >> stringSize;
|
||||
|
||||
auto readResult = socket->readBytes(stringSize, nullptr, nullptr);
|
||||
|
||||
if (!readResult.first) return false;
|
||||
|
||||
// read last 2 bytes (\r\n)
|
||||
char c;
|
||||
socket->readByte(&c, nullptr);
|
||||
socket->readByte(&c, nullptr);
|
||||
|
||||
tokens.push_back(readResult.second);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedisServer::handleCommand(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 1) return false;
|
||||
|
||||
auto cb = makeCancellationRequestWithTimeout(30, _stopHandlingConnections);
|
||||
std::stringstream ss;
|
||||
|
||||
// return 2 nested arrays
|
||||
ss << "*2\r\n";
|
||||
|
||||
//
|
||||
// publish
|
||||
//
|
||||
ss << "*6\r\n";
|
||||
ss << writeString("publish"); // 1
|
||||
ss << ":3\r\n"; // 2
|
||||
ss << "*0\r\n"; // 3
|
||||
ss << ":1\r\n"; // 4
|
||||
ss << ":2\r\n"; // 5
|
||||
ss << ":1\r\n"; // 6
|
||||
|
||||
//
|
||||
// subscribe
|
||||
//
|
||||
ss << "*6\r\n";
|
||||
ss << writeString("subscribe"); // 1
|
||||
ss << ":2\r\n"; // 2
|
||||
ss << "*0\r\n"; // 3
|
||||
ss << ":1\r\n"; // 4
|
||||
ss << ":1\r\n"; // 5
|
||||
ss << ":1\r\n"; // 6
|
||||
|
||||
socket->writeBytes(ss.str(), cb);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedisServer::handleSubscribe(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 2) return false;
|
||||
|
||||
auto cb = makeCancellationRequestWithTimeout(30, _stopHandlingConnections);
|
||||
std::string channel = tokens[1];
|
||||
|
||||
// Respond
|
||||
socket->writeBytes("*3\r\n", cb);
|
||||
socket->writeBytes(writeString("subscribe"), cb);
|
||||
socket->writeBytes(writeString(channel), cb);
|
||||
socket->writeBytes(":1\r\n", cb);
|
||||
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
_subscribers[channel].insert(socket.get());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedisServer::handlePublish(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 3) return false;
|
||||
|
||||
auto cb = makeCancellationRequestWithTimeout(30, _stopHandlingConnections);
|
||||
std::string channel = tokens[1];
|
||||
std::string data = tokens[2];
|
||||
|
||||
// now dispatch the message to subscribers (write custom method)
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
auto it = _subscribers.find(channel);
|
||||
if (it == _subscribers.end())
|
||||
{
|
||||
// return the number of clients that received the message, 0 in that case
|
||||
socket->writeBytes(":0\r\n", cb);
|
||||
return true;
|
||||
}
|
||||
|
||||
auto subscribers = it->second;
|
||||
for (auto jt : subscribers)
|
||||
{
|
||||
jt->writeBytes("*3\r\n", cb);
|
||||
jt->writeBytes(writeString("message"), cb);
|
||||
jt->writeBytes(writeString(channel), cb);
|
||||
jt->writeBytes(writeString(data), cb);
|
||||
}
|
||||
|
||||
// return the number of clients that received the message.
|
||||
std::stringstream ss;
|
||||
ss << ":" << std::to_string(subscribers.size()) << "\r\n";
|
||||
socket->writeBytes(ss.str(), cb);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -1,64 +0,0 @@
|
||||
/*
|
||||
* IXRedisServer.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXSocket.h"
|
||||
#include "IXSocketServer.h"
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility> // pair
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class RedisServer final : public SocketServer
|
||||
{
|
||||
public:
|
||||
RedisServer(int port = SocketServer::kDefaultPort,
|
||||
const std::string& host = SocketServer::kDefaultHost,
|
||||
int backlog = SocketServer::kDefaultTcpBacklog,
|
||||
size_t maxConnections = SocketServer::kDefaultMaxConnections,
|
||||
int addressFamily = SocketServer::kDefaultAddressFamily);
|
||||
virtual ~RedisServer();
|
||||
virtual void stop() final;
|
||||
|
||||
private:
|
||||
// Member variables
|
||||
std::atomic<int> _connectedClientsCount;
|
||||
|
||||
// Subscribers
|
||||
// We could store connection states in there, to add better debugging
|
||||
// since a connection state has a readable ID
|
||||
std::map<std::string, std::set<Socket*>> _subscribers;
|
||||
std::mutex _mutex;
|
||||
|
||||
std::atomic<bool> _stopHandlingConnections;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(std::unique_ptr<Socket>,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
|
||||
bool startsWith(const std::string& str, const std::string& start);
|
||||
std::string writeString(const std::string& str);
|
||||
|
||||
bool parseRequest(std::unique_ptr<Socket>& socket, std::vector<std::string>& tokens);
|
||||
|
||||
bool handlePublish(std::unique_ptr<Socket>& socket, const std::vector<std::string>& tokens);
|
||||
|
||||
bool handleSubscribe(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens);
|
||||
|
||||
bool handleCommand(std::unique_ptr<Socket>& socket, const std::vector<std::string>& tokens);
|
||||
|
||||
void cleanupSubscribers(std::unique_ptr<Socket>& socket);
|
||||
};
|
||||
} // namespace ix
|
@ -1,61 +0,0 @@
|
||||
/*
|
||||
* IXSnakeConnectionState.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXRedisClient.h"
|
||||
#include <future>
|
||||
#include <ixwebsocket/IXConnectionState.h>
|
||||
#include <string>
|
||||
|
||||
namespace snake
|
||||
{
|
||||
class SnakeConnectionState : public ix::ConnectionState
|
||||
{
|
||||
public:
|
||||
std::string getNonce()
|
||||
{
|
||||
return _nonce;
|
||||
}
|
||||
|
||||
void setNonce(const std::string& nonce)
|
||||
{
|
||||
_nonce = nonce;
|
||||
}
|
||||
|
||||
std::string appkey()
|
||||
{
|
||||
return _appkey;
|
||||
}
|
||||
void setAppkey(const std::string& appkey)
|
||||
{
|
||||
_appkey = appkey;
|
||||
}
|
||||
|
||||
std::string role()
|
||||
{
|
||||
return _role;
|
||||
}
|
||||
void setRole(const std::string& role)
|
||||
{
|
||||
_role = role;
|
||||
}
|
||||
|
||||
ix::RedisClient& redisClient()
|
||||
{
|
||||
return _redisClient;
|
||||
}
|
||||
|
||||
std::future<void> fut;
|
||||
|
||||
private:
|
||||
std::string _nonce;
|
||||
std::string _role;
|
||||
std::string _appkey;
|
||||
|
||||
ix::RedisClient _redisClient;
|
||||
};
|
||||
} // namespace snake
|
@ -1,26 +0,0 @@
|
||||
/*
|
||||
* IXSnakeProtocol.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class WebSocket;
|
||||
}
|
||||
|
||||
namespace snake
|
||||
{
|
||||
class SnakeConnectionState;
|
||||
struct AppConfig;
|
||||
|
||||
void processCobraMessage(std::shared_ptr<SnakeConnectionState> state,
|
||||
std::shared_ptr<ix::WebSocket> ws,
|
||||
const AppConfig& appConfig,
|
||||
const std::string& str);
|
||||
} // namespace snake
|
@ -1,145 +0,0 @@
|
||||
/*
|
||||
* IXSnakeServer.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXSnakeServer.h"
|
||||
|
||||
#include "IXAppConfig.h"
|
||||
#include "IXSnakeConnectionState.h"
|
||||
#include "IXSnakeProtocol.h"
|
||||
#include <iostream>
|
||||
#include <ixcore/utils/IXCoreLogger.h>
|
||||
#include <sstream>
|
||||
|
||||
|
||||
namespace snake
|
||||
{
|
||||
SnakeServer::SnakeServer(const AppConfig& appConfig)
|
||||
: _appConfig(appConfig)
|
||||
, _server(appConfig.port, appConfig.hostname)
|
||||
{
|
||||
_server.setTLSOptions(appConfig.socketTLSOptions);
|
||||
|
||||
if (appConfig.disablePong)
|
||||
{
|
||||
_server.disablePong();
|
||||
}
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "Listening on " << appConfig.hostname << ":" << appConfig.port;
|
||||
ix::CoreLogger::log(ss.str().c_str());
|
||||
}
|
||||
|
||||
//
|
||||
// Parse appkey from this uri. Won't work if multiple args are present in the uri
|
||||
// Uri: /v2?appkey=FC2F10139A2BAc53BB72D9db967b024f
|
||||
//
|
||||
std::string SnakeServer::parseAppKey(const std::string& path)
|
||||
{
|
||||
std::string::size_type idx;
|
||||
|
||||
idx = path.rfind('=');
|
||||
if (idx != std::string::npos)
|
||||
{
|
||||
std::string appkey = path.substr(idx + 1);
|
||||
return appkey;
|
||||
}
|
||||
else
|
||||
{
|
||||
return std::string();
|
||||
}
|
||||
}
|
||||
|
||||
bool SnakeServer::run()
|
||||
{
|
||||
auto factory = []() -> std::shared_ptr<ix::ConnectionState> {
|
||||
return std::make_shared<SnakeConnectionState>();
|
||||
};
|
||||
_server.setConnectionStateFactory(factory);
|
||||
|
||||
_server.setOnConnectionCallback(
|
||||
[this](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ix::ConnectionState> connectionState) {
|
||||
auto state = std::dynamic_pointer_cast<SnakeConnectionState>(connectionState);
|
||||
|
||||
webSocket->setOnMessageCallback(
|
||||
[this, webSocket, state](const ix::WebSocketMessagePtr& msg) {
|
||||
std::stringstream ss;
|
||||
ix::LogLevel logLevel = ix::LogLevel::Debug;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
ss << "New connection" << std::endl;
|
||||
ss << "id: " << state->getId() << std::endl;
|
||||
ss << "Uri: " << msg->openInfo.uri << std::endl;
|
||||
ss << "Headers:" << std::endl;
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
ss << it.first << ": " << it.second << std::endl;
|
||||
}
|
||||
|
||||
std::string appkey = parseAppKey(msg->openInfo.uri);
|
||||
state->setAppkey(appkey);
|
||||
|
||||
// Connect to redis first
|
||||
if (!state->redisClient().connect(_appConfig.redisHosts[0],
|
||||
_appConfig.redisPort))
|
||||
{
|
||||
ss << "Cannot connect to redis host" << std::endl;
|
||||
logLevel = ix::LogLevel::Error;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
ss << "Closed connection"
|
||||
<< " code " << msg->closeInfo.code << " reason "
|
||||
<< msg->closeInfo.reason << std::endl;
|
||||
}
|
||||
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;
|
||||
logLevel = ix::LogLevel::Error;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
ss << "Received message fragment" << std::endl;
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
ss << "Received " << msg->wireSize << " bytes" << std::endl;
|
||||
processCobraMessage(state, webSocket, _appConfig, msg->str);
|
||||
}
|
||||
|
||||
ix::CoreLogger::log(ss.str().c_str(), logLevel);
|
||||
});
|
||||
});
|
||||
|
||||
auto res = _server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
std::cerr << res.second << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
_server.start();
|
||||
return true;
|
||||
}
|
||||
|
||||
void SnakeServer::runForever()
|
||||
{
|
||||
if (run())
|
||||
{
|
||||
_server.wait();
|
||||
}
|
||||
}
|
||||
|
||||
void SnakeServer::stop()
|
||||
{
|
||||
_server.stop();
|
||||
}
|
||||
} // namespace snake
|
@ -1,44 +0,0 @@
|
||||
/*
|
||||
* IXBench.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXBench.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
Bench::Bench(const std::string& description)
|
||||
: _description(description)
|
||||
, _start(std::chrono::high_resolution_clock::now())
|
||||
, _reported(false)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
Bench::~Bench()
|
||||
{
|
||||
if (!_reported)
|
||||
{
|
||||
report();
|
||||
}
|
||||
}
|
||||
|
||||
void Bench::report()
|
||||
{
|
||||
auto now = std::chrono::high_resolution_clock::now();
|
||||
auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now - _start);
|
||||
|
||||
_ms = milliseconds.count();
|
||||
std::cerr << _description << " completed in " << _ms << "ms" << std::endl;
|
||||
|
||||
_reported = true;
|
||||
}
|
||||
|
||||
uint64_t Bench::getDuration() const
|
||||
{
|
||||
return _ms;
|
||||
}
|
||||
} // namespace ix
|
@ -1,28 +0,0 @@
|
||||
/*
|
||||
* IXBench.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include <chrono>
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class Bench
|
||||
{
|
||||
public:
|
||||
Bench(const std::string& description);
|
||||
~Bench();
|
||||
|
||||
void report();
|
||||
uint64_t getDuration() const;
|
||||
|
||||
private:
|
||||
std::string _description;
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> _start;
|
||||
uint64_t _ms;
|
||||
bool _reported;
|
||||
};
|
||||
} // namespace ix
|
@ -6,20 +6,18 @@
|
||||
|
||||
#include "IXCancellationRequest.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
CancellationRequest makeCancellationRequestWithTimeout(
|
||||
int secs, std::atomic<bool>& requestInitCancellation)
|
||||
CancellationRequest makeCancellationRequestWithTimeout(int secs,
|
||||
std::atomic<bool>& requestInitCancellation)
|
||||
{
|
||||
assert(secs > 0);
|
||||
|
||||
auto start = std::chrono::system_clock::now();
|
||||
auto timeout = std::chrono::seconds(secs);
|
||||
|
||||
auto isCancellationRequested = [&requestInitCancellation, start, timeout]() -> bool {
|
||||
auto isCancellationRequested = [&requestInitCancellation, start, timeout]() -> bool
|
||||
{
|
||||
// Was an explicit cancellation requested ?
|
||||
if (requestInitCancellation) return true;
|
||||
|
||||
@ -32,4 +30,4 @@ namespace ix
|
||||
|
||||
return isCancellationRequested;
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -6,13 +6,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <atomic>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
using CancellationRequest = std::function<bool()>;
|
||||
|
||||
CancellationRequest makeCancellationRequestWithTimeout(
|
||||
int seconds, std::atomic<bool>& requestInitCancellation);
|
||||
} // namespace ix
|
||||
CancellationRequest makeCancellationRequestWithTimeout(int seconds,
|
||||
std::atomic<bool>& requestInitCancellation);
|
||||
}
|
||||
|
||||
|
@ -10,8 +10,7 @@ namespace ix
|
||||
{
|
||||
std::atomic<uint64_t> ConnectionState::_globalId(0);
|
||||
|
||||
ConnectionState::ConnectionState()
|
||||
: _terminated(false)
|
||||
ConnectionState::ConnectionState() : _terminated(false)
|
||||
{
|
||||
computeId();
|
||||
}
|
||||
@ -40,4 +39,5 @@ namespace ix
|
||||
{
|
||||
_terminated = true;
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
@ -6,15 +6,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class ConnectionState
|
||||
{
|
||||
class ConnectionState {
|
||||
public:
|
||||
ConnectionState();
|
||||
virtual ~ConnectionState() = default;
|
||||
@ -33,4 +32,6 @@ namespace ix
|
||||
|
||||
static std::atomic<uint64_t> _globalId;
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
||||
|
@ -4,38 +4,35 @@
|
||||
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
//
|
||||
// On Windows Universal Platform (uwp), gai_strerror defaults behavior is to returns wchar_t
|
||||
// which is different from all other platforms. We want the non unicode version.
|
||||
// See https://github.com/microsoft/vcpkg/pull/11030
|
||||
// We could do this in IXNetSystem.cpp but so far we are only using gai_strerror in here.
|
||||
//
|
||||
#ifdef _UNICODE
|
||||
#undef _UNICODE
|
||||
#endif
|
||||
#ifdef UNICODE
|
||||
#undef UNICODE
|
||||
#endif
|
||||
|
||||
#include "IXDNSLookup.h"
|
||||
|
||||
#include "IXNetSystem.h"
|
||||
#include <chrono>
|
||||
|
||||
#include <string.h>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
const int64_t DNSLookup::kDefaultWait = 1; // ms
|
||||
const int64_t DNSLookup::kDefaultWait = 10; // ms
|
||||
|
||||
DNSLookup::DNSLookup(const std::string& hostname, int port, int64_t wait)
|
||||
: _hostname(hostname)
|
||||
, _port(port)
|
||||
, _wait(wait)
|
||||
, _res(nullptr)
|
||||
, _done(false)
|
||||
std::atomic<uint64_t> DNSLookup::_nextId(0);
|
||||
std::set<uint64_t> DNSLookup::_activeJobs;
|
||||
std::mutex DNSLookup::_activeJobsMutex;
|
||||
|
||||
DNSLookup::DNSLookup(const std::string& hostname, int port, int64_t wait) :
|
||||
_port(port),
|
||||
_wait(wait),
|
||||
_res(nullptr),
|
||||
_done(false),
|
||||
_id(_nextId++)
|
||||
{
|
||||
;
|
||||
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,
|
||||
@ -51,7 +48,8 @@ namespace ix
|
||||
std::string sport = std::to_string(port);
|
||||
|
||||
struct addrinfo* res;
|
||||
int getaddrinfo_result = getaddrinfo(hostname.c_str(), sport.c_str(), &hints, &res);
|
||||
int getaddrinfo_result = getaddrinfo(hostname.c_str(), sport.c_str(),
|
||||
&hints, &res);
|
||||
if (getaddrinfo_result)
|
||||
{
|
||||
errMsg = gai_strerror(getaddrinfo_result);
|
||||
@ -62,29 +60,29 @@ namespace ix
|
||||
|
||||
struct addrinfo* DNSLookup::resolve(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested,
|
||||
bool cancellable)
|
||||
bool blocking)
|
||||
{
|
||||
return cancellable ? resolveCancellable(errMsg, isCancellationRequested)
|
||||
: resolveUnCancellable(errMsg, isCancellationRequested);
|
||||
return blocking ? resolveBlocking(errMsg, isCancellationRequested)
|
||||
: resolveAsync(errMsg, isCancellationRequested);
|
||||
}
|
||||
|
||||
struct addrinfo* DNSLookup::resolveUnCancellable(
|
||||
std::string& errMsg, const CancellationRequest& isCancellationRequested)
|
||||
struct addrinfo* DNSLookup::resolveBlocking(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
errMsg = "no error";
|
||||
|
||||
// Maybe a cancellation request got in before the background thread terminated ?
|
||||
if (isCancellationRequested())
|
||||
if (isCancellationRequested && isCancellationRequested())
|
||||
{
|
||||
errMsg = "cancellation requested";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return getAddrInfo(_hostname, _port, errMsg);
|
||||
return getAddrInfo(getHostname(), _port, errMsg);
|
||||
}
|
||||
|
||||
struct addrinfo* DNSLookup::resolveCancellable(
|
||||
std::string& errMsg, const CancellationRequest& isCancellationRequested)
|
||||
struct addrinfo* DNSLookup::resolveAsync(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
errMsg = "no error";
|
||||
|
||||
@ -96,31 +94,33 @@ 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
|
||||
//
|
||||
auto ptr = shared_from_this();
|
||||
std::weak_ptr<DNSLookup> self(ptr);
|
||||
_thread = std::thread(&DNSLookup::run, this, _id, getHostname(), _port);
|
||||
_thread.detach();
|
||||
|
||||
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();
|
||||
std::unique_lock<std::mutex> lock(_conditionVariableMutex);
|
||||
|
||||
while (!_done)
|
||||
{
|
||||
// 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));
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Were we cancelled ?
|
||||
if (isCancellationRequested())
|
||||
if (isCancellationRequested && isCancellationRequested())
|
||||
{
|
||||
errMsg = "cancellation requested";
|
||||
return nullptr;
|
||||
@ -128,7 +128,7 @@ namespace ix
|
||||
}
|
||||
|
||||
// Maybe a cancellation request got in before the bg terminated ?
|
||||
if (isCancellationRequested())
|
||||
if (isCancellationRequested && isCancellationRequested())
|
||||
{
|
||||
errMsg = "cancellation requested";
|
||||
return nullptr;
|
||||
@ -138,9 +138,7 @@ namespace ix
|
||||
return getRes();
|
||||
}
|
||||
|
||||
void DNSLookup::run(std::weak_ptr<DNSLookup> self,
|
||||
std::string hostname,
|
||||
int port) // thread runner
|
||||
void DNSLookup::run(uint64_t id, const 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
|
||||
@ -148,14 +146,33 @@ namespace ix
|
||||
std::string errMsg;
|
||||
struct addrinfo* res = getAddrInfo(hostname, port, errMsg);
|
||||
|
||||
if (auto lock = self.lock())
|
||||
// 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)
|
||||
{
|
||||
// Copy result into the member variables
|
||||
setRes(res);
|
||||
setErrMsg(errMsg);
|
||||
|
||||
_done = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// 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)
|
||||
@ -181,4 +198,4 @@ namespace ix
|
||||
std::lock_guard<std::mutex> lock(_resMutex);
|
||||
return _res;
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -11,37 +11,42 @@
|
||||
#pragma once
|
||||
|
||||
#include "IXCancellationRequest.h"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <set>
|
||||
|
||||
struct addrinfo;
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class DNSLookup : public std::enable_shared_from_this<DNSLookup>
|
||||
{
|
||||
class DNSLookup {
|
||||
public:
|
||||
DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
|
||||
~DNSLookup() = default;
|
||||
DNSLookup(const std::string& hostname,
|
||||
int port,
|
||||
int64_t wait = DNSLookup::kDefaultWait);
|
||||
~DNSLookup();
|
||||
|
||||
struct addrinfo* resolve(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested,
|
||||
bool cancellable = true);
|
||||
bool blocking = false);
|
||||
|
||||
private:
|
||||
struct addrinfo* resolveCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveUnCancellable(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveAsync(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
struct addrinfo* resolveBlocking(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
|
||||
static struct addrinfo* getAddrInfo(const std::string& hostname,
|
||||
int port,
|
||||
std::string& errMsg);
|
||||
|
||||
void run(std::weak_ptr<DNSLookup> self, std::string hostname, int port); // thread runner
|
||||
void run(uint64_t id, const std::string& hostname, int port); // thread runner
|
||||
|
||||
void setHostname(const std::string& hostname);
|
||||
const std::string& getHostname();
|
||||
|
||||
void setErrMsg(const std::string& errMsg);
|
||||
const std::string& getErrMsg();
|
||||
@ -50,9 +55,10 @@ 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;
|
||||
@ -61,5 +67,15 @@ 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
|
||||
}
|
||||
|
@ -1,25 +0,0 @@
|
||||
/*
|
||||
* 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 = (retry_count < 26) ? (std::pow(2, retry_count) * 100) : 0;
|
||||
|
||||
if (wait_time > maxWaitBetweenReconnectionRetries || wait_time == 0)
|
||||
{
|
||||
wait_time = maxWaitBetweenReconnectionRetries;
|
||||
}
|
||||
|
||||
return wait_time;
|
||||
}
|
||||
} // namespace ix
|
@ -1,15 +0,0 @@
|
||||
/*
|
||||
* 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
|
@ -1,168 +0,0 @@
|
||||
/*
|
||||
* 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::pair<std::string, int> Http::parseStatusLine(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 httpVersion;
|
||||
if (tokens.size() >= 1)
|
||||
{
|
||||
httpVersion = trim(tokens[0]);
|
||||
}
|
||||
|
||||
int statusCode = -1;
|
||||
if (tokens.size() >= 2)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << trim(tokens[1]);
|
||||
ss >> statusCode;
|
||||
}
|
||||
|
||||
return std::make_pair(httpVersion, statusCode);
|
||||
}
|
||||
|
||||
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::unique_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::unique_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);
|
||||
}
|
||||
} // namespace ix
|
@ -1,126 +0,0 @@
|
||||
/*
|
||||
* IXHttp.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXProgressCallback.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
|
||||
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::unordered_map<std::string, std::string>;
|
||||
using HttpFormDataParameters = std::unordered_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;
|
||||
std::string multipartBoundary;
|
||||
int connectTimeout = 60;
|
||||
int transferTimeout = 1800;
|
||||
bool followRedirects = true;
|
||||
int maxRedirects = 5;
|
||||
bool verbose = false;
|
||||
bool compress = true;
|
||||
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::unique_ptr<Socket>& socket);
|
||||
static bool sendResponse(HttpResponsePtr response, std::unique_ptr<Socket>& socket);
|
||||
|
||||
static std::pair<std::string, int> parseStatusLine(const std::string& line);
|
||||
static std::tuple<std::string, std::string, std::string> parseRequestLine(
|
||||
const std::string& line);
|
||||
static std::string trim(const std::string& str);
|
||||
};
|
||||
} // namespace ix
|
@ -5,17 +5,15 @@
|
||||
*/
|
||||
|
||||
#include "IXHttpClient.h"
|
||||
|
||||
#include "IXSocketFactory.h"
|
||||
#include "IXUrlParser.h"
|
||||
#include "IXUserAgent.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include <assert.h>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <random>
|
||||
#include "IXSocketFactory.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
#include <zlib.h>
|
||||
|
||||
namespace ix
|
||||
@ -23,118 +21,29 @@ namespace ix
|
||||
const std::string HttpClient::kPost = "POST";
|
||||
const std::string HttpClient::kGet = "GET";
|
||||
const std::string HttpClient::kHead = "HEAD";
|
||||
const std::string HttpClient::kDel = "DEL";
|
||||
const std::string HttpClient::kPut = "PUT";
|
||||
const std::string HttpClient::kPatch = "PATCH";
|
||||
|
||||
HttpClient::HttpClient(bool async)
|
||||
: _async(async)
|
||||
, _stop(false)
|
||||
, _forceBody(false)
|
||||
HttpClient::HttpClient()
|
||||
{
|
||||
if (!_async) return;
|
||||
|
||||
_thread = std::thread(&HttpClient::run, this);
|
||||
}
|
||||
|
||||
HttpClient::~HttpClient()
|
||||
{
|
||||
if (!_thread.joinable()) return;
|
||||
|
||||
_stop = true;
|
||||
_condition.notify_one();
|
||||
_thread.join();
|
||||
}
|
||||
|
||||
void HttpClient::setTLSOptions(const SocketTLSOptions& tlsOptions)
|
||||
HttpResponse HttpClient::request(
|
||||
const std::string& url,
|
||||
const std::string& verb,
|
||||
const std::string& body,
|
||||
const HttpRequestArgs& args,
|
||||
int redirects)
|
||||
{
|
||||
_tlsOptions = tlsOptions;
|
||||
}
|
||||
|
||||
void HttpClient::setForceBody(bool value)
|
||||
{
|
||||
_forceBody = value;
|
||||
}
|
||||
|
||||
HttpRequestArgsPtr HttpClient::createRequest(const std::string& url, const std::string& verb)
|
||||
{
|
||||
auto request = std::make_shared<HttpRequestArgs>();
|
||||
request->url = url;
|
||||
request->verb = verb;
|
||||
return request;
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
// acquire lock
|
||||
std::unique_lock<std::mutex> lock(_queueMutex);
|
||||
|
||||
// add the task
|
||||
_queue.push(std::make_pair(args, onResponseCallback));
|
||||
} // release lock
|
||||
|
||||
// wake up one thread
|
||||
_condition.notify_one();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void HttpClient::run()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
HttpRequestArgsPtr args;
|
||||
OnResponseCallback onResponseCallback;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(_queueMutex);
|
||||
|
||||
while (!_stop && _queue.empty())
|
||||
{
|
||||
_condition.wait(lock);
|
||||
}
|
||||
|
||||
if (_stop) return;
|
||||
|
||||
auto p = _queue.front();
|
||||
_queue.pop();
|
||||
|
||||
args = p.first;
|
||||
onResponseCallback = p.second;
|
||||
}
|
||||
|
||||
if (_stop) return;
|
||||
|
||||
HttpResponsePtr response = request(args->url, args->verb, args->body, args);
|
||||
onResponseCallback(response);
|
||||
|
||||
if (_stop) return;
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::request(const std::string& url,
|
||||
const std::string& verb,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args,
|
||||
int redirects)
|
||||
{
|
||||
// We only have one socket connection, so we cannot
|
||||
// make multiple requests concurrently.
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
|
||||
uint64_t uploadSize = 0;
|
||||
uint64_t downloadSize = 0;
|
||||
int code = 0;
|
||||
WebSocketHttpHeaders headers;
|
||||
std::string payload;
|
||||
std::string description;
|
||||
|
||||
std::string protocol, host, path, query;
|
||||
int port;
|
||||
@ -143,79 +52,48 @@ namespace ix
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Cannot parse url: " << url;
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::UrlMalformed,
|
||||
headers,
|
||||
payload,
|
||||
ss.str(),
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::UrlMalformed,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
bool tls = protocol == "https";
|
||||
std::string errorMsg;
|
||||
_socket = createSocket(tls, -1, errorMsg, _tlsOptions);
|
||||
_socket = createSocket(tls, errorMsg);
|
||||
|
||||
if (!_socket)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::CannotCreateSocket,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::CannotCreateSocket,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Build request string
|
||||
std::stringstream ss;
|
||||
ss << verb << " " << path << " HTTP/1.1\r\n";
|
||||
ss << "Host: " << host << "\r\n";
|
||||
ss << "User-Agent: ixwebsocket/1.0.0" << "\r\n";
|
||||
ss << "Accept: */*" << "\r\n";
|
||||
|
||||
if (args->compress)
|
||||
if (args.compress)
|
||||
{
|
||||
ss << "Accept-Encoding: gzip"
|
||||
<< "\r\n";
|
||||
ss << "Accept-Encoding: gzip" << "\r\n";
|
||||
}
|
||||
|
||||
// Append extra headers
|
||||
for (auto&& it : args->extraHeaders)
|
||||
for (auto&& it : args.extraHeaders)
|
||||
{
|
||||
ss << it.first << ": " << it.second << "\r\n";
|
||||
}
|
||||
|
||||
// Set a default Accept header if none is present
|
||||
if (headers.find("Accept") == headers.end())
|
||||
{
|
||||
ss << "Accept: */*"
|
||||
<< "\r\n";
|
||||
}
|
||||
|
||||
// Set a default User agent if none is present
|
||||
if (headers.find("User-Agent") == headers.end())
|
||||
{
|
||||
ss << "User-Agent: " << userAgent() << "\r\n";
|
||||
}
|
||||
|
||||
if (verb == kPost || verb == kPut || verb == kPatch || _forceBody)
|
||||
if (verb == kPost)
|
||||
{
|
||||
ss << "Content-Length: " << body.size() << "\r\n";
|
||||
|
||||
// Set default Content-Type if unspecified
|
||||
if (args->extraHeaders.find("Content-Type") == args->extraHeaders.end())
|
||||
if (args.extraHeaders.find("Content-Type") == args.extraHeaders.end())
|
||||
{
|
||||
if (args->multipartBoundary.empty())
|
||||
{
|
||||
ss << "Content-Type: application/x-www-form-urlencoded"
|
||||
<< "\r\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Content-Type: multipart/form-data; boundary=" << args->multipartBoundary
|
||||
<< "\r\n";
|
||||
}
|
||||
ss << "Content-Type: application/x-www-form-urlencoded" << "\r\n";
|
||||
}
|
||||
ss << "\r\n";
|
||||
ss << body;
|
||||
@ -227,37 +105,35 @@ namespace ix
|
||||
|
||||
std::string req(ss.str());
|
||||
std::string errMsg;
|
||||
std::atomic<bool> requestInitCancellation(false);
|
||||
|
||||
// Make a cancellation object dealing with connection timeout
|
||||
auto isCancellationRequested =
|
||||
makeCancellationRequestWithTimeout(args->connectTimeout, _stop);
|
||||
makeCancellationRequestWithTimeout(args.connectTimeout, requestInitCancellation);
|
||||
|
||||
bool success = _socket->connect(host, port, errMsg, isCancellationRequested);
|
||||
if (!success)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Cannot connect to url: " << url << " / error : " << errMsg;
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::CannotConnect,
|
||||
headers,
|
||||
payload,
|
||||
ss.str(),
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
ss << "Cannot connect to url: " << url;
|
||||
return std::make_tuple(code, HttpErrorCode::CannotConnect,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Make a new cancellation object dealing with transfer timeout
|
||||
isCancellationRequested = makeCancellationRequestWithTimeout(args->transferTimeout, _stop);
|
||||
isCancellationRequested =
|
||||
makeCancellationRequestWithTimeout(args.transferTimeout, requestInitCancellation);
|
||||
|
||||
if (args->verbose)
|
||||
if (args.verbose)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Sending " << verb << " request "
|
||||
<< "to " << host << ":" << port << std::endl
|
||||
<< "request size: " << req.size() << " bytes" << std::endl
|
||||
<< "=============" << std::endl
|
||||
<< req << "=============" << std::endl
|
||||
<< req
|
||||
<< "=============" << std::endl
|
||||
<< std::endl;
|
||||
|
||||
log(ss.str(), args);
|
||||
@ -266,14 +142,9 @@ namespace ix
|
||||
if (!_socket->writeBytes(req, isCancellationRequested))
|
||||
{
|
||||
std::string errorMsg("Cannot send request");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::SendError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::SendError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
uploadSize = req.size();
|
||||
@ -285,17 +156,12 @@ namespace ix
|
||||
if (!lineValid)
|
||||
{
|
||||
std::string errorMsg("Cannot retrieve status line");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::CannotReadStatusLine,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::CannotReadStatusLine,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
if (args->verbose)
|
||||
if (args.verbose)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Status line " << line;
|
||||
@ -305,14 +171,9 @@ 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,
|
||||
description,
|
||||
HttpErrorCode::MissingStatus,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::MissingStatus,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
auto result = parseHttpHeaders(_socket, isCancellationRequested);
|
||||
@ -322,61 +183,41 @@ namespace ix
|
||||
if (!headersValid)
|
||||
{
|
||||
std::string errorMsg("Cannot parse http headers");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::HeaderParsingError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::HeaderParsingError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Redirect ?
|
||||
if ((code >= 301 && code <= 308) && args->followRedirects)
|
||||
if ((code >= 301 && code <= 308) && args.followRedirects)
|
||||
{
|
||||
if (headers.find("Location") == headers.end())
|
||||
{
|
||||
std::string errorMsg("Missing location header for redirect");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::MissingLocation,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::MissingLocation,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
if (redirects >= args->maxRedirects)
|
||||
if (redirects >= args.maxRedirects)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "Too many redirects: " << redirects;
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::TooManyRedirects,
|
||||
headers,
|
||||
payload,
|
||||
ss.str(),
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::TooManyRedirects,
|
||||
headers, payload, ss.str(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Recurse
|
||||
std::string location = headers["Location"];
|
||||
return request(location, verb, body, args, redirects + 1);
|
||||
return request(location, verb, body, args, redirects+1);
|
||||
}
|
||||
|
||||
if (verb == "HEAD")
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::Ok,
|
||||
headers,
|
||||
payload,
|
||||
std::string(),
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::Ok,
|
||||
headers, payload, std::string(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
// Parse response:
|
||||
@ -389,19 +230,15 @@ namespace ix
|
||||
|
||||
payload.reserve(contentLength);
|
||||
|
||||
auto chunkResult = _socket->readBytes(
|
||||
contentLength, args->onProgressCallback, isCancellationRequested);
|
||||
auto chunkResult = _socket->readBytes(contentLength,
|
||||
args.onProgressCallback,
|
||||
isCancellationRequested);
|
||||
if (!chunkResult.first)
|
||||
{
|
||||
errorMsg = "Cannot read chunk";
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::ChunkReadError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
payload += chunkResult.second;
|
||||
}
|
||||
@ -417,14 +254,9 @@ namespace ix
|
||||
|
||||
if (!lineResult.first)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::ChunkReadError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
uint64_t chunkSize;
|
||||
@ -432,29 +264,26 @@ namespace ix
|
||||
ss << std::hex << line;
|
||||
ss >> chunkSize;
|
||||
|
||||
if (args->verbose)
|
||||
if (args.verbose)
|
||||
{
|
||||
std::stringstream oss;
|
||||
oss << "Reading " << chunkSize << " bytes" << std::endl;
|
||||
oss << "Reading " << chunkSize << " bytes"
|
||||
<< std::endl;
|
||||
log(oss.str(), args);
|
||||
}
|
||||
|
||||
payload.reserve(payload.size() + (size_t) chunkSize);
|
||||
payload.reserve(payload.size() + chunkSize);
|
||||
|
||||
// Read a chunk
|
||||
auto chunkResult = _socket->readBytes(
|
||||
(size_t) chunkSize, args->onProgressCallback, isCancellationRequested);
|
||||
auto chunkResult = _socket->readBytes(chunkSize,
|
||||
args.onProgressCallback,
|
||||
isCancellationRequested);
|
||||
if (!chunkResult.first)
|
||||
{
|
||||
errorMsg = "Cannot read chunk";
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::ChunkReadError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
payload += chunkResult.second;
|
||||
|
||||
@ -463,14 +292,9 @@ namespace ix
|
||||
|
||||
if (!lineResult.first)
|
||||
{
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::ChunkReadError,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::ChunkReadError,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
if (chunkSize == 0) break;
|
||||
@ -483,14 +307,9 @@ namespace ix
|
||||
else
|
||||
{
|
||||
std::string errorMsg("Cannot read http body");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::CannotReadBody,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::CannotReadBody,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
downloadSize = payload.size();
|
||||
@ -502,92 +321,52 @@ namespace ix
|
||||
if (!gzipInflate(payload, decompressedPayload))
|
||||
{
|
||||
std::string errorMsg("Error decompressing payload");
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::Gzip,
|
||||
headers,
|
||||
payload,
|
||||
errorMsg,
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::Gzip,
|
||||
headers, payload, errorMsg,
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
payload = decompressedPayload;
|
||||
}
|
||||
|
||||
return std::make_shared<HttpResponse>(code,
|
||||
description,
|
||||
HttpErrorCode::Ok,
|
||||
headers,
|
||||
payload,
|
||||
std::string(),
|
||||
uploadSize,
|
||||
downloadSize);
|
||||
return std::make_tuple(code, HttpErrorCode::Ok,
|
||||
headers, payload, std::string(),
|
||||
uploadSize, downloadSize);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::get(const std::string& url, HttpRequestArgsPtr args)
|
||||
HttpResponse HttpClient::get(const std::string& url,
|
||||
const HttpRequestArgs& args)
|
||||
{
|
||||
return request(url, kGet, std::string(), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::head(const std::string& url, HttpRequestArgsPtr args)
|
||||
HttpResponse HttpClient::head(const std::string& url,
|
||||
const HttpRequestArgs& args)
|
||||
{
|
||||
return request(url, kHead, std::string(), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::del(const std::string& url, HttpRequestArgsPtr args)
|
||||
{
|
||||
return request(url, kDel, std::string(), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::post(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args)
|
||||
HttpResponse HttpClient::post(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
const HttpRequestArgs& args)
|
||||
{
|
||||
return request(url, kPost, serializeHttpParameters(httpParameters), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::post(const std::string& url,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args)
|
||||
HttpResponse HttpClient::post(const std::string& url,
|
||||
const std::string& body,
|
||||
const HttpRequestArgs& args)
|
||||
{
|
||||
return request(url, kPost, body, args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::put(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args)
|
||||
{
|
||||
return request(url, kPut, serializeHttpParameters(httpParameters), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::put(const std::string& url,
|
||||
const std::string& body,
|
||||
const HttpRequestArgsPtr args)
|
||||
{
|
||||
return request(url, kPut, body, args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::patch(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args)
|
||||
{
|
||||
return request(url, kPatch, serializeHttpParameters(httpParameters), args);
|
||||
}
|
||||
|
||||
HttpResponsePtr HttpClient::patch(const std::string& url,
|
||||
const std::string& body,
|
||||
const HttpRequestArgsPtr args)
|
||||
{
|
||||
return request(url, kPatch, body, args);
|
||||
}
|
||||
|
||||
std::string HttpClient::urlEncode(const std::string& value)
|
||||
{
|
||||
std::ostringstream escaped;
|
||||
escaped.fill('0');
|
||||
escaped << std::hex;
|
||||
|
||||
for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i)
|
||||
for (std::string::const_iterator i = value.begin(), n = value.end();
|
||||
i != n; ++i)
|
||||
{
|
||||
std::string::value_type c = (*i);
|
||||
|
||||
@ -615,64 +394,21 @@ namespace ix
|
||||
|
||||
for (auto&& it : httpParameters)
|
||||
{
|
||||
ss << urlEncode(it.first) << "=" << urlEncode(it.second);
|
||||
ss << urlEncode(it.first)
|
||||
<< "="
|
||||
<< urlEncode(it.second);
|
||||
|
||||
if (i++ < (count - 1))
|
||||
if (i++ < (count-1))
|
||||
{
|
||||
ss << "&";
|
||||
ss << "&";
|
||||
}
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::string HttpClient::serializeHttpFormDataParameters(
|
||||
const std::string& multipartBoundary,
|
||||
const HttpFormDataParameters& httpFormDataParameters,
|
||||
const HttpParameters& httpParameters)
|
||||
{
|
||||
//
|
||||
// --AaB03x
|
||||
// Content-Disposition: form-data; name="submit-name"
|
||||
|
||||
// Larry
|
||||
// --AaB03x
|
||||
// Content-Disposition: form-data; name="foo.txt"; filename="file1.txt"
|
||||
// Content-Type: text/plain
|
||||
|
||||
// ... contents of file1.txt ...
|
||||
// --AaB03x--
|
||||
//
|
||||
std::stringstream ss;
|
||||
|
||||
for (auto&& it : httpFormDataParameters)
|
||||
{
|
||||
ss << "--" << multipartBoundary << "\r\n"
|
||||
<< "Content-Disposition:"
|
||||
<< " form-data; name=\"" << it.first << "\";"
|
||||
<< " filename=\"" << it.first << "\""
|
||||
<< "\r\n"
|
||||
<< "Content-Type: application/octet-stream"
|
||||
<< "\r\n"
|
||||
<< "\r\n"
|
||||
<< it.second << "\r\n";
|
||||
}
|
||||
|
||||
for (auto&& it : httpParameters)
|
||||
{
|
||||
ss << "--" << multipartBoundary << "\r\n"
|
||||
<< "Content-Disposition:"
|
||||
<< " form-data; name=\"" << it.first << "\";"
|
||||
<< "\r\n"
|
||||
<< "\r\n"
|
||||
<< it.second << "\r\n";
|
||||
}
|
||||
|
||||
ss << "--" << multipartBoundary << "--\r\n";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool HttpClient::gzipInflate(const std::string& in, std::string& out)
|
||||
bool HttpClient::gzipInflate(
|
||||
const std::string& in,
|
||||
std::string& out)
|
||||
{
|
||||
z_stream inflateState;
|
||||
std::memset(&inflateState, 0, sizeof(inflateState));
|
||||
@ -683,13 +419,13 @@ namespace ix
|
||||
inflateState.avail_in = 0;
|
||||
inflateState.next_in = Z_NULL;
|
||||
|
||||
if (inflateInit2(&inflateState, 16 + MAX_WBITS) != Z_OK)
|
||||
if (inflateInit2(&inflateState, 16+MAX_WBITS) != Z_OK)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
inflateState.avail_in = (uInt) in.size();
|
||||
inflateState.next_in = (unsigned char*) (const_cast<char*>(in.data()));
|
||||
inflateState.next_in = (unsigned char *)(const_cast<char *>(in.data()));
|
||||
|
||||
const int kBufferSize = 1 << 14;
|
||||
|
||||
@ -709,31 +445,22 @@ namespace ix
|
||||
return false;
|
||||
}
|
||||
|
||||
out.append(reinterpret_cast<char*>(compressBuffer.get()),
|
||||
kBufferSize - inflateState.avail_out);
|
||||
out.append(
|
||||
reinterpret_cast<char *>(compressBuffer.get()),
|
||||
kBufferSize - inflateState.avail_out
|
||||
);
|
||||
} while (inflateState.avail_out == 0);
|
||||
|
||||
inflateEnd(&inflateState);
|
||||
return true;
|
||||
}
|
||||
|
||||
void HttpClient::log(const std::string& msg, HttpRequestArgsPtr args)
|
||||
void HttpClient::log(const std::string& msg,
|
||||
const HttpRequestArgs& args)
|
||||
{
|
||||
if (args->logger)
|
||||
if (args.logger)
|
||||
{
|
||||
args->logger(msg);
|
||||
args.logger(msg);
|
||||
}
|
||||
}
|
||||
|
||||
std::string HttpClient::generateMultipartBoundary()
|
||||
{
|
||||
std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
|
||||
|
||||
static std::random_device rd;
|
||||
static std::mt19937 generator(rd());
|
||||
|
||||
std::shuffle(str.begin(), str.end(), generator);
|
||||
|
||||
return str;
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -6,107 +6,102 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXHttp.h"
|
||||
#include "IXSocket.h"
|
||||
#include "IXSocketTLSOptions.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <tuple>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
|
||||
#include "IXSocket.h"
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class HttpClient
|
||||
enum class HttpErrorCode
|
||||
{
|
||||
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
|
||||
};
|
||||
|
||||
using HttpResponse = std::tuple<int, // status
|
||||
HttpErrorCode, // error code
|
||||
WebSocketHttpHeaders,
|
||||
std::string, // payload
|
||||
std::string, // error msg
|
||||
uint64_t, // upload size
|
||||
uint64_t>; // download size
|
||||
|
||||
using HttpParameters = std::map<std::string, std::string>;
|
||||
using Logger = std::function<void(const std::string&)>;
|
||||
|
||||
struct HttpRequestArgs
|
||||
{
|
||||
std::string url;
|
||||
WebSocketHttpHeaders extraHeaders;
|
||||
std::string body;
|
||||
int connectTimeout;
|
||||
int transferTimeout;
|
||||
bool followRedirects;
|
||||
int maxRedirects;
|
||||
bool verbose;
|
||||
bool compress;
|
||||
Logger logger;
|
||||
OnProgressCallback onProgressCallback;
|
||||
};
|
||||
|
||||
class HttpClient {
|
||||
public:
|
||||
HttpClient(bool async = false);
|
||||
HttpClient();
|
||||
~HttpClient();
|
||||
|
||||
HttpResponsePtr get(const std::string& url, HttpRequestArgsPtr args);
|
||||
HttpResponsePtr head(const std::string& url, HttpRequestArgsPtr args);
|
||||
HttpResponsePtr del(const std::string& url, HttpRequestArgsPtr args);
|
||||
HttpResponse get(const std::string& url,
|
||||
const HttpRequestArgs& args);
|
||||
HttpResponse head(const std::string& url,
|
||||
const HttpRequestArgs& args);
|
||||
|
||||
HttpResponsePtr post(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args);
|
||||
HttpResponsePtr post(const std::string& url,
|
||||
HttpResponse post(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
const HttpRequestArgs& args);
|
||||
HttpResponse post(const std::string& url,
|
||||
const std::string& body,
|
||||
const HttpRequestArgs& args);
|
||||
|
||||
private:
|
||||
HttpResponse request(const std::string& url,
|
||||
const std::string& verb,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args);
|
||||
|
||||
HttpResponsePtr put(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args);
|
||||
HttpResponsePtr put(const std::string& url,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args);
|
||||
|
||||
HttpResponsePtr patch(const std::string& url,
|
||||
const HttpParameters& httpParameters,
|
||||
HttpRequestArgsPtr args);
|
||||
HttpResponsePtr patch(const std::string& url,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args);
|
||||
|
||||
HttpResponsePtr request(const std::string& url,
|
||||
const std::string& verb,
|
||||
const std::string& body,
|
||||
HttpRequestArgsPtr args,
|
||||
int redirects = 0);
|
||||
void setForceBody(bool value);
|
||||
// Async API
|
||||
HttpRequestArgsPtr createRequest(const std::string& url = std::string(),
|
||||
const std::string& verb = HttpClient::kGet);
|
||||
|
||||
bool performRequest(HttpRequestArgsPtr request,
|
||||
const OnResponseCallback& onResponseCallback);
|
||||
|
||||
// TLS
|
||||
void setTLSOptions(const SocketTLSOptions& tlsOptions);
|
||||
const HttpRequestArgs& args,
|
||||
int redirects = 0);
|
||||
|
||||
std::string serializeHttpParameters(const HttpParameters& httpParameters);
|
||||
|
||||
std::string serializeHttpFormDataParameters(
|
||||
const std::string& multipartBoundary,
|
||||
const HttpFormDataParameters& httpFormDataParameters,
|
||||
const HttpParameters& httpParameters = HttpParameters());
|
||||
|
||||
std::string generateMultipartBoundary();
|
||||
|
||||
std::string urlEncode(const std::string& value);
|
||||
|
||||
void log(const std::string& msg, const HttpRequestArgs& args);
|
||||
|
||||
bool gzipInflate(
|
||||
const std::string& in,
|
||||
std::string& out);
|
||||
|
||||
std::shared_ptr<Socket> _socket;
|
||||
|
||||
const static std::string kPost;
|
||||
const static std::string kGet;
|
||||
const static std::string kHead;
|
||||
const static std::string kDel;
|
||||
const static std::string kPut;
|
||||
const static std::string kPatch;
|
||||
|
||||
private:
|
||||
void log(const std::string& msg, HttpRequestArgsPtr args);
|
||||
|
||||
bool gzipInflate(const std::string& in, std::string& out);
|
||||
|
||||
// Async API background thread runner
|
||||
void run();
|
||||
// Async API
|
||||
bool _async;
|
||||
std::queue<std::pair<HttpRequestArgsPtr, OnResponseCallback>> _queue;
|
||||
mutable std::mutex _queueMutex;
|
||||
std::condition_variable _condition;
|
||||
std::atomic<bool> _stop;
|
||||
std::thread _thread;
|
||||
|
||||
std::unique_ptr<Socket> _socket;
|
||||
std::mutex _mutex; // to protect accessing the _socket (only one socket per client)
|
||||
|
||||
SocketTLSOptions _tlsOptions;
|
||||
|
||||
bool _forceBody;
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -1,173 +0,0 @@
|
||||
/*
|
||||
* IXHttpServer.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXHttpServer.h"
|
||||
|
||||
#include "IXNetSystem.h"
|
||||
#include "IXSocketConnect.h"
|
||||
#include "IXUserAgent.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#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
|
||||
|
||||
namespace ix
|
||||
{
|
||||
HttpServer::HttpServer(
|
||||
int port, const std::string& host, int backlog, size_t maxConnections, int addressFamily)
|
||||
: SocketServer(port, host, backlog, maxConnections, addressFamily)
|
||||
, _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(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
_connectedClientsCount++;
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["Server"] = userAgent();
|
||||
|
||||
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());
|
||||
|
||||
// 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);
|
||||
});
|
||||
}
|
||||
|
||||
void HttpServer::makeRedirectServer(const std::string& redirectUrl)
|
||||
{
|
||||
//
|
||||
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
|
||||
//
|
||||
setOnConnectionCallback(
|
||||
[this,
|
||||
redirectUrl](HttpRequestPtr request,
|
||||
std::shared_ptr<ConnectionState> /*connectionState*/) -> HttpResponsePtr {
|
||||
WebSocketHttpHeaders headers;
|
||||
headers["Server"] = userAgent();
|
||||
|
||||
// Log request
|
||||
std::stringstream ss;
|
||||
ss << request->method << " " << request->headers["User-Agent"] << " "
|
||||
<< request->uri;
|
||||
logInfo(ss.str());
|
||||
|
||||
if (request->method == "POST")
|
||||
{
|
||||
return std::make_shared<HttpResponse>(
|
||||
200, "OK", HttpErrorCode::Ok, headers, std::string());
|
||||
}
|
||||
|
||||
headers["Location"] = redirectUrl;
|
||||
|
||||
return std::make_shared<HttpResponse>(
|
||||
301, "OK", HttpErrorCode::Ok, headers, std::string());
|
||||
});
|
||||
}
|
||||
} // namespace ix
|
@ -1,52 +0,0 @@
|
||||
/*
|
||||
* 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,
|
||||
int addressFamily = SocketServer::kDefaultAddressFamily);
|
||||
virtual ~HttpServer();
|
||||
virtual void stop() final;
|
||||
|
||||
void setOnConnectionCallback(const OnConnectionCallback& callback);
|
||||
|
||||
void makeRedirectServer(const std::string& redirectUrl);
|
||||
|
||||
private:
|
||||
// Member variables
|
||||
OnConnectionCallback _onConnectionCallback;
|
||||
std::atomic<int> _connectedClientsCount;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(std::unique_ptr<Socket>,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
|
||||
void setDefaultConnectionCallback();
|
||||
};
|
||||
} // namespace ix
|
@ -15,8 +15,9 @@ 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;
|
||||
@ -29,84 +30,10 @@ namespace ix
|
||||
{
|
||||
#ifdef _WIN32
|
||||
int err = WSACleanup();
|
||||
|
||||
return err == 0;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
//
|
||||
// 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)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
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;
|
||||
#else
|
||||
return ::poll(fds, nfds, timeout);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -7,35 +7,25 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <WS2tcpip.h>
|
||||
#include <WinSock2.h>
|
||||
#include <basetsd.h>
|
||||
#include <io.h>
|
||||
#include <ws2def.h>
|
||||
|
||||
// Define our own poll on Windows, as a wrapper on top of select
|
||||
typedef unsigned long int nfds_t;
|
||||
|
||||
# include <WS2tcpip.h>
|
||||
# include <WinSock2.h>
|
||||
# include <basetsd.h>
|
||||
# include <io.h>
|
||||
# include <ws2def.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <poll.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
# include <arpa/inet.h>
|
||||
# include <errno.h>
|
||||
# include <netdb.h>
|
||||
# include <netinet/tcp.h>
|
||||
# include <sys/select.h>
|
||||
# include <sys/socket.h>
|
||||
# include <sys/stat.h>
|
||||
# include <sys/time.h>
|
||||
# include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
bool initNetSystem();
|
||||
bool uninitNetSystem();
|
||||
|
||||
int poll(struct pollfd* fds, nfds_t nfds, int timeout);
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -42,4 +42,5 @@ namespace ix
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
@ -11,8 +11,7 @@
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterrupt
|
||||
{
|
||||
class SelectInterrupt {
|
||||
public:
|
||||
SelectInterrupt();
|
||||
virtual ~SelectInterrupt();
|
||||
@ -24,4 +23,6 @@ namespace ix
|
||||
virtual uint64_t read();
|
||||
virtual int getFd() const;
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
||||
|
116
ixwebsocket/IXSelectInterruptEventFd.cpp
Normal file
116
ixwebsocket/IXSelectInterruptEventFd.cpp
Normal file
@ -0,0 +1,116 @@
|
||||
/*
|
||||
* IXSelectInterruptEventFd.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
//
|
||||
// On Linux we use eventd to wake up select.
|
||||
//
|
||||
|
||||
//
|
||||
// Linux/Android has a special type of virtual files. select(2) will react
|
||||
// when reading/writing to those files, unlike closing sockets.
|
||||
//
|
||||
// https://linux.die.net/man/2/eventfd
|
||||
// http://www.sourcexr.com/articles/2013/10/26/lightweight-inter-process-signaling-with-eventfd
|
||||
//
|
||||
// eventfd was added in Linux kernel 2.x, and our oldest Android (Kitkat 4.4)
|
||||
// is on Kernel 3.x
|
||||
//
|
||||
// cf Android/Kernel table here
|
||||
// https://android.stackexchange.com/questions/51651/which-android-runs-which-linux-kernel
|
||||
//
|
||||
// On macOS we use UNIX pipes to wake up select.
|
||||
//
|
||||
|
||||
#include "IXSelectInterruptEventFd.h"
|
||||
|
||||
#include <sys/eventfd.h>
|
||||
|
||||
#include <unistd.h> // for write
|
||||
#include <string.h> // for strerror
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <assert.h>
|
||||
#include <sstream>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
SelectInterruptEventFd::SelectInterruptEventFd()
|
||||
{
|
||||
_eventfd = -1;
|
||||
}
|
||||
|
||||
SelectInterruptEventFd::~SelectInterruptEventFd()
|
||||
{
|
||||
::close(_eventfd);
|
||||
}
|
||||
|
||||
bool SelectInterruptEventFd::init(std::string& errorMsg)
|
||||
{
|
||||
// calling init twice is a programming error
|
||||
assert(_eventfd == -1);
|
||||
|
||||
_eventfd = eventfd(0, 0);
|
||||
if (_eventfd < 0)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "SelectInterruptEventFd::init() failed in eventfd()"
|
||||
<< " : " << strerror(errno);
|
||||
errorMsg = ss.str();
|
||||
|
||||
_eventfd = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fcntl(_eventfd, F_SETFL, O_NONBLOCK) == -1)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "SelectInterruptEventFd::init() failed in fcntl() call"
|
||||
<< " : " << strerror(errno);
|
||||
errorMsg = ss.str();
|
||||
|
||||
_eventfd = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SelectInterruptEventFd::notify(uint64_t value)
|
||||
{
|
||||
int fd = _eventfd;
|
||||
|
||||
if (fd == -1) return false;
|
||||
|
||||
// we should write 8 bytes for an uint64_t
|
||||
return write(fd, &value, sizeof(value)) == 8;
|
||||
}
|
||||
|
||||
// TODO: return max uint64_t for errors ?
|
||||
uint64_t SelectInterruptEventFd::read()
|
||||
{
|
||||
int fd = _eventfd;
|
||||
|
||||
uint64_t value = 0;
|
||||
::read(fd, &value, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
bool SelectInterruptEventFd::clear()
|
||||
{
|
||||
if (_eventfd == -1) return false;
|
||||
|
||||
// 0 is a special value ; select will not wake up
|
||||
uint64_t value = 0;
|
||||
|
||||
// we should write 8 bytes for an uint64_t
|
||||
return write(_eventfd, &value, sizeof(value)) == 8;
|
||||
}
|
||||
|
||||
int SelectInterruptEventFd::getFd() const
|
||||
{
|
||||
return _eventfd;
|
||||
}
|
||||
}
|
32
ixwebsocket/IXSelectInterruptEventFd.h
Normal file
32
ixwebsocket/IXSelectInterruptEventFd.h
Normal file
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* IXSelectInterruptEventFd.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2018-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXSelectInterrupt.h"
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterruptEventFd final : public SelectInterrupt {
|
||||
public:
|
||||
SelectInterruptEventFd();
|
||||
virtual ~SelectInterruptEventFd();
|
||||
|
||||
bool init(std::string& errorMsg) final;
|
||||
|
||||
bool notify(uint64_t value) final;
|
||||
bool clear() final;
|
||||
uint64_t read() final;
|
||||
int getFd() const final;
|
||||
|
||||
private:
|
||||
int _eventfd;
|
||||
};
|
||||
}
|
||||
|
@ -7,19 +7,19 @@
|
||||
#include "IXSelectInterruptFactory.h"
|
||||
|
||||
#if defined(__linux__) || defined(__APPLE__)
|
||||
#include "IXSelectInterruptPipe.h"
|
||||
# include <ixwebsocket/IXSelectInterruptPipe.h>
|
||||
#else
|
||||
#include "IXSelectInterrupt.h"
|
||||
# include <ixwebsocket/IXSelectInterrupt.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
SelectInterruptPtr createSelectInterrupt()
|
||||
std::shared_ptr<SelectInterrupt> createSelectInterrupt()
|
||||
{
|
||||
#if defined(__linux__) || defined(__APPLE__)
|
||||
return std::make_unique<SelectInterruptPipe>();
|
||||
return std::make_shared<SelectInterruptPipe>();
|
||||
#else
|
||||
return std::make_unique<SelectInterrupt>();
|
||||
return std::make_shared<SelectInterrupt>();
|
||||
#endif
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -11,6 +11,5 @@
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterrupt;
|
||||
using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
|
||||
SelectInterruptPtr createSelectInterrupt();
|
||||
} // namespace ix
|
||||
std::shared_ptr<SelectInterrupt> createSelectInterrupt();
|
||||
}
|
||||
|
@ -10,12 +10,12 @@
|
||||
|
||||
#include "IXSelectInterruptPipe.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sstream>
|
||||
#include <string.h> // for strerror
|
||||
#include <unistd.h> // for write
|
||||
#include <string.h> // for strerror
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <assert.h>
|
||||
#include <sstream>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
@ -143,4 +143,4 @@ namespace ix
|
||||
|
||||
return _fildes[kPipeReadIndex];
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -7,14 +7,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "IXSelectInterrupt.h"
|
||||
#include <mutex>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterruptPipe final : public SelectInterrupt
|
||||
{
|
||||
class SelectInterruptPipe final : public SelectInterrupt {
|
||||
public:
|
||||
SelectInterruptPipe();
|
||||
virtual ~SelectInterruptPipe();
|
||||
@ -37,4 +37,5 @@ namespace ix
|
||||
static const int kPipeReadIndex;
|
||||
static const int kPipeWriteIndex;
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
@ -10,3 +10,4 @@ namespace ix
|
||||
{
|
||||
void setThreadName(const std::string& name);
|
||||
}
|
||||
|
||||
|
@ -5,20 +5,21 @@
|
||||
*/
|
||||
|
||||
#include "IXSocket.h"
|
||||
|
||||
#include "IXSocketConnect.h"
|
||||
#include "IXNetSystem.h"
|
||||
#include "IXSelectInterrupt.h"
|
||||
#include "IXSelectInterruptFactory.h"
|
||||
#include "IXSocketConnect.h"
|
||||
#include <algorithm>
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#ifdef min
|
||||
#undef min
|
||||
#endif
|
||||
@ -31,9 +32,9 @@ namespace ix
|
||||
const uint64_t Socket::kCloseRequest = 2;
|
||||
constexpr size_t Socket::kChunkSize;
|
||||
|
||||
Socket::Socket(int fd)
|
||||
: _sockfd(fd)
|
||||
, _selectInterrupt(createSelectInterrupt())
|
||||
Socket::Socket(int fd) :
|
||||
_sockfd(fd),
|
||||
_selectInterrupt(createSelectInterrupt())
|
||||
{
|
||||
;
|
||||
}
|
||||
@ -43,45 +44,43 @@ namespace ix
|
||||
close();
|
||||
}
|
||||
|
||||
PollResultType Socket::poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
const SelectInterruptPtr& selectInterrupt)
|
||||
PollResultType Socket::poll(int 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
|
||||
// have 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];
|
||||
memset(fds, 0, sizeof(fds));
|
||||
|
||||
fds[0].fd = sockfd;
|
||||
fds[0].events = (readyToRead) ? POLLIN : POLLOUT;
|
||||
|
||||
// this is ignored by poll, but our select based poll wrapper on Windows needs it
|
||||
fds[0].events |= POLLERR;
|
||||
|
||||
// File descriptor used to interrupt select when needed
|
||||
int interruptFd = -1;
|
||||
if (selectInterrupt)
|
||||
if (_sockfd == -1)
|
||||
{
|
||||
interruptFd = selectInterrupt->getFd();
|
||||
|
||||
if (interruptFd != -1)
|
||||
{
|
||||
nfds = 2;
|
||||
fds[1].fd = interruptFd;
|
||||
fds[1].events = POLLIN;
|
||||
}
|
||||
return PollResultType::Error;
|
||||
}
|
||||
|
||||
int ret = ix::poll(fds, nfds, timeoutMs);
|
||||
return isReadyToRead(timeoutMs);
|
||||
}
|
||||
|
||||
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;
|
||||
FD_SET(_sockfd, fds);
|
||||
|
||||
// File descriptor used to interrupt select when needed
|
||||
int interruptFd = _selectInterrupt->getFd();
|
||||
if (interruptFd != -1)
|
||||
{
|
||||
FD_SET(interruptFd, fds);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
PollResultType pollResult = PollResultType::ReadyForRead;
|
||||
if (ret < 0)
|
||||
@ -92,9 +91,9 @@ namespace ix
|
||||
{
|
||||
pollResult = PollResultType::Timeout;
|
||||
}
|
||||
else if (interruptFd != -1 && fds[1].revents & POLLIN)
|
||||
else if (interruptFd != -1 && FD_ISSET(interruptFd, &rfds))
|
||||
{
|
||||
uint64_t value = selectInterrupt->read();
|
||||
uint64_t value = _selectInterrupt->read();
|
||||
|
||||
if (value == kSendRequest)
|
||||
{
|
||||
@ -105,40 +104,13 @@ namespace ix
|
||||
pollResult = PollResultType::CloseRequest;
|
||||
}
|
||||
}
|
||||
else if (sockfd != -1 && readyToRead && fds[0].revents & POLLIN)
|
||||
else if (sockfd != -1 && readyToRead && FD_ISSET(sockfd, &rfds))
|
||||
{
|
||||
pollResult = PollResultType::ReadyForRead;
|
||||
}
|
||||
else if (sockfd != -1 && !readyToRead && fds[0].revents & POLLOUT)
|
||||
else if (sockfd != -1 && !readyToRead && FD_ISSET(sockfd, &wfds))
|
||||
{
|
||||
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
|
||||
}
|
||||
else if (sockfd != -1 && (fds[0].revents & POLLERR || fds[0].revents & POLLHUP ||
|
||||
fds[0].revents & POLLNVAL))
|
||||
{
|
||||
pollResult = PollResultType::Error;
|
||||
}
|
||||
|
||||
return pollResult;
|
||||
@ -146,42 +118,22 @@ namespace ix
|
||||
|
||||
PollResultType Socket::isReadyToRead(int timeoutMs)
|
||||
{
|
||||
if (_sockfd == -1)
|
||||
{
|
||||
return PollResultType::Error;
|
||||
}
|
||||
|
||||
bool readyToRead = true;
|
||||
return poll(readyToRead, timeoutMs, _sockfd, _selectInterrupt);
|
||||
return select(readyToRead, timeoutMs);
|
||||
}
|
||||
|
||||
PollResultType Socket::isReadyToWrite(int timeoutMs)
|
||||
{
|
||||
if (_sockfd == -1)
|
||||
{
|
||||
return PollResultType::Error;
|
||||
}
|
||||
|
||||
bool readyToRead = false;
|
||||
return poll(readyToRead, timeoutMs, _sockfd, _selectInterrupt);
|
||||
return select(readyToRead, timeoutMs);
|
||||
}
|
||||
|
||||
// Wake up from poll/select by writing to the pipe which is watched by select
|
||||
bool Socket::wakeUpFromPoll(uint64_t wakeUpCode)
|
||||
bool Socket::wakeUpFromPoll(uint8_t wakeUpCode)
|
||||
{
|
||||
return _selectInterrupt->notify(wakeUpCode);
|
||||
}
|
||||
|
||||
bool Socket::accept(std::string& errMsg)
|
||||
{
|
||||
if (_sockfd == -1)
|
||||
{
|
||||
errMsg = "Socket is uninitialized";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Socket::connect(const std::string& host,
|
||||
int port,
|
||||
std::string& errMsg,
|
||||
@ -217,7 +169,7 @@ namespace ix
|
||||
|
||||
ssize_t Socket::send(const std::string& buffer)
|
||||
{
|
||||
return send((char*) &buffer[0], buffer.size());
|
||||
return send((char*)&buffer[0], buffer.size());
|
||||
}
|
||||
|
||||
ssize_t Socket::recv(void* buffer, size_t length)
|
||||
@ -272,28 +224,19 @@ 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;
|
||||
|
||||
ssize_t ret = send((char*) &str[offset], len);
|
||||
char* buffer = const_cast<char*>(str.c_str());
|
||||
int len = (int) str.size();
|
||||
|
||||
ssize_t ret = send(buffer, len);
|
||||
|
||||
// We wrote some bytes, as needed, all good.
|
||||
if (ret > 0)
|
||||
{
|
||||
if (ret == len)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
offset += ret;
|
||||
len -= ret;
|
||||
continue;
|
||||
}
|
||||
return ret == len;
|
||||
}
|
||||
// There is possibly something to be writen, try again
|
||||
else if (ret < 0 && Socket::isWaitNeeded())
|
||||
@ -308,7 +251,8 @@ namespace ix
|
||||
}
|
||||
}
|
||||
|
||||
bool Socket::readByte(void* buffer, const CancellationRequest& isCancellationRequested)
|
||||
bool Socket::readByte(void* buffer,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
@ -347,7 +291,7 @@ namespace ix
|
||||
std::string line;
|
||||
line.reserve(64);
|
||||
|
||||
for (int i = 0; i < 2 || (line[i - 2] != '\r' && line[i - 1] != '\n'); ++i)
|
||||
for (int i = 0; i < 2 || (line[i-2] != '\r' && line[i-1] != '\n'); ++i)
|
||||
{
|
||||
if (!readByte(&c, isCancellationRequested))
|
||||
{
|
||||
@ -376,21 +320,22 @@ namespace ix
|
||||
{
|
||||
if (isCancellationRequested && isCancellationRequested())
|
||||
{
|
||||
const std::string errorMsg("Cancellation Requested");
|
||||
return std::make_pair(false, errorMsg);
|
||||
return std::make_pair(false, std::string());
|
||||
}
|
||||
|
||||
size_t size = std::min(kChunkSize, length - output.size());
|
||||
ssize_t ret = recv((char*) &_readBuffer[0], size);
|
||||
ssize_t ret = recv((char*)&_readBuffer[0], size);
|
||||
|
||||
if (ret > 0)
|
||||
if (ret <= 0 && !Socket::isWaitNeeded())
|
||||
{
|
||||
output.insert(output.end(), _readBuffer.begin(), _readBuffer.begin() + ret);
|
||||
// Error
|
||||
return std::make_pair(false, std::string());
|
||||
}
|
||||
else if (ret <= 0 && !Socket::isWaitNeeded())
|
||||
else
|
||||
{
|
||||
const std::string errorMsg("Recv Error");
|
||||
return std::make_pair(false, errorMsg);
|
||||
output.insert(output.end(),
|
||||
_readBuffer.begin(),
|
||||
_readBuffer.begin() + ret);
|
||||
}
|
||||
|
||||
if (onProgressCallback) onProgressCallback((int) output.size(), (int) length);
|
||||
@ -399,11 +344,11 @@ namespace ix
|
||||
// This way we are not busy looping
|
||||
if (isReadyToRead(1) == PollResultType::Error)
|
||||
{
|
||||
const std::string errorMsg("Poll Error");
|
||||
return std::make_pair(false, errorMsg);
|
||||
return std::make_pair(false, std::string());
|
||||
}
|
||||
}
|
||||
|
||||
return std::make_pair(true, std::string(output.begin(), output.end()));
|
||||
return std::make_pair(true, std::string(output.begin(),
|
||||
output.end()));
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -6,12 +6,12 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <BaseTsd.h>
|
||||
@ -24,11 +24,11 @@ typedef SSIZE_T ssize_t;
|
||||
#undef EINVAL
|
||||
|
||||
// map to WSA error codes
|
||||
#define EWOULDBLOCK WSAEWOULDBLOCK
|
||||
#define EAGAIN WSATRY_AGAIN
|
||||
#define EINPROGRESS WSAEINPROGRESS
|
||||
#define EBADF WSAEBADF
|
||||
#define EINVAL WSAEINVAL
|
||||
#define EWOULDBLOCK WSAEWOULDBLOCK
|
||||
#define EAGAIN WSATRY_AGAIN
|
||||
#define EINPROGRESS WSAEINPROGRESS
|
||||
#define EBADF WSAEBADF
|
||||
#define EINVAL WSAEINVAL
|
||||
|
||||
#endif
|
||||
|
||||
@ -38,20 +38,18 @@ typedef SSIZE_T ssize_t;
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterrupt;
|
||||
using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
|
||||
|
||||
enum class PollResultType
|
||||
{
|
||||
ReadyForRead = 0,
|
||||
ReadyForWrite = 1,
|
||||
Timeout = 2,
|
||||
Error = 3,
|
||||
SendRequest = 4,
|
||||
CloseRequest = 5
|
||||
ReadyForRead = 0,
|
||||
ReadyForWrite = 1,
|
||||
Timeout = 2,
|
||||
Error = 3,
|
||||
SendRequest = 4,
|
||||
CloseRequest = 5
|
||||
};
|
||||
|
||||
class Socket
|
||||
{
|
||||
class Socket {
|
||||
public:
|
||||
Socket(int fd = -1);
|
||||
virtual ~Socket();
|
||||
@ -59,44 +57,40 @@ namespace ix
|
||||
|
||||
// Functions to check whether there is activity on the socket
|
||||
PollResultType poll(int timeoutMs = kDefaultPollTimeout);
|
||||
bool wakeUpFromPoll(uint64_t wakeUpCode);
|
||||
bool wakeUpFromPoll(uint8_t wakeUpCode);
|
||||
|
||||
PollResultType isReadyToWrite(int timeoutMs);
|
||||
PollResultType isReadyToRead(int timeoutMs);
|
||||
|
||||
// Virtual methods
|
||||
virtual bool accept(std::string& errMsg);
|
||||
|
||||
virtual bool connect(const std::string& host,
|
||||
virtual bool connect(const std::string& url,
|
||||
int port,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
virtual void close();
|
||||
|
||||
virtual ssize_t send(char* buffer, size_t length);
|
||||
ssize_t send(const std::string& buffer);
|
||||
virtual ssize_t send(const std::string& buffer);
|
||||
virtual ssize_t recv(void* buffer, size_t length);
|
||||
|
||||
// Blocking and cancellable versions, working with socket that can be set
|
||||
// to non blocking mode. Used during HTTP upgrade.
|
||||
bool readByte(void* buffer, const CancellationRequest& isCancellationRequested);
|
||||
bool writeBytes(const std::string& str, const CancellationRequest& isCancellationRequested);
|
||||
bool readByte(void* buffer,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
bool writeBytes(const std::string& str,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
|
||||
std::pair<bool, std::string> readLine(const CancellationRequest& isCancellationRequested);
|
||||
std::pair<bool, std::string> readBytes(size_t length,
|
||||
const OnProgressCallback& onProgressCallback,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
std::pair<bool, std::string> readLine(
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
std::pair<bool, std::string> readBytes(
|
||||
size_t length,
|
||||
const OnProgressCallback& onProgressCallback,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
|
||||
static int getErrno();
|
||||
static bool isWaitNeeded();
|
||||
static void closeSocket(int fd);
|
||||
|
||||
static PollResultType poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
const SelectInterruptPtr& selectInterrupt);
|
||||
|
||||
|
||||
// Used as special codes for pipe communication
|
||||
static const uint64_t kSendRequest;
|
||||
static const uint64_t kCloseRequest;
|
||||
@ -106,6 +100,8 @@ namespace ix
|
||||
std::mutex _socketMutex;
|
||||
|
||||
private:
|
||||
PollResultType select(bool readyToRead, int timeoutMs);
|
||||
|
||||
static const int kDefaultPollTimeout;
|
||||
static const int kDefaultPollNoTimeout;
|
||||
|
||||
@ -113,6 +109,6 @@ namespace ix
|
||||
std::vector<uint8_t> _readBuffer;
|
||||
static constexpr size_t kChunkSize = 1 << 15;
|
||||
|
||||
SelectInterruptPtr _selectInterrupt;
|
||||
std::shared_ptr<SelectInterrupt> _selectInterrupt;
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -1,20 +1,16 @@
|
||||
/*
|
||||
* IXSocketAppleSSL.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2020 Machine Zone, Inc. All rights reserved.
|
||||
* Copyright (c) 2017-2018 Machine Zone, Inc. All rights reserved.
|
||||
*
|
||||
* Adapted from Satori SDK Apple SSL code.
|
||||
*/
|
||||
#ifdef IXWEBSOCKET_USE_SECURE_TRANSPORT
|
||||
|
||||
#include "IXSocketAppleSSL.h"
|
||||
|
||||
#include "IXSocketConnect.h"
|
||||
#include <errno.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@ -22,16 +18,131 @@
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <errno.h>
|
||||
#define socketerrno errno
|
||||
|
||||
#include <Security/SecureTransport.h>
|
||||
|
||||
namespace {
|
||||
|
||||
OSStatus read_from_socket(SSLConnectionRef connection, void *data, size_t *len)
|
||||
{
|
||||
int fd = (int) (long) connection;
|
||||
if (fd < 0)
|
||||
return errSSLInternal;
|
||||
|
||||
assert(data != nullptr);
|
||||
assert(len != nullptr);
|
||||
|
||||
size_t requested_sz = *len;
|
||||
|
||||
ssize_t status = read(fd, data, requested_sz);
|
||||
|
||||
if (status > 0)
|
||||
{
|
||||
*len = (size_t) status;
|
||||
if (requested_sz > *len)
|
||||
return errSSLWouldBlock;
|
||||
else
|
||||
return noErr;
|
||||
}
|
||||
else if (0 == status)
|
||||
{
|
||||
*len = 0;
|
||||
return errSSLClosedGraceful;
|
||||
}
|
||||
else
|
||||
{
|
||||
*len = 0;
|
||||
switch (errno) {
|
||||
case ENOENT:
|
||||
return errSSLClosedGraceful;
|
||||
|
||||
case EAGAIN:
|
||||
return errSSLWouldBlock;
|
||||
|
||||
case ECONNRESET:
|
||||
return errSSLClosedAbort;
|
||||
|
||||
default:
|
||||
return errSecIO;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OSStatus write_to_socket(SSLConnectionRef connection, const void *data, size_t *len)
|
||||
{
|
||||
int fd = (int) (long) connection;
|
||||
if (fd < 0)
|
||||
return errSSLInternal;
|
||||
|
||||
assert(data != nullptr);
|
||||
assert(len != nullptr);
|
||||
|
||||
size_t to_write_sz = *len;
|
||||
ssize_t status = write(fd, data, to_write_sz);
|
||||
|
||||
if (status > 0)
|
||||
{
|
||||
*len = (size_t) status;
|
||||
if (to_write_sz > *len)
|
||||
return errSSLWouldBlock;
|
||||
else
|
||||
return noErr;
|
||||
}
|
||||
else if (0 == status)
|
||||
{
|
||||
*len = 0;
|
||||
return errSSLClosedGraceful;
|
||||
}
|
||||
else
|
||||
{
|
||||
*len = 0;
|
||||
if (EAGAIN == errno)
|
||||
{
|
||||
return errSSLWouldBlock;
|
||||
}
|
||||
else
|
||||
{
|
||||
return errSecIO;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string getSSLErrorDescription(OSStatus status)
|
||||
{
|
||||
std::string errMsg("Unknown SSL error.");
|
||||
|
||||
CFErrorRef error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, status, NULL);
|
||||
if (error)
|
||||
{
|
||||
CFStringRef message = CFErrorCopyDescription(error);
|
||||
if (message)
|
||||
{
|
||||
char localBuffer[128];
|
||||
Boolean success;
|
||||
success = CFStringGetCString(message, localBuffer, 128,
|
||||
CFStringGetSystemEncoding());
|
||||
if (success)
|
||||
{
|
||||
errMsg = localBuffer;
|
||||
}
|
||||
CFRelease(message);
|
||||
}
|
||||
CFRelease(error);
|
||||
}
|
||||
|
||||
return errMsg;
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
namespace ix
|
||||
{
|
||||
SocketAppleSSL::SocketAppleSSL(const SocketTLSOptions& tlsOptions, int fd)
|
||||
: Socket(fd)
|
||||
, _sslContext(nullptr)
|
||||
, _tlsOptions(tlsOptions)
|
||||
SocketAppleSSL::SocketAppleSSL(int fd) : Socket(fd),
|
||||
_sslContext(nullptr)
|
||||
{
|
||||
;
|
||||
}
|
||||
@ -41,151 +152,6 @@ namespace ix
|
||||
SocketAppleSSL::close();
|
||||
}
|
||||
|
||||
std::string SocketAppleSSL::getSSLErrorDescription(OSStatus status)
|
||||
{
|
||||
std::string errMsg("Unknown SSL error.");
|
||||
|
||||
CFErrorRef error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, status, NULL);
|
||||
if (error)
|
||||
{
|
||||
CFStringRef message = CFErrorCopyDescription(error);
|
||||
if (message)
|
||||
{
|
||||
char localBuffer[128];
|
||||
Boolean success;
|
||||
success = CFStringGetCString(message, localBuffer, 128, kCFStringEncodingUTF8);
|
||||
if (success)
|
||||
{
|
||||
errMsg = localBuffer;
|
||||
}
|
||||
CFRelease(message);
|
||||
}
|
||||
CFRelease(error);
|
||||
}
|
||||
|
||||
return errMsg;
|
||||
}
|
||||
|
||||
OSStatus SocketAppleSSL::readFromSocket(SSLConnectionRef connection, void* data, size_t* len)
|
||||
{
|
||||
int fd = (int) (long) connection;
|
||||
if (fd < 0) return errSSLInternal;
|
||||
|
||||
assert(data != nullptr);
|
||||
assert(len != nullptr);
|
||||
|
||||
size_t requested_sz = *len;
|
||||
|
||||
ssize_t status = read(fd, data, requested_sz);
|
||||
|
||||
if (status > 0)
|
||||
{
|
||||
*len = (size_t) status;
|
||||
if (requested_sz > *len)
|
||||
{
|
||||
return errSSLWouldBlock;
|
||||
}
|
||||
else
|
||||
{
|
||||
return noErr;
|
||||
}
|
||||
}
|
||||
else if (status == 0)
|
||||
{
|
||||
*len = 0;
|
||||
return errSSLClosedGraceful;
|
||||
}
|
||||
else
|
||||
{
|
||||
*len = 0;
|
||||
switch (errno)
|
||||
{
|
||||
case ENOENT: return errSSLClosedGraceful;
|
||||
|
||||
case EAGAIN: return errSSLWouldBlock; // EWOULDBLOCK is a define for EAGAIN on osx
|
||||
case EINPROGRESS: return errSSLWouldBlock;
|
||||
|
||||
case ECONNRESET: return errSSLClosedAbort;
|
||||
|
||||
default: return errSecIO;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OSStatus SocketAppleSSL::writeToSocket(SSLConnectionRef connection,
|
||||
const void* data,
|
||||
size_t* len)
|
||||
{
|
||||
int fd = (int) (long) connection;
|
||||
if (fd < 0) return errSSLInternal;
|
||||
|
||||
assert(data != nullptr);
|
||||
assert(len != nullptr);
|
||||
|
||||
size_t to_write_sz = *len;
|
||||
ssize_t status = write(fd, data, to_write_sz);
|
||||
|
||||
if (status > 0)
|
||||
{
|
||||
*len = (size_t) status;
|
||||
if (to_write_sz > *len)
|
||||
{
|
||||
return errSSLWouldBlock;
|
||||
}
|
||||
else
|
||||
{
|
||||
return noErr;
|
||||
}
|
||||
}
|
||||
else if (status == 0)
|
||||
{
|
||||
*len = 0;
|
||||
return errSSLClosedGraceful;
|
||||
}
|
||||
else
|
||||
{
|
||||
*len = 0;
|
||||
switch (errno)
|
||||
{
|
||||
case ENOENT: return errSSLClosedGraceful;
|
||||
|
||||
case EAGAIN: return errSSLWouldBlock; // EWOULDBLOCK is a define for EAGAIN on osx
|
||||
case EINPROGRESS: return errSSLWouldBlock;
|
||||
|
||||
case ECONNRESET: return errSSLClosedAbort;
|
||||
|
||||
default: return errSecIO;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool SocketAppleSSL::accept(std::string& errMsg)
|
||||
{
|
||||
errMsg = "TLS not supported yet in server mode with apple ssl backend";
|
||||
return false;
|
||||
}
|
||||
|
||||
OSStatus SocketAppleSSL::tlsHandShake(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
OSStatus status;
|
||||
|
||||
do
|
||||
{
|
||||
status = SSLHandshake(_sslContext);
|
||||
|
||||
// Interrupt the handshake
|
||||
if (isCancellationRequested())
|
||||
{
|
||||
errMsg = "Cancellation requested";
|
||||
return errSSLInternal;
|
||||
}
|
||||
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
// No wait support
|
||||
bool SocketAppleSSL::connect(const std::string& host,
|
||||
int port,
|
||||
@ -201,32 +167,18 @@ namespace ix
|
||||
|
||||
_sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
|
||||
|
||||
SSLSetIOFuncs(
|
||||
_sslContext, SocketAppleSSL::readFromSocket, SocketAppleSSL::writeToSocket);
|
||||
SSLSetConnection(_sslContext, (SSLConnectionRef)(long) _sockfd);
|
||||
SSLSetIOFuncs(_sslContext, read_from_socket, write_to_socket);
|
||||
SSLSetConnection(_sslContext, (SSLConnectionRef) (long) _sockfd);
|
||||
SSLSetProtocolVersionMin(_sslContext, kTLSProtocol12);
|
||||
SSLSetPeerDomainName(_sslContext, host.c_str(), host.size());
|
||||
|
||||
if (_tlsOptions.isPeerVerifyDisabled())
|
||||
{
|
||||
Boolean option(1);
|
||||
SSLSetSessionOption(_sslContext, kSSLSessionOptionBreakOnServerAuth, option);
|
||||
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
|
||||
if (status == errSSLServerAuthCompleted)
|
||||
{
|
||||
// proceed with the handshake
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
}
|
||||
do {
|
||||
status = SSLHandshake(_sslContext);
|
||||
} while (errSSLWouldBlock == status ||
|
||||
errSSLServerAuthCompleted == status);
|
||||
}
|
||||
|
||||
if (status != noErr)
|
||||
if (noErr != status)
|
||||
{
|
||||
errMsg = getSSLErrorDescription(status);
|
||||
close();
|
||||
@ -251,48 +203,44 @@ namespace ix
|
||||
|
||||
ssize_t SocketAppleSSL::send(char* buf, size_t nbyte)
|
||||
{
|
||||
OSStatus status = errSSLWouldBlock;
|
||||
while (status == errSSLWouldBlock)
|
||||
{
|
||||
ssize_t ret = 0;
|
||||
OSStatus status;
|
||||
do {
|
||||
size_t processed = 0;
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
status = SSLWrite(_sslContext, buf, nbyte, &processed);
|
||||
ret += processed;
|
||||
buf += processed;
|
||||
nbyte -= processed;
|
||||
} while (nbyte > 0 && errSSLWouldBlock == status);
|
||||
|
||||
if (processed > 0) return (ssize_t) processed;
|
||||
if (ret == 0 && errSSLClosedAbort != status)
|
||||
ret = -1;
|
||||
return ret;
|
||||
}
|
||||
|
||||
// The connection was reset, inform the caller that this
|
||||
// Socket should close
|
||||
if (status == errSSLClosedGraceful || status == errSSLClosedNoNotify ||
|
||||
status == errSSLClosedAbort)
|
||||
{
|
||||
errno = ECONNRESET;
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (status == errSSLWouldBlock)
|
||||
{
|
||||
errno = EWOULDBLOCK;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
ssize_t SocketAppleSSL::send(const std::string& buffer)
|
||||
{
|
||||
return send((char*)&buffer[0], buffer.size());
|
||||
}
|
||||
|
||||
// No wait support
|
||||
ssize_t SocketAppleSSL::recv(void* buf, size_t nbyte)
|
||||
{
|
||||
OSStatus status = errSSLWouldBlock;
|
||||
while (status == errSSLWouldBlock)
|
||||
while (errSSLWouldBlock == status)
|
||||
{
|
||||
size_t processed = 0;
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
status = SSLRead(_sslContext, buf, nbyte, &processed);
|
||||
|
||||
if (processed > 0) return (ssize_t) processed;
|
||||
if (processed > 0)
|
||||
return (ssize_t) processed;
|
||||
|
||||
// The connection was reset, inform the caller that this
|
||||
// Socket should close
|
||||
if (status == errSSLClosedGraceful || status == errSSLClosedNoNotify ||
|
||||
if (status == errSSLClosedGraceful ||
|
||||
status == errSSLClosedNoNotify ||
|
||||
status == errSSLClosedAbort)
|
||||
{
|
||||
errno = ECONNRESET;
|
||||
@ -308,6 +256,4 @@ namespace ix
|
||||
return -1;
|
||||
}
|
||||
|
||||
} // namespace ix
|
||||
|
||||
#endif // IXWEBSOCKET_USE_SECURE_TRANSPORT
|
||||
}
|
||||
|
@ -1,17 +1,17 @@
|
||||
/*
|
||||
* IXSocketAppleSSL.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017-2020 Machine Zone, Inc. All rights reserved.
|
||||
* Copyright (c) 2017-2018 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#ifdef IXWEBSOCKET_USE_SECURE_TRANSPORT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXCancellationRequest.h"
|
||||
#include "IXSocket.h"
|
||||
#include "IXSocketTLSOptions.h"
|
||||
#include <Security/SecureTransport.h>
|
||||
#include "IXCancellationRequest.h"
|
||||
|
||||
#include <Security/Security.h>
|
||||
#include <Security/SecureTransport.h>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
namespace ix
|
||||
@ -19,11 +19,9 @@ namespace ix
|
||||
class SocketAppleSSL final : public Socket
|
||||
{
|
||||
public:
|
||||
SocketAppleSSL(const SocketTLSOptions& tlsOptions, int fd = -1);
|
||||
SocketAppleSSL(int fd = -1);
|
||||
~SocketAppleSSL();
|
||||
|
||||
virtual bool accept(std::string& errMsg) final;
|
||||
|
||||
virtual bool connect(const std::string& host,
|
||||
int port,
|
||||
std::string& errMsg,
|
||||
@ -31,22 +29,12 @@ namespace ix
|
||||
virtual void close() final;
|
||||
|
||||
virtual ssize_t send(char* buffer, size_t length) final;
|
||||
virtual ssize_t send(const std::string& buffer) final;
|
||||
virtual ssize_t recv(void* buffer, size_t length) final;
|
||||
|
||||
private:
|
||||
static std::string getSSLErrorDescription(OSStatus status);
|
||||
static OSStatus writeToSocket(SSLConnectionRef connection, const void* data, size_t* len);
|
||||
static OSStatus readFromSocket(SSLConnectionRef connection, void* data, size_t* len);
|
||||
|
||||
OSStatus tlsHandShake(std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
|
||||
SSLContextRef _sslContext;
|
||||
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe
|
||||
|
||||
SocketTLSOptions _tlsOptions;
|
||||
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe
|
||||
};
|
||||
|
||||
} // namespace ix
|
||||
|
||||
#endif // IXWEBSOCKET_USE_SECURE_TRANSPORT
|
||||
}
|
||||
|
@ -5,36 +5,36 @@
|
||||
*/
|
||||
|
||||
#include "IXSocketConnect.h"
|
||||
|
||||
#include "IXDNSLookup.h"
|
||||
#include "IXNetSystem.h"
|
||||
#include "IXSelectInterrupt.h"
|
||||
#include "IXSocket.h"
|
||||
#include <fcntl.h>
|
||||
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
// Android needs extra headers for TCP_NODELAY and IPPROTO_TCP
|
||||
#ifdef ANDROID
|
||||
#include <linux/in.h>
|
||||
#include <linux/tcp.h>
|
||||
# include <linux/in.h>
|
||||
# include <linux/tcp.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
//
|
||||
// This function can be cancelled every 50 ms
|
||||
// This is important so that we don't block the main UI thread when shutting down a
|
||||
// connection which is already trying to reconnect, and can be blocked waiting for
|
||||
// ::connect to respond.
|
||||
// This is important so that we don't block the main UI thread when shutting down a connection which is
|
||||
// already trying to reconnect, and can be blocked waiting for ::connect to respond.
|
||||
//
|
||||
int SocketConnect::connectToAddress(const struct addrinfo* address,
|
||||
int SocketConnect::connectToAddress(const struct addrinfo *address,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
errMsg = "no error";
|
||||
|
||||
int fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
|
||||
int fd = socket(address->ai_family,
|
||||
address->ai_socktype,
|
||||
address->ai_protocol);
|
||||
if (fd < 0)
|
||||
{
|
||||
errMsg = "Cannot create a socket";
|
||||
@ -63,30 +63,55 @@ namespace ix
|
||||
return -1;
|
||||
}
|
||||
|
||||
int timeoutMs = 10;
|
||||
bool readyToRead = false;
|
||||
auto selectInterrupt = std::make_unique<SelectInterrupt>();
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, fd, selectInterrupt);
|
||||
// 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
|
||||
|
||||
if (pollResult == PollResultType::Timeout)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
else if (pollResult == PollResultType::Error)
|
||||
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))
|
||||
{
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = std::string("Connect error: ") + strerror(Socket::getErrno());
|
||||
errMsg = std::string("Connect error, select error: ") + strerror(Socket::getErrno());
|
||||
return -1;
|
||||
}
|
||||
else if (pollResult == PollResultType::ReadyForWrite)
|
||||
|
||||
// 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
|
||||
{
|
||||
return fd;
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = strerror(optval);
|
||||
return -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
Socket::closeSocket(fd);
|
||||
errMsg = std::string("Connect error: ") + strerror(Socket::getErrno());
|
||||
return -1;
|
||||
// Success !
|
||||
return fd;
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,8 +128,8 @@ namespace ix
|
||||
//
|
||||
// First do DNS resolution
|
||||
//
|
||||
auto dnsLookup = std::make_shared<DNSLookup>(hostname, port);
|
||||
struct addrinfo* res = dnsLookup->resolve(errMsg, isCancellationRequested);
|
||||
DNSLookup dnsLookup(hostname, port);
|
||||
struct addrinfo *res = dnsLookup.resolve(errMsg, isCancellationRequested);
|
||||
if (res == nullptr)
|
||||
{
|
||||
return -1;
|
||||
@ -113,7 +138,7 @@ namespace ix
|
||||
int sockfd = -1;
|
||||
|
||||
// iterate through the records to find a working peer
|
||||
struct addrinfo* address;
|
||||
struct addrinfo *address;
|
||||
for (address = res; address != nullptr; address = address->ai_next)
|
||||
{
|
||||
//
|
||||
@ -148,7 +173,8 @@ namespace ix
|
||||
// 3. (apple) prevent SIGPIPE from being emitted when the remote end disconnect
|
||||
#ifdef SO_NOSIGPIPE
|
||||
int value = 1;
|
||||
setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void*) &value, sizeof(value));
|
||||
setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE,
|
||||
(void *)&value, sizeof(value));
|
||||
#endif
|
||||
}
|
||||
} // namespace ix
|
||||
}
|
||||
|
@ -7,14 +7,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "IXCancellationRequest.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
struct addrinfo;
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class SocketConnect
|
||||
{
|
||||
class SocketConnect {
|
||||
public:
|
||||
static int connect(const std::string& hostname,
|
||||
int port,
|
||||
@ -24,8 +24,9 @@ namespace ix
|
||||
static void configure(int sockfd);
|
||||
|
||||
private:
|
||||
static int connectToAddress(const struct addrinfo* address,
|
||||
static int connectToAddress(const struct addrinfo *address,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
};
|
||||
} // namespace ix
|
||||
}
|
||||
|
||||
|
@ -8,45 +8,42 @@
|
||||
|
||||
#ifdef IXWEBSOCKET_USE_TLS
|
||||
|
||||
#ifdef IXWEBSOCKET_USE_MBED_TLS
|
||||
#include "IXSocketMbedTLS.h"
|
||||
#elif defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
#include "IXSocketOpenSSL.h"
|
||||
#elif __APPLE__
|
||||
#include "IXSocketAppleSSL.h"
|
||||
#endif
|
||||
# ifdef __APPLE__
|
||||
# include <ixwebsocket/IXSocketAppleSSL.h>
|
||||
# elif defined(_WIN32)
|
||||
# include <ixwebsocket/IXSocketSChannel.h>
|
||||
# else
|
||||
# include <ixwebsocket/IXSocketOpenSSL.h>
|
||||
# endif
|
||||
|
||||
#else
|
||||
|
||||
#include "IXSocket.h"
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::unique_ptr<Socket> createSocket(bool tls,
|
||||
int fd,
|
||||
std::string& errorMsg,
|
||||
const SocketTLSOptions& tlsOptions)
|
||||
std::shared_ptr<Socket> createSocket(bool tls,
|
||||
std::string& errorMsg)
|
||||
{
|
||||
(void) tlsOptions;
|
||||
errorMsg.clear();
|
||||
std::unique_ptr<Socket> socket;
|
||||
std::shared_ptr<Socket> socket;
|
||||
|
||||
if (!tls)
|
||||
{
|
||||
socket = std::make_unique<Socket>(fd);
|
||||
socket = std::make_shared<Socket>();
|
||||
}
|
||||
else
|
||||
{
|
||||
#ifdef IXWEBSOCKET_USE_TLS
|
||||
#if defined(IXWEBSOCKET_USE_MBED_TLS)
|
||||
socket = std::make_unique<SocketMbedTLS>(tlsOptions, fd);
|
||||
#elif defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
socket = std::make_unique<SocketOpenSSL>(tlsOptions, fd);
|
||||
#elif defined(__APPLE__)
|
||||
socket = std::make_unique<SocketAppleSSL>(tlsOptions, fd);
|
||||
#endif
|
||||
# ifdef __APPLE__
|
||||
socket = std::make_shared<SocketAppleSSL>();
|
||||
# elif defined(_WIN32)
|
||||
socket = std::make_shared<SocketSChannel>();
|
||||
# else
|
||||
socket = std::make_shared<SocketOpenSSL>();
|
||||
# endif
|
||||
#else
|
||||
errorMsg = "TLS support is not enabled on this platform.";
|
||||
return nullptr;
|
||||
@ -60,4 +57,18 @@ namespace ix
|
||||
|
||||
return socket;
|
||||
}
|
||||
} // namespace ix
|
||||
|
||||
std::shared_ptr<Socket> createSocket(int fd,
|
||||
std::string& errorMsg)
|
||||
{
|
||||
errorMsg.clear();
|
||||
|
||||
std::shared_ptr<Socket> socket = std::make_shared<Socket>(fd);
|
||||
if (!socket->init(errorMsg))
|
||||
{
|
||||
socket.reset();
|
||||
}
|
||||
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user