Compare commits
74 Commits
v8.2.3
...
feature/we
Author | SHA1 | Date | |
---|---|---|---|
cc588f9c05 | |||
415f6b4832 | |||
13d3300a40 | |||
432f0570f4 | |||
37a054723a | |||
c57cf413fb | |||
f1c106728b | |||
2eb5c9480e | |||
f9d75c9374 | |||
d1cd5e62ac | |||
f3b97097cd | |||
605be72579 | |||
49ff3789b5 | |||
96d61c6e5b | |||
9a23c5aaac | |||
d81e4d4fc0 | |||
bd44d32fdb | |||
b6abc12ecd | |||
2268b743ae | |||
1d3db5f75b | |||
296762ce06 | |||
e465f7af52 | |||
f8bf1fe7cd | |||
cfa5718e40 | |||
40c619c1ec | |||
22b02e0e5c | |||
738a3bf1c5 | |||
598fb071e3 | |||
686aface26 | |||
3073dd3f06 | |||
68c64f3f69 | |||
771ebb2a4c | |||
0fffb1e894 | |||
18164c0c38 | |||
d2db7310ff | |||
09e4584fc8 | |||
da36856d85 | |||
dffa759f71 | |||
61e789d6a4 | |||
37cb2cc266 | |||
179e17895d | |||
9f818c7acf | |||
9dcc2538ae | |||
f41a54186c | |||
e0733d205c | |||
f72f845ad2 | |||
b7e7837d76 | |||
fe966b19c7 | |||
a0ffb2ba53 | |||
5ad54a8904 | |||
10e132e8ef | |||
5ce846f48b | |||
1d6373335c | |||
829751b7af | |||
5691b55967 | |||
575bceb1ec | |||
6085839ef7 | |||
696d802703 | |||
b287730c19 | |||
d6f534de06 | |||
8ec515f292 | |||
c6204f4d90 | |||
7dfad9c0cc | |||
21fac0be6c | |||
0bddf5e096 | |||
946a8231e0 | |||
49d1e8493a | |||
6198657dd6 | |||
385d6f5f4a | |||
3919153a7b | |||
e8f81776f9 | |||
0bb5462504 | |||
44f599747e | |||
9801ebdb36 |
97
.github/workflows/ccpp.yml
vendored
97
.github/workflows/ccpp.yml
vendored
@ -1,51 +1,78 @@
|
||||
name: unittest
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
|
||||
on: [push]
|
||||
|
||||
# fake comment to trigger an action 1
|
||||
jobs:
|
||||
linux:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: make test
|
||||
run: make test
|
||||
|
||||
mac:
|
||||
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
|
||||
- name: make test
|
||||
run: make test
|
||||
run: make test_tsan_openssl
|
||||
|
||||
# We don't need to have redis running anymore, as we have our fake limited one
|
||||
# - name: install redis
|
||||
# run: brew install redis
|
||||
#
|
||||
# - name: start redis server
|
||||
# run: brew services start redis
|
||||
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_mbedtls:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: seanmiddleditch/gha-setup-vsdevenv@master
|
||||
- run: |
|
||||
vcpkg install zlib:x64-windows
|
||||
vcpkg install mbedtls:x64-windows
|
||||
- run: |
|
||||
mkdir build
|
||||
cd build
|
||||
cmake -DCMAKE_TOOLCHAIN_FILE=c:/vcpkg/scripts/buildsystems/vcpkg.cmake -DCMAKE_CXX_COMPILER=cl.exe -DUSE_MBED_TLS=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
|
||||
|
||||
#
|
||||
# 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
|
||||
|
||||
# # Windows does not work yet, I'm stuck at getting CMake to run + finding vcpkg
|
||||
# win:
|
||||
# runs-on: windows-2016
|
||||
#
|
||||
# steps:
|
||||
# - uses: actions/checkout@v1
|
||||
#
|
||||
# - name: run cmake
|
||||
# run: |
|
||||
# "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"
|
||||
# mkdir build
|
||||
# cd build
|
||||
# cmake -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%\scripts\buildsystems\vcpkg.cmake -DUSE_WS=1 -DUSE_TEST=1 -DUSE_TLS=1 -G"NMake Makefiles" ..
|
||||
# - name: build
|
||||
# run: |
|
||||
# "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"
|
||||
# cd build
|
||||
# nmake
|
||||
# - name: run tests
|
||||
# run:
|
||||
# cd test
|
||||
# ..\build\test\ixwebsocket_unittest.exe
|
||||
|
25
.github/workflows/mkdocs.yml
vendored
Normal file
25
.github/workflows/mkdocs.yml
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
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
Normal file
19
.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
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'
|
59
.travis.yml
59
.travis.yml
@ -1,59 +0,0 @@
|
||||
language: bash
|
||||
|
||||
# See https://github.com/amaiorano/vectrexy/blob/master/.travis.yml
|
||||
# for ideas on installing vcpkg
|
||||
|
||||
matrix:
|
||||
include:
|
||||
# macOS
|
||||
# - os: osx
|
||||
# env:
|
||||
# - HOMEBREW_NO_AUTO_UPDATE=1
|
||||
# compiler: clang
|
||||
# script:
|
||||
# - brew install redis
|
||||
# - brew services start redis
|
||||
# - brew install mbedtls
|
||||
# - python test/run.py
|
||||
# - make ws
|
||||
|
||||
Linux
|
||||
- os: linux
|
||||
dist: bionic
|
||||
before_install:
|
||||
- sudo apt-get install -y libmbedtls-dev
|
||||
- sudo apt-get install -y redis-server
|
||||
script:
|
||||
- python test/run.py
|
||||
# - make ws
|
||||
env:
|
||||
- CC=gcc
|
||||
- CXX=g++
|
||||
|
||||
# Clang + Linux disabled for now
|
||||
# - os: linux
|
||||
# dist: xenial
|
||||
# script: python test/run.py
|
||||
# env:
|
||||
# - CC=clang
|
||||
# - CXX=clang++
|
||||
|
||||
# Windows
|
||||
# - os: windows
|
||||
# env:
|
||||
# - CMAKE_PATH="/c/Program Files/CMake/bin"
|
||||
# script:
|
||||
# - cd third_party/zlib
|
||||
# - cmake .
|
||||
# - cmake --build . --target install
|
||||
# - cd ../..
|
||||
# # - cd third_party/mbedtls
|
||||
# # - cmake .
|
||||
# # - cmake --build . --target install
|
||||
# # - cd ../..
|
||||
# - export PATH=$CMAKE_PATH:$PATH
|
||||
# - cd test
|
||||
# - cmake .
|
||||
# - cmake --build --parallel .
|
||||
# - ixwebsocket_unittest.exe
|
||||
# # - python test/run.py
|
@ -5,7 +5,7 @@ include(FindPackageHandleStandardArgs)
|
||||
find_path(JSONCPP_INCLUDE_DIRS json/json.h)
|
||||
find_library(JSONCPP_LIBRARY jsoncpp)
|
||||
|
||||
find_package_handle_standard_args(JSONCPP
|
||||
find_package_handle_standard_args(JsonCpp
|
||||
FOUND_VAR
|
||||
JSONCPP_FOUND
|
||||
REQUIRED_VARS
|
||||
|
@ -21,6 +21,7 @@ if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
endif()
|
||||
|
||||
set( IXWEBSOCKET_SOURCES
|
||||
ixwebsocket/IXBench.cpp
|
||||
ixwebsocket/IXCancellationRequest.cpp
|
||||
ixwebsocket/IXConnectionState.cpp
|
||||
ixwebsocket/IXDNSLookup.cpp
|
||||
@ -36,13 +37,14 @@ set( IXWEBSOCKET_SOURCES
|
||||
ixwebsocket/IXSocketFactory.cpp
|
||||
ixwebsocket/IXSocketServer.cpp
|
||||
ixwebsocket/IXSocketTLSOptions.cpp
|
||||
ixwebsocket/IXUdpSocket.cpp
|
||||
ixwebsocket/IXUrlParser.cpp
|
||||
ixwebsocket/IXUserAgent.cpp
|
||||
ixwebsocket/IXWebSocket.cpp
|
||||
ixwebsocket/IXWebSocketCloseConstants.cpp
|
||||
ixwebsocket/IXWebSocketHandshake.cpp
|
||||
ixwebsocket/IXWebSocketHttpHeaders.cpp
|
||||
ixwebsocket/IXWebSocketMessageQueue.cpp
|
||||
ixwebsocket/IXWebSocketMessage.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflate.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateCodec.cpp
|
||||
ixwebsocket/IXWebSocketPerMessageDeflateOptions.cpp
|
||||
@ -52,6 +54,7 @@ set( IXWEBSOCKET_SOURCES
|
||||
)
|
||||
|
||||
set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXBench.h
|
||||
ixwebsocket/IXCancellationRequest.h
|
||||
ixwebsocket/IXConnectionState.h
|
||||
ixwebsocket/IXDNSLookup.h
|
||||
@ -69,6 +72,7 @@ set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXSocketFactory.h
|
||||
ixwebsocket/IXSocketServer.h
|
||||
ixwebsocket/IXSocketTLSOptions.h
|
||||
ixwebsocket/IXUdpSocket.h
|
||||
ixwebsocket/IXUrlParser.h
|
||||
ixwebsocket/IXUtf8Validator.h
|
||||
ixwebsocket/IXUserAgent.h
|
||||
@ -80,7 +84,6 @@ set( IXWEBSOCKET_HEADERS
|
||||
ixwebsocket/IXWebSocketHttpHeaders.h
|
||||
ixwebsocket/IXWebSocketInitResult.h
|
||||
ixwebsocket/IXWebSocketMessage.h
|
||||
ixwebsocket/IXWebSocketMessageQueue.h
|
||||
ixwebsocket/IXWebSocketMessageType.h
|
||||
ixwebsocket/IXWebSocketOpenInfo.h
|
||||
ixwebsocket/IXWebSocketPerMessageDeflate.h
|
||||
@ -116,13 +119,14 @@ endif()
|
||||
option(USE_TLS "Enable TLS support" FALSE)
|
||||
|
||||
if (USE_TLS)
|
||||
if (WIN32)
|
||||
option(USE_MBED_TLS "Use Mbed TLS" ON)
|
||||
else()
|
||||
option(USE_MBED_TLS "Use Mbed TLS" OFF)
|
||||
endif()
|
||||
option(USE_MBED_TLS "Use Mbed TLS" OFF)
|
||||
option(USE_OPEN_SSL "Use OpenSSL" OFF)
|
||||
|
||||
|
||||
# default to mbedtls on windows if nothing is configured
|
||||
if (WIN32 AND NOT USE_OPEN_SSL AND NOT USE_MBED_TLS)
|
||||
option(USE_MBED_TLS "Use Mbed TLS" ON)
|
||||
endif()
|
||||
|
||||
if (USE_MBED_TLS)
|
||||
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketMbedTLS.h)
|
||||
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketMbedTLS.cpp)
|
||||
@ -196,7 +200,9 @@ if (USE_TLS AND USE_MBED_TLS)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
find_package(ZLIB)
|
||||
if (NOT ZLIB_FOUND)
|
||||
find_package(ZLIB)
|
||||
endif()
|
||||
if (ZLIB_FOUND)
|
||||
include_directories(${ZLIB_INCLUDE_DIRS})
|
||||
target_link_libraries(ixwebsocket ${ZLIB_LIBRARIES})
|
||||
|
@ -1 +1 @@
|
||||
docker/Dockerfile.centos
|
||||
docker/Dockerfile.alpine
|
@ -1,12 +1,13 @@
|
||||
FROM alpine:3.11 as build
|
||||
|
||||
RUN apk add --no-cache gcc g++ musl-dev linux-headers cmake openssl-dev
|
||||
RUN apk add --no-cache make
|
||||
RUN apk add --no-cache zlib-dev
|
||||
RUN apk add --no-cache \
|
||||
gcc g++ musl-dev linux-headers \
|
||||
cmake mbedtls-dev make zlib-dev
|
||||
|
||||
RUN addgroup -S app && adduser -S -G app app
|
||||
RUN chown -R app:app /opt
|
||||
RUN chown -R app:app /usr/local
|
||||
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
|
||||
@ -14,22 +15,21 @@ COPY --chown=app:app . /opt
|
||||
WORKDIR /opt
|
||||
|
||||
USER app
|
||||
RUN [ "make", "ws_install" ]
|
||||
RUN [ "rm", "-rf", "build" ]
|
||||
RUN make ws_mbedtls_install && \
|
||||
sh tools/trim_repo_for_docker.sh
|
||||
|
||||
FROM alpine:3.11 as runtime
|
||||
|
||||
RUN apk add --no-cache libstdc++
|
||||
RUN apk add --no-cache strace
|
||||
RUN apk add --no-cache gdb
|
||||
RUN apk add --no-cache libstdc++ mbedtls ca-certificates && \
|
||||
addgroup -S app && \
|
||||
adduser -S -G app app
|
||||
|
||||
RUN addgroup -S app && adduser -S -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
|
||||
# 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
|
||||
|
@ -1,6 +1,9 @@
|
||||
FROM centos:8 as build
|
||||
|
||||
RUN yum install -y gcc-c++ make cmake zlib-devel openssl-devel redhat-rpm-config
|
||||
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
|
||||
@ -12,13 +15,16 @@ COPY --chown=app:app . /opt
|
||||
WORKDIR /opt
|
||||
|
||||
USER app
|
||||
RUN [ "make", "ws_install" ]
|
||||
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
|
||||
|
@ -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
|
||||
@ -27,7 +27,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
|
||||
|
@ -2,14 +2,14 @@
|
||||
FROM ubuntu:bionic 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
|
||||
|
@ -2,14 +2,14 @@
|
||||
FROM ubuntu:disco 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
|
||||
|
@ -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,6 +1,152 @@
|
||||
# Changelog
|
||||
All changes to this project will be documented in this file.
|
||||
|
||||
## [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
|
||||
@ -63,7 +209,7 @@ All changes to this project will be documented in this file.
|
||||
|
||||
## [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
|
||||
(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
|
||||
|
||||
|
@ -47,12 +47,12 @@ vcpkg install ixwebsocket
|
||||
|
||||
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
|
||||
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.
|
||||
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
|
||||
|
||||
|
@ -8,6 +8,8 @@ The per message deflate compression option is supported. It can lead to very nic
|
||||
|
||||
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.
|
||||
@ -26,7 +28,13 @@ The library has an interactive tool which is handy for testing compatibility ith
|
||||
|
||||
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 travis.
|
||||
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
|
||||
|
||||
@ -73,5 +81,3 @@ Here is a simplistic diagram which explains how the code is structured in term o
|
||||
| |
|
||||
+-----------------------+
|
||||
```
|
||||
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||

|
||||

|
||||
|
||||
## Introduction
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
|
||||
## Example code
|
||||
|
||||
```cpp
|
||||
```c++
|
||||
// Required on Windows
|
||||
ix::initNetSystem();
|
||||
|
||||
@ -44,7 +44,22 @@ webSocket.send("hello world");
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
|
94
docs/packages.md
Normal file
94
docs/packages.md
Normal file
@ -0,0 +1,94 @@
|
||||
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.
|
@ -35,7 +35,7 @@ webSocket.setUrl(url);
|
||||
|
||||
// Optional heart beat, sent every 45 seconds when there is not any traffic
|
||||
// to make sure that load balancers do not kill an idle connection.
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
webSocket.setPingInterval(45);
|
||||
|
||||
// Per message deflate connection is enabled by default. You can tweak its parameters or disable it
|
||||
webSocket.disablePerMessageDeflate();
|
||||
@ -174,7 +174,7 @@ when there is no any traffic to make sure that load balancers do not kill an
|
||||
idle connection.
|
||||
|
||||
```cpp
|
||||
webSocket.setHeartBeatPeriod(45);
|
||||
webSocket.setPingInterval(45);
|
||||
```
|
||||
|
||||
### Supply extra HTTP headers.
|
||||
@ -244,39 +244,6 @@ webSocket.setMaxWaitBetweenReconnectionRetries(5 * 1000); // 5000ms = 5s
|
||||
uint32_t m = webSocket.getMaxWaitBetweenReconnectionRetries();
|
||||
```
|
||||
|
||||
### TLS support and configuration
|
||||
|
||||
To leverage TLS features, the library must be compiled with the option `USE_TLS=1`.
|
||||
|
||||
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"
|
||||
});
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
## WebSocket server API
|
||||
|
||||
```cpp
|
||||
@ -464,3 +431,39 @@ setOnConnectionCallback(
|
||||
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",
|
||||
.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.
|
||||
|
||||
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
|
||||
|
@ -7,12 +7,14 @@ set (IXBOTS_SOURCES
|
||||
ixbots/IXCobraToSentryBot.cpp
|
||||
ixbots/IXCobraToStatsdBot.cpp
|
||||
ixbots/IXQueueManager.cpp
|
||||
ixbots/IXStatsdClient.cpp
|
||||
)
|
||||
|
||||
set (IXBOTS_HEADERS
|
||||
ixbots/IXCobraToSentryBot.h
|
||||
ixbots/IXCobraToStatsdBot.h
|
||||
ixbots/IXQueueManager.h
|
||||
ixbots/IXStatsdClient.h
|
||||
)
|
||||
|
||||
add_library(ixbots STATIC
|
||||
@ -30,16 +32,14 @@ if (NOT SPDLOG_FOUND)
|
||||
set(SPDLOG_INCLUDE_DIRS ../third_party/spdlog/include)
|
||||
endif()
|
||||
|
||||
set(STATSD_CLIENT_INCLUDE_DIRS ../third_party/statsd-client-cpp/src)
|
||||
|
||||
set(IXBOTS_INCLUDE_DIRS
|
||||
.
|
||||
..
|
||||
../ixcore
|
||||
../ixwebsocket
|
||||
../ixcobra
|
||||
../ixsentry
|
||||
${JSONCPP_INCLUDE_DIRS}
|
||||
${SPDLOG_INCLUDE_DIRS}
|
||||
${STATSD_CLIENT_INCLUDE_DIRS})
|
||||
${SPDLOG_INCLUDE_DIRS})
|
||||
|
||||
target_include_directories( ixbots PUBLIC ${IXBOTS_INCLUDE_DIRS} )
|
||||
|
@ -19,6 +19,7 @@ namespace ix
|
||||
int cobra_to_sentry_bot(const CobraConfig& config,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& position,
|
||||
SentryClient& sentryClient,
|
||||
bool verbose,
|
||||
bool strict,
|
||||
@ -36,8 +37,9 @@ namespace ix
|
||||
std::atomic<bool> errorSending(false);
|
||||
std::atomic<bool> stop(false);
|
||||
std::atomic<bool> throttled(false);
|
||||
std::atomic<bool> fatalCobraError(false);
|
||||
|
||||
QueueManager queueManager(maxQueueSize, stop);
|
||||
QueueManager queueManager(maxQueueSize);
|
||||
|
||||
auto timer = [&sentCount, &receivedCount, &stop] {
|
||||
while (!stop)
|
||||
@ -173,10 +175,12 @@ namespace ix
|
||||
conn.setEventCallback([&conn,
|
||||
&channel,
|
||||
&filter,
|
||||
&position,
|
||||
&jsonWriter,
|
||||
verbose,
|
||||
&throttled,
|
||||
&receivedCount,
|
||||
&fatalCobraError,
|
||||
&queueManager](ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
@ -200,6 +204,7 @@ namespace ix
|
||||
spdlog::info("Subscriber authenticated");
|
||||
conn.subscribe(channel,
|
||||
filter,
|
||||
position,
|
||||
[&jsonWriter, verbose, &throttled, &receivedCount, &queueManager](
|
||||
const Json::Value& msg, const std::string& position) {
|
||||
if (verbose)
|
||||
@ -237,6 +242,21 @@ namespace ix
|
||||
{
|
||||
spdlog::info("Received websocket pong");
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Handshake_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Handshake error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authentication_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Authentication error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscription_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Subscription error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Run forever
|
||||
@ -248,6 +268,7 @@ namespace ix
|
||||
std::this_thread::sleep_for(duration);
|
||||
|
||||
if (strict && errorSending) break;
|
||||
if (fatalCobraError) break;
|
||||
}
|
||||
}
|
||||
// Run for a duration, used by unittesting now
|
||||
@ -259,6 +280,7 @@ namespace ix
|
||||
std::this_thread::sleep_for(duration);
|
||||
|
||||
if (strict && errorSending) break;
|
||||
if (fatalCobraError) break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -269,12 +291,15 @@ namespace ix
|
||||
conn.disconnect();
|
||||
stop = true;
|
||||
|
||||
// progress thread
|
||||
t1.join();
|
||||
if (t2.joinable()) t2.join();
|
||||
spdlog::info("heartbeat thread done");
|
||||
|
||||
// heartbeat thread
|
||||
if (t2.joinable()) t2.join();
|
||||
|
||||
// sentry sender thread
|
||||
t3.join();
|
||||
|
||||
return (strict && errorSending) ? -1 : (int) sentCount;
|
||||
return ((strict && errorSending) || fatalCobraError) ? -1 : (int) sentCount;
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -1,7 +1,7 @@
|
||||
/*
|
||||
* IXCobraToSentryBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
@ -14,6 +14,7 @@ namespace ix
|
||||
int cobra_to_sentry_bot(const CobraConfig& config,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& position,
|
||||
SentryClient& sentryClient,
|
||||
bool verbose,
|
||||
bool strict,
|
||||
|
@ -6,6 +6,7 @@
|
||||
|
||||
#include "IXCobraToStatsdBot.h"
|
||||
#include "IXQueueManager.h"
|
||||
#include "IXStatsdClient.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@ -16,10 +17,6 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <statsd_client.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
// fields are command line argument that can be specified multiple times
|
||||
@ -43,7 +40,7 @@ namespace ix
|
||||
// Extract an attribute from a Json Value.
|
||||
// extractAttr("foo.bar", {"foo": {"bar": "baz"}}) => baz
|
||||
//
|
||||
std::string extractAttr(const std::string& attr, const Json::Value& jsonValue)
|
||||
Json::Value extractAttr(const std::string& attr, const Json::Value& jsonValue)
|
||||
{
|
||||
// Split by .
|
||||
std::string token;
|
||||
@ -56,17 +53,21 @@ namespace ix
|
||||
val = val[token];
|
||||
}
|
||||
|
||||
return val.asString();
|
||||
return val;
|
||||
}
|
||||
|
||||
int cobra_to_statsd_bot(const ix::CobraConfig& config,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& host,
|
||||
int port,
|
||||
const std::string& prefix,
|
||||
const std::string& position,
|
||||
StatsdClient& statsdClient,
|
||||
const std::string& fields,
|
||||
bool verbose)
|
||||
const std::string& gauge,
|
||||
const std::string& timer,
|
||||
bool verbose,
|
||||
size_t maxQueueSize,
|
||||
bool enableHeartbeat,
|
||||
int runtime)
|
||||
{
|
||||
ix::CobraConnection conn;
|
||||
conn.configure(config);
|
||||
@ -78,26 +79,30 @@ namespace ix
|
||||
std::atomic<uint64_t> sentCount(0);
|
||||
std::atomic<uint64_t> receivedCount(0);
|
||||
std::atomic<bool> stop(false);
|
||||
std::atomic<bool> fatalCobraError(false);
|
||||
|
||||
size_t maxQueueSize = 1000;
|
||||
QueueManager queueManager(maxQueueSize, stop);
|
||||
QueueManager queueManager(maxQueueSize);
|
||||
|
||||
auto timer = [&sentCount, &receivedCount] {
|
||||
while (true)
|
||||
auto progress = [&sentCount, &receivedCount, &stop] {
|
||||
while (!stop)
|
||||
{
|
||||
spdlog::info("messages received {} sent {}", receivedCount, sentCount);
|
||||
|
||||
auto duration = std::chrono::seconds(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
}
|
||||
|
||||
spdlog::info("timer thread done");
|
||||
};
|
||||
|
||||
std::thread t1(timer);
|
||||
std::thread t1(progress);
|
||||
|
||||
auto heartbeat = [&sentCount, &receivedCount] {
|
||||
auto heartbeat = [&sentCount, &receivedCount, &stop, &enableHeartbeat] {
|
||||
std::string state("na");
|
||||
|
||||
while (true)
|
||||
if (!enableHeartbeat) return;
|
||||
|
||||
while (!stop)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "messages received " << receivedCount;
|
||||
@ -115,45 +120,88 @@ namespace ix
|
||||
auto duration = std::chrono::minutes(1);
|
||||
std::this_thread::sleep_for(duration);
|
||||
}
|
||||
|
||||
spdlog::info("heartbeat thread done");
|
||||
};
|
||||
|
||||
std::thread t2(heartbeat);
|
||||
|
||||
auto statsdSender = [&queueManager, &host, &port, &sentCount, &tokens, &prefix, &stop] {
|
||||
// statsd client
|
||||
// test with netcat as a server: `nc -ul 8125`
|
||||
bool statsdBatch = true;
|
||||
#ifndef _WIN32
|
||||
statsd::StatsdClient statsdClient(host, port, prefix, statsdBatch);
|
||||
#else
|
||||
int statsdClient;
|
||||
#endif
|
||||
auto statsdSender = [&statsdClient, &queueManager, &sentCount, &tokens, &stop, &gauge, &timer, &fatalCobraError, &verbose] {
|
||||
while (true)
|
||||
{
|
||||
Json::Value msg = queueManager.pop();
|
||||
|
||||
if (msg.isNull()) continue;
|
||||
if (stop) return;
|
||||
if (msg.isNull()) continue;
|
||||
|
||||
std::string id;
|
||||
for (auto&& attr : tokens)
|
||||
{
|
||||
id += ".";
|
||||
id += extractAttr(attr, msg);
|
||||
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
|
||||
{
|
||||
spdlog::error("Gauge {} is not a numberic type", gauge);
|
||||
fatalCobraError = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (verbose)
|
||||
{
|
||||
spdlog::info("{} - {} -> {}", id, attrName, x);
|
||||
}
|
||||
|
||||
if (!gauge.empty())
|
||||
{
|
||||
statsdClient.gauge(id, x);
|
||||
}
|
||||
else
|
||||
{
|
||||
statsdClient.timing(id, x);
|
||||
}
|
||||
}
|
||||
|
||||
sentCount += 1;
|
||||
|
||||
#ifndef _WIN32
|
||||
statsdClient.count(id, 1);
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
std::thread t3(statsdSender);
|
||||
|
||||
conn.setEventCallback(
|
||||
[&conn, &channel, &filter, &jsonWriter, verbose, &queueManager, &receivedCount](
|
||||
[&conn, &channel, &filter, &position, &jsonWriter, verbose, &queueManager, &receivedCount, &fatalCobraError](
|
||||
ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
@ -177,6 +225,7 @@ namespace ix
|
||||
spdlog::info("Subscriber authenticated");
|
||||
conn.subscribe(channel,
|
||||
filter,
|
||||
position,
|
||||
[&jsonWriter, &queueManager, verbose, &receivedCount](
|
||||
const Json::Value& msg, const std::string& position) {
|
||||
if (verbose)
|
||||
@ -210,14 +259,62 @@ namespace ix
|
||||
{
|
||||
spdlog::info("Received websocket pong");
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Handshake_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Handshake error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Authentication_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Authentication error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscription_Error)
|
||||
{
|
||||
spdlog::error("Subscriber: Subscription error: {}", errMsg);
|
||||
fatalCobraError = true;
|
||||
}
|
||||
});
|
||||
|
||||
while (true)
|
||||
// Run forever
|
||||
if (runtime == -1)
|
||||
{
|
||||
std::chrono::duration<double, std::milli> duration(1000);
|
||||
std::this_thread::sleep_for(duration);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
//
|
||||
// Cleanup.
|
||||
// join all the bg threads and stop them.
|
||||
//
|
||||
conn.disconnect();
|
||||
stop = true;
|
||||
|
||||
// progress thread
|
||||
t1.join();
|
||||
|
||||
// heartbeat thread
|
||||
if (t2.joinable()) t2.join();
|
||||
|
||||
// statsd sender thread
|
||||
t3.join();
|
||||
|
||||
return fatalCobraError ? -1 : (int) sentCount;
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -1,11 +1,12 @@
|
||||
/*
|
||||
* IXCobraToStatsdBot.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
|
||||
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <ixcobra/IXCobraConfig.h>
|
||||
#include <ixbots/IXStatsdClient.h>
|
||||
#include <string>
|
||||
#include <stddef.h>
|
||||
|
||||
@ -14,9 +15,13 @@ namespace ix
|
||||
int cobra_to_statsd_bot(const ix::CobraConfig& config,
|
||||
const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& host,
|
||||
int port,
|
||||
const std::string& prefix,
|
||||
const std::string& position,
|
||||
StatsdClient& statsdClient,
|
||||
const std::string& fields,
|
||||
bool verbose);
|
||||
const std::string& gauge,
|
||||
const std::string& timer,
|
||||
bool verbose,
|
||||
size_t maxQueueSize,
|
||||
bool enableHeartbeat,
|
||||
int runtime);
|
||||
} // namespace ix
|
||||
|
@ -7,7 +7,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <atomic>
|
||||
#include <json/json.h>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
@ -19,9 +18,8 @@ namespace ix
|
||||
class QueueManager
|
||||
{
|
||||
public:
|
||||
QueueManager(size_t maxQueueSize, std::atomic<bool>& stop)
|
||||
QueueManager(size_t maxQueueSize)
|
||||
: _maxQueueSize(maxQueueSize)
|
||||
, _stop(stop)
|
||||
{
|
||||
}
|
||||
|
||||
@ -33,6 +31,5 @@ namespace ix
|
||||
std::mutex _mutex;
|
||||
std::condition_variable _condition;
|
||||
size_t _maxQueueSize;
|
||||
std::atomic<bool>& _stop;
|
||||
};
|
||||
}
|
||||
|
152
ixbots/ixbots/IXStatsdClient.cpp
Normal file
152
ixbots/ixbots/IXStatsdClient.cpp
Normal file
@ -0,0 +1,152 @@
|
||||
/*
|
||||
* 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 <ixwebsocket/IXNetSystem.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <iostream>
|
||||
|
||||
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
|
58
ixbots/ixbots/IXStatsdClient.h
Normal file
58
ixbots/ixbots/IXStatsdClient.h
Normal file
@ -0,0 +1,58 @@
|
||||
/*
|
||||
* IXStatsdClient.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <ixwebsocket/IXUdpSocket.h>
|
||||
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
|
||||
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
|
@ -166,7 +166,8 @@ namespace ix
|
||||
}
|
||||
else if (action == "auth/handshake/error")
|
||||
{
|
||||
invokeErrorCallback("Handshake error", msg->str);
|
||||
invokeEventCallback(ix::CobraConnection_EventType_Handshake_Error,
|
||||
msg->str);
|
||||
}
|
||||
else if (action == "auth/authenticate/ok")
|
||||
{
|
||||
@ -176,7 +177,8 @@ namespace ix
|
||||
}
|
||||
else if (action == "auth/authenticate/error")
|
||||
{
|
||||
invokeErrorCallback("Authentication error", msg->str);
|
||||
invokeEventCallback(ix::CobraConnection_EventType_Authentication_Error,
|
||||
msg->str);
|
||||
}
|
||||
else if (action == "rtm/subscription/data")
|
||||
{
|
||||
@ -191,7 +193,8 @@ namespace ix
|
||||
}
|
||||
else if (action == "rtm/subscribe/error")
|
||||
{
|
||||
invokeErrorCallback("Subscription error", msg->str);
|
||||
invokeEventCallback(ix::CobraConnection_EventType_Subscription_Error,
|
||||
msg->str);
|
||||
}
|
||||
else if (action == "rtm/unsubscribe/ok")
|
||||
{
|
||||
@ -270,10 +273,6 @@ namespace ix
|
||||
// This should keep the connection open and prevent some load balancers such as
|
||||
// the Amazon one from shutting it down
|
||||
_webSocket->setPingInterval(kPingIntervalSecs);
|
||||
|
||||
// If we don't receive a pong back, declare loss after 3 * N seconds
|
||||
// (will be 90s now), and close and restart the connection
|
||||
_webSocket->setPingTimeout(3 * kPingIntervalSecs);
|
||||
}
|
||||
|
||||
void CobraConnection::configure(const ix::CobraConfig& config)
|
||||
@ -565,6 +564,7 @@ namespace ix
|
||||
|
||||
void CobraConnection::subscribe(const std::string& channel,
|
||||
const std::string& filter,
|
||||
const std::string& position,
|
||||
SubscriptionCallback cb)
|
||||
{
|
||||
// Create and send a subscribe pdu
|
||||
@ -576,6 +576,11 @@ namespace ix
|
||||
body["filter"] = filter;
|
||||
}
|
||||
|
||||
if (!position.empty())
|
||||
{
|
||||
body["position"] = position;
|
||||
}
|
||||
|
||||
Json::Value pdu;
|
||||
pdu["action"] = "rtm/subscribe";
|
||||
pdu["body"] = body;
|
||||
|
@ -19,6 +19,10 @@
|
||||
|
||||
#include "IXCobraConfig.h"
|
||||
|
||||
#ifdef max
|
||||
#undef max
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class WebSocket;
|
||||
@ -33,7 +37,10 @@ namespace ix
|
||||
CobraConnection_EventType_Subscribed = 4,
|
||||
CobraConnection_EventType_UnSubscribed = 5,
|
||||
CobraConnection_EventType_Published = 6,
|
||||
CobraConnection_EventType_Pong = 7
|
||||
CobraConnection_EventType_Pong = 7,
|
||||
CobraConnection_EventType_Handshake_Error = 8,
|
||||
CobraConnection_EventType_Authentication_Error = 9,
|
||||
CobraConnection_EventType_Subscription_Error = 10
|
||||
};
|
||||
|
||||
enum CobraConnectionPublishMode
|
||||
@ -98,6 +105,7 @@ namespace ix
|
||||
// message arrives.
|
||||
void subscribe(const std::string& channel,
|
||||
const std::string& filter = std::string(),
|
||||
const std::string& position = std::string(),
|
||||
SubscriptionCallback cb = nullptr);
|
||||
|
||||
/// Unsubscribe from a channel
|
||||
|
@ -27,20 +27,12 @@ namespace ix
|
||||
;
|
||||
}
|
||||
|
||||
void CobraMetricsPublisher::configure(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& channel,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
bool enablePerMessageDeflate,
|
||||
const SocketTLSOptions& socketTLSOptions)
|
||||
void CobraMetricsPublisher::configure(const CobraConfig& config,
|
||||
const std::string& channel)
|
||||
{
|
||||
// Configure the satori connection and start its publish background thread
|
||||
_cobra_metrics_theaded_publisher.configure(config, channel);
|
||||
_cobra_metrics_theaded_publisher.start();
|
||||
|
||||
_cobra_metrics_theaded_publisher.configure(appkey, endpoint, channel,
|
||||
rolename, rolesecret,
|
||||
enablePerMessageDeflate, socketTLSOptions);
|
||||
}
|
||||
|
||||
Json::Value& CobraMetricsPublisher::getGenericAttributes()
|
||||
|
@ -40,13 +40,8 @@ namespace ix
|
||||
|
||||
/// Configuration / set keys, etc...
|
||||
/// All input data but the channel name is encrypted with rc4
|
||||
void configure(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& channel,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
bool enablePerMessageDeflate,
|
||||
const SocketTLSOptions& socketTLSOptions);
|
||||
void configure(const CobraConfig& config,
|
||||
const std::string& channel);
|
||||
|
||||
/// Setter for the list of blacklisted metrics ids.
|
||||
/// That list is sorted internally for fast lookups
|
||||
|
@ -92,22 +92,14 @@ namespace ix
|
||||
_thread = std::thread(&CobraMetricsThreadedPublisher::run, this);
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::configure(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& channel,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
bool enablePerMessageDeflate,
|
||||
const SocketTLSOptions& socketTLSOptions)
|
||||
void CobraMetricsThreadedPublisher::configure(const CobraConfig& config,
|
||||
const std::string& channel)
|
||||
{
|
||||
ix::IXCoreLogger::Log(config.socketTLSOptions.getDescription().c_str());
|
||||
|
||||
_channel = channel;
|
||||
_cobra_connection.configure(config);
|
||||
|
||||
ix::IXCoreLogger::Log(socketTLSOptions.getDescription().c_str());
|
||||
|
||||
ix::WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions(enablePerMessageDeflate);
|
||||
_cobra_connection.configure(appkey, endpoint,
|
||||
rolename, rolesecret,
|
||||
webSocketPerMessageDeflateOptions, socketTLSOptions);
|
||||
}
|
||||
|
||||
void CobraMetricsThreadedPublisher::pushMessage(MessageKind messageKind)
|
||||
|
@ -27,13 +27,8 @@ namespace ix
|
||||
~CobraMetricsThreadedPublisher();
|
||||
|
||||
/// Configuration / set keys, etc...
|
||||
void configure(const std::string& appkey,
|
||||
const std::string& endpoint,
|
||||
const std::string& channel,
|
||||
const std::string& rolename,
|
||||
const std::string& rolesecret,
|
||||
bool enablePerMessageDeflate,
|
||||
const SocketTLSOptions& socketTLSOptions);
|
||||
void configure(const CobraConfig& config,
|
||||
const std::string& channel);
|
||||
|
||||
/// Start the worker thread, used for background publishing
|
||||
void start();
|
||||
|
@ -23,7 +23,7 @@ add_library(ixcrypto STATIC
|
||||
${IXCRYPTO_HEADERS}
|
||||
)
|
||||
|
||||
set(IXCRYPTO_INCLUDE_DIRS
|
||||
set(IXCRYPTO_INCLUDE_DIRS
|
||||
.
|
||||
../ixcore)
|
||||
|
||||
@ -31,10 +31,6 @@ target_include_directories( ixcrypto PUBLIC ${IXCRYPTO_INCLUDE_DIRS} )
|
||||
|
||||
# hmac computation needs a crypto library
|
||||
|
||||
if (WIN32)
|
||||
set(USE_MBED_TLS TRUE)
|
||||
endif()
|
||||
|
||||
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_TLS)
|
||||
if (USE_MBED_TLS)
|
||||
find_package(MbedTLS REQUIRED)
|
||||
@ -51,4 +47,3 @@ else()
|
||||
target_link_libraries(ixcrypto ${OPENSSL_LIBRARIES})
|
||||
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_OPEN_SSL)
|
||||
endif()
|
||||
|
||||
|
@ -14,7 +14,7 @@
|
||||
#elif defined(IXCRYPTO_USE_OPEN_SSL)
|
||||
# include <openssl/hmac.h>
|
||||
#else
|
||||
# error "Unsupported configuration"
|
||||
# include <assert.h>
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
@ -40,7 +40,7 @@ namespace ix
|
||||
(unsigned char *) data.c_str(), (int) data.size(),
|
||||
(unsigned char *) hash, nullptr);
|
||||
#else
|
||||
# error "Unsupported configuration"
|
||||
assert(false && "hmac not implemented on this platform");
|
||||
#endif
|
||||
|
||||
std::string hashString(reinterpret_cast<char*>(hash), hashSize);
|
||||
|
@ -9,7 +9,6 @@
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <sstream>
|
||||
|
@ -9,11 +9,12 @@
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class Socket;
|
||||
|
||||
class RedisClient
|
||||
{
|
||||
public:
|
||||
@ -56,7 +57,7 @@ namespace ix
|
||||
private:
|
||||
std::string writeString(const std::string& str);
|
||||
|
||||
std::shared_ptr<Socket> _socket;
|
||||
std::unique_ptr<Socket> _socket;
|
||||
std::atomic<bool> _stop;
|
||||
};
|
||||
} // namespace ix
|
||||
|
@ -11,7 +11,6 @@
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXCancellationRequest.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
@ -44,7 +43,7 @@ namespace ix
|
||||
SocketServer::stop();
|
||||
}
|
||||
|
||||
void RedisServer::handleConnection(std::shared_ptr<Socket> socket,
|
||||
void RedisServer::handleConnection(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
_connectedClientsCount++;
|
||||
@ -103,13 +102,13 @@ namespace ix
|
||||
_connectedClientsCount--;
|
||||
}
|
||||
|
||||
void RedisServer::cleanupSubscribers(std::shared_ptr<Socket> socket)
|
||||
void RedisServer::cleanupSubscribers(std::unique_ptr<Socket>& socket)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
|
||||
for (auto&& it : _subscribers)
|
||||
{
|
||||
it.second.erase(socket);
|
||||
it.second.erase(socket.get());
|
||||
}
|
||||
|
||||
for (auto it : _subscribers)
|
||||
@ -146,7 +145,7 @@ namespace ix
|
||||
}
|
||||
|
||||
bool RedisServer::parseRequest(
|
||||
std::shared_ptr<Socket> socket,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
std::vector<std::string>& tokens)
|
||||
{
|
||||
// Parse first line
|
||||
@ -188,17 +187,11 @@ namespace ix
|
||||
tokens.push_back(readResult.second);
|
||||
}
|
||||
|
||||
for (auto&& token : tokens)
|
||||
{
|
||||
std::cerr << token << " ";
|
||||
}
|
||||
std::cerr << std::endl;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedisServer::handleCommand(
|
||||
std::shared_ptr<Socket> socket,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 1) return false;
|
||||
@ -237,7 +230,7 @@ namespace ix
|
||||
}
|
||||
|
||||
bool RedisServer::handleSubscribe(
|
||||
std::shared_ptr<Socket> socket,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 2) return false;
|
||||
@ -252,13 +245,13 @@ namespace ix
|
||||
socket->writeBytes(":1\r\n", cb);
|
||||
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
_subscribers[channel].insert(socket);
|
||||
_subscribers[channel].insert(socket.get());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RedisServer::handlePublish(
|
||||
std::shared_ptr<Socket> socket,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens)
|
||||
{
|
||||
if (tokens.size() != 3) return false;
|
||||
|
@ -37,13 +37,13 @@ namespace ix
|
||||
// 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<std::shared_ptr<Socket>>> _subscribers;
|
||||
std::map<std::string, std::set<Socket*>> _subscribers;
|
||||
std::mutex _mutex;
|
||||
|
||||
std::atomic<bool> _stopHandlingConnections;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(std::shared_ptr<Socket>,
|
||||
virtual void handleConnection(std::unique_ptr<Socket>,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
|
||||
@ -51,18 +51,18 @@ namespace ix
|
||||
std::string writeString(const std::string& str);
|
||||
|
||||
bool parseRequest(
|
||||
std::shared_ptr<Socket> socket,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
std::vector<std::string>& tokens);
|
||||
|
||||
bool handlePublish(std::shared_ptr<Socket> socket,
|
||||
bool handlePublish(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens);
|
||||
|
||||
bool handleSubscribe(std::shared_ptr<Socket> socket,
|
||||
bool handleSubscribe(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens);
|
||||
|
||||
bool handleCommand(std::shared_ptr<Socket> socket,
|
||||
bool handleCommand(std::unique_ptr<Socket>& socket,
|
||||
const std::vector<std::string>& tokens);
|
||||
|
||||
void cleanupSubscribers(std::shared_ptr<Socket> socket);
|
||||
void cleanupSubscribers(std::unique_ptr<Socket>& socket);
|
||||
};
|
||||
} // namespace ix
|
||||
|
44
ixwebsocket/IXBench.cpp
Normal file
44
ixwebsocket/IXBench.cpp
Normal file
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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
|
28
ixwebsocket/IXBench.h
Normal file
28
ixwebsocket/IXBench.h
Normal file
@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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
|
@ -92,7 +92,8 @@ namespace ix
|
||||
return std::make_tuple(method, requestUri, httpVersion);
|
||||
}
|
||||
|
||||
std::tuple<bool, std::string, HttpRequestPtr> Http::parseRequest(std::shared_ptr<Socket> socket)
|
||||
std::tuple<bool, std::string, HttpRequestPtr> Http::parseRequest(
|
||||
std::unique_ptr<Socket>& socket)
|
||||
{
|
||||
HttpRequestPtr httpRequest;
|
||||
|
||||
@ -133,7 +134,7 @@ namespace ix
|
||||
return std::make_tuple(true, "", httpRequest);
|
||||
}
|
||||
|
||||
bool Http::sendResponse(HttpResponsePtr response, std::shared_ptr<Socket> socket)
|
||||
bool Http::sendResponse(HttpResponsePtr response, std::unique_ptr<Socket>& socket)
|
||||
{
|
||||
// Write the response to the socket
|
||||
std::stringstream ss;
|
||||
|
@ -115,8 +115,8 @@ namespace ix
|
||||
{
|
||||
public:
|
||||
static std::tuple<bool, std::string, HttpRequestPtr> parseRequest(
|
||||
std::shared_ptr<Socket> socket);
|
||||
static bool sendResponse(HttpResponsePtr response, std::shared_ptr<Socket> socket);
|
||||
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(
|
||||
|
@ -95,7 +95,7 @@ namespace ix
|
||||
std::atomic<bool> _stop;
|
||||
std::thread _thread;
|
||||
|
||||
std::shared_ptr<Socket> _socket;
|
||||
std::unique_ptr<Socket> _socket;
|
||||
std::mutex _mutex; // to protect accessing the _socket (only one socket per client)
|
||||
|
||||
SocketTLSOptions _tlsOptions;
|
||||
|
@ -69,7 +69,7 @@ namespace ix
|
||||
_onConnectionCallback = callback;
|
||||
}
|
||||
|
||||
void HttpServer::handleConnection(std::shared_ptr<Socket> socket,
|
||||
void HttpServer::handleConnection(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
_connectedClientsCount++;
|
||||
|
@ -43,7 +43,7 @@ namespace ix
|
||||
std::atomic<int> _connectedClientsCount;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(std::shared_ptr<Socket>,
|
||||
virtual void handleConnection(std::unique_ptr<Socket>,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
|
||||
|
@ -14,12 +14,12 @@
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::shared_ptr<SelectInterrupt> createSelectInterrupt()
|
||||
SelectInterruptPtr createSelectInterrupt()
|
||||
{
|
||||
#if defined(__linux__) || defined(__APPLE__)
|
||||
return std::make_shared<SelectInterruptPipe>();
|
||||
return std::make_unique<SelectInterruptPipe>();
|
||||
#else
|
||||
return std::make_shared<SelectInterrupt>();
|
||||
return std::make_unique<SelectInterrupt>();
|
||||
#endif
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -11,5 +11,6 @@
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterrupt;
|
||||
std::shared_ptr<SelectInterrupt> createSelectInterrupt();
|
||||
using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
|
||||
SelectInterruptPtr createSelectInterrupt();
|
||||
} // namespace ix
|
||||
|
@ -46,7 +46,7 @@ namespace ix
|
||||
PollResultType Socket::poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
std::shared_ptr<SelectInterrupt> selectInterrupt)
|
||||
const SelectInterruptPtr& selectInterrupt)
|
||||
{
|
||||
//
|
||||
// We used to use ::select to poll but on Android 9 we get large fds out of
|
||||
|
@ -38,6 +38,7 @@ typedef SSIZE_T ssize_t;
|
||||
namespace ix
|
||||
{
|
||||
class SelectInterrupt;
|
||||
using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
|
||||
|
||||
enum class PollResultType
|
||||
{
|
||||
@ -66,7 +67,7 @@ namespace ix
|
||||
// Virtual methods
|
||||
virtual bool accept(std::string& errMsg);
|
||||
|
||||
virtual bool connect(const std::string& url,
|
||||
virtual bool connect(const std::string& host,
|
||||
int port,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
@ -93,7 +94,7 @@ namespace ix
|
||||
static PollResultType poll(bool readyToRead,
|
||||
int timeoutMs,
|
||||
int sockfd,
|
||||
std::shared_ptr<SelectInterrupt> selectInterrupt = nullptr);
|
||||
const SelectInterruptPtr& selectInterrupt);
|
||||
|
||||
|
||||
// Used as special codes for pipe communication
|
||||
@ -112,6 +113,6 @@ namespace ix
|
||||
std::vector<uint8_t> _readBuffer;
|
||||
static constexpr size_t kChunkSize = 1 << 15;
|
||||
|
||||
std::shared_ptr<SelectInterrupt> _selectInterrupt;
|
||||
SelectInterruptPtr _selectInterrupt;
|
||||
};
|
||||
} // namespace ix
|
||||
|
@ -164,6 +164,26 @@ namespace ix
|
||||
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,
|
||||
@ -190,26 +210,17 @@ namespace ix
|
||||
Boolean option(1);
|
||||
SSLSetSessionOption(_sslContext, kSSLSessionOptionBreakOnServerAuth, option);
|
||||
|
||||
do
|
||||
{
|
||||
status = SSLHandshake(_sslContext);
|
||||
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
|
||||
if (status == errSSLServerAuthCompleted)
|
||||
{
|
||||
// proceed with the handshake
|
||||
do
|
||||
{
|
||||
status = SSLHandshake(_sslContext);
|
||||
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
do
|
||||
{
|
||||
status = SSLHandshake(_sslContext);
|
||||
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
|
||||
status = tlsHandShake(errMsg, isCancellationRequested);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -37,6 +37,9 @@ namespace ix
|
||||
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
|
||||
|
||||
|
@ -8,6 +8,7 @@
|
||||
|
||||
#include "IXDNSLookup.h"
|
||||
#include "IXNetSystem.h"
|
||||
#include "IXSelectInterrupt.h"
|
||||
#include "IXSocket.h"
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
@ -64,7 +65,8 @@ namespace ix
|
||||
|
||||
int timeoutMs = 10;
|
||||
bool readyToRead = false;
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, fd);
|
||||
auto selectInterrupt = std::make_unique<SelectInterrupt>();
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, fd, selectInterrupt);
|
||||
|
||||
if (pollResult == PollResultType::Timeout)
|
||||
{
|
||||
|
@ -24,28 +24,28 @@
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::shared_ptr<Socket> createSocket(bool tls,
|
||||
std::unique_ptr<Socket> createSocket(bool tls,
|
||||
int fd,
|
||||
std::string& errorMsg,
|
||||
const SocketTLSOptions& tlsOptions)
|
||||
{
|
||||
(void) tlsOptions;
|
||||
errorMsg.clear();
|
||||
std::shared_ptr<Socket> socket;
|
||||
std::unique_ptr<Socket> socket;
|
||||
|
||||
if (!tls)
|
||||
{
|
||||
socket = std::make_shared<Socket>(fd);
|
||||
socket = std::make_unique<Socket>(fd);
|
||||
}
|
||||
else
|
||||
{
|
||||
#ifdef IXWEBSOCKET_USE_TLS
|
||||
#if defined(IXWEBSOCKET_USE_MBED_TLS)
|
||||
socket = std::make_shared<SocketMbedTLS>(tlsOptions, fd);
|
||||
socket = std::make_unique<SocketMbedTLS>(tlsOptions, fd);
|
||||
#elif defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
socket = std::make_shared<SocketOpenSSL>(tlsOptions, fd);
|
||||
socket = std::make_unique<SocketOpenSSL>(tlsOptions, fd);
|
||||
#elif defined(__APPLE__)
|
||||
socket = std::make_shared<SocketAppleSSL>(tlsOptions, fd);
|
||||
socket = std::make_unique<SocketAppleSSL>(tlsOptions, fd);
|
||||
#endif
|
||||
#else
|
||||
errorMsg = "TLS support is not enabled on this platform.";
|
||||
|
@ -14,7 +14,7 @@
|
||||
namespace ix
|
||||
{
|
||||
class Socket;
|
||||
std::shared_ptr<Socket> createSocket(bool tls,
|
||||
std::unique_ptr<Socket> createSocket(bool tls,
|
||||
int fd,
|
||||
std::string& errorMsg,
|
||||
const SocketTLSOptions& tlsOptions);
|
||||
|
@ -195,8 +195,17 @@ namespace ix
|
||||
int res;
|
||||
do
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
res = mbedtls_ssl_handshake(&_ssl);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
res = mbedtls_ssl_handshake(&_ssl);
|
||||
}
|
||||
|
||||
if (isCancellationRequested())
|
||||
{
|
||||
errMsg = "Cancellation requested";
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
} while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE);
|
||||
|
||||
if (res != 0)
|
||||
|
@ -21,6 +21,57 @@
|
||||
#endif
|
||||
#define socketerrno errno
|
||||
|
||||
#ifdef _WIN32
|
||||
namespace
|
||||
{
|
||||
bool loadWindowsSystemCertificates(SSL_CTX* ssl, std::string& errorMsg)
|
||||
{
|
||||
DWORD flags = CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG |
|
||||
CERT_SYSTEM_STORE_CURRENT_USER;
|
||||
HCERTSTORE systemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, flags, L"Root");
|
||||
|
||||
if (!systemStore)
|
||||
{
|
||||
errorMsg = "CertOpenStore failed with ";
|
||||
errorMsg += std::to_string(GetLastError());
|
||||
return false;
|
||||
}
|
||||
|
||||
PCCERT_CONTEXT certificateIterator = NULL;
|
||||
X509_STORE* opensslStore = SSL_CTX_get_cert_store(ssl);
|
||||
|
||||
int certificateCount = 0;
|
||||
while (certificateIterator = CertEnumCertificatesInStore(systemStore, certificateIterator))
|
||||
{
|
||||
X509* x509 = d2i_X509(NULL,
|
||||
(const unsigned char**) &certificateIterator->pbCertEncoded,
|
||||
certificateIterator->cbCertEncoded);
|
||||
|
||||
if (x509)
|
||||
{
|
||||
if (X509_STORE_add_cert(opensslStore, x509) == 1)
|
||||
{
|
||||
++certificateCount;
|
||||
}
|
||||
|
||||
X509_free(x509);
|
||||
}
|
||||
}
|
||||
|
||||
CertFreeCertificateContext(certificateIterator);
|
||||
CertCloseStore(systemStore, 0);
|
||||
|
||||
if (certificateCount == 0)
|
||||
{
|
||||
errorMsg = "No certificates found";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
namespace ix
|
||||
{
|
||||
const std::string kDefaultCiphers =
|
||||
@ -224,7 +275,9 @@ namespace ix
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SocketOpenSSL::openSSLClientHandshake(const std::string& host, std::string& errMsg)
|
||||
bool SocketOpenSSL::openSSLClientHandshake(const std::string& host,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
@ -233,6 +286,12 @@ namespace ix
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isCancellationRequested())
|
||||
{
|
||||
errMsg = "Cancellation requested";
|
||||
return false;
|
||||
}
|
||||
|
||||
ERR_clear_error();
|
||||
int connect_result = SSL_connect(_ssl_connection);
|
||||
if (connect_result == 1)
|
||||
@ -328,6 +387,12 @@ namespace ix
|
||||
{
|
||||
if (_tlsOptions.isUsingSystemDefaults())
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (!loadWindowsSystemCertificates(_ssl_context, errMsg))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
if (SSL_CTX_set_default_verify_paths(_ssl_context) == 0)
|
||||
{
|
||||
auto sslErr = ERR_get_error();
|
||||
@ -335,6 +400,7 @@ namespace ix
|
||||
errMsg += ERR_error_string(sslErr, nullptr);
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else if (SSL_CTX_load_verify_locations(
|
||||
_ssl_context, _tlsOptions.caFile.c_str(), NULL) != 1)
|
||||
@ -577,7 +643,7 @@ namespace ix
|
||||
X509_VERIFY_PARAM* param = SSL_get0_param(_ssl_connection);
|
||||
X509_VERIFY_PARAM_set1_host(param, host.c_str(), 0);
|
||||
#endif
|
||||
handshakeSuccessful = openSSLClientHandshake(host, errMsg);
|
||||
handshakeSuccessful = openSSLClientHandshake(host, errMsg, isCancellationRequested);
|
||||
}
|
||||
|
||||
if (!handshakeSuccessful)
|
||||
|
@ -39,7 +39,9 @@ namespace ix
|
||||
void openSSLInitialize();
|
||||
std::string getSSLError(int ret);
|
||||
SSL_CTX* openSSLCreateContext(std::string& errMsg);
|
||||
bool openSSLClientHandshake(const std::string& hostname, std::string& errMsg);
|
||||
bool openSSLClientHandshake(const std::string& hostname,
|
||||
std::string& errMsg,
|
||||
const CancellationRequest& isCancellationRequested);
|
||||
bool openSSLCheckServerCert(SSL* ssl, const std::string& hostname, std::string& errMsg);
|
||||
bool checkHost(const std::string& host, const char* pattern);
|
||||
bool handleTLSOptions(std::string& errMsg);
|
||||
|
@ -7,6 +7,7 @@
|
||||
#include "IXSocketServer.h"
|
||||
|
||||
#include "IXNetSystem.h"
|
||||
#include "IXSelectInterrupt.h"
|
||||
#include "IXSetThreadName.h"
|
||||
#include "IXSocket.h"
|
||||
#include "IXSocketConnect.h"
|
||||
@ -257,7 +258,9 @@ namespace ix
|
||||
// Use poll to check whether a new connection is in progress
|
||||
int timeoutMs = 10;
|
||||
bool readyToRead = true;
|
||||
PollResultType pollResult = Socket::poll(readyToRead, timeoutMs, _serverFd);
|
||||
auto selectInterrupt = std::make_unique<SelectInterrupt>();
|
||||
PollResultType pollResult =
|
||||
Socket::poll(readyToRead, timeoutMs, _serverFd, selectInterrupt);
|
||||
|
||||
if (pollResult == PollResultType::Error)
|
||||
{
|
||||
@ -338,7 +341,8 @@ namespace ix
|
||||
std::lock_guard<std::mutex> lock(_connectionsThreadsMutex);
|
||||
_connectionsThreads.push_back(std::make_pair(
|
||||
connectionState,
|
||||
std::thread(&SocketServer::handleConnection, this, socket, connectionState)));
|
||||
std::thread(
|
||||
&SocketServer::handleConnection, this, std::move(socket), connectionState)));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -101,7 +101,7 @@ namespace ix
|
||||
// the factory to create ConnectionState objects
|
||||
ConnectionStateFactory _connectionStateFactory;
|
||||
|
||||
virtual void handleConnection(std::shared_ptr<Socket>,
|
||||
virtual void handleConnection(std::unique_ptr<Socket>,
|
||||
std::shared_ptr<ConnectionState> connectionState) = 0;
|
||||
virtual size_t getConnectedClientsCount() = 0;
|
||||
|
||||
|
96
ixwebsocket/IXUdpSocket.cpp
Normal file
96
ixwebsocket/IXUdpSocket.cpp
Normal file
@ -0,0 +1,96 @@
|
||||
/*
|
||||
* IXUdpSocket.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXUdpSocket.h"
|
||||
|
||||
#include "IXNetSystem.h"
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
UdpSocket::UdpSocket(int fd)
|
||||
: _sockfd(fd)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
UdpSocket::~UdpSocket()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
void UdpSocket::close()
|
||||
{
|
||||
if (_sockfd == -1) return;
|
||||
|
||||
closeSocket(_sockfd);
|
||||
_sockfd = -1;
|
||||
}
|
||||
|
||||
int UdpSocket::getErrno()
|
||||
{
|
||||
int err;
|
||||
|
||||
#ifdef _WIN32
|
||||
err = WSAGetLastError();
|
||||
#else
|
||||
err = errno;
|
||||
#endif
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
void UdpSocket::closeSocket(int fd)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
closesocket(fd);
|
||||
#else
|
||||
::close(fd);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool UdpSocket::init(const std::string& host, int port, std::string& errMsg)
|
||||
{
|
||||
_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (_sockfd < 0)
|
||||
{
|
||||
errMsg = "Could not create socket";
|
||||
return false;
|
||||
}
|
||||
|
||||
memset(&_server, 0, sizeof(_server));
|
||||
_server.sin_family = AF_INET;
|
||||
_server.sin_port = htons(port);
|
||||
|
||||
// DNS resolution.
|
||||
struct addrinfo hints, *result = nullptr;
|
||||
memset(&hints, 0, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_DGRAM;
|
||||
|
||||
int ret = getaddrinfo(host.c_str(), nullptr, &hints, &result);
|
||||
if (ret != 0)
|
||||
{
|
||||
errMsg = strerror(UdpSocket::getErrno());
|
||||
freeaddrinfo(result);
|
||||
close();
|
||||
return false;
|
||||
}
|
||||
|
||||
struct sockaddr_in* host_addr = (struct sockaddr_in*) result->ai_addr;
|
||||
memcpy(&_server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));
|
||||
freeaddrinfo(result);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
ssize_t UdpSocket::sendto(const std::string& buffer)
|
||||
{
|
||||
return (ssize_t)::sendto(
|
||||
_sockfd, buffer.data(), buffer.size(), 0, (struct sockaddr*) &_server, sizeof(_server));
|
||||
}
|
||||
} // namespace ix
|
40
ixwebsocket/IXUdpSocket.h
Normal file
40
ixwebsocket/IXUdpSocket.h
Normal file
@ -0,0 +1,40 @@
|
||||
/*
|
||||
* IXUdpSocket.h
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <BaseTsd.h>
|
||||
typedef SSIZE_T ssize_t;
|
||||
#endif
|
||||
|
||||
#include "IXNetSystem.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
class UdpSocket
|
||||
{
|
||||
public:
|
||||
UdpSocket(int fd = -1);
|
||||
~UdpSocket();
|
||||
|
||||
// Virtual methods
|
||||
bool init(const std::string& host, int port, std::string& errMsg);
|
||||
ssize_t sendto(const std::string& buffer);
|
||||
void close();
|
||||
|
||||
static int getErrno();
|
||||
static void closeSocket(int fd);
|
||||
|
||||
private:
|
||||
std::atomic<int> _sockfd;
|
||||
struct sockaddr_in _server;
|
||||
};
|
||||
} // namespace ix
|
@ -71,7 +71,7 @@ namespace ix
|
||||
#elif defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
ss << " ssl/OpenSSL " << OPENSSL_VERSION_TEXT;
|
||||
#elif __APPLE__
|
||||
ss << " ssl/DarwinSSL";
|
||||
ss << " ssl/SecureTransport";
|
||||
#endif
|
||||
#else
|
||||
ss << " nossl";
|
||||
|
@ -19,7 +19,6 @@ namespace ix
|
||||
OnTrafficTrackerCallback WebSocket::_onTrafficTrackerCallback = nullptr;
|
||||
const int WebSocket::kDefaultHandShakeTimeoutSecs(60);
|
||||
const int WebSocket::kDefaultPingIntervalSecs(-1);
|
||||
const int WebSocket::kDefaultPingTimeoutSecs(-1);
|
||||
const bool WebSocket::kDefaultEnablePong(true);
|
||||
const uint32_t WebSocket::kDefaultMaxWaitBetweenReconnectionRetries(10 * 1000); // 10s
|
||||
|
||||
@ -31,17 +30,16 @@ namespace ix
|
||||
, _handshakeTimeoutSecs(kDefaultHandShakeTimeoutSecs)
|
||||
, _enablePong(kDefaultEnablePong)
|
||||
, _pingIntervalSecs(kDefaultPingIntervalSecs)
|
||||
, _pingTimeoutSecs(kDefaultPingTimeoutSecs)
|
||||
, _webSocketMessage(std::make_unique<WebSocketMessage>(WebSocketMessageType::Message))
|
||||
, _webSocketErrorMessage(std::make_unique<WebSocketMessage>(WebSocketMessageType::Error))
|
||||
, _webSocketOpenMessage(std::make_unique<WebSocketMessage>(WebSocketMessageType::Open))
|
||||
, _webSocketCloseMessage(std::make_unique<WebSocketMessage>(WebSocketMessageType::Close))
|
||||
{
|
||||
_ws.setOnCloseCallback(
|
||||
[this](uint16_t code, const std::string& reason, size_t wireSize, bool remote) {
|
||||
_onMessageCallback(
|
||||
std::make_shared<WebSocketMessage>(WebSocketMessageType::Close,
|
||||
"",
|
||||
wireSize,
|
||||
WebSocketErrorInfo(),
|
||||
WebSocketOpenInfo(),
|
||||
WebSocketCloseInfo(code, reason, remote)));
|
||||
_webSocketCloseMessage->wireSize = wireSize;
|
||||
_webSocketCloseMessage->closeInfo = WebSocketCloseInfo(code, reason, remote);
|
||||
_onMessageCallback(_webSocketCloseMessage);
|
||||
});
|
||||
}
|
||||
|
||||
@ -86,18 +84,6 @@ namespace ix
|
||||
return _perMessageDeflateOptions;
|
||||
}
|
||||
|
||||
void WebSocket::setHeartBeatPeriod(int heartBeatPeriodSecs)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_pingIntervalSecs = heartBeatPeriodSecs;
|
||||
}
|
||||
|
||||
int WebSocket::getHeartBeatPeriod() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
return _pingIntervalSecs;
|
||||
}
|
||||
|
||||
void WebSocket::setPingInterval(int pingIntervalSecs)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
@ -110,18 +96,6 @@ namespace ix
|
||||
return _pingIntervalSecs;
|
||||
}
|
||||
|
||||
void WebSocket::setPingTimeout(int pingTimeoutSecs)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_pingTimeoutSecs = pingTimeoutSecs;
|
||||
}
|
||||
|
||||
int WebSocket::getPingTimeout() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
return _pingTimeoutSecs;
|
||||
}
|
||||
|
||||
void WebSocket::enablePong()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
@ -186,11 +160,8 @@ namespace ix
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_ws.configure(_perMessageDeflateOptions,
|
||||
_socketTLSOptions,
|
||||
_enablePong,
|
||||
_pingIntervalSecs,
|
||||
_pingTimeoutSecs);
|
||||
_ws.configure(
|
||||
_perMessageDeflateOptions, _socketTLSOptions, _enablePong, _pingIntervalSecs);
|
||||
}
|
||||
|
||||
WebSocketHttpHeaders headers(_extraHeaders);
|
||||
@ -222,40 +193,41 @@ namespace ix
|
||||
return status;
|
||||
}
|
||||
|
||||
_onMessageCallback(std::make_shared<WebSocketMessage>(
|
||||
WebSocketMessageType::Open,
|
||||
"",
|
||||
0,
|
||||
WebSocketErrorInfo(),
|
||||
WebSocketOpenInfo(status.uri, status.headers, status.protocol),
|
||||
WebSocketCloseInfo()));
|
||||
_webSocketOpenMessage->openInfo = WebSocketOpenInfo(status.uri, status.headers, status.protocol),
|
||||
_onMessageCallback(_webSocketOpenMessage);
|
||||
|
||||
if (_pingIntervalSecs > 0)
|
||||
{
|
||||
// Send a heart beat right away
|
||||
_ws.sendHeartBeat();
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
WebSocketInitResult WebSocket::connectToSocket(std::shared_ptr<Socket> socket, int timeoutSecs)
|
||||
WebSocketInitResult WebSocket::connectToSocket(std::unique_ptr<Socket> socket, int timeoutSecs)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_configMutex);
|
||||
_ws.configure(_perMessageDeflateOptions,
|
||||
_socketTLSOptions,
|
||||
_enablePong,
|
||||
_pingIntervalSecs,
|
||||
_pingTimeoutSecs);
|
||||
_ws.configure(
|
||||
_perMessageDeflateOptions, _socketTLSOptions, _enablePong, _pingIntervalSecs);
|
||||
}
|
||||
|
||||
WebSocketInitResult status = _ws.connectToSocket(socket, timeoutSecs);
|
||||
WebSocketInitResult status = _ws.connectToSocket(std::move(socket), timeoutSecs);
|
||||
if (!status.success)
|
||||
{
|
||||
return status;
|
||||
}
|
||||
|
||||
_onMessageCallback(
|
||||
std::make_shared<WebSocketMessage>(WebSocketMessageType::Open,
|
||||
"",
|
||||
0,
|
||||
WebSocketErrorInfo(),
|
||||
WebSocketOpenInfo(status.uri, status.headers),
|
||||
WebSocketCloseInfo()));
|
||||
_webSocketOpenMessage->openInfo = WebSocketOpenInfo(status.uri, status.headers);
|
||||
_onMessageCallback(_webSocketOpenMessage);
|
||||
|
||||
if (_pingIntervalSecs > 0)
|
||||
{
|
||||
// Send a heart beat right away
|
||||
_ws.sendHeartBeat();
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
@ -328,12 +300,8 @@ namespace ix
|
||||
connectErr.reason = status.errorStr;
|
||||
connectErr.http_status = status.http_status;
|
||||
|
||||
_onMessageCallback(std::make_shared<WebSocketMessage>(WebSocketMessageType::Error,
|
||||
"",
|
||||
0,
|
||||
connectErr,
|
||||
WebSocketOpenInfo(),
|
||||
WebSocketCloseInfo()));
|
||||
_webSocketErrorMessage->errorInfo = connectErr;
|
||||
_onMessageCallback(_webSocketErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -399,18 +367,15 @@ namespace ix
|
||||
break;
|
||||
}
|
||||
|
||||
WebSocketErrorInfo webSocketErrorInfo;
|
||||
webSocketErrorInfo.decompressionError = decompressionError;
|
||||
|
||||
bool binary = messageKind == WebSocketTransport::MessageKind::MSG_BINARY;
|
||||
|
||||
_onMessageCallback(std::make_shared<WebSocketMessage>(webSocketMessageType,
|
||||
msg,
|
||||
wireSize,
|
||||
webSocketErrorInfo,
|
||||
WebSocketOpenInfo(),
|
||||
WebSocketCloseInfo(),
|
||||
binary));
|
||||
_webSocketMessage->type = webSocketMessageType;
|
||||
_webSocketMessage->str = msg;
|
||||
_webSocketMessage->wireSize = wireSize;
|
||||
_webSocketMessage->errorInfo.decompressionError = decompressionError;
|
||||
_webSocketMessage->binary = binary;
|
||||
|
||||
_onMessageCallback(_webSocketMessage);
|
||||
|
||||
WebSocket::invokeTrafficTrackerCallback(wireSize, true);
|
||||
});
|
||||
|
@ -52,9 +52,7 @@ namespace ix
|
||||
void setPerMessageDeflateOptions(
|
||||
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
|
||||
void setTLSOptions(const SocketTLSOptions& socketTLSOptions);
|
||||
void setHeartBeatPeriod(int heartBeatPeriodSecs);
|
||||
void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod
|
||||
void setPingTimeout(int pingTimeoutSecs);
|
||||
void setPingInterval(int pingIntervalSecs);
|
||||
void enablePong();
|
||||
void disablePong();
|
||||
void enablePerMessageDeflate();
|
||||
@ -94,9 +92,7 @@ namespace ix
|
||||
|
||||
const std::string& getUrl() const;
|
||||
const WebSocketPerMessageDeflateOptions& getPerMessageDeflateOptions() const;
|
||||
int getHeartBeatPeriod() const;
|
||||
int getPingInterval() const;
|
||||
int getPingTimeout() const;
|
||||
size_t bufferedAmount() const;
|
||||
|
||||
void enableAutomaticReconnection();
|
||||
@ -117,7 +113,7 @@ namespace ix
|
||||
static void invokeTrafficTrackerCallback(size_t size, bool incoming);
|
||||
|
||||
// Server
|
||||
WebSocketInitResult connectToSocket(std::shared_ptr<Socket>, int timeoutSecs);
|
||||
WebSocketInitResult connectToSocket(std::unique_ptr<Socket>, int timeoutSecs);
|
||||
|
||||
WebSocketTransport _ws;
|
||||
|
||||
@ -159,6 +155,12 @@ namespace ix
|
||||
static const int kDefaultPingIntervalSecs;
|
||||
static const int kDefaultPingTimeoutSecs;
|
||||
|
||||
// One message ptr for each message kinds
|
||||
WebSocketMessagePtr _webSocketMessage;
|
||||
WebSocketMessagePtr _webSocketErrorMessage;
|
||||
WebSocketMessagePtr _webSocketOpenMessage;
|
||||
WebSocketMessagePtr _webSocketCloseMessage;
|
||||
|
||||
// Subprotocols
|
||||
std::vector<std::string> _subProtocols;
|
||||
|
||||
|
@ -6,6 +6,9 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
struct WebSocketCloseInfo
|
||||
|
@ -6,6 +6,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace ix
|
||||
@ -17,5 +18,10 @@ namespace ix
|
||||
int http_status = 0;
|
||||
std::string reason;
|
||||
bool decompressionError = false;
|
||||
|
||||
WebSocketErrorInfo()
|
||||
{
|
||||
;
|
||||
}
|
||||
};
|
||||
} // namespace ix
|
||||
|
@ -21,8 +21,8 @@ namespace ix
|
||||
{
|
||||
WebSocketHandshake::WebSocketHandshake(
|
||||
std::atomic<bool>& requestInitCancellation,
|
||||
std::shared_ptr<Socket> socket,
|
||||
WebSocketPerMessageDeflate& perMessageDeflate,
|
||||
std::unique_ptr<Socket>& socket,
|
||||
WebSocketPerMessageDeflatePtr& perMessageDeflate,
|
||||
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
|
||||
std::atomic<bool>& enablePerMessageDeflate)
|
||||
: _requestInitCancellation(requestInitCancellation)
|
||||
@ -230,7 +230,7 @@ namespace ix
|
||||
_enablePerMessageDeflate = false;
|
||||
}
|
||||
// Otherwise try to initialize the deflate engine (zlib)
|
||||
else if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions))
|
||||
else if (!_perMessageDeflate->init(webSocketPerMessageDeflateOptions))
|
||||
{
|
||||
return WebSocketInitResult(
|
||||
false, 0, "Failed to initialize per message deflate engine");
|
||||
@ -341,7 +341,7 @@ namespace ix
|
||||
{
|
||||
_enablePerMessageDeflate = true;
|
||||
|
||||
if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions))
|
||||
if (!_perMessageDeflate->init(webSocketPerMessageDeflateOptions))
|
||||
{
|
||||
return WebSocketInitResult(
|
||||
false, 0, "Failed to initialize per message deflate engine");
|
||||
|
@ -23,8 +23,8 @@ namespace ix
|
||||
{
|
||||
public:
|
||||
WebSocketHandshake(std::atomic<bool>& requestInitCancellation,
|
||||
std::shared_ptr<Socket> _socket,
|
||||
WebSocketPerMessageDeflate& perMessageDeflate,
|
||||
std::unique_ptr<Socket>& _socket,
|
||||
WebSocketPerMessageDeflatePtr& perMessageDeflate,
|
||||
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
|
||||
std::atomic<bool>& enablePerMessageDeflate);
|
||||
|
||||
@ -46,8 +46,8 @@ namespace ix
|
||||
bool insensitiveStringCompare(const std::string& a, const std::string& b);
|
||||
|
||||
std::atomic<bool>& _requestInitCancellation;
|
||||
std::shared_ptr<Socket> _socket;
|
||||
WebSocketPerMessageDeflate& _perMessageDeflate;
|
||||
std::unique_ptr<Socket>& _socket;
|
||||
WebSocketPerMessageDeflatePtr& _perMessageDeflate;
|
||||
WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions;
|
||||
std::atomic<bool>& _enablePerMessageDeflate;
|
||||
};
|
||||
|
@ -32,7 +32,7 @@ namespace ix
|
||||
}
|
||||
|
||||
std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders(
|
||||
std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested)
|
||||
std::unique_ptr<Socket>& socket, const CancellationRequest& isCancellationRequested)
|
||||
{
|
||||
WebSocketHttpHeaders headers;
|
||||
|
||||
|
@ -29,5 +29,5 @@ namespace ix
|
||||
using WebSocketHttpHeaders = std::map<std::string, std::string, CaseInsensitiveLess>;
|
||||
|
||||
std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders(
|
||||
std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested);
|
||||
std::unique_ptr<Socket>& socket, const CancellationRequest& isCancellationRequested);
|
||||
} // namespace ix
|
||||
|
12
ixwebsocket/IXWebSocketMessage.cpp
Normal file
12
ixwebsocket/IXWebSocketMessage.cpp
Normal file
@ -0,0 +1,12 @@
|
||||
/*
|
||||
* IXWebSocketMessage.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXWebSocketMessage.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
std::string WebSocketMessage::kStr("foo");
|
||||
}
|
@ -19,22 +19,23 @@ namespace ix
|
||||
struct WebSocketMessage
|
||||
{
|
||||
WebSocketMessageType type;
|
||||
std::string str;
|
||||
std::string& str;
|
||||
size_t wireSize;
|
||||
WebSocketErrorInfo errorInfo;
|
||||
WebSocketOpenInfo openInfo;
|
||||
WebSocketCloseInfo closeInfo;
|
||||
bool binary;
|
||||
|
||||
static std::string kStr;
|
||||
|
||||
WebSocketMessage(WebSocketMessageType t,
|
||||
const std::string& s,
|
||||
size_t w,
|
||||
WebSocketErrorInfo e,
|
||||
WebSocketOpenInfo o,
|
||||
WebSocketCloseInfo c,
|
||||
size_t w = 0,
|
||||
WebSocketErrorInfo e = WebSocketErrorInfo(),
|
||||
WebSocketOpenInfo o = WebSocketOpenInfo(),
|
||||
WebSocketCloseInfo c = WebSocketCloseInfo(),
|
||||
bool b = false)
|
||||
: type(t)
|
||||
, str(std::move(s))
|
||||
, str(WebSocketMessage::kStr)
|
||||
, wireSize(w)
|
||||
, errorInfo(e)
|
||||
, openInfo(o)
|
||||
@ -43,7 +44,12 @@ namespace ix
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
// void setStr(const std::string& s)
|
||||
// {
|
||||
// str = std::move(s);
|
||||
// }
|
||||
};
|
||||
|
||||
using WebSocketMessagePtr = std::shared_ptr<WebSocketMessage>;
|
||||
using WebSocketMessagePtr = std::unique_ptr<WebSocketMessage>;
|
||||
} // namespace ix
|
||||
|
@ -1,86 +0,0 @@
|
||||
/*
|
||||
* IXWebSocketMessageQueue.cpp
|
||||
* Author: Korchynskyi Dmytro
|
||||
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXWebSocketMessageQueue.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
WebSocketMessageQueue::WebSocketMessageQueue(WebSocket* websocket)
|
||||
{
|
||||
bindWebsocket(websocket);
|
||||
}
|
||||
|
||||
WebSocketMessageQueue::~WebSocketMessageQueue()
|
||||
{
|
||||
if (!_messages.empty())
|
||||
{
|
||||
// not handled all messages
|
||||
}
|
||||
|
||||
bindWebsocket(nullptr);
|
||||
}
|
||||
|
||||
void WebSocketMessageQueue::bindWebsocket(WebSocket* websocket)
|
||||
{
|
||||
if (_websocket == websocket) return;
|
||||
|
||||
// unbind old
|
||||
if (_websocket)
|
||||
{
|
||||
// set dummy callback just to avoid crash
|
||||
_websocket->setOnMessageCallback([](const WebSocketMessagePtr&) {});
|
||||
}
|
||||
|
||||
_websocket = websocket;
|
||||
|
||||
// bind new
|
||||
if (_websocket)
|
||||
{
|
||||
_websocket->setOnMessageCallback([this](const WebSocketMessagePtr& msg) {
|
||||
std::lock_guard<std::mutex> lock(_messagesMutex);
|
||||
_messages.emplace_back(std::move(msg));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void WebSocketMessageQueue::setOnMessageCallback(const OnMessageCallback& callback)
|
||||
{
|
||||
_onMessageUserCallback = callback;
|
||||
}
|
||||
|
||||
void WebSocketMessageQueue::setOnMessageCallback(OnMessageCallback&& callback)
|
||||
{
|
||||
_onMessageUserCallback = std::move(callback);
|
||||
}
|
||||
|
||||
WebSocketMessagePtr WebSocketMessageQueue::popMessage()
|
||||
{
|
||||
WebSocketMessagePtr message;
|
||||
std::lock_guard<std::mutex> lock(_messagesMutex);
|
||||
|
||||
if (!_messages.empty())
|
||||
{
|
||||
message = std::move(_messages.front());
|
||||
_messages.pop_front();
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
void WebSocketMessageQueue::poll(int count)
|
||||
{
|
||||
if (!_onMessageUserCallback) return;
|
||||
|
||||
WebSocketMessagePtr message;
|
||||
|
||||
while (count > 0 && (message = popMessage()))
|
||||
{
|
||||
_onMessageUserCallback(message);
|
||||
--count;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ix
|
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* IXWebSocketMessageQueue.h
|
||||
* Author: Korchynskyi Dmytro
|
||||
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "IXWebSocket.h"
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
|
||||
namespace ix
|
||||
{
|
||||
//
|
||||
// A helper class to dispatch websocket message callbacks in your thread.
|
||||
//
|
||||
class WebSocketMessageQueue
|
||||
{
|
||||
public:
|
||||
WebSocketMessageQueue(WebSocket* websocket = nullptr);
|
||||
~WebSocketMessageQueue();
|
||||
|
||||
void bindWebsocket(WebSocket* websocket);
|
||||
|
||||
void setOnMessageCallback(const OnMessageCallback& callback);
|
||||
void setOnMessageCallback(OnMessageCallback&& callback);
|
||||
|
||||
void poll(int count = 512);
|
||||
|
||||
protected:
|
||||
WebSocketMessagePtr popMessage();
|
||||
|
||||
private:
|
||||
WebSocket* _websocket = nullptr;
|
||||
OnMessageCallback _onMessageUserCallback;
|
||||
std::mutex _messagesMutex;
|
||||
std::list<WebSocketMessagePtr> _messages;
|
||||
};
|
||||
} // namespace ix
|
@ -6,6 +6,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include "IXWebSocketHttpHeaders.h"
|
||||
|
||||
namespace ix
|
||||
{
|
||||
struct WebSocketOpenInfo
|
||||
|
@ -57,4 +57,6 @@ namespace ix
|
||||
std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor;
|
||||
std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor;
|
||||
};
|
||||
|
||||
using WebSocketPerMessageDeflatePtr = std::unique_ptr<WebSocketPerMessageDeflate>;
|
||||
} // namespace ix
|
||||
|
@ -87,10 +87,17 @@ namespace ix
|
||||
//
|
||||
size_t output;
|
||||
|
||||
// Clear output
|
||||
out.clear();
|
||||
|
||||
if (in.empty())
|
||||
{
|
||||
uint8_t buf[6] = {0x02, 0x00, 0x00, 0x00, 0xff, 0xff};
|
||||
out.append((char*) (buf), 6);
|
||||
// See issue #167
|
||||
// The normal buffer size should be 6 but
|
||||
// we remove the 4 octets from the tail (#4)
|
||||
uint8_t buf[2] = {0x02, 0x00};
|
||||
out.append((char*) (buf), 2);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -170,6 +177,9 @@ namespace ix
|
||||
_inflateState.avail_in = (uInt) inFixed.size();
|
||||
_inflateState.next_in = (unsigned char*) (const_cast<char*>(inFixed.data()));
|
||||
|
||||
// Clear output
|
||||
out.clear();
|
||||
|
||||
do
|
||||
{
|
||||
_inflateState.avail_out = (uInt) _compressBufferSize;
|
||||
|
@ -71,7 +71,7 @@ namespace ix
|
||||
_onConnectionCallback = callback;
|
||||
}
|
||||
|
||||
void WebSocketServer::handleConnection(std::shared_ptr<Socket> socket,
|
||||
void WebSocketServer::handleConnection(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState)
|
||||
{
|
||||
setThreadName("WebSocketServer::" + connectionState->getId());
|
||||
@ -96,7 +96,7 @@ namespace ix
|
||||
_clients.insert(webSocket);
|
||||
}
|
||||
|
||||
auto status = webSocket->connectToSocket(socket, _handshakeTimeoutSecs);
|
||||
auto status = webSocket->connectToSocket(std::move(socket), _handshakeTimeoutSecs);
|
||||
if (status.success)
|
||||
{
|
||||
// Process incoming messages and execute callbacks
|
||||
|
@ -59,7 +59,7 @@ namespace ix
|
||||
const static bool kDefaultEnablePong;
|
||||
|
||||
// Methods
|
||||
virtual void handleConnection(std::shared_ptr<Socket> socket,
|
||||
virtual void handleConnection(std::unique_ptr<Socket> socket,
|
||||
std::shared_ptr<ConnectionState> connectionState) final;
|
||||
virtual size_t getConnectedClientsCount() final;
|
||||
};
|
||||
|
@ -51,26 +51,10 @@
|
||||
#include <vector>
|
||||
|
||||
|
||||
namespace
|
||||
{
|
||||
int greatestCommonDivisor(int a, int b)
|
||||
{
|
||||
while (b != 0)
|
||||
{
|
||||
int t = b;
|
||||
b = a % b;
|
||||
a = t;
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace ix
|
||||
{
|
||||
const std::string WebSocketTransport::kPingMessage("ixwebsocket::heartbeat");
|
||||
const int WebSocketTransport::kDefaultPingIntervalSecs(-1);
|
||||
const int WebSocketTransport::kDefaultPingTimeoutSecs(-1);
|
||||
const bool WebSocketTransport::kDefaultEnablePong(true);
|
||||
const int WebSocketTransport::kClosingMaximumWaitingDelayInMs(300);
|
||||
constexpr size_t WebSocketTransport::kChunkSize;
|
||||
@ -78,7 +62,7 @@ namespace ix
|
||||
WebSocketTransport::WebSocketTransport()
|
||||
: _useMask(true)
|
||||
, _blockingSend(false)
|
||||
, _compressedMessage(false)
|
||||
, _receivedMessageCompressed(false)
|
||||
, _readyState(ReadyState::CLOSED)
|
||||
, _closeCode(WebSocketCloseConstants::kInternalErrorCode)
|
||||
, _closeReason(WebSocketCloseConstants::kInternalErrorMessage)
|
||||
@ -89,11 +73,8 @@ namespace ix
|
||||
, _closingTimePoint(std::chrono::steady_clock::now())
|
||||
, _enablePong(kDefaultEnablePong)
|
||||
, _pingIntervalSecs(kDefaultPingIntervalSecs)
|
||||
, _pingTimeoutSecs(kDefaultPingTimeoutSecs)
|
||||
, _pingIntervalOrTimeoutGCDSecs(-1)
|
||||
, _nextGCDTimePoint(std::chrono::steady_clock::now())
|
||||
, _pongReceived(false)
|
||||
, _lastSendPingTimePoint(std::chrono::steady_clock::now())
|
||||
, _lastReceivePongTimePoint(std::chrono::steady_clock::now())
|
||||
{
|
||||
_readbuf.resize(kChunkSize);
|
||||
}
|
||||
@ -107,29 +88,13 @@ namespace ix
|
||||
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
|
||||
const SocketTLSOptions& socketTLSOptions,
|
||||
bool enablePong,
|
||||
int pingIntervalSecs,
|
||||
int pingTimeoutSecs)
|
||||
int pingIntervalSecs)
|
||||
{
|
||||
_perMessageDeflateOptions = perMessageDeflateOptions;
|
||||
_enablePerMessageDeflate = _perMessageDeflateOptions.enabled();
|
||||
_socketTLSOptions = socketTLSOptions;
|
||||
_enablePong = enablePong;
|
||||
_pingIntervalSecs = pingIntervalSecs;
|
||||
_pingTimeoutSecs = pingTimeoutSecs;
|
||||
|
||||
if (pingIntervalSecs > 0 && pingTimeoutSecs > 0)
|
||||
{
|
||||
_pingIntervalOrTimeoutGCDSecs =
|
||||
greatestCommonDivisor(pingIntervalSecs, pingTimeoutSecs);
|
||||
}
|
||||
else if (_pingTimeoutSecs > 0)
|
||||
{
|
||||
_pingIntervalOrTimeoutGCDSecs = pingTimeoutSecs;
|
||||
}
|
||||
else
|
||||
{
|
||||
_pingIntervalOrTimeoutGCDSecs = pingIntervalSecs;
|
||||
}
|
||||
}
|
||||
|
||||
// Client
|
||||
@ -152,6 +117,7 @@ namespace ix
|
||||
std::string errorMsg;
|
||||
bool tls = protocol == "wss";
|
||||
_socket = createSocket(tls, -1, errorMsg, _socketTLSOptions);
|
||||
_perMessageDeflate = std::make_unique<WebSocketPerMessageDeflate>();
|
||||
|
||||
if (!_socket)
|
||||
{
|
||||
@ -174,7 +140,7 @@ namespace ix
|
||||
}
|
||||
|
||||
// Server
|
||||
WebSocketInitResult WebSocketTransport::connectToSocket(std::shared_ptr<Socket> socket,
|
||||
WebSocketInitResult WebSocketTransport::connectToSocket(std::unique_ptr<Socket> socket,
|
||||
int timeoutSecs)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_socketMutex);
|
||||
@ -183,7 +149,8 @@ namespace ix
|
||||
_useMask = false;
|
||||
_blockingSend = true;
|
||||
|
||||
_socket = socket;
|
||||
_socket = std::move(socket);
|
||||
_perMessageDeflate = std::make_unique<WebSocketPerMessageDeflate>();
|
||||
|
||||
WebSocketHandshake webSocketHandshake(_requestInitCancellation,
|
||||
_socket,
|
||||
@ -220,7 +187,8 @@ namespace ix
|
||||
}
|
||||
else if (readyState == ReadyState::OPEN)
|
||||
{
|
||||
initTimePointsAndGCDAfterConnect();
|
||||
initTimePointsAfterConnect();
|
||||
_pongReceived = false;
|
||||
}
|
||||
|
||||
_readyState = readyState;
|
||||
@ -231,22 +199,12 @@ namespace ix
|
||||
_onCloseCallback = onCloseCallback;
|
||||
}
|
||||
|
||||
void WebSocketTransport::initTimePointsAndGCDAfterConnect()
|
||||
void WebSocketTransport::initTimePointsAfterConnect()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_lastSendPingTimePointMutex);
|
||||
_lastSendPingTimePoint = std::chrono::steady_clock::now();
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_lastReceivePongTimePointMutex);
|
||||
_lastReceivePongTimePoint = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
if (_pingIntervalOrTimeoutGCDSecs > 0)
|
||||
{
|
||||
_nextGCDTimePoint = std::chrono::steady_clock::now() +
|
||||
std::chrono::seconds(_pingIntervalOrTimeoutGCDSecs);
|
||||
}
|
||||
}
|
||||
|
||||
// Only consider send PING time points for that computation.
|
||||
@ -259,13 +217,12 @@ namespace ix
|
||||
return now - _lastSendPingTimePoint > std::chrono::seconds(_pingIntervalSecs);
|
||||
}
|
||||
|
||||
bool WebSocketTransport::pingTimeoutExceeded()
|
||||
WebSocketSendInfo WebSocketTransport::sendHeartBeat()
|
||||
{
|
||||
if (_pingTimeoutSecs <= 0) return false;
|
||||
|
||||
std::lock_guard<std::mutex> lock(_lastReceivePongTimePointMutex);
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
return now - _lastReceivePongTimePoint > std::chrono::seconds(_pingTimeoutSecs);
|
||||
_pongReceived = false;
|
||||
std::stringstream ss;
|
||||
ss << kPingMessage << "::" << _pingIntervalSecs << "s";
|
||||
return sendPing(ss.str());
|
||||
}
|
||||
|
||||
bool WebSocketTransport::closingDelayExceeded()
|
||||
@ -279,46 +236,32 @@ namespace ix
|
||||
{
|
||||
if (_readyState == ReadyState::OPEN)
|
||||
{
|
||||
// if (1) ping timeout is enabled and (2) duration since last received
|
||||
// ping response (PONG) exceeds the maximum delay, then close the connection
|
||||
if (pingTimeoutExceeded())
|
||||
if (pingIntervalExceeded())
|
||||
{
|
||||
close(WebSocketCloseConstants::kInternalErrorCode,
|
||||
WebSocketCloseConstants::kPingTimeoutMessage);
|
||||
}
|
||||
// If ping is enabled and no ping has been sent for a duration
|
||||
// exceeding our ping interval, send a ping to the server.
|
||||
else if (pingIntervalExceeded())
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << kPingMessage << "::" << _pingIntervalSecs << "s";
|
||||
sendPing(ss.str());
|
||||
if (!_pongReceived)
|
||||
{
|
||||
// ping response (PONG) exceeds the maximum delay, close the connection
|
||||
close(WebSocketCloseConstants::kInternalErrorCode,
|
||||
WebSocketCloseConstants::kPingTimeoutMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
sendHeartBeat();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No timeout if state is not OPEN, otherwise computed
|
||||
// pingIntervalOrTimeoutGCD (equals to -1 if no ping and no ping timeout are set)
|
||||
int lastingTimeoutDelayInMs =
|
||||
(_readyState != ReadyState::OPEN) ? 0 : _pingIntervalOrTimeoutGCDSecs;
|
||||
int lastingTimeoutDelayInMs = (_readyState != ReadyState::OPEN) ? 0 : _pingIntervalSecs;
|
||||
|
||||
if (_pingIntervalOrTimeoutGCDSecs > 0)
|
||||
if (_pingIntervalSecs > 0)
|
||||
{
|
||||
// compute lasting delay to wait for next ping / timeout, if at least one set
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
if (now >= _nextGCDTimePoint)
|
||||
{
|
||||
_nextGCDTimePoint = now + std::chrono::seconds(_pingIntervalOrTimeoutGCDSecs);
|
||||
|
||||
lastingTimeoutDelayInMs = _pingIntervalOrTimeoutGCDSecs * 1000;
|
||||
}
|
||||
else
|
||||
{
|
||||
lastingTimeoutDelayInMs =
|
||||
(int) std::chrono::duration_cast<std::chrono::milliseconds>(_nextGCDTimePoint -
|
||||
now)
|
||||
.count();
|
||||
}
|
||||
lastingTimeoutDelayInMs = (int) std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now - _lastSendPingTimePoint)
|
||||
.count();
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
@ -550,7 +493,7 @@ namespace ix
|
||||
? MessageKind::MSG_TEXT
|
||||
: MessageKind::MSG_BINARY;
|
||||
|
||||
_compressedMessage = _enablePerMessageDeflate && ws.rsv1;
|
||||
_receivedMessageCompressed = _enablePerMessageDeflate && ws.rsv1;
|
||||
|
||||
// Continuation message needs to follow a non-fin TEXT or BINARY message
|
||||
if (!_chunks.empty())
|
||||
@ -572,10 +515,12 @@ namespace ix
|
||||
//
|
||||
if (ws.fin && _chunks.empty())
|
||||
{
|
||||
emitMessage(
|
||||
_fragmentedMessageKind, frameData, _compressedMessage, onMessageCallback);
|
||||
emitMessage(_fragmentedMessageKind,
|
||||
frameData,
|
||||
_receivedMessageCompressed,
|
||||
onMessageCallback);
|
||||
|
||||
_compressedMessage = false;
|
||||
_receivedMessageCompressed = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -592,11 +537,11 @@ namespace ix
|
||||
{
|
||||
emitMessage(_fragmentedMessageKind,
|
||||
getMergedChunks(),
|
||||
_compressedMessage,
|
||||
_receivedMessageCompressed,
|
||||
onMessageCallback);
|
||||
|
||||
_chunks.clear();
|
||||
_compressedMessage = false;
|
||||
_receivedMessageCompressed = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -626,9 +571,7 @@ namespace ix
|
||||
}
|
||||
else if (ws.opcode == wsheader_type::PONG)
|
||||
{
|
||||
std::lock_guard<std::mutex> lck(_lastReceivePongTimePointMutex);
|
||||
_lastReceivePongTimePoint = std::chrono::steady_clock::now();
|
||||
|
||||
_pongReceived = true;
|
||||
emitMessage(MessageKind::PONG, frameData, false, onMessageCallback);
|
||||
}
|
||||
else if (ws.opcode == wsheader_type::CLOSE)
|
||||
@ -684,7 +627,7 @@ namespace ix
|
||||
// send back the CLOSE frame
|
||||
sendCloseFrame(code, reason);
|
||||
|
||||
_socket->wakeUpFromPoll(Socket::kCloseRequest);
|
||||
wakeUpFromPoll(Socket::kCloseRequest);
|
||||
|
||||
bool remote = true;
|
||||
closeSocketAndSwitchToClosedState(code, reason, _rxbuf.size(), remote);
|
||||
@ -771,17 +714,16 @@ namespace ix
|
||||
// When the RSV1 bit is 1 it means the message is compressed
|
||||
if (compressedMessage && messageKind != MessageKind::FRAGMENT)
|
||||
{
|
||||
std::string decompressedMessage;
|
||||
bool success = _perMessageDeflate.decompress(message, decompressedMessage);
|
||||
bool success = _perMessageDeflate->decompress(message, _decompressedMessage);
|
||||
|
||||
if (messageKind == MessageKind::MSG_TEXT && !validateUtf8(decompressedMessage))
|
||||
if (messageKind == MessageKind::MSG_TEXT && !validateUtf8(_decompressedMessage))
|
||||
{
|
||||
close(WebSocketCloseConstants::kInvalidFramePayloadData,
|
||||
WebSocketCloseConstants::kInvalidFramePayloadDataMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
onMessageCallback(decompressedMessage, wireSize, !success, messageKind);
|
||||
onMessageCallback(_decompressedMessage, wireSize, !success, messageKind);
|
||||
}
|
||||
}
|
||||
else
|
||||
@ -818,7 +760,6 @@ namespace ix
|
||||
|
||||
size_t payloadSize = message.size();
|
||||
size_t wireSize = message.size();
|
||||
std::string compressedMessage;
|
||||
bool compressionError = false;
|
||||
|
||||
std::string::const_iterator message_begin = message.begin();
|
||||
@ -826,7 +767,7 @@ namespace ix
|
||||
|
||||
if (compress)
|
||||
{
|
||||
if (!_perMessageDeflate.compress(message, compressedMessage))
|
||||
if (!_perMessageDeflate->compress(message, _compressedMessage))
|
||||
{
|
||||
bool success = false;
|
||||
compressionError = true;
|
||||
@ -835,10 +776,10 @@ namespace ix
|
||||
return WebSocketSendInfo(success, compressionError, payloadSize, wireSize);
|
||||
}
|
||||
compressionError = false;
|
||||
wireSize = compressedMessage.size();
|
||||
wireSize = _compressedMessage.size();
|
||||
|
||||
message_begin = compressedMessage.begin();
|
||||
message_end = compressedMessage.end();
|
||||
message_begin = _compressedMessage.begin();
|
||||
message_end = _compressedMessage.end();
|
||||
}
|
||||
|
||||
{
|
||||
@ -904,7 +845,7 @@ namespace ix
|
||||
// Request to flush the send buffer on the background thread if it isn't empty
|
||||
if (!isSendBufferEmpty())
|
||||
{
|
||||
_socket->wakeUpFromPoll(Socket::kSendRequest);
|
||||
wakeUpFromPoll(Socket::kSendRequest);
|
||||
|
||||
// FIXME: we should have a timeout when sending large messages: see #131
|
||||
if (_blockingSend && !flushSendBuffer())
|
||||
@ -1122,6 +1063,12 @@ namespace ix
|
||||
_socket->close();
|
||||
}
|
||||
|
||||
bool WebSocketTransport::wakeUpFromPoll(uint64_t wakeUpCode)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_socketMutex);
|
||||
return _socket->wakeUpFromPoll(wakeUpCode);
|
||||
}
|
||||
|
||||
void WebSocketTransport::closeSocketAndSwitchToClosedState(uint16_t code,
|
||||
const std::string& reason,
|
||||
size_t closeWireSize,
|
||||
@ -1169,8 +1116,9 @@ namespace ix
|
||||
setReadyState(ReadyState::CLOSING);
|
||||
|
||||
sendCloseFrame(code, reason);
|
||||
|
||||
// wake up the poll, but do not close yet
|
||||
_socket->wakeUpFromPoll(Socket::kSendRequest);
|
||||
wakeUpFromPoll(Socket::kSendRequest);
|
||||
}
|
||||
|
||||
size_t WebSocketTransport::bufferedAmount() const
|
||||
|
@ -75,8 +75,7 @@ namespace ix
|
||||
void configure(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
|
||||
const SocketTLSOptions& socketTLSOptions,
|
||||
bool enablePong,
|
||||
int pingIntervalSecs,
|
||||
int pingTimeoutSecs);
|
||||
int pingIntervalSecs);
|
||||
|
||||
// Client
|
||||
WebSocketInitResult connectToUrl(const std::string& url,
|
||||
@ -84,7 +83,7 @@ namespace ix
|
||||
int timeoutSecs);
|
||||
|
||||
// Server
|
||||
WebSocketInitResult connectToSocket(std::shared_ptr<Socket> socket, int timeoutSecs);
|
||||
WebSocketInitResult connectToSocket(std::unique_ptr<Socket> socket, int timeoutSecs);
|
||||
|
||||
PollResult poll();
|
||||
WebSocketSendInfo sendBinary(const std::string& message,
|
||||
@ -106,6 +105,9 @@ namespace ix
|
||||
void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback);
|
||||
size_t bufferedAmount() const;
|
||||
|
||||
// internal
|
||||
WebSocketSendInfo sendHeartBeat();
|
||||
|
||||
private:
|
||||
std::string _url;
|
||||
|
||||
@ -163,13 +165,13 @@ namespace ix
|
||||
MessageKind _fragmentedMessageKind;
|
||||
|
||||
// Ditto for whether a message is compressed
|
||||
bool _compressedMessage;
|
||||
bool _receivedMessageCompressed;
|
||||
|
||||
// Fragments are 32K long
|
||||
static constexpr size_t kChunkSize = 1 << 15;
|
||||
|
||||
// Underlying TCP socket
|
||||
std::shared_ptr<Socket> _socket;
|
||||
std::unique_ptr<Socket> _socket;
|
||||
std::mutex _socketMutex;
|
||||
|
||||
// Hold the state of the connection (OPEN, CLOSED, etc...)
|
||||
@ -183,10 +185,13 @@ namespace ix
|
||||
mutable std::mutex _closeDataMutex;
|
||||
|
||||
// Data used for Per Message Deflate compression (with zlib)
|
||||
WebSocketPerMessageDeflate _perMessageDeflate;
|
||||
WebSocketPerMessageDeflatePtr _perMessageDeflate;
|
||||
WebSocketPerMessageDeflateOptions _perMessageDeflateOptions;
|
||||
std::atomic<bool> _enablePerMessageDeflate;
|
||||
|
||||
std::string _decompressedMessage;
|
||||
std::string _compressedMessage;
|
||||
|
||||
// Used to control TLS connection behavior
|
||||
SocketTLSOptions _socketTLSOptions;
|
||||
|
||||
@ -202,39 +207,24 @@ namespace ix
|
||||
static const bool kDefaultEnablePong;
|
||||
|
||||
// Optional ping and pong timeout
|
||||
// if both ping interval and timeout are set (> 0),
|
||||
// then use GCD of these value to wait for the lowest time
|
||||
int _pingIntervalSecs;
|
||||
int _pingTimeoutSecs;
|
||||
int _pingIntervalOrTimeoutGCDSecs;
|
||||
std::atomic<bool> _pongReceived;
|
||||
|
||||
static const int kDefaultPingIntervalSecs;
|
||||
static const int kDefaultPingTimeoutSecs;
|
||||
static const std::string kPingMessage;
|
||||
|
||||
// Record time step for ping/ ping timeout to ensure we wait for the right left duration
|
||||
std::chrono::time_point<std::chrono::steady_clock> _nextGCDTimePoint;
|
||||
|
||||
// We record when ping are being sent so that we can know when to send the next one
|
||||
// We also record when pong are being sent as a reply to pings, to close the connections
|
||||
// if no pong were received sufficiently fast.
|
||||
mutable std::mutex _lastSendPingTimePointMutex;
|
||||
mutable std::mutex _lastReceivePongTimePointMutex;
|
||||
std::chrono::time_point<std::chrono::steady_clock> _lastSendPingTimePoint;
|
||||
std::chrono::time_point<std::chrono::steady_clock> _lastReceivePongTimePoint;
|
||||
|
||||
// If this function returns true, it is time to send a new ping
|
||||
bool pingIntervalExceeded();
|
||||
|
||||
// No PONG data was received through the socket for longer than ping timeout delay
|
||||
bool pingTimeoutExceeded();
|
||||
void initTimePointsAfterConnect();
|
||||
|
||||
// after calling close(), if no CLOSE frame answer is received back from the remote, we
|
||||
// should close the connexion
|
||||
bool closingDelayExceeded();
|
||||
|
||||
void initTimePointsAndGCDAfterConnect();
|
||||
|
||||
void sendCloseFrame(uint16_t code, const std::string& reason);
|
||||
|
||||
void closeSocketAndSwitchToClosedState(uint16_t code,
|
||||
@ -242,6 +232,8 @@ namespace ix
|
||||
size_t closeWireSize,
|
||||
bool remote);
|
||||
|
||||
bool wakeUpFromPoll(uint64_t wakeUpCode);
|
||||
|
||||
bool flushSendBuffer();
|
||||
bool sendOnSocket();
|
||||
bool receiveFromSocket();
|
||||
|
@ -6,4 +6,4 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#define IX_WEBSOCKET_VERSION "8.2.3"
|
||||
#define IX_WEBSOCKET_VERSION "9.2.6"
|
||||
|
68
makefile
68
makefile
@ -1,5 +1,13 @@
|
||||
#
|
||||
# This makefile is just used to easily work with docker (linux build)
|
||||
# This makefile is used for convenience, and wrap simple cmake commands
|
||||
# You don't need to use it as an end user, it is more for developer.
|
||||
#
|
||||
# * work with docker (linux build)
|
||||
# * execute the unittest
|
||||
#
|
||||
# The default target will install ws, the command line tool coming with
|
||||
# IXWebSocket into /usr/local/bin
|
||||
#
|
||||
#
|
||||
all: brew
|
||||
|
||||
@ -8,14 +16,23 @@ install: brew
|
||||
# Use -DCMAKE_INSTALL_PREFIX= to install into another location
|
||||
# on osx it is good practice to make /usr/local user writable
|
||||
# sudo chown -R `whoami`/staff /usr/local
|
||||
#
|
||||
# Release, Debug, MinSizeRel, RelWithDebInfo are the build types
|
||||
#
|
||||
brew:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_TEST=1 .. ; make -j 4 install)
|
||||
|
||||
# Docker default target. We've add problem with OpenSSL and TLS 1.3 (on the
|
||||
# server side ?) and I can't work-around it easily, so we're using mbedtls on
|
||||
# Linux for the SSL backend, which works great.
|
||||
ws_mbedtls_install:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=MinSizeRel -DUSE_TLS=1 -DUSE_WS=1 -DUSE_MBED_TLS=1 .. ; make -j 4 install)
|
||||
|
||||
ws:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j 4)
|
||||
|
||||
ws_install:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j 4 install)
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=MinSizeRel -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j 4 install)
|
||||
|
||||
ws_openssl:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_OPEN_SSL=1 .. ; make -j 4)
|
||||
@ -65,6 +82,8 @@ docker_push:
|
||||
docker push ${LATEST}
|
||||
docker push ${IMG}
|
||||
|
||||
deploy: docker docker_push
|
||||
|
||||
run:
|
||||
docker run --cap-add sys_ptrace --entrypoint=sh -it bsergean/ws:build
|
||||
|
||||
@ -87,12 +106,51 @@ test:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_TEST=1 .. ; make -j 4)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_openssl:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_OPEN_SSL=1 -DUSE_TEST=1 .. ; make -j 4)
|
||||
test_tsan:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableThreadSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_mbedtls:
|
||||
test_ubsan:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableUndefinedBehaviorSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_asan:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableAddressSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_tsan_openssl:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 -DUSE_OPEN_SSL=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableThreadSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_ubsan_openssl:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 -DUSE_OPEN_SSL=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableUndefinedBehaviorSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_tsan_openssl_release:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Release -DUSE_TLS=1 -DUSE_TEST=1 -DUSE_OPEN_SSL=1 .. && xcodebuild -project ixwebsocket.xcodeproj -configuration Release -target ixwebsocket_unittest -enableThreadSanitizer YES)
|
||||
(cd build/test ; ln -sf Release/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_tsan_mbedtls:
|
||||
mkdir -p build && (cd build && cmake -GXcode -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_TEST=1 -DUSE_MBED_TLS=1 .. && xcodebuild -project ixwebsocket.xcodeproj -target ixwebsocket_unittest -enableThreadSanitizer YES)
|
||||
(cd build/test ; ln -sf Debug/ixwebsocket_unittest)
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
build_test_openssl:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_OPEN_SSL=1 -DUSE_TEST=1 .. ; make -j 4)
|
||||
|
||||
test_openssl: build_test_openssl
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
build_test_mbedtls:
|
||||
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_MBED_TLS=1 -DUSE_TEST=1 .. ; make -j 4)
|
||||
|
||||
test_mbedtls: build_test_mbedtls
|
||||
(cd test ; python2.7 run.py -r)
|
||||
|
||||
test_no_ssl:
|
||||
|
@ -50,26 +50,22 @@ set (SOURCES
|
||||
IXHttpServerTest.cpp
|
||||
IXUnityBuildsTest.cpp
|
||||
IXHttpTest.cpp
|
||||
IXCobraChatTest.cpp
|
||||
IXCobraMetricsPublisherTest.cpp
|
||||
IXDNSLookupTest.cpp
|
||||
IXWebSocketSubProtocolTest.cpp
|
||||
IXSentryClientTest.cpp
|
||||
IXWebSocketChatTest.cpp
|
||||
IXCobraToSentryBotTest.cpp
|
||||
IXWebSocketBroadcastTest.cpp
|
||||
)
|
||||
|
||||
# Some unittest don't work on windows yet
|
||||
# Windows without TLS does not have hmac yet
|
||||
if (UNIX)
|
||||
list(APPEND SOURCES
|
||||
IXWebSocketCloseTest.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
# Some unittest fail for dubious reason on Ubuntu Xenial with TSAN
|
||||
if (MAC OR WIN32)
|
||||
list(APPEND SOURCES
|
||||
IXWebSocketMessageQTest.cpp
|
||||
IXCobraChatTest.cpp
|
||||
IXCobraMetricsPublisherTest.cpp
|
||||
IXCobraToSentryBotTest.cpp
|
||||
IXCobraToStatsdBotTest.cpp
|
||||
)
|
||||
endif()
|
||||
|
||||
@ -94,13 +90,14 @@ if (JSONCPP_FOUND)
|
||||
target_link_libraries(ixwebsocket_unittest ${JSONCPP_LIBRARIES})
|
||||
endif()
|
||||
|
||||
# library with the most dependencies come first
|
||||
target_link_libraries(ixwebsocket_unittest ixbots)
|
||||
target_link_libraries(ixwebsocket_unittest ixsnake)
|
||||
target_link_libraries(ixwebsocket_unittest ixcobra)
|
||||
target_link_libraries(ixwebsocket_unittest ixsentry)
|
||||
target_link_libraries(ixwebsocket_unittest ixwebsocket)
|
||||
target_link_libraries(ixwebsocket_unittest ixcrypto)
|
||||
target_link_libraries(ixwebsocket_unittest ixcore)
|
||||
target_link_libraries(ixwebsocket_unittest ixsentry)
|
||||
target_link_libraries(ixwebsocket_unittest ixbots)
|
||||
|
||||
target_link_libraries(ixwebsocket_unittest spdlog)
|
||||
|
||||
|
@ -14993,4 +14993,3 @@ using Catch::Detail::Approx;
|
||||
// end catch_reenable_warnings.h
|
||||
// end catch.hpp
|
||||
#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
|
||||
|
||||
|
@ -37,7 +37,9 @@ namespace
|
||||
class CobraChat
|
||||
{
|
||||
public:
|
||||
CobraChat(const std::string& user, const std::string& session, const std::string& endpoint);
|
||||
CobraChat(const std::string& user,
|
||||
const std::string& session,
|
||||
const ix::CobraConfig& config);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
@ -54,7 +56,7 @@ namespace
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
std::string _endpoint;
|
||||
ix::CobraConfig _cobraConfig;
|
||||
|
||||
std::queue<Json::Value> _publish_queue;
|
||||
mutable std::mutex _queue_mutex;
|
||||
@ -72,10 +74,10 @@ namespace
|
||||
|
||||
CobraChat::CobraChat(const std::string& user,
|
||||
const std::string& session,
|
||||
const std::string& endpoint)
|
||||
const ix::CobraConfig& config)
|
||||
: _user(user)
|
||||
, _session(session)
|
||||
, _endpoint(endpoint)
|
||||
, _cobraConfig(config)
|
||||
, _stop(false)
|
||||
, _connectedAndSubscribed(false)
|
||||
{
|
||||
@ -122,32 +124,38 @@ namespace
|
||||
void CobraChat::subscribe(const std::string& channel)
|
||||
{
|
||||
std::string filter;
|
||||
_conn.subscribe(
|
||||
channel, filter, [this](const Json::Value& msg, const std::string& /*position*/) {
|
||||
spdlog::info("receive {}", msg.toStyledString());
|
||||
std::string position("$");
|
||||
|
||||
if (!msg.isObject()) return;
|
||||
if (!msg.isMember("user")) return;
|
||||
if (!msg.isMember("text")) return;
|
||||
if (!msg.isMember("session")) return;
|
||||
_conn.subscribe(channel,
|
||||
filter,
|
||||
position,
|
||||
[this](const Json::Value& msg, const std::string& /*position*/) {
|
||||
spdlog::info("receive {}", msg.toStyledString());
|
||||
|
||||
std::string msg_user = msg["user"].asString();
|
||||
std::string msg_text = msg["text"].asString();
|
||||
std::string msg_session = msg["session"].asString();
|
||||
if (!msg.isObject()) return;
|
||||
if (!msg.isMember("user")) return;
|
||||
if (!msg.isMember("text")) return;
|
||||
if (!msg.isMember("session")) return;
|
||||
|
||||
// We are not interested in messages
|
||||
// from a different session.
|
||||
if (msg_session != _session) return;
|
||||
std::string msg_user = msg["user"].asString();
|
||||
std::string msg_text = msg["text"].asString();
|
||||
std::string msg_session = msg["session"].asString();
|
||||
|
||||
// We are not interested in our own messages
|
||||
if (msg_user == _user) return;
|
||||
// We are not interested in messages
|
||||
// from a different session.
|
||||
if (msg_session != _session) return;
|
||||
|
||||
_receivedQueue.push(msg);
|
||||
// We are not interested in our own messages
|
||||
if (msg_user == _user) return;
|
||||
|
||||
std::stringstream ss;
|
||||
ss << std::endl << msg_user << " > " << msg_text << std::endl << _user << " > ";
|
||||
log(ss.str());
|
||||
});
|
||||
_receivedQueue.push(msg);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << std::endl
|
||||
<< msg_user << " > " << msg_text << std::endl
|
||||
<< _user << " > ";
|
||||
log(ss.str());
|
||||
});
|
||||
}
|
||||
|
||||
void CobraChat::sendMessage(const std::string& text)
|
||||
@ -167,19 +175,9 @@ namespace
|
||||
//
|
||||
void CobraChat::run()
|
||||
{
|
||||
// "chat" conf
|
||||
std::string appkey("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string channel = _session;
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
SocketTLSOptions socketTLSOptions;
|
||||
|
||||
_conn.configure(appkey,
|
||||
_endpoint,
|
||||
role,
|
||||
secret,
|
||||
ix::WebSocketPerMessageDeflateOptions(true),
|
||||
socketTLSOptions);
|
||||
_conn.configure(_cobraConfig);
|
||||
_conn.connect();
|
||||
|
||||
_conn.setEventCallback([this, channel](ix::CobraConnectionEventType eventType,
|
||||
@ -263,7 +261,7 @@ TEST_CASE("Cobra_chat", "[cobra_chat]")
|
||||
SECTION("Exchange and count sent/received messages.")
|
||||
{
|
||||
int port = getFreePort();
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port);
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port, true);
|
||||
|
||||
// Start a redis server
|
||||
ix::RedisServer redisServer(appConfig.redisPort);
|
||||
@ -279,13 +277,20 @@ TEST_CASE("Cobra_chat", "[cobra_chat]")
|
||||
setupTrafficTrackerCallback();
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
std::string appkey("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
std::string endpoint = makeCobraEndpoint(port, true);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "ws://localhost:" << port;
|
||||
std::string endpoint = ss.str();
|
||||
ix::CobraConfig config;
|
||||
config.endpoint = endpoint;
|
||||
config.appkey = appkey;
|
||||
config.rolename = role;
|
||||
config.rolesecret = secret;
|
||||
config.socketTLSOptions = makeClientTLSOptions();
|
||||
|
||||
CobraChat chatA("jean", session, endpoint);
|
||||
CobraChat chatB("paul", session, endpoint);
|
||||
CobraChat chatA("jean", session, config);
|
||||
CobraChat chatB("paul", session, config);
|
||||
|
||||
chatA.start();
|
||||
chatB.start();
|
||||
|
@ -33,17 +33,6 @@ namespace
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// This project / appkey is configure on cobra to not do any batching.
|
||||
// This way we can start a subscriber and receive all messages as they come in.
|
||||
//
|
||||
std::string APPKEY("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string CHANNEL("unittest_channel");
|
||||
std::string PUBLISHER_ROLE("_pub");
|
||||
std::string PUBLISHER_SECRET("1c04DB8fFe76A4EeFE3E318C72d771db");
|
||||
std::string SUBSCRIBER_ROLE("_sub");
|
||||
std::string SUBSCRIBER_SECRET("66B1dA3ED5fA074EB5AE84Dd8CE3b5ba");
|
||||
|
||||
std::atomic<bool> gStop;
|
||||
std::atomic<bool> gSubscriberConnectedAndSubscribed;
|
||||
std::atomic<size_t> gUniqueMessageIdsCount;
|
||||
@ -55,28 +44,21 @@ namespace
|
||||
//
|
||||
// Background thread subscribe to the channel and validates what was sent
|
||||
//
|
||||
void startSubscriber(const std::string& endpoint)
|
||||
void startSubscriber(const ix::CobraConfig& config, const std::string& channel)
|
||||
{
|
||||
gSubscriberConnectedAndSubscribed = false;
|
||||
gUniqueMessageIdsCount = 0;
|
||||
gMessageCount = 0;
|
||||
|
||||
ix::CobraConnection conn;
|
||||
SocketTLSOptions socketTLSOptions;
|
||||
|
||||
conn.configure(APPKEY,
|
||||
endpoint,
|
||||
SUBSCRIBER_ROLE,
|
||||
SUBSCRIBER_SECRET,
|
||||
ix::WebSocketPerMessageDeflateOptions(true),
|
||||
socketTLSOptions);
|
||||
conn.configure(config);
|
||||
conn.connect();
|
||||
|
||||
conn.setEventCallback([&conn](ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId) {
|
||||
conn.setEventCallback([&conn, &channel](ix::CobraConnectionEventType eventType,
|
||||
const std::string& errMsg,
|
||||
const ix::WebSocketHttpHeaders& headers,
|
||||
const std::string& subscriptionId,
|
||||
CobraConnection::MsgId msgId) {
|
||||
if (eventType == ix::CobraConnection_EventType_Open)
|
||||
{
|
||||
TLogger() << "Subscriber connected:";
|
||||
@ -93,23 +75,27 @@ namespace
|
||||
{
|
||||
log("Subscriber authenticated");
|
||||
std::string filter;
|
||||
conn.subscribe(
|
||||
CHANNEL, filter, [](const Json::Value& msg, const std::string& /*position*/) {
|
||||
log(msg.toStyledString());
|
||||
std::string position("$");
|
||||
|
||||
std::string id = msg["id"].asString();
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(gProtectIds);
|
||||
gIds.insert(id);
|
||||
}
|
||||
conn.subscribe(channel,
|
||||
filter,
|
||||
position,
|
||||
[](const Json::Value& msg, const std::string& /*position*/) {
|
||||
log(msg.toStyledString());
|
||||
|
||||
gMessageCount++;
|
||||
});
|
||||
std::string id = msg["id"].asString();
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(gProtectIds);
|
||||
gIds.insert(id);
|
||||
}
|
||||
|
||||
gMessageCount++;
|
||||
});
|
||||
}
|
||||
else if (eventType == ix::CobraConnection_EventType_Subscribed)
|
||||
{
|
||||
TLogger() << "Subscriber: subscribed to channel " << subscriptionId;
|
||||
if (subscriptionId == CHANNEL)
|
||||
if (subscriptionId == channel)
|
||||
{
|
||||
gSubscriberConnectedAndSubscribed = true;
|
||||
}
|
||||
@ -121,7 +107,7 @@ namespace
|
||||
else if (eventType == ix::CobraConnection_EventType_UnSubscribed)
|
||||
{
|
||||
TLogger() << "Subscriber: ununexpected from channel " << subscriptionId;
|
||||
if (subscriptionId != CHANNEL)
|
||||
if (subscriptionId != channel)
|
||||
{
|
||||
TLogger() << "Subscriber: unexpected channel " << subscriptionId;
|
||||
}
|
||||
@ -138,7 +124,7 @@ namespace
|
||||
std::this_thread::sleep_for(duration);
|
||||
}
|
||||
|
||||
conn.unsubscribe(CHANNEL);
|
||||
conn.unsubscribe(channel);
|
||||
conn.disconnect();
|
||||
|
||||
gUniqueMessageIdsCount = gIds.size();
|
||||
@ -163,7 +149,8 @@ namespace
|
||||
TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
{
|
||||
int port = getFreePort();
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port);
|
||||
bool preferTLS = true;
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port, preferTLS);
|
||||
|
||||
// Start a redis server
|
||||
ix::RedisServer redisServer(appConfig.redisPort);
|
||||
@ -177,15 +164,21 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
|
||||
setupTrafficTrackerCallback();
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "ws://localhost:" << port;
|
||||
std::string endpoint = ss.str();
|
||||
std::string channel = ix::generateSessionId();
|
||||
std::string endpoint = makeCobraEndpoint(port, preferTLS);
|
||||
std::string appkey("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
|
||||
// Make channel name unique
|
||||
CHANNEL += uuid4();
|
||||
ix::CobraConfig config;
|
||||
config.endpoint = endpoint;
|
||||
config.appkey = appkey;
|
||||
config.rolename = role;
|
||||
config.rolesecret = secret;
|
||||
config.socketTLSOptions = makeClientTLSOptions();
|
||||
|
||||
gStop = false;
|
||||
std::thread bgThread(&startSubscriber, endpoint);
|
||||
std::thread subscriberThread(&startSubscriber, config, channel);
|
||||
|
||||
int timeout = 10 * 1000; // 10s
|
||||
|
||||
@ -205,18 +198,9 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
}
|
||||
|
||||
ix::CobraMetricsPublisher cobraMetricsPublisher;
|
||||
|
||||
SocketTLSOptions socketTLSOptions;
|
||||
bool perMessageDeflate = true;
|
||||
cobraMetricsPublisher.configure(APPKEY,
|
||||
endpoint,
|
||||
CHANNEL,
|
||||
PUBLISHER_ROLE,
|
||||
PUBLISHER_SECRET,
|
||||
perMessageDeflate,
|
||||
socketTLSOptions);
|
||||
cobraMetricsPublisher.configure(config, channel);
|
||||
cobraMetricsPublisher.setSession(uuid4());
|
||||
cobraMetricsPublisher.enable(true); // disabled by default, needs to be enabled to be active
|
||||
cobraMetricsPublisher.enable(true);
|
||||
|
||||
Json::Value data;
|
||||
data["foo"] = "bar";
|
||||
@ -292,7 +276,7 @@ TEST_CASE("Cobra_Metrics_Publisher", "[cobra]")
|
||||
|
||||
// Now stop the thread
|
||||
gStop = true;
|
||||
bgThread.join();
|
||||
subscriberThread.join();
|
||||
|
||||
//
|
||||
// Validate that we received all message kinds, and the correct number of messages
|
||||
|
@ -1,7 +1,7 @@
|
||||
/*
|
||||
* cmd_satori_chat.cpp
|
||||
* IXCobraToSentryTest.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2017 Machine Zone. All rights reserved.
|
||||
* Copyright (c) 2020 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
@ -42,18 +42,9 @@ namespace
|
||||
void runPublisher(const ix::CobraConfig& config, const std::string& channel)
|
||||
{
|
||||
ix::CobraMetricsPublisher cobraMetricsPublisher;
|
||||
|
||||
SocketTLSOptions socketTLSOptions;
|
||||
bool perMessageDeflate = true;
|
||||
cobraMetricsPublisher.configure(config.appkey,
|
||||
config.endpoint,
|
||||
channel,
|
||||
config.rolename,
|
||||
config.rolesecret,
|
||||
perMessageDeflate,
|
||||
socketTLSOptions);
|
||||
cobraMetricsPublisher.configure(config, channel);
|
||||
cobraMetricsPublisher.setSession(uuid4());
|
||||
cobraMetricsPublisher.enable(true); // disabled by default, needs to be enabled to be active
|
||||
cobraMetricsPublisher.enable(true);
|
||||
|
||||
Json::Value msg;
|
||||
msg["fps"] = 60;
|
||||
@ -78,12 +69,12 @@ namespace
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Cobra_to_sentry_bot", "[foo]")
|
||||
TEST_CASE("Cobra_to_sentry_bot", "[cobra_bots]")
|
||||
{
|
||||
SECTION("Exchange and count sent/received messages.")
|
||||
{
|
||||
int port = getFreePort();
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port);
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port, true);
|
||||
|
||||
// Start a redis server
|
||||
ix::RedisServer redisServer(appConfig.redisPort);
|
||||
@ -96,10 +87,7 @@ TEST_CASE("Cobra_to_sentry_bot", "[foo]")
|
||||
snakeServer.run();
|
||||
|
||||
// Start a fake sentry http server
|
||||
SocketTLSOptions tlsOptionsServer;
|
||||
tlsOptionsServer.certFile = ".certs/trusted-server-crt.pem";
|
||||
tlsOptionsServer.keyFile = ".certs/trusted-server-key.pem";
|
||||
tlsOptionsServer.caFile = ".certs/trusted-ca-crt.pem";
|
||||
SocketTLSOptions tlsOptionsServer = makeServerTLSOptions(true);
|
||||
|
||||
int sentryPort = getFreePort();
|
||||
ix::HttpServer sentryServer(sentryPort, "127.0.0.1");
|
||||
@ -139,20 +127,19 @@ TEST_CASE("Cobra_to_sentry_bot", "[foo]")
|
||||
std::string appkey("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
|
||||
std::stringstream ss;
|
||||
ss << "ws://localhost:" << port;
|
||||
std::string endpoint = ss.str();
|
||||
std::string endpoint = makeCobraEndpoint(port, true);
|
||||
|
||||
ix::CobraConfig config;
|
||||
config.endpoint = endpoint;
|
||||
config.appkey = appkey;
|
||||
config.rolename = role;
|
||||
config.rolesecret = secret;
|
||||
config.socketTLSOptions = makeClientTLSOptions();
|
||||
|
||||
std::thread publisherThread(runPublisher, config, channel);
|
||||
|
||||
std::string filter;
|
||||
std::string position("$");
|
||||
bool verbose = true;
|
||||
bool strict = true;
|
||||
size_t maxQueueSize = 10;
|
||||
@ -163,15 +150,10 @@ TEST_CASE("Cobra_to_sentry_bot", "[foo]")
|
||||
// -> https://github.com/openssl/openssl/issues/7967
|
||||
// https://xxxxx:yyyyyy@sentry.io/1234567
|
||||
std::stringstream oss;
|
||||
std::string scheme("http://");
|
||||
|
||||
oss << scheme << "xxxxxxx:yyyyyyy@localhost:" << sentryPort << "/1234567";
|
||||
oss << getHttpScheme() << "xxxxxxx:yyyyyyy@localhost:" << sentryPort << "/1234567";
|
||||
std::string dsn = oss.str();
|
||||
|
||||
SocketTLSOptions tlsOptionsClient;
|
||||
tlsOptionsClient.certFile = ".certs/trusted-client-crt.pem";
|
||||
tlsOptionsClient.keyFile = ".certs/trusted-client-key.pem";
|
||||
tlsOptionsClient.caFile = ".certs/trusted-ca-crt.pem";
|
||||
SocketTLSOptions tlsOptionsClient = makeClientTLSOptions();
|
||||
|
||||
SentryClient sentryClient(dsn);
|
||||
sentryClient.setTLSOptions(tlsOptionsClient);
|
||||
@ -182,6 +164,7 @@ TEST_CASE("Cobra_to_sentry_bot", "[foo]")
|
||||
int sentCount = cobra_to_sentry_bot(config,
|
||||
channel,
|
||||
filter,
|
||||
position,
|
||||
sentryClient,
|
||||
verbose,
|
||||
strict,
|
||||
|
145
test/IXCobraToStatsdBotTest.cpp
Normal file
145
test/IXCobraToStatsdBotTest.cpp
Normal file
@ -0,0 +1,145 @@
|
||||
/*
|
||||
* IXCobraToStatsdTest.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2020 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <ixbots/IXCobraToStatsdBot.h>
|
||||
#include <ixcobra/IXCobraConnection.h>
|
||||
#include <ixcobra/IXCobraMetricsPublisher.h>
|
||||
#include <ixcrypto/IXUuid.h>
|
||||
#include <ixsentry/IXSentryClient.h>
|
||||
#include <ixsnake/IXRedisServer.h>
|
||||
#include <ixsnake/IXSnakeServer.h>
|
||||
#include <ixwebsocket/IXHttpServer.h>
|
||||
#include <ixwebsocket/IXUserAgent.h>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
namespace
|
||||
{
|
||||
void runPublisher(const ix::CobraConfig& config, const std::string& channel)
|
||||
{
|
||||
ix::CobraMetricsPublisher cobraMetricsPublisher;
|
||||
cobraMetricsPublisher.configure(config, channel);
|
||||
cobraMetricsPublisher.setSession(uuid4());
|
||||
cobraMetricsPublisher.enable(true);
|
||||
|
||||
Json::Value msg;
|
||||
msg["fps"] = 60;
|
||||
|
||||
cobraMetricsPublisher.setGenericAttributes("game", "ody");
|
||||
|
||||
// Wait a bit
|
||||
ix::msleep(500);
|
||||
|
||||
// publish some messages
|
||||
cobraMetricsPublisher.push("sms_metric_A_id", msg); // (msg #1)
|
||||
cobraMetricsPublisher.push("sms_metric_B_id", msg); // (msg #2)
|
||||
ix::msleep(500);
|
||||
|
||||
cobraMetricsPublisher.push("sms_metric_A_id", msg); // (msg #3)
|
||||
cobraMetricsPublisher.push("sms_metric_D_id", msg); // (msg #4)
|
||||
ix::msleep(500);
|
||||
|
||||
cobraMetricsPublisher.push("sms_metric_A_id", msg); // (msg #4)
|
||||
cobraMetricsPublisher.push("sms_metric_F_id", msg); // (msg #5)
|
||||
ix::msleep(500);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Cobra_to_statsd_bot", "[cobra_bots]")
|
||||
{
|
||||
SECTION("Exchange and count sent/received messages.")
|
||||
{
|
||||
int port = getFreePort();
|
||||
snake::AppConfig appConfig = makeSnakeServerConfig(port, true);
|
||||
|
||||
// Start a redis server
|
||||
ix::RedisServer redisServer(appConfig.redisPort);
|
||||
auto res = redisServer.listen();
|
||||
REQUIRE(res.first);
|
||||
redisServer.start();
|
||||
|
||||
// Start a snake server
|
||||
snake::SnakeServer snakeServer(appConfig);
|
||||
snakeServer.run();
|
||||
|
||||
// Start a fake statsd server (ultimately)
|
||||
|
||||
// Run the bot for a small amount of time
|
||||
std::string channel = ix::generateSessionId();
|
||||
std::string appkey("FC2F10139A2BAc53BB72D9db967b024f");
|
||||
std::string role = "_sub";
|
||||
std::string secret = "66B1dA3ED5fA074EB5AE84Dd8CE3b5ba";
|
||||
std::string endpoint = makeCobraEndpoint(port, true);
|
||||
|
||||
ix::CobraConfig config;
|
||||
config.endpoint = endpoint;
|
||||
config.appkey = appkey;
|
||||
config.rolename = role;
|
||||
config.rolesecret = secret;
|
||||
config.socketTLSOptions = makeClientTLSOptions();
|
||||
|
||||
std::thread publisherThread(runPublisher, config, channel);
|
||||
|
||||
std::string filter;
|
||||
std::string position("$");
|
||||
bool verbose = true;
|
||||
size_t maxQueueSize = 10;
|
||||
bool enableHeartbeat = false;
|
||||
|
||||
// Only run the bot for 3 seconds
|
||||
int runtime = 3;
|
||||
|
||||
std::string hostname("127.0.0.1");
|
||||
// std::string hostname("www.google.com");
|
||||
int statsdPort = 8125;
|
||||
std::string prefix("ix.test");
|
||||
StatsdClient statsdClient(hostname, statsdPort, prefix);
|
||||
|
||||
std::string errMsg;
|
||||
bool initialized = statsdClient.init(errMsg);
|
||||
if (!initialized)
|
||||
{
|
||||
spdlog::error(errMsg);
|
||||
}
|
||||
REQUIRE(initialized);
|
||||
|
||||
std::string fields("device.game\ndevice.os_name");
|
||||
std::string gauge;
|
||||
std::string timer;
|
||||
|
||||
int sentCount = ix::cobra_to_statsd_bot(config,
|
||||
channel,
|
||||
filter,
|
||||
position,
|
||||
statsdClient,
|
||||
fields,
|
||||
gauge,
|
||||
timer,
|
||||
verbose,
|
||||
maxQueueSize,
|
||||
enableHeartbeat,
|
||||
runtime);
|
||||
//
|
||||
// We want at least 2 messages to be sent
|
||||
//
|
||||
REQUIRE(sentCount >= 2);
|
||||
|
||||
// Give us 1s for all messages to be received
|
||||
ix::msleep(1000);
|
||||
|
||||
spdlog::info("Stopping snake server...");
|
||||
snakeServer.stop();
|
||||
|
||||
spdlog::info("Stopping redis server...");
|
||||
redisServer.stop();
|
||||
|
||||
publisherThread.join();
|
||||
}
|
||||
}
|
@ -149,7 +149,61 @@ namespace ix
|
||||
return std::string(vec.begin(), vec.end());
|
||||
}
|
||||
|
||||
snake::AppConfig makeSnakeServerConfig(int port)
|
||||
SocketTLSOptions makeClientTLSOptions()
|
||||
{
|
||||
SocketTLSOptions tlsOptionsClient;
|
||||
tlsOptionsClient.certFile = ".certs/trusted-client-crt.pem";
|
||||
tlsOptionsClient.keyFile = ".certs/trusted-client-key.pem";
|
||||
tlsOptionsClient.caFile = ".certs/trusted-ca-crt.pem";
|
||||
|
||||
return tlsOptionsClient;
|
||||
}
|
||||
|
||||
SocketTLSOptions makeServerTLSOptions(bool preferTLS)
|
||||
{
|
||||
// Start a fake sentry http server
|
||||
SocketTLSOptions tlsOptionsServer;
|
||||
tlsOptionsServer.certFile = ".certs/trusted-server-crt.pem";
|
||||
tlsOptionsServer.keyFile = ".certs/trusted-server-key.pem";
|
||||
tlsOptionsServer.caFile = ".certs/trusted-ca-crt.pem";
|
||||
|
||||
#if defined(IXWEBSOCKET_USE_MBED_TLS) || defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
tlsOptionsServer.tls = preferTLS;
|
||||
#else
|
||||
tlsOptionsServer.tls = false;
|
||||
#endif
|
||||
return tlsOptionsServer;
|
||||
}
|
||||
|
||||
std::string getHttpScheme()
|
||||
{
|
||||
#if defined(IXWEBSOCKET_USE_MBED_TLS) || defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
std::string scheme("https://");
|
||||
#else
|
||||
std::string scheme("http://");
|
||||
#endif
|
||||
return scheme;
|
||||
}
|
||||
|
||||
std::string getWsScheme(bool preferTLS)
|
||||
{
|
||||
std::string scheme;
|
||||
#if defined(IXWEBSOCKET_USE_MBED_TLS) || defined(IXWEBSOCKET_USE_OPEN_SSL)
|
||||
if (preferTLS)
|
||||
{
|
||||
scheme = "wss://";
|
||||
}
|
||||
else
|
||||
{
|
||||
scheme = "ws://";
|
||||
}
|
||||
#else
|
||||
scheme = "ws://";
|
||||
#endif
|
||||
return scheme;
|
||||
}
|
||||
|
||||
snake::AppConfig makeSnakeServerConfig(int port, bool preferTLS)
|
||||
{
|
||||
snake::AppConfig appConfig;
|
||||
appConfig.port = port;
|
||||
@ -158,6 +212,7 @@ namespace ix
|
||||
appConfig.redisPort = getFreePort();
|
||||
appConfig.redisPassword = "";
|
||||
appConfig.redisHosts.push_back("localhost"); // only one host supported now
|
||||
appConfig.socketTLSOptions = makeServerTLSOptions(preferTLS);
|
||||
|
||||
std::string appsConfigPath("appsConfig.json");
|
||||
|
||||
@ -178,4 +233,13 @@ namespace ix
|
||||
|
||||
return appConfig;
|
||||
}
|
||||
|
||||
std::string makeCobraEndpoint(int port, bool preferTLS)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << getWsScheme(preferTLS) << "localhost:" << port;
|
||||
std::string endpoint = ss.str();
|
||||
|
||||
return endpoint;
|
||||
}
|
||||
} // namespace ix
|
||||
|
@ -9,6 +9,7 @@
|
||||
#include "IXGetFreePort.h"
|
||||
#include <iostream>
|
||||
#include <ixsnake/IXAppConfig.h>
|
||||
#include <ixwebsocket/IXSocketTLSOptions.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <mutex>
|
||||
#include <spdlog/spdlog.h>
|
||||
@ -50,5 +51,12 @@ namespace ix
|
||||
|
||||
bool startWebSocketEchoServer(ix::WebSocketServer& server);
|
||||
|
||||
snake::AppConfig makeSnakeServerConfig(int port);
|
||||
snake::AppConfig makeSnakeServerConfig(int port, bool preferTLS);
|
||||
|
||||
SocketTLSOptions makeClientTLSOptions();
|
||||
SocketTLSOptions makeServerTLSOptions(bool preferTLS);
|
||||
std::string getHttpScheme();
|
||||
std::string getWsScheme(bool preferTLS);
|
||||
|
||||
std::string makeCobraEndpoint(int port, bool preferTLS);
|
||||
} // namespace ix
|
||||
|
@ -28,7 +28,6 @@
|
||||
#include <ixwebsocket/IXWebSocketHandshake.h>
|
||||
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
|
||||
#include <ixwebsocket/IXWebSocketMessage.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageQueue.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageType.h>
|
||||
#include <ixwebsocket/IXWebSocketOpenInfo.h>
|
||||
#include <ixwebsocket/IXWebSocketPerMessageDeflate.h>
|
||||
|
306
test/IXWebSocketBroadcastTest.cpp
Normal file
306
test/IXWebSocketBroadcastTest.cpp
Normal file
@ -0,0 +1,306 @@
|
||||
/*
|
||||
* IXWebSocketServerTest.cpp
|
||||
* Author: Benjamin Sergeant
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include "msgpack11.hpp"
|
||||
#include <iostream>
|
||||
#include <ixwebsocket/IXSocket.h>
|
||||
#include <ixwebsocket/IXSocketFactory.h>
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
|
||||
using msgpack11::MsgPack;
|
||||
using namespace ix;
|
||||
|
||||
namespace
|
||||
{
|
||||
class WebSocketChat
|
||||
{
|
||||
public:
|
||||
WebSocketChat(const std::string& user, const std::string& session, int port);
|
||||
|
||||
void subscribe(const std::string& channel);
|
||||
void start();
|
||||
void stop();
|
||||
bool isReady() const;
|
||||
|
||||
void sendMessage(const std::string& text);
|
||||
size_t getReceivedMessagesCount() const;
|
||||
const std::vector<std::string>& getReceivedMessages() const;
|
||||
|
||||
std::string encodeMessage(const std::string& text);
|
||||
std::pair<std::string, std::string> decodeMessage(const std::string& str);
|
||||
void appendMessage(const std::string& message);
|
||||
|
||||
private:
|
||||
std::string _user;
|
||||
std::string _session;
|
||||
int _port;
|
||||
|
||||
ix::WebSocket _webSocket;
|
||||
|
||||
std::vector<std::string> _receivedMessages;
|
||||
mutable std::mutex _mutex;
|
||||
};
|
||||
|
||||
WebSocketChat::WebSocketChat(const std::string& user, const std::string& session, int port)
|
||||
: _user(user)
|
||||
, _session(session)
|
||||
, _port(port)
|
||||
{
|
||||
_webSocket.setTLSOptions(makeClientTLSOptions());
|
||||
}
|
||||
|
||||
size_t WebSocketChat::getReceivedMessagesCount() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
return _receivedMessages.size();
|
||||
}
|
||||
|
||||
const std::vector<std::string>& WebSocketChat::getReceivedMessages() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
return _receivedMessages;
|
||||
}
|
||||
|
||||
void WebSocketChat::appendMessage(const std::string& message)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(_mutex);
|
||||
_receivedMessages.push_back(message);
|
||||
}
|
||||
|
||||
bool WebSocketChat::isReady() const
|
||||
{
|
||||
return _webSocket.getReadyState() == ix::ReadyState::Open;
|
||||
}
|
||||
|
||||
void WebSocketChat::stop()
|
||||
{
|
||||
_webSocket.stop();
|
||||
}
|
||||
|
||||
void WebSocketChat::start()
|
||||
{
|
||||
std::string url;
|
||||
{
|
||||
bool preferTLS = true;
|
||||
url = makeCobraEndpoint(_port, preferTLS);
|
||||
}
|
||||
|
||||
_webSocket.setUrl(url);
|
||||
|
||||
std::stringstream ss;
|
||||
log(std::string("Connecting to url: ") + url);
|
||||
|
||||
_webSocket.setOnMessageCallback([this](const ix::WebSocketMessagePtr& msg) {
|
||||
std::stringstream ss;
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
ss << "websocket_broadcast_client: " << _user << " Connected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
ss << "websocket_broadcast_client: " << _user << " disconnected !";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
auto result = decodeMessage(msg->str);
|
||||
|
||||
// Our "chat" / "broacast" node.js server does not send us
|
||||
// the messages we send, so we don't need to have a msg_user != user
|
||||
// as we do for the satori chat example.
|
||||
|
||||
// store text
|
||||
appendMessage(result.second);
|
||||
|
||||
std::string payload = result.second;
|
||||
if (payload.size() > 2000)
|
||||
{
|
||||
payload = "<message too large>";
|
||||
}
|
||||
|
||||
ss << std::endl << result.first << " > " << payload << std::endl << _user << " > ";
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "websocket_broadcast_client: " << _user << " Error ! "
|
||||
<< msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Ping)
|
||||
{
|
||||
log("websocket_broadcast_client: received ping message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Pong)
|
||||
{
|
||||
log("websocket_broadcast_client: received pong message");
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Fragment)
|
||||
{
|
||||
log("websocket_broadcast_client: received message fragment");
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Unexpected ix::WebSocketMessageType";
|
||||
log(ss.str());
|
||||
}
|
||||
});
|
||||
|
||||
_webSocket.start();
|
||||
}
|
||||
|
||||
std::pair<std::string, std::string> WebSocketChat::decodeMessage(const std::string& str)
|
||||
{
|
||||
std::string errMsg;
|
||||
MsgPack msg = MsgPack::parse(str, errMsg);
|
||||
|
||||
std::string msg_user = msg["user"].string_value();
|
||||
std::string msg_text = msg["text"].string_value();
|
||||
|
||||
return std::pair<std::string, std::string>(msg_user, msg_text);
|
||||
}
|
||||
|
||||
std::string WebSocketChat::encodeMessage(const std::string& text)
|
||||
{
|
||||
std::map<MsgPack, MsgPack> obj;
|
||||
obj["user"] = _user;
|
||||
obj["text"] = text;
|
||||
|
||||
MsgPack msg(obj);
|
||||
|
||||
std::string output = msg.dump();
|
||||
return output;
|
||||
}
|
||||
|
||||
void WebSocketChat::sendMessage(const std::string& text)
|
||||
{
|
||||
_webSocket.sendBinary(encodeMessage(text));
|
||||
}
|
||||
|
||||
bool startServer(ix::WebSocketServer& server, std::string& connectionId)
|
||||
{
|
||||
bool preferTLS = true;
|
||||
server.setTLSOptions(makeServerTLSOptions(preferTLS));
|
||||
|
||||
server.setOnConnectionCallback([&server, &connectionId](
|
||||
std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback([webSocket, connectionState, &connectionId, &server](
|
||||
const ix::WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
TLogger() << "New connection";
|
||||
connectionState->computeId();
|
||||
TLogger() << "id: " << connectionState->getId();
|
||||
TLogger() << "Uri: " << msg->openInfo.uri;
|
||||
TLogger() << "Headers:";
|
||||
for (auto it : msg->openInfo.headers)
|
||||
{
|
||||
TLogger() << it.first << ": " << it.second;
|
||||
}
|
||||
|
||||
connectionId = connectionState->getId();
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
TLogger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->send(msg->str, msg->binary);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
TLogger() << res.second;
|
||||
return false;
|
||||
}
|
||||
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_broadcast_server", "[websocket_server]")
|
||||
{
|
||||
SECTION("Connect to the server, do not send anything. Should timeout and return 400")
|
||||
{
|
||||
int port = getFreePort();
|
||||
ix::WebSocketServer server(port);
|
||||
std::string connectionId;
|
||||
REQUIRE(startServer(server, connectionId));
|
||||
|
||||
std::string session = ix::generateSessionId();
|
||||
std::vector<std::shared_ptr<WebSocketChat>> chatClients;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
{
|
||||
std::string user("user_" + std::to_string(i));
|
||||
chatClients.push_back(std::make_shared<WebSocketChat>(user, session, port));
|
||||
chatClients[i]->start();
|
||||
ix::msleep(50);
|
||||
}
|
||||
|
||||
// Wait for all chat instance to be ready
|
||||
while (true)
|
||||
{
|
||||
bool allReady = true;
|
||||
for (size_t i = 0; i < chatClients.size(); ++i)
|
||||
{
|
||||
allReady &= chatClients[i]->isReady();
|
||||
}
|
||||
if (allReady) break;
|
||||
ix::msleep(10);
|
||||
}
|
||||
|
||||
for (int j = 0; j < 1000; j++)
|
||||
{
|
||||
for (size_t i = 0; i < chatClients.size(); ++i)
|
||||
{
|
||||
chatClients[i]->sendMessage("hello world");
|
||||
}
|
||||
|
||||
if (j == 250)
|
||||
{
|
||||
server.stop();
|
||||
ix::msleep(100);
|
||||
}
|
||||
if (j == 500)
|
||||
{
|
||||
server.start();
|
||||
ix::msleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
// wait 1 second
|
||||
ix::msleep(2000);
|
||||
|
||||
// Stop all clients
|
||||
size_t messageCount = chatClients.size() * 50;
|
||||
for (size_t i = 0; i < chatClients.size(); ++i)
|
||||
{
|
||||
REQUIRE(chatClients[i]->getReceivedMessagesCount() >= messageCount);
|
||||
chatClients[i]->stop();
|
||||
}
|
||||
|
||||
// Give us 500ms for the server to notice that clients went away
|
||||
ix::msleep(500);
|
||||
server.stop();
|
||||
REQUIRE(server.getClients().size() == 0);
|
||||
}
|
||||
}
|
@ -1,178 +0,0 @@
|
||||
/*
|
||||
* IXWebSocketMessageQTest.cpp
|
||||
* Author: Korchynskyi Dmytro
|
||||
* Copyright (c) 2019 Machine Zone. All rights reserved.
|
||||
*/
|
||||
|
||||
#include "IXTest.h"
|
||||
#include "catch.hpp"
|
||||
#include <ixwebsocket/IXWebSocket.h>
|
||||
#include <ixwebsocket/IXWebSocketMessageQueue.h>
|
||||
#include <ixwebsocket/IXWebSocketServer.h>
|
||||
#include <thread>
|
||||
|
||||
using namespace ix;
|
||||
|
||||
namespace
|
||||
{
|
||||
bool startServer(ix::WebSocketServer& server)
|
||||
{
|
||||
server.setOnConnectionCallback([&server](std::shared_ptr<ix::WebSocket> webSocket,
|
||||
std::shared_ptr<ConnectionState> connectionState) {
|
||||
webSocket->setOnMessageCallback(
|
||||
[connectionState, &server](const WebSocketMessagePtr& msg) {
|
||||
if (msg->type == ix::WebSocketMessageType::Open)
|
||||
{
|
||||
TLogger() << "New connection";
|
||||
connectionState->computeId();
|
||||
TLogger() << "id: " << connectionState->getId();
|
||||
TLogger() << "Uri: " << msg->openInfo.uri;
|
||||
TLogger() << "Headers:";
|
||||
for (auto&& it : msg->openInfo.headers)
|
||||
{
|
||||
TLogger() << it.first << ": " << it.second;
|
||||
}
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Close)
|
||||
{
|
||||
TLogger() << "Closed connection";
|
||||
}
|
||||
else if (msg->type == ix::WebSocketMessageType::Message)
|
||||
{
|
||||
TLogger() << "Message received: " << msg->str;
|
||||
|
||||
for (auto&& client : server.getClients())
|
||||
{
|
||||
client->send(msg->str);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
auto res = server.listen();
|
||||
if (!res.first)
|
||||
{
|
||||
TLogger() << res.second;
|
||||
return false;
|
||||
}
|
||||
|
||||
server.start();
|
||||
return true;
|
||||
}
|
||||
|
||||
class MsgQTestClient
|
||||
{
|
||||
public:
|
||||
MsgQTestClient()
|
||||
{
|
||||
msgQ.bindWebsocket(&ws);
|
||||
|
||||
msgQ.setOnMessageCallback([this](const WebSocketMessagePtr& msg) {
|
||||
REQUIRE(mainThreadId == std::this_thread::get_id());
|
||||
|
||||
std::stringstream ss;
|
||||
if (msg->type == WebSocketMessageType::Open)
|
||||
{
|
||||
log("client connected");
|
||||
sendNextMessage();
|
||||
}
|
||||
else if (msg->type == WebSocketMessageType::Close)
|
||||
{
|
||||
log("client disconnected");
|
||||
}
|
||||
else if (msg->type == WebSocketMessageType::Error)
|
||||
{
|
||||
ss << "Error ! " << msg->errorInfo.reason;
|
||||
log(ss.str());
|
||||
testDone = true;
|
||||
}
|
||||
else if (msg->type == WebSocketMessageType::Pong)
|
||||
{
|
||||
ss << "Received pong message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == WebSocketMessageType::Ping)
|
||||
{
|
||||
ss << "Received ping message " << msg->str;
|
||||
log(ss.str());
|
||||
}
|
||||
else if (msg->type == WebSocketMessageType::Message)
|
||||
{
|
||||
REQUIRE(msg->str.compare("Hey dude!") == 0);
|
||||
++receivedCount;
|
||||
ss << "Received message " << msg->str;
|
||||
log(ss.str());
|
||||
sendNextMessage();
|
||||
}
|
||||
else
|
||||
{
|
||||
ss << "Invalid WebSocketMessageType";
|
||||
log(ss.str());
|
||||
testDone = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void sendNextMessage()
|
||||
{
|
||||
if (receivedCount >= 3)
|
||||
{
|
||||
testDone = true;
|
||||
succeeded = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto info = ws.sendText("Hey dude!");
|
||||
if (info.success)
|
||||
log("sent message");
|
||||
else
|
||||
log("send failed");
|
||||
}
|
||||
}
|
||||
|
||||
void run(const std::string& url)
|
||||
{
|
||||
mainThreadId = std::this_thread::get_id();
|
||||
testDone = false;
|
||||
receivedCount = 0;
|
||||
|
||||
ws.setUrl(url);
|
||||
ws.start();
|
||||
|
||||
while (!testDone)
|
||||
{
|
||||
msgQ.poll();
|
||||
msleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
bool isSucceeded() const
|
||||
{
|
||||
return succeeded;
|
||||
}
|
||||
|
||||
private:
|
||||
WebSocket ws;
|
||||
WebSocketMessageQueue msgQ;
|
||||
bool testDone = false;
|
||||
uint32_t receivedCount = 0;
|
||||
std::thread::id mainThreadId;
|
||||
bool succeeded = false;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Websocket_message_queue", "[websocket_message_q]")
|
||||
{
|
||||
SECTION("Send several messages")
|
||||
{
|
||||
int port = getFreePort();
|
||||
WebSocketServer server(port);
|
||||
REQUIRE(startServer(server));
|
||||
|
||||
MsgQTestClient testClient;
|
||||
testClient.run("ws://127.0.0.1:" + std::to_string(port));
|
||||
REQUIRE(testClient.isSucceeded());
|
||||
|
||||
server.stop();
|
||||
}
|
||||
}
|
@ -65,7 +65,7 @@ namespace
|
||||
// Set a 1 second heartbeat with the setter method to test
|
||||
if (_useHeartBeatMethod)
|
||||
{
|
||||
_webSocket.setHeartBeatPeriod(1);
|
||||
_webSocket.setPingInterval(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -378,9 +378,9 @@ TEST_CASE("Websocket_ping_data_sent_setPingInterval_full", "[setPingInterval]")
|
||||
}
|
||||
}
|
||||
|
||||
// Using setHeartBeatPeriod
|
||||
// Using setPingInterval
|
||||
|
||||
TEST_CASE("Websocket_ping_no_data_sent_setHeartBeatPeriod", "[setHeartBeatPeriod]")
|
||||
TEST_CASE("Websocket_ping_no_data_sent_setHeartBeatPeriod", "[setPingInterval]")
|
||||
{
|
||||
SECTION("Make sure that ping messages are sent when no other data are sent.")
|
||||
{
|
||||
@ -424,7 +424,7 @@ TEST_CASE("Websocket_ping_no_data_sent_setHeartBeatPeriod", "[setHeartBeatPeriod
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Websocket_ping_data_sent_setHeartBeatPeriod", "[setHeartBeatPeriod]")
|
||||
TEST_CASE("Websocket_ping_data_sent_setHeartBeatPeriod", "[setPingInterval]")
|
||||
{
|
||||
SECTION("Make sure that ping messages are sent, even if other messages are sent")
|
||||
{
|
||||
|
@ -62,7 +62,7 @@ namespace ix
|
||||
{
|
||||
if (client != webSocket)
|
||||
{
|
||||
client->send(msg->str);
|
||||
client->send(msg->str, msg->binary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because one or more lines are too long
@ -823,7 +823,7 @@ $ honcho start
|
||||
15:29:57 send.1 | [2020-01-05 15:29:57.399] [info] ws_send: received message (25183026 bytes)
|
||||
15:29:57 send.1 | [2020-01-05 15:29:57.399] [info] ws_send: Done !
|
||||
15:29:59 send.1 | [2020-01-05 15:29:59.233] [info] ws_send: connection closed: code 1000 reason Normal closure
|
||||
15:29:59 send.1 |
|
||||
15:29:59 send.1 |
|
||||
15:29:59 system | send.1 stopped (rc=0)
|
||||
15:29:59 system | sending SIGTERM to nginx.1 (pid 75372)
|
||||
15:29:59 system | sending SIGTERM to websocket_server.1 (pid 75374)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user