Compare commits

..

71 Commits

Author SHA1 Message Date
1d3db5f75b (cobra to statsd bot) add ability to extract a numerical value and send a timer event to statsd, with the --timer option 2020-03-30 16:08:47 -07:00
296762ce06 add a docker deploy makefile target to build docker and push the built container in one shot 2020-03-29 22:08:36 -07:00
e465f7af52 (cobra to statsd bot) bot init was missing + capture socket error 2020-03-29 22:03:27 -07:00
f8bf1fe7cd (cobra to statsd bot) add ability to extract a numerical value and send a gauge event to statsd 2020-03-29 19:32:43 -07:00
cfa5718e40 (ws cobra subscriber) use a Json::StreamWriter to write to std::cout, and save one std::string allocation for each message printed 2020-03-29 15:24:46 -07:00
40c619c1ec (docker) trim down docker image (300M -> 12M) / binary built without symbol and size optimization, and source code not copied over 2020-03-29 13:06:44 -07:00
22b02e0e5c update doc 2020-03-28 10:46:42 -07:00
738a3bf1c5 update bundled jsoncpp to 1.9.3
(still comment the deprecation warning, which we should eventually fix ...)
2020-03-28 10:44:05 -07:00
598fb071e3 have some make target compile in release with debug 2020-03-28 10:33:22 -07:00
686aface26 bump version to 9.1.3 2020-03-28 10:33:05 -07:00
3073dd3f06 alpine docker file installs ca-certificates (for TLS) 2020-03-28 10:32:25 -07:00
68c64f3f69 use alpine as the docker distribution 2020-03-27 17:38:35 -07:00
771ebb2a4c (mac ssl) rename DarwinSSL -> SecureTransport (see this too -> https://github.com/curl/curl/issues/3733) 2020-03-26 19:40:52 -07:00
0fffb1e894 (websocket) fix data race accessing _socket object without mutex protection when calling wakeUpFromPoll in WebSocketTransport.cpp 2020-03-26 19:31:59 -07:00
18164c0c38 New CI builder: Mac + MbedTLS + Thread Sanitizer 2020-03-26 19:16:04 -07:00
d2db7310ff (ixcobra) add explicit event types for handshake, authentication and subscription failure, and handle those by exiting in ws_cobra_subcribe and friends 2020-03-26 18:54:28 -07:00
09e4584fc8 New CI builder: Mac + OpenSSL + Thread Sanitizer 2020-03-26 16:46:47 -07:00
da36856d85 Only find zlib if it has not already been found. (#169) 2020-03-26 09:39:51 -07:00
dffa759f71 move IXBench code under ixwebsocker folder 2020-03-24 20:53:25 -07:00
61e789d6a4 formatting 2020-03-24 20:37:55 -07:00
37cb2cc266 (ws connect) display statistics about how much time it takes to stop the connection / cf #168 2020-03-24 20:29:09 -07:00
179e17895d unique_ptr for sockets 2020-03-24 12:48:55 -07:00
9f818c7acf (socket) selectInterrupt member is an unique_ptr instead of being a shared_ptr 2020-03-24 10:00:41 -07:00
9dcc2538ae (websocket) reset per-message deflate codec everytime we connect to a server/client 2020-03-23 18:46:30 -07:00
f41a54186c (websocket) fix #167, a long standing issue with sending empty messages with per-message deflate extension (and hopefully other zlib bug) 2020-03-23 15:21:53 -07:00
e0733d205c fix linux linker error 2020-03-22 21:59:30 -07:00
f72f845ad2 trim headers and unused code in IXUdpSocket 2020-03-22 21:51:41 -07:00
b7e7837d76 fix simple compile error 2020-03-22 19:43:43 -07:00
fe966b19c7 re-enable unittests 2020-03-22 19:39:28 -07:00
a0ffb2ba53 cobra to statsd bot ported to windows + add unittest 2020-03-22 19:37:04 -07:00
5ad54a8904 pre-commit / fix simple file trailing things 2020-03-21 19:31:38 -07:00
10e132e8ef remove std::cerr in IXRedisServer which triggers a tsan error 2020-03-20 17:50:08 -07:00
5ce846f48b indent files 2020-03-20 17:00:18 -07:00
1d6373335c (websocket+tls) fix hang in tls handshake which could lead to ANR, discovered through unittesting. 2020-03-20 16:57:27 -07:00
829751b7af (cobra) CobraMetricsPublisher can be configure with an ix::CobraConfig + more unittest use SSL in server + client 2020-03-20 12:22:00 -07:00
5691b55967 (unittest) / try to run the cobra 2 sentry bot test with SSL if the platform supports it 2020-03-19 18:50:46 -07:00
575bceb1ec add make target for ubsan, tsan and asan, and enable running the unittest on mac with tsan 2020-03-18 20:53:54 -07:00
6085839ef7 minor refactoring 2020-03-18 11:45:28 -07:00
696d802703 bump version 2020-03-18 01:15:15 -07:00
b287730c19 Simplify ping/pong based heartbeat implementation 2020-03-18 01:14:08 -07:00
d6f534de06 (ws) ws echo_server gains a new option (-p) to disable responding to pings with pongs 2020-03-18 00:01:57 -07:00
8ec515f292 (ws) ws connect gains a new option to set the interval at which to send pings 2020-03-17 23:54:32 -07:00
c6204f4d90 tweak mkdoc action 2020-03-17 10:47:06 -07:00
7dfad9c0cc more docs 2020-03-17 10:41:20 -07:00
21fac0be6c Create mkdocs.yaml github action from the web-ui 2020-03-17 10:22:58 -07:00
0bddf5e096 remove workflow created manually 2020-03-17 10:21:51 -07:00
946a8231e0 add ci to build documentation 2020-03-17 10:14:41 -07:00
49d1e8493a update build badge on doc 2020-03-17 10:09:41 -07:00
6198657dd6 do not trigger unittest when the docs is changed 2020-03-17 08:54:31 -07:00
385d6f5f4a (doc) move tls options to its own section 2020-03-17 08:49:42 -07:00
3919153a7b close #164 / add reference to tls option which must be set to true in server mode 2020-03-17 08:45:39 -07:00
e8f81776f9 (cobra to sentry bot + docker) default docker file uses mbedtls + ws cobra_to_sentry pass tls options to sentryClient. 2020-03-16 10:05:21 -07:00
0bb5462504 Feature/ci windows (#163)
* win only

* disable ixcrypto mbedtls search on windows

* ws cmakefile do not search for openssl

* ci builds files on top of cmaking

* ci builds files on top of cmaking / syntax tweak

* use gha-setup-vsdevenv syntax

* build fix and hacks

* try to run unittest on win

* try to run unittest on win (syntax error)

* unittest wip

* wip

* wip again

* wip again (working-directory)

* cleanup

* dumb compile error
2020-03-15 18:38:09 -07:00
44f599747e (cobra client) ws cobra subscribe resubscribe at latest position after being disconnected 2020-03-13 17:30:31 -07:00
9801ebdb36 (cobra client) can subscribe with a position 2020-03-13 16:06:13 -07:00
332ffb0603 (cobra client) pass the message position to the subscription data callback 2020-03-13 12:49:37 -07:00
90df3d1805 (openssl tls backend) Fix a hand in OpenSSL when using TLS v1.3 ... by disabling TLS v1.3 2020-03-12 16:27:25 -07:00
bda1bb6ab4 expose a way to set tls options for a sentry client, for testing 2020-03-12 16:18:28 -07:00
d4e1f71e3c (cobra2sentry bot) take a sentry client as input instead of a dsn 2020-03-12 12:30:58 -07:00
adf6aa1d6c (cobra2sentry bot) remove the jobs option passed to ws, and only use one sentry sender 2020-03-12 12:24:25 -07:00
cb1f9f5a44 clang formatting 2020-03-12 12:15:56 -07:00
83ae105edb minor refactoring to delete files which are not needed 2020-03-12 12:13:31 -07:00
7642ccc99e (unittest) fix silly compile error with renaming of Logger to TLogger 2020-03-12 11:15:54 -07:00
cb1ec7dc96 add unittest for cobra to sentry bots 2020-03-12 09:07:01 -07:00
09b9483ddf fix casing problem with cmake filename 2020-03-11 16:04:16 -07:00
27a8ae309f build failure on Linux 2020-03-11 15:59:48 -07:00
3df7c942d7 move sentry and statsd cobra ws commands into a new ixbots folder 2020-03-11 15:55:56 -07:00
6a4d69afc5 (cobra) IXCobraConfig struct has tlsOptions and per message deflate options 2020-03-11 12:40:32 -07:00
0a11132b07 (cobra) add IXCobraConfig struct to pass cobra config around 2020-03-11 10:48:41 -07:00
cb9f0cb968 (doc) mention that OpenSSL can be used on Windows 2020-03-11 10:18:48 -07:00
b1f30bb40f (ws cobra_subscribe) add a --fluentd option to wrap a message in an enveloppe so that fluentd can recognize it 2020-03-09 15:25:43 -07:00
166 changed files with 5654 additions and 6393 deletions

View File

@ -1,51 +1,53 @@
name: unittest name: unittest
on:
push:
paths-ignore:
- 'docs/**'
on: [push]
# fake comment to trigger an action 1
jobs: jobs:
linux: linux:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: make test - name: make test
run: make test run: make test
mac: mac_tsan_sectransport:
runs-on: macOS-latest runs-on: macOS-latest
steps: steps:
- uses: actions/checkout@v1 - 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 - 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 mac_tsan_mbedtls:
# - name: install redis runs-on: macOS-latest
# run: brew install redis steps:
# - uses: actions/checkout@v1
# - name: start redis server - name: install mbedtls
# run: brew services start redis run: brew install mbedtls
- name: make test
run: make test_tsan_mbedtls
# # Windows does not work yet, I'm stuck at getting CMake to run + finding vcpkg win:
# win: runs-on: windows-latest
# runs-on: windows-2016 steps:
# - uses: actions/checkout@v1
# steps: - uses: seanmiddleditch/gha-setup-vsdevenv@master
# - uses: actions/checkout@v1 - run: |
# mkdir build
# - name: run cmake cd build
# run: | cmake -DCMAKE_CXX_COMPILER=cl.exe -DUSE_WS=1 -DUSE_TEST=1 ..
# "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat" - run: cmake --build build
# mkdir build
# cd build # Running the unittest does not work
# cmake -DCMAKE_TOOLCHAIN_FILE=%VCPKG_INSTALLATION_ROOT%\scripts\buildsystems\vcpkg.cmake -DUSE_WS=1 -DUSE_TEST=1 -DUSE_TLS=1 -G"NMake Makefiles" .. #- run: ../build/test/ixwebsocket_unittest.exe
# - name: build # working-directory: test
# 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

23
.github/workflows/mkdocs.yml vendored Normal file
View File

@ -0,0 +1,23 @@
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
- name: Build doc
run: |
git pull
mkdocs gh-deploy

View File

@ -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

19
CMake/FindSpdLog.cmake Normal file
View File

@ -0,0 +1,19 @@
# Find package structure taken from libcurl
include(FindPackageHandleStandardArgs)
find_path(SPDLOG_INCLUDE_DIRS spdlog/spdlog.h)
find_library(JSONCPP_LIBRARY spdlog)
find_package_handle_standard_args(SPDLOG
FOUND_VAR
SPDLOG_FOUND
REQUIRED_VARS
SPDLOG_LIBRARY
SPDLOG_INCLUDE_DIRS
FAIL_MESSAGE
"Could NOT find spdlog"
)
set(SPDLOG_INCLUDE_DIRS ${SPDLOG_INCLUDE_DIRS})
set(SPDLOG_LIBRARIES ${SPDLOG_LIBRARY})

View File

@ -21,6 +21,7 @@ if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
endif() endif()
set( IXWEBSOCKET_SOURCES set( IXWEBSOCKET_SOURCES
ixwebsocket/IXBench.cpp
ixwebsocket/IXCancellationRequest.cpp ixwebsocket/IXCancellationRequest.cpp
ixwebsocket/IXConnectionState.cpp ixwebsocket/IXConnectionState.cpp
ixwebsocket/IXDNSLookup.cpp ixwebsocket/IXDNSLookup.cpp
@ -36,6 +37,7 @@ set( IXWEBSOCKET_SOURCES
ixwebsocket/IXSocketFactory.cpp ixwebsocket/IXSocketFactory.cpp
ixwebsocket/IXSocketServer.cpp ixwebsocket/IXSocketServer.cpp
ixwebsocket/IXSocketTLSOptions.cpp ixwebsocket/IXSocketTLSOptions.cpp
ixwebsocket/IXUdpSocket.cpp
ixwebsocket/IXUrlParser.cpp ixwebsocket/IXUrlParser.cpp
ixwebsocket/IXUserAgent.cpp ixwebsocket/IXUserAgent.cpp
ixwebsocket/IXWebSocket.cpp ixwebsocket/IXWebSocket.cpp
@ -52,6 +54,7 @@ set( IXWEBSOCKET_SOURCES
) )
set( IXWEBSOCKET_HEADERS set( IXWEBSOCKET_HEADERS
ixwebsocket/IXBench.h
ixwebsocket/IXCancellationRequest.h ixwebsocket/IXCancellationRequest.h
ixwebsocket/IXConnectionState.h ixwebsocket/IXConnectionState.h
ixwebsocket/IXDNSLookup.h ixwebsocket/IXDNSLookup.h
@ -69,6 +72,7 @@ set( IXWEBSOCKET_HEADERS
ixwebsocket/IXSocketFactory.h ixwebsocket/IXSocketFactory.h
ixwebsocket/IXSocketServer.h ixwebsocket/IXSocketServer.h
ixwebsocket/IXSocketTLSOptions.h ixwebsocket/IXSocketTLSOptions.h
ixwebsocket/IXUdpSocket.h
ixwebsocket/IXUrlParser.h ixwebsocket/IXUrlParser.h
ixwebsocket/IXUtf8Validator.h ixwebsocket/IXUtf8Validator.h
ixwebsocket/IXUserAgent.h ixwebsocket/IXUserAgent.h
@ -122,7 +126,7 @@ if (USE_TLS)
option(USE_MBED_TLS "Use Mbed TLS" OFF) option(USE_MBED_TLS "Use Mbed TLS" OFF)
endif() endif()
option(USE_OPEN_SSL "Use OpenSSL" OFF) option(USE_OPEN_SSL "Use OpenSSL" OFF)
if (USE_MBED_TLS) if (USE_MBED_TLS)
list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketMbedTLS.h) list( APPEND IXWEBSOCKET_HEADERS ixwebsocket/IXSocketMbedTLS.h)
list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketMbedTLS.cpp) list( APPEND IXWEBSOCKET_SOURCES ixwebsocket/IXSocketMbedTLS.cpp)
@ -196,7 +200,9 @@ if (USE_TLS AND USE_MBED_TLS)
endif() endif()
endif() endif()
find_package(ZLIB) if (NOT ZLIB_FOUND)
find_package(ZLIB)
endif()
if (ZLIB_FOUND) if (ZLIB_FOUND)
include_directories(${ZLIB_INCLUDE_DIRS}) include_directories(${ZLIB_INCLUDE_DIRS})
target_link_libraries(ixwebsocket ${ZLIB_LIBRARIES}) target_link_libraries(ixwebsocket ${ZLIB_LIBRARIES})
@ -230,9 +236,9 @@ if (USE_WS OR USE_TEST)
add_subdirectory(ixcobra) add_subdirectory(ixcobra)
add_subdirectory(ixsnake) add_subdirectory(ixsnake)
add_subdirectory(ixsentry) add_subdirectory(ixsentry)
add_subdirectory(ixbots)
add_subdirectory(third_party/spdlog spdlog) add_subdirectory(third_party/spdlog spdlog)
add_subdirectory(third_party/sentry-native sentry-native)
if (USE_WS) if (USE_WS)
add_subdirectory(ws) add_subdirectory(ws)

View File

@ -1 +1 @@
docker/Dockerfile.centos docker/Dockerfile.alpine

View File

@ -1,12 +1,13 @@
FROM alpine:3.11 as build 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 \
RUN apk add --no-cache make gcc g++ musl-dev linux-headers \
RUN apk add --no-cache zlib-dev cmake mbedtls-dev make zlib-dev
RUN addgroup -S app && adduser -S -G app app RUN addgroup -S app && \
RUN chown -R app:app /opt adduser -S -G app app && \
RUN chown -R app:app /usr/local 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 # There is a bug in CMake where we cannot build from the root top folder
# So we build from /opt # So we build from /opt
@ -14,22 +15,21 @@ COPY --chown=app:app . /opt
WORKDIR /opt WORKDIR /opt
USER app USER app
RUN [ "make", "ws_install" ] RUN make ws_mbedtls_install && \
RUN [ "rm", "-rf", "build" ] sh tools/trim_repo_for_docker.sh
FROM alpine:3.11 as runtime FROM alpine:3.11 as runtime
RUN apk add --no-cache libstdc++ RUN apk add --no-cache libstdc++ mbedtls ca-certificates && \
RUN apk add --no-cache strace addgroup -S app && \
RUN apk add --no-cache gdb 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 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 # Now run in usermode
USER app USER app

View File

@ -1,6 +1,9 @@
FROM centos:8 as build 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 groupadd app && useradd -g app app
RUN chown -R app:app /opt RUN chown -R app:app /opt
@ -12,13 +15,16 @@ COPY --chown=app:app . /opt
WORKDIR /opt WORKDIR /opt
USER app USER app
RUN [ "make", "ws_install" ] RUN [ "make", "ws_mbedtls_install" ]
RUN [ "rm", "-rf", "build" ] RUN [ "rm", "-rf", "build" ]
FROM centos:8 as runtime FROM centos:8 as runtime
RUN yum install -y gdb strace RUN yum install -y gdb strace
RUN yum install -y epel-release
RUN yum install -y mbedtls
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 COPY --chown=app:app --from=build /usr/local/bin/ws /usr/local/bin/ws
RUN chmod +x /usr/local/bin/ws RUN chmod +x /usr/local/bin/ws

View File

@ -2,14 +2,14 @@
FROM debian:buster as build FROM debian:buster as build
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update RUN apt-get update
RUN apt-get -y install wget RUN apt-get -y install wget
RUN mkdir -p /tmp/cmake RUN mkdir -p /tmp/cmake
WORKDIR /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 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 libssl-dev
RUN apt-get -y install libz-dev RUN apt-get -y install libz-dev
RUN apt-get -y install make RUN apt-get -y install make
@ -25,9 +25,9 @@ RUN ["make"]
FROM debian:buster as runtime FROM debian:buster as runtime
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update RUN apt-get update
# Runtime # Runtime
RUN apt-get install -y libssl1.1 RUN apt-get install -y libssl1.1
RUN apt-get install -y ca-certificates RUN apt-get install -y ca-certificates
RUN ["update-ca-certificates"] RUN ["update-ca-certificates"]

View File

@ -8,7 +8,7 @@ RUN yum install -y openssl-devel
RUN yum install -y wget RUN yum install -y wget
RUN mkdir -p /tmp/cmake RUN mkdir -p /tmp/cmake
WORKDIR /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 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 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 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 COPY --chown=app:app --from=build /usr/local/bin/ws /usr/local/bin/ws
RUN chmod +x /usr/local/bin/ws RUN chmod +x /usr/local/bin/ws
RUN ldd /usr/local/bin/ws RUN ldd /usr/local/bin/ws

View File

@ -2,14 +2,14 @@
FROM ubuntu:bionic as build FROM ubuntu:bionic as build
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update RUN apt-get update
RUN apt-get -y install wget RUN apt-get -y install wget
RUN mkdir -p /tmp/cmake RUN mkdir -p /tmp/cmake
WORKDIR /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 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 libssl-dev
RUN apt-get -y install libz-dev RUN apt-get -y install libz-dev
RUN apt-get -y install make RUN apt-get -y install make

View File

@ -2,14 +2,14 @@
FROM ubuntu:disco as build FROM ubuntu:disco as build
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update RUN apt-get update
RUN apt-get -y install wget RUN apt-get -y install wget
RUN mkdir -p /tmp/cmake RUN mkdir -p /tmp/cmake
WORKDIR /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 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 libssl-dev
RUN apt-get -y install libz-dev RUN apt-get -y install libz-dev
RUN apt-get -y install make RUN apt-get -y install make

View File

@ -2,14 +2,14 @@
FROM ubuntu:xenial as build FROM ubuntu:xenial as build
ENV DEBIAN_FRONTEND noninteractive ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update RUN apt-get update
RUN apt-get -y install wget RUN apt-get -y install wget
RUN mkdir -p /tmp/cmake RUN mkdir -p /tmp/cmake
WORKDIR /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 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 libssl-dev
RUN apt-get -y install libz-dev RUN apt-get -y install libz-dev
RUN apt-get -y install make RUN apt-get -y install make

View File

@ -1,6 +1,148 @@
# Changelog # Changelog
All changes to this project will be documented in this file. All changes to this project will be documented in this file.
## [9.1.9] - 2020-03-30
(cobra to statsd bot) add ability to extract a numerical value and send a timer event to statsd, with the --timer option
## [9.1.8] - 2020-03-29
(cobra to statsd bot) bot init was missing + capture socket error
## [9.1.7] - 2020-03-29
(cobra to statsd bot) add ability to extract a numerical value and send a gauge event to statsd, with the --gauge option
## [9.1.6] - 2020-03-29
(ws cobra subscriber) use a Json::StreamWriter to write to std::cout, and save one std::string allocation for each message printed
## [9.1.5] - 2020-03-29
(docker) trim down docker image (300M -> 12M) / binary built without symbol and size optimization, and source code not copied over
## [9.1.4] - 2020-03-28
(jsoncpp) update bundled copy to version 1.9.3 (at sha 3beb37ea14aec1bdce1a6d542dc464d00f4a6cec)
## [9.1.3] - 2020-03-27
(docker) alpine docker build with release with debug info, and bundle ca-certificates
## [9.1.2] - 2020-03-26
(mac ssl) rename DarwinSSL -> SecureTransport (see this too -> https://github.com/curl/curl/issues/3733)
## [9.1.1] - 2020-03-26
(websocket) fix data race accessing _socket object without mutex protection when calling wakeUpFromPoll in WebSocketTransport.cpp
## [9.1.0] - 2020-03-26
(ixcobra) add explicit event types for handshake, authentication and subscription failure, and handle those by exiting in ws_cobra_subcribe and friends
## [9.0.3] - 2020-03-24
(ws connect) display statistics about how much time it takes to stop the connection
## [9.0.2] - 2020-03-24
(socket) works with unique_ptr<Socket> instead of shared_ptr<Socket> in many places
## [9.0.1] - 2020-03-24
(socket) selectInterrupt member is an unique_ptr instead of being a shared_ptr
## [9.0.0] - 2020-03-23
(websocket) reset per-message deflate codec everytime we connect to a server/client
## [8.3.4] - 2020-03-23
(websocket) fix #167, a long standing issue with sending empty messages with per-message deflate extension (and hopefully other zlib bug)
## [8.3.3] - 2020-03-22
(cobra to statsd) port to windows and add a unittest
## [8.3.2] - 2020-03-20
(websocket+tls) fix hang in tls handshake which could lead to ANR, discovered through unittesting.
## [8.3.1] - 2020-03-20
(cobra) CobraMetricsPublisher can be configure with an ix::CobraConfig + more unittest use SSL in server + client
## [8.3.0] - 2020-03-18
(websocket) Simplify ping/pong based heartbeat implementation
## [8.2.7] - 2020-03-17
(ws) ws connect gains a new option to set the interval at which to send pings
(ws) ws echo_server gains a new option (-p) to disable responding to pings with pongs
```
IXWebSocket$ ws connect --ping_interval 2 wss://echo.websocket.org
Type Ctrl-D to exit prompt...
Connecting to url: wss://echo.websocket.org
> ws_connect: connected
[2020-03-17 23:53:02.726] [info] Uri: /
[2020-03-17 23:53:02.726] [info] Headers:
[2020-03-17 23:53:02.727] [info] Connection: Upgrade
[2020-03-17 23:53:02.727] [info] Date: Wed, 18 Mar 2020 06:45:05 GMT
[2020-03-17 23:53:02.727] [info] Sec-WebSocket-Accept: 0gtqbxW0aVL/QI/ICpLFnRaiKgA=
[2020-03-17 23:53:02.727] [info] sec-websocket-extensions:
[2020-03-17 23:53:02.727] [info] Server: Kaazing Gateway
[2020-03-17 23:53:02.727] [info] Upgrade: websocket
[2020-03-17 23:53:04.894] [info] Received pong
[2020-03-17 23:53:06.859] [info] Received pong
[2020-03-17 23:53:08.881] [info] Received pong
[2020-03-17 23:53:10.848] [info] Received pong
[2020-03-17 23:53:12.898] [info] Received pong
[2020-03-17 23:53:14.865] [info] Received pong
[2020-03-17 23:53:16.890] [info] Received pong
[2020-03-17 23:53:18.853] [info] Received pong
[2020-03-17 23:53:19.388] [info]
ws_connect: connection closed: code 1000 reason Normal closure
[2020-03-17 23:53:19.502] [info] Received 208 bytes
[2020-03-17 23:53:19.502] [info] Sent 0 bytes
```
## [8.2.6] - 2020-03-16
(cobra to sentry bot + docker) default docker file uses mbedtls + ws cobra_to_sentry pass tls options to sentryClient.
## [8.2.5] - 2020-03-13
(cobra client) ws cobra subscribe resubscribe at latest position after being disconnected
## [8.2.4] - 2020-03-13
(cobra client) can subscribe with a position
## [8.2.3] - 2020-03-13
(cobra client) pass the message position to the subscription data callback
## [8.2.2] - 2020-03-12
(openssl tls backend) Fix a hand in OpenSSL when using TLS v1.3 ... by disabling TLS v1.3
## [8.2.1] - 2020-03-11
(cobra) IXCobraConfig struct has tlsOptions and per message deflate options
## [8.2.0] - 2020-03-11
(cobra) add IXCobraConfig struct to pass cobra config around
## [8.1.9] - 2020-03-09
(ws cobra_subscribe) add a --fluentd option to wrap a message in an enveloppe so that fluentd can recognize it
## [8.1.8] - 2020-03-02 ## [8.1.8] - 2020-03-02
(websocket server) fix regression with disabling zlib extension on the server side. If a client does not support this extension the server will handle it fine. We still need to figure out how to disable the option. (websocket server) fix regression with disabling zlib extension on the server side. If a client does not support this extension the server will handle it fine. We still need to figure out how to disable the option.
@ -43,7 +185,7 @@ All changes to this project will be documented in this file.
## [8.0.6] - 2020-01-31 ## [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 ## [8.0.5] - 2020-01-31

View File

@ -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_)). 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` * Conan 1.21.0 and up: `ixwebsocket/7.9.2`
* Earlier versions: `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 ### Docker

View File

@ -6,7 +6,7 @@ The per message deflate compression option is supported. It can lead to very nic
### TLS/SSL ### TLS/SSL
Connections can be optionally secured and encrypted with TLS/SSL when using a wss:// endpoint, or using normal un-encrypted socket with ws:// endpoints. AppleSSL is used on iOS and macOS, OpenSSL is used on Android and Linux, mbedTLS is used on Windows. 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.
### Polling and background thread work ### Polling and background thread work
@ -73,5 +73,3 @@ Here is a simplistic diagram which explains how the code is structured in term o
| | | |
+-----------------------+ +-----------------------+
``` ```

View File

@ -1,4 +1,4 @@
![Alt text](https://travis-ci.org/machinezone/IXWebSocket.svg?branch=master) ![Build status](https://github.com/machinezone/IXWebSocket/workflows/unittest/badge.svg)
## Introduction ## Introduction
@ -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. 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 ## Contributing

View File

@ -244,39 +244,6 @@ webSocket.setMaxWaitBetweenReconnectionRetries(5 * 1000); // 5000ms = 5s
uint32_t m = webSocket.getMaxWaitBetweenReconnectionRetries(); 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 ## WebSocket server API
```cpp ```cpp
@ -464,3 +431,37 @@ setOnConnectionCallback(
content); content);
} }
``` ```
## 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",
.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

45
ixbots/CMakeLists.txt Normal file
View File

@ -0,0 +1,45 @@
#
# Author: Benjamin Sergeant
# Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
#
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
${IXBOTS_SOURCES}
${IXBOTS_HEADERS}
)
find_package(JsonCpp)
if (NOT JSONCPP_FOUND)
set(JSONCPP_INCLUDE_DIRS ../third_party/jsoncpp)
endif()
find_package(SpdLog)
if (NOT SPDLOG_FOUND)
set(SPDLOG_INCLUDE_DIRS ../third_party/spdlog/include)
endif()
set(IXBOTS_INCLUDE_DIRS
.
..
../ixcore
../ixwebsocket
../ixcobra
../ixsentry
${JSONCPP_INCLUDE_DIRS}
${SPDLOG_INCLUDE_DIRS})
target_include_directories( ixbots PUBLIC ${IXBOTS_INCLUDE_DIRS} )

View File

@ -1,17 +1,14 @@
/* /*
* ws_cobra_to_sentry.cpp * IXCobraToSentryBot.cpp
* Author: Benjamin Sergeant * Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved. * Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/ */
#include <atomic> #include "IXCobraToSentryBot.h"
#include "IXQueueManager.h"
#include <chrono> #include <chrono>
#include <condition_variable>
#include <ixcobra/IXCobraConnection.h> #include <ixcobra/IXCobraConnection.h>
#include <ixsentry/IXSentryClient.h>
#include <map>
#include <mutex>
#include <queue>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <sstream> #include <sstream>
#include <thread> #include <thread>
@ -19,99 +16,19 @@
namespace ix namespace ix
{ {
class QueueManager int cobra_to_sentry_bot(const CobraConfig& config,
{ const std::string& channel,
public: const std::string& filter,
QueueManager(size_t maxQueueSize, std::atomic<bool>& stop) const std::string& position,
: _maxQueueSize(maxQueueSize) SentryClient& sentryClient,
, _stop(stop) bool verbose,
{ bool strict,
} size_t maxQueueSize,
bool enableHeartbeat,
Json::Value pop(); int runtime)
void add(Json::Value msg);
private:
std::map<std::string, std::queue<Json::Value>> _queues;
std::mutex _mutex;
std::condition_variable _condition;
size_t _maxQueueSize;
std::atomic<bool>& _stop;
};
Json::Value QueueManager::pop()
{
std::unique_lock<std::mutex> lock(_mutex);
if (_queues.empty())
{
Json::Value val;
return val;
}
std::vector<std::string> games;
for (auto it : _queues)
{
games.push_back(it.first);
}
std::random_shuffle(games.begin(), games.end());
std::string game = games[0];
_condition.wait(lock, [this] { return !_stop; });
if (_queues[game].empty())
{
Json::Value val;
return val;
}
auto msg = _queues[game].front();
_queues[game].pop();
return msg;
}
void QueueManager::add(Json::Value msg)
{
std::unique_lock<std::mutex> lock(_mutex);
std::string game;
if (msg.isMember("device") && msg["device"].isMember("game"))
{
game = msg["device"]["game"].asString();
}
if (game.empty()) return;
// if the sending is not fast enough there is no point
// in queuing too many events.
if (_queues[game].size() < _maxQueueSize)
{
_queues[game].push(msg);
_condition.notify_one();
}
}
int ws_cobra_to_sentry_main(const std::string& appkey,
const std::string& endpoint,
const std::string& rolename,
const std::string& rolesecret,
const std::string& channel,
const std::string& filter,
const std::string& dsn,
bool verbose,
bool strict,
int jobs,
size_t maxQueueSize,
const ix::SocketTLSOptions& tlsOptions)
{ {
ix::CobraConnection conn; ix::CobraConnection conn;
conn.configure(appkey, conn.configure(config);
endpoint,
rolename,
rolesecret,
ix::WebSocketPerMessageDeflateOptions(true),
tlsOptions);
conn.connect(); conn.connect();
Json::FastWriter jsonWriter; Json::FastWriter jsonWriter;
@ -120,25 +37,30 @@ namespace ix
std::atomic<bool> errorSending(false); std::atomic<bool> errorSending(false);
std::atomic<bool> stop(false); std::atomic<bool> stop(false);
std::atomic<bool> throttled(false); std::atomic<bool> throttled(false);
std::atomic<bool> fatalCobraError(false);
QueueManager queueManager(maxQueueSize, stop); QueueManager queueManager(maxQueueSize);
auto timer = [&sentCount, &receivedCount] { auto timer = [&sentCount, &receivedCount, &stop] {
while (true) while (!stop)
{ {
spdlog::info("messages received {} sent {}", receivedCount, sentCount); spdlog::info("messages received {} sent {}", receivedCount, sentCount);
auto duration = std::chrono::seconds(1); auto duration = std::chrono::seconds(1);
std::this_thread::sleep_for(duration); std::this_thread::sleep_for(duration);
} }
spdlog::info("timer thread done");
}; };
std::thread t1(timer); std::thread t1(timer);
auto heartbeat = [&sentCount, &receivedCount] { auto heartbeat = [&sentCount, &receivedCount, &stop, &enableHeartbeat] {
std::string state("na"); std::string state("na");
while (true) if (!enableHeartbeat) return;
while (!stop)
{ {
std::stringstream ss; std::stringstream ss;
ss << "messages received " << receivedCount; ss << "messages received " << receivedCount;
@ -156,20 +78,21 @@ namespace ix
auto duration = std::chrono::minutes(1); auto duration = std::chrono::minutes(1);
std::this_thread::sleep_for(duration); std::this_thread::sleep_for(duration);
} }
spdlog::info("heartbeat thread done");
}; };
std::thread t2(heartbeat); std::thread t2(heartbeat);
auto sentrySender = auto sentrySender =
[&queueManager, verbose, &errorSending, &sentCount, &stop, &throttled, &dsn] { [&queueManager, verbose, &errorSending, &sentCount, &stop, &throttled, &sentryClient] {
SentryClient sentryClient(dsn);
while (true) while (true)
{ {
Json::Value msg = queueManager.pop(); Json::Value msg = queueManager.pop();
if (stop) break;
if (msg.isNull()) continue; if (msg.isNull()) continue;
if (stop) return;
auto ret = sentryClient.send(msg, verbose); auto ret = sentryClient.send(msg, verbose);
HttpResponsePtr response = ret.first; HttpResponsePtr response = ret.first;
@ -241,25 +164,23 @@ namespace ix
++sentCount; ++sentCount;
} }
if (stop) return; if (stop) break;
} }
spdlog::info("sentrySender thread done");
}; };
// Create a thread pool std::thread t3(sentrySender);
spdlog::info("Starting {} sentry sender jobs", jobs);
std::vector<std::thread> pool;
for (int i = 0; i < jobs; i++)
{
pool.push_back(std::thread(sentrySender));
}
conn.setEventCallback([&conn, conn.setEventCallback([&conn,
&channel, &channel,
&filter, &filter,
&position,
&jsonWriter, &jsonWriter,
verbose, verbose,
&throttled, &throttled,
&receivedCount, &receivedCount,
&fatalCobraError,
&queueManager](ix::CobraConnectionEventType eventType, &queueManager](ix::CobraConnectionEventType eventType,
const std::string& errMsg, const std::string& errMsg,
const ix::WebSocketHttpHeaders& headers, const ix::WebSocketHttpHeaders& headers,
@ -283,11 +204,12 @@ namespace ix
spdlog::info("Subscriber authenticated"); spdlog::info("Subscriber authenticated");
conn.subscribe(channel, conn.subscribe(channel,
filter, filter,
position,
[&jsonWriter, verbose, &throttled, &receivedCount, &queueManager]( [&jsonWriter, verbose, &throttled, &receivedCount, &queueManager](
const Json::Value& msg) { const Json::Value& msg, const std::string& position) {
if (verbose) if (verbose)
{ {
spdlog::info(jsonWriter.write(msg)); spdlog::info("Subscriber received message {} -> {}", position, jsonWriter.write(msg));
} }
// If we cannot send to sentry fast enough, drop the message // If we cannot send to sentry fast enough, drop the message
@ -320,26 +242,64 @@ namespace ix
{ {
spdlog::info("Received websocket pong"); 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)
{ {
auto duration = std::chrono::seconds(1); while (true)
std::this_thread::sleep_for(duration); {
auto duration = std::chrono::seconds(1);
std::this_thread::sleep_for(duration);
if (strict && errorSending) break; if (strict && errorSending) break;
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 (strict && errorSending) break;
if (fatalCobraError) break;
}
} }
conn.disconnect(); //
// Cleanup.
// join all the bg threads and stop them. // join all the bg threads and stop them.
//
conn.disconnect();
stop = true; stop = true;
for (int i = 0; i < jobs; i++)
{
spdlog::error("joining thread {}", i);
pool[i].join();
}
return (strict && errorSending) ? 1 : 0; // progress thread
t1.join();
// heartbeat thread
if (t2.joinable()) t2.join();
// sentry sender thread
t3.join();
return ((strict && errorSending) || fatalCobraError) ? -1 : (int) sentCount;
} }
} // namespace ix } // namespace ix

View File

@ -0,0 +1,24 @@
/*
* IXCobraToSentryBot.h
* Author: Benjamin Sergeant
* Copyright (c) 2019-2020 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <ixcobra/IXCobraConfig.h>
#include <ixsentry/IXSentryClient.h>
#include <string>
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,
size_t maxQueueSize,
bool enableHeartbeat,
int runtime);
} // namespace ix

View File

@ -1,9 +1,13 @@
/* /*
* ws_cobra_to_statsd.cpp * IXCobraToStatsdBot.cpp
* Author: Benjamin Sergeant * Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved. * Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/ */
#include "IXCobraToStatsdBot.h"
#include "IXQueueManager.h"
#include "IXStatsdClient.h"
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
@ -13,63 +17,6 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
#ifndef _WIN32
#include <statsd_client.h>
#endif
namespace
{
class QueueManager
{
public:
QueueManager(size_t maxQueueSize, std::atomic<bool>& stop)
: _maxQueueSize(maxQueueSize)
, _stop(stop)
{
}
Json::Value pop();
void add(Json::Value msg);
private:
std::queue<Json::Value> _queue;
std::mutex _mutex;
std::condition_variable _condition;
size_t _maxQueueSize;
std::atomic<bool>& _stop;
};
Json::Value QueueManager::pop()
{
std::unique_lock<std::mutex> lock(_mutex);
if (_queue.empty())
{
Json::Value val;
return val;
}
_condition.wait(lock, [this] { return !_stop; });
auto msg = _queue.front();
_queue.pop();
return msg;
}
void QueueManager::add(Json::Value msg)
{
std::unique_lock<std::mutex> lock(_mutex);
// if the sending is not fast enough there is no point
// in queuing too many events.
if (_queue.size() < _maxQueueSize)
{
_queue.push(msg);
_condition.notify_one();
}
}
} // namespace
namespace ix namespace ix
{ {
// fields are command line argument that can be specified multiple times // fields are command line argument that can be specified multiple times
@ -93,7 +40,7 @@ namespace ix
// Extract an attribute from a Json Value. // Extract an attribute from a Json Value.
// extractAttr("foo.bar", {"foo": {"bar": "baz"}}) => baz // 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 . // Split by .
std::string token; std::string token;
@ -106,29 +53,24 @@ namespace ix
val = val[token]; val = val[token];
} }
return val.asString(); return val;
} }
int ws_cobra_to_statsd_main(const std::string& appkey, int cobra_to_statsd_bot(const ix::CobraConfig& config,
const std::string& endpoint, const std::string& channel,
const std::string& rolename, const std::string& filter,
const std::string& rolesecret, const std::string& position,
const std::string& channel, StatsdClient& statsdClient,
const std::string& filter, const std::string& fields,
const std::string& host, const std::string& gauge,
int port, const std::string& timer,
const std::string& prefix, bool verbose,
const std::string& fields, size_t maxQueueSize,
bool verbose, bool enableHeartbeat,
const ix::SocketTLSOptions& tlsOptions) int runtime)
{ {
ix::CobraConnection conn; ix::CobraConnection conn;
conn.configure(appkey, conn.configure(config);
endpoint,
rolename,
rolesecret,
ix::WebSocketPerMessageDeflateOptions(true),
tlsOptions);
conn.connect(); conn.connect();
auto tokens = parseFields(fields); auto tokens = parseFields(fields);
@ -137,26 +79,30 @@ namespace ix
std::atomic<uint64_t> sentCount(0); std::atomic<uint64_t> sentCount(0);
std::atomic<uint64_t> receivedCount(0); std::atomic<uint64_t> receivedCount(0);
std::atomic<bool> stop(false); std::atomic<bool> stop(false);
std::atomic<bool> fatalCobraError(false);
size_t maxQueueSize = 1000; QueueManager queueManager(maxQueueSize);
QueueManager queueManager(maxQueueSize, stop);
auto timer = [&sentCount, &receivedCount] { auto progress = [&sentCount, &receivedCount, &stop] {
while (true) while (!stop)
{ {
spdlog::info("messages received {} sent {}", receivedCount, sentCount); spdlog::info("messages received {} sent {}", receivedCount, sentCount);
auto duration = std::chrono::seconds(1); auto duration = std::chrono::seconds(1);
std::this_thread::sleep_for(duration); 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"); std::string state("na");
while (true) if (!enableHeartbeat) return;
while (!stop)
{ {
std::stringstream ss; std::stringstream ss;
ss << "messages received " << receivedCount; ss << "messages received " << receivedCount;
@ -174,45 +120,88 @@ namespace ix
auto duration = std::chrono::minutes(1); auto duration = std::chrono::minutes(1);
std::this_thread::sleep_for(duration); std::this_thread::sleep_for(duration);
} }
spdlog::info("heartbeat thread done");
}; };
std::thread t2(heartbeat); std::thread t2(heartbeat);
auto statsdSender = [&queueManager, &host, &port, &sentCount, &tokens, &prefix, &stop] { auto statsdSender = [&statsdClient, &queueManager, &sentCount, &tokens, &stop, &gauge, &timer, &fatalCobraError, &verbose] {
// 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
while (true) while (true)
{ {
Json::Value msg = queueManager.pop(); Json::Value msg = queueManager.pop();
if (msg.isNull()) continue;
if (stop) return; if (stop) return;
if (msg.isNull()) continue;
std::string id; std::string id;
for (auto&& attr : tokens) for (auto&& attr : tokens)
{ {
id += "."; 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; sentCount += 1;
#ifndef _WIN32
statsdClient.count(id, 1);
#endif
} }
}; };
std::thread t3(statsdSender); std::thread t3(statsdSender);
conn.setEventCallback( conn.setEventCallback(
[&conn, &channel, &filter, &jsonWriter, verbose, &queueManager, &receivedCount]( [&conn, &channel, &filter, &position, &jsonWriter, verbose, &queueManager, &receivedCount, &fatalCobraError](
ix::CobraConnectionEventType eventType, ix::CobraConnectionEventType eventType,
const std::string& errMsg, const std::string& errMsg,
const ix::WebSocketHttpHeaders& headers, const ix::WebSocketHttpHeaders& headers,
@ -236,11 +225,12 @@ namespace ix
spdlog::info("Subscriber authenticated"); spdlog::info("Subscriber authenticated");
conn.subscribe(channel, conn.subscribe(channel,
filter, filter,
position,
[&jsonWriter, &queueManager, verbose, &receivedCount]( [&jsonWriter, &queueManager, verbose, &receivedCount](
const Json::Value& msg) { const Json::Value& msg, const std::string& position) {
if (verbose) if (verbose)
{ {
spdlog::info(jsonWriter.write(msg)); spdlog::info("Subscriber received message {} -> {}", position, jsonWriter.write(msg));
} }
receivedCount++; receivedCount++;
@ -269,14 +259,62 @@ namespace ix
{ {
spdlog::info("Received websocket pong"); 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); while (true)
std::this_thread::sleep_for(duration); {
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 } // namespace ix

View File

@ -0,0 +1,27 @@
/*
* IXCobraToStatsdBot.h
* Author: Benjamin Sergeant
* 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>
namespace ix
{
int cobra_to_statsd_bot(const ix::CobraConfig& config,
const std::string& channel,
const std::string& filter,
const std::string& position,
StatsdClient& statsdClient,
const std::string& fields,
const std::string& gauge,
const std::string& timer,
bool verbose,
size_t maxQueueSize,
bool enableHeartbeat,
int runtime);
} // namespace ix

View File

@ -0,0 +1,66 @@
/*
* IXQueueManager.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#include "IXQueueManager.h"
#include <vector>
#include <algorithm>
namespace ix
{
Json::Value QueueManager::pop()
{
std::unique_lock<std::mutex> lock(_mutex);
if (_queues.empty())
{
Json::Value val;
return val;
}
std::vector<std::string> games;
for (auto it : _queues)
{
games.push_back(it.first);
}
std::random_shuffle(games.begin(), games.end());
std::string game = games[0];
auto duration = std::chrono::seconds(1);
_condition.wait_for(lock, duration);
if (_queues[game].empty())
{
Json::Value val;
return val;
}
auto msg = _queues[game].front();
_queues[game].pop();
return msg;
}
void QueueManager::add(Json::Value msg)
{
std::unique_lock<std::mutex> lock(_mutex);
std::string game;
if (msg.isMember("device") && msg["device"].isMember("game"))
{
game = msg["device"]["game"].asString();
}
if (game.empty()) return;
// if the sending is not fast enough there is no point
// in queuing too many events.
if (_queues[game].size() < _maxQueueSize)
{
_queues[game].push(msg);
_condition.notify_one();
}
}
}

View File

@ -0,0 +1,35 @@
/*
* IXQueueManager.h
* Author: Benjamin Sergeant
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <stddef.h>
#include <json/json.h>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <map>
namespace ix
{
class QueueManager
{
public:
QueueManager(size_t maxQueueSize)
: _maxQueueSize(maxQueueSize)
{
}
Json::Value pop();
void add(Json::Value msg);
private:
std::map<std::string, std::queue<Json::Value>> _queues;
std::mutex _mutex;
std::condition_variable _condition;
size_t _maxQueueSize;
};
}

View 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

View 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

View File

@ -13,6 +13,7 @@ set (IXCOBRA_HEADERS
ixcobra/IXCobraConnection.h ixcobra/IXCobraConnection.h
ixcobra/IXCobraMetricsThreadedPublisher.h ixcobra/IXCobraMetricsThreadedPublisher.h
ixcobra/IXCobraMetricsPublisher.h ixcobra/IXCobraMetricsPublisher.h
ixcobra/IXCobraConfig.h
) )
add_library(ixcobra STATIC add_library(ixcobra STATIC

View File

@ -0,0 +1,35 @@
/*
* IXCobraConfig.h
* Author: Benjamin Sergeant
* Copyright (c) 2020 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
#include <ixwebsocket/IXSocketTLSOptions.h>
namespace ix
{
struct CobraConfig
{
std::string appkey;
std::string endpoint;
std::string rolename;
std::string rolesecret;
WebSocketPerMessageDeflateOptions webSocketPerMessageDeflateOptions;
SocketTLSOptions socketTLSOptions;
CobraConfig(const std::string& a = std::string(),
const std::string& e = std::string(),
const std::string& r = std::string(),
const std::string& s = std::string())
: appkey(a)
, endpoint(e)
, rolename(r)
, rolesecret(s)
{
;
}
};
} // namespace ix

View File

@ -166,7 +166,8 @@ namespace ix
} }
else if (action == "auth/handshake/error") 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") else if (action == "auth/authenticate/ok")
{ {
@ -176,7 +177,8 @@ namespace ix
} }
else if (action == "auth/authenticate/error") 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") else if (action == "rtm/subscription/data")
{ {
@ -191,7 +193,8 @@ namespace ix
} }
else if (action == "rtm/subscribe/error") 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") else if (action == "rtm/unsubscribe/ok")
{ {
@ -270,10 +273,16 @@ namespace ix
// This should keep the connection open and prevent some load balancers such as // This should keep the connection open and prevent some load balancers such as
// the Amazon one from shutting it down // the Amazon one from shutting it down
_webSocket->setPingInterval(kPingIntervalSecs); _webSocket->setPingInterval(kPingIntervalSecs);
}
// If we don't receive a pong back, declare loss after 3 * N seconds void CobraConnection::configure(const ix::CobraConfig& config)
// (will be 90s now), and close and restart the connection {
_webSocket->setPingTimeout(3 * kPingIntervalSecs); configure(config.appkey,
config.endpoint,
config.rolename,
config.rolesecret,
config.webSocketPerMessageDeflateOptions,
config.socketTLSOptions);
} }
// //
@ -431,9 +440,12 @@ namespace ix
if (!body.isMember("messages")) return false; if (!body.isMember("messages")) return false;
Json::Value messages = body["messages"]; Json::Value messages = body["messages"];
if (!body.isMember("position")) return false;
std::string position = body["position"].asString();
for (auto&& msg : messages) for (auto&& msg : messages)
{ {
cb->second(msg); cb->second(msg, position);
} }
return true; return true;
@ -552,6 +564,7 @@ namespace ix
void CobraConnection::subscribe(const std::string& channel, void CobraConnection::subscribe(const std::string& channel,
const std::string& filter, const std::string& filter,
const std::string& position,
SubscriptionCallback cb) SubscriptionCallback cb)
{ {
// Create and send a subscribe pdu // Create and send a subscribe pdu
@ -563,6 +576,11 @@ namespace ix
body["filter"] = filter; body["filter"] = filter;
} }
if (!position.empty())
{
body["position"] = position;
}
Json::Value pdu; Json::Value pdu;
pdu["action"] = "rtm/subscribe"; pdu["action"] = "rtm/subscribe";
pdu["body"] = body; pdu["body"] = body;

View File

@ -17,6 +17,12 @@
#include <unordered_map> #include <unordered_map>
#include <limits> #include <limits>
#include "IXCobraConfig.h"
#ifdef max
#undef max
#endif
namespace ix namespace ix
{ {
class WebSocket; class WebSocket;
@ -31,7 +37,10 @@ namespace ix
CobraConnection_EventType_Subscribed = 4, CobraConnection_EventType_Subscribed = 4,
CobraConnection_EventType_UnSubscribed = 5, CobraConnection_EventType_UnSubscribed = 5,
CobraConnection_EventType_Published = 6, 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 enum CobraConnectionPublishMode
@ -40,7 +49,7 @@ namespace ix
CobraConnection_PublishMode_Batch = 1 CobraConnection_PublishMode_Batch = 1
}; };
using SubscriptionCallback = std::function<void(const Json::Value&)>; using SubscriptionCallback = std::function<void(const Json::Value&, const std::string&)>;
using EventCallback = std::function<void(CobraConnectionEventType, using EventCallback = std::function<void(CobraConnectionEventType,
const std::string&, const std::string&,
const WebSocketHttpHeaders&, const WebSocketHttpHeaders&,
@ -67,6 +76,8 @@ namespace ix
const WebSocketPerMessageDeflateOptions& webSocketPerMessageDeflateOptions, const WebSocketPerMessageDeflateOptions& webSocketPerMessageDeflateOptions,
const SocketTLSOptions& socketTLSOptions); const SocketTLSOptions& socketTLSOptions);
void configure(const ix::CobraConfig& config);
/// Set the traffic tracker callback /// Set the traffic tracker callback
static void setTrafficTrackerCallback(const TrafficTrackerCallback& callback); static void setTrafficTrackerCallback(const TrafficTrackerCallback& callback);
@ -94,6 +105,7 @@ namespace ix
// message arrives. // message arrives.
void subscribe(const std::string& channel, void subscribe(const std::string& channel,
const std::string& filter = std::string(), const std::string& filter = std::string(),
const std::string& position = std::string(),
SubscriptionCallback cb = nullptr); SubscriptionCallback cb = nullptr);
/// Unsubscribe from a channel /// Unsubscribe from a channel

View File

@ -27,20 +27,12 @@ namespace ix
; ;
} }
void CobraMetricsPublisher::configure(const std::string& appkey, void CobraMetricsPublisher::configure(const CobraConfig& config,
const std::string& endpoint, const std::string& channel)
const std::string& channel,
const std::string& rolename,
const std::string& rolesecret,
bool enablePerMessageDeflate,
const SocketTLSOptions& socketTLSOptions)
{ {
// Configure the satori connection and start its publish background thread // 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.start();
_cobra_metrics_theaded_publisher.configure(appkey, endpoint, channel,
rolename, rolesecret,
enablePerMessageDeflate, socketTLSOptions);
} }
Json::Value& CobraMetricsPublisher::getGenericAttributes() Json::Value& CobraMetricsPublisher::getGenericAttributes()

View File

@ -40,13 +40,8 @@ namespace ix
/// Configuration / set keys, etc... /// Configuration / set keys, etc...
/// All input data but the channel name is encrypted with rc4 /// All input data but the channel name is encrypted with rc4
void configure(const std::string& appkey, void configure(const CobraConfig& config,
const std::string& endpoint, const std::string& channel);
const std::string& channel,
const std::string& rolename,
const std::string& rolesecret,
bool enablePerMessageDeflate,
const SocketTLSOptions& socketTLSOptions);
/// Setter for the list of blacklisted metrics ids. /// Setter for the list of blacklisted metrics ids.
/// That list is sorted internally for fast lookups /// That list is sorted internally for fast lookups

View File

@ -92,22 +92,14 @@ namespace ix
_thread = std::thread(&CobraMetricsThreadedPublisher::run, this); _thread = std::thread(&CobraMetricsThreadedPublisher::run, this);
} }
void CobraMetricsThreadedPublisher::configure(const std::string& appkey, void CobraMetricsThreadedPublisher::configure(const CobraConfig& config,
const std::string& endpoint, const std::string& channel)
const std::string& channel,
const std::string& rolename,
const std::string& rolesecret,
bool enablePerMessageDeflate,
const SocketTLSOptions& socketTLSOptions)
{ {
ix::IXCoreLogger::Log(config.socketTLSOptions.getDescription().c_str());
_channel = channel; _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) void CobraMetricsThreadedPublisher::pushMessage(MessageKind messageKind)

View File

@ -27,13 +27,8 @@ namespace ix
~CobraMetricsThreadedPublisher(); ~CobraMetricsThreadedPublisher();
/// Configuration / set keys, etc... /// Configuration / set keys, etc...
void configure(const std::string& appkey, void configure(const CobraConfig& config,
const std::string& endpoint, const std::string& channel);
const std::string& channel,
const std::string& rolename,
const std::string& rolesecret,
bool enablePerMessageDeflate,
const SocketTLSOptions& socketTLSOptions);
/// Start the worker thread, used for background publishing /// Start the worker thread, used for background publishing
void start(); void start();

View File

@ -23,7 +23,7 @@ add_library(ixcrypto STATIC
${IXCRYPTO_HEADERS} ${IXCRYPTO_HEADERS}
) )
set(IXCRYPTO_INCLUDE_DIRS set(IXCRYPTO_INCLUDE_DIRS
. .
../ixcore) ../ixcore)
@ -31,10 +31,6 @@ target_include_directories( ixcrypto PUBLIC ${IXCRYPTO_INCLUDE_DIRS} )
# hmac computation needs a crypto library # hmac computation needs a crypto library
if (WIN32)
set(USE_MBED_TLS TRUE)
endif()
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_TLS) target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_TLS)
if (USE_MBED_TLS) if (USE_MBED_TLS)
find_package(MbedTLS REQUIRED) find_package(MbedTLS REQUIRED)
@ -51,4 +47,3 @@ else()
target_link_libraries(ixcrypto ${OPENSSL_LIBRARIES}) target_link_libraries(ixcrypto ${OPENSSL_LIBRARIES})
target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_OPEN_SSL) target_compile_definitions(ixcrypto PUBLIC IXCRYPTO_USE_OPEN_SSL)
endif() endif()

View File

@ -14,7 +14,7 @@
#elif defined(IXCRYPTO_USE_OPEN_SSL) #elif defined(IXCRYPTO_USE_OPEN_SSL)
# include <openssl/hmac.h> # include <openssl/hmac.h>
#else #else
# error "Unsupported configuration" # include <assert.h>
#endif #endif
namespace ix namespace ix
@ -40,7 +40,7 @@ namespace ix
(unsigned char *) data.c_str(), (int) data.size(), (unsigned char *) data.c_str(), (int) data.size(),
(unsigned char *) hash, nullptr); (unsigned char *) hash, nullptr);
#else #else
# error "Unsupported configuration" assert(false && "hmac not implemented on this platform");
#endif #endif
std::string hashString(reinterpret_cast<char*>(hash), hashSize); std::string hashString(reinterpret_cast<char*>(hash), hashSize);

View File

@ -40,6 +40,11 @@ namespace ix
} }
} }
void SentryClient::setTLSOptions(const SocketTLSOptions& tlsOptions)
{
_httpClient->setTLSOptions(tlsOptions);
}
int64_t SentryClient::getTimestamp() int64_t SentryClient::getTimestamp()
{ {
const auto tp = std::chrono::system_clock::now(); const auto tp = std::chrono::system_clock::now();

View File

@ -8,6 +8,7 @@
#include <algorithm> #include <algorithm>
#include <ixwebsocket/IXHttpClient.h> #include <ixwebsocket/IXHttpClient.h>
#include <ixwebsocket/IXSocketTLSOptions.h>
#include <json/json.h> #include <json/json.h>
#include <regex> #include <regex>
#include <memory> #include <memory>
@ -24,6 +25,9 @@ namespace ix
Json::Value parseLuaStackTrace(const std::string& stack); Json::Value parseLuaStackTrace(const std::string& stack);
// Mostly for testing
void setTLSOptions(const SocketTLSOptions& tlsOptions);
void uploadMinidump( void uploadMinidump(
const std::string& sentryMetadata, const std::string& sentryMetadata,
const std::string& minidumpBytes, const std::string& minidumpBytes,

View File

@ -9,7 +9,6 @@
#include <cstring> #include <cstring>
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <ixwebsocket/IXSocket.h>
#include <ixwebsocket/IXSocketFactory.h> #include <ixwebsocket/IXSocketFactory.h>
#include <ixwebsocket/IXSocketTLSOptions.h> #include <ixwebsocket/IXSocketTLSOptions.h>
#include <sstream> #include <sstream>

View File

@ -9,11 +9,12 @@
#include <atomic> #include <atomic>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <string>
#include <ixwebsocket/IXSocket.h>
namespace ix namespace ix
{ {
class Socket;
class RedisClient class RedisClient
{ {
public: public:
@ -56,7 +57,7 @@ namespace ix
private: private:
std::string writeString(const std::string& str); std::string writeString(const std::string& str);
std::shared_ptr<Socket> _socket; std::unique_ptr<Socket> _socket;
std::atomic<bool> _stop; std::atomic<bool> _stop;
}; };
} // namespace ix } // namespace ix

View File

@ -11,7 +11,6 @@
#include <ixwebsocket/IXSocket.h> #include <ixwebsocket/IXSocket.h>
#include <ixwebsocket/IXCancellationRequest.h> #include <ixwebsocket/IXCancellationRequest.h>
#include <fstream> #include <fstream>
#include <iostream>
#include <sstream> #include <sstream>
#include <vector> #include <vector>
@ -44,7 +43,7 @@ namespace ix
SocketServer::stop(); SocketServer::stop();
} }
void RedisServer::handleConnection(std::shared_ptr<Socket> socket, void RedisServer::handleConnection(std::unique_ptr<Socket> socket,
std::shared_ptr<ConnectionState> connectionState) std::shared_ptr<ConnectionState> connectionState)
{ {
_connectedClientsCount++; _connectedClientsCount++;
@ -103,13 +102,13 @@ namespace ix
_connectedClientsCount--; _connectedClientsCount--;
} }
void RedisServer::cleanupSubscribers(std::shared_ptr<Socket> socket) void RedisServer::cleanupSubscribers(std::unique_ptr<Socket>& socket)
{ {
std::lock_guard<std::mutex> lock(_mutex); std::lock_guard<std::mutex> lock(_mutex);
for (auto&& it : _subscribers) for (auto&& it : _subscribers)
{ {
it.second.erase(socket); it.second.erase(socket.get());
} }
for (auto it : _subscribers) for (auto it : _subscribers)
@ -146,7 +145,7 @@ namespace ix
} }
bool RedisServer::parseRequest( bool RedisServer::parseRequest(
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
std::vector<std::string>& tokens) std::vector<std::string>& tokens)
{ {
// Parse first line // Parse first line
@ -188,17 +187,11 @@ namespace ix
tokens.push_back(readResult.second); tokens.push_back(readResult.second);
} }
for (auto&& token : tokens)
{
std::cerr << token << " ";
}
std::cerr << std::endl;
return true; return true;
} }
bool RedisServer::handleCommand( bool RedisServer::handleCommand(
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
const std::vector<std::string>& tokens) const std::vector<std::string>& tokens)
{ {
if (tokens.size() != 1) return false; if (tokens.size() != 1) return false;
@ -237,7 +230,7 @@ namespace ix
} }
bool RedisServer::handleSubscribe( bool RedisServer::handleSubscribe(
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
const std::vector<std::string>& tokens) const std::vector<std::string>& tokens)
{ {
if (tokens.size() != 2) return false; if (tokens.size() != 2) return false;
@ -252,13 +245,13 @@ namespace ix
socket->writeBytes(":1\r\n", cb); socket->writeBytes(":1\r\n", cb);
std::lock_guard<std::mutex> lock(_mutex); std::lock_guard<std::mutex> lock(_mutex);
_subscribers[channel].insert(socket); _subscribers[channel].insert(socket.get());
return true; return true;
} }
bool RedisServer::handlePublish( bool RedisServer::handlePublish(
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
const std::vector<std::string>& tokens) const std::vector<std::string>& tokens)
{ {
if (tokens.size() != 3) return false; if (tokens.size() != 3) return false;

View File

@ -37,13 +37,13 @@ namespace ix
// Subscribers // Subscribers
// We could store connection states in there, to add better debugging // We could store connection states in there, to add better debugging
// since a connection state has a readable ID // 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::mutex _mutex;
std::atomic<bool> _stopHandlingConnections; std::atomic<bool> _stopHandlingConnections;
// Methods // Methods
virtual void handleConnection(std::shared_ptr<Socket>, virtual void handleConnection(std::unique_ptr<Socket>,
std::shared_ptr<ConnectionState> connectionState) final; std::shared_ptr<ConnectionState> connectionState) final;
virtual size_t getConnectedClientsCount() final; virtual size_t getConnectedClientsCount() final;
@ -51,18 +51,18 @@ namespace ix
std::string writeString(const std::string& str); std::string writeString(const std::string& str);
bool parseRequest( bool parseRequest(
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
std::vector<std::string>& tokens); 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); 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); 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); const std::vector<std::string>& tokens);
void cleanupSubscribers(std::shared_ptr<Socket> socket); void cleanupSubscribers(std::unique_ptr<Socket>& socket);
}; };
} // namespace ix } // namespace ix

View File

@ -189,7 +189,7 @@ namespace snake
nlohmann::json response = { nlohmann::json response = {
{"action", "rtm/subscription/data"}, {"action", "rtm/subscription/data"},
{"id", id++}, {"id", id++},
{"body", {{"subscription_id", subscriptionId}, {"messages", {msg}}}}}; {"body", {{"subscription_id", subscriptionId}, {"position", "0-0"}, {"messages", {msg}}}}};
ws->sendText(response.dump()); ws->sendText(response.dump());
}; };

44
ixwebsocket/IXBench.cpp Normal file
View 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
View 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

View File

@ -92,7 +92,8 @@ namespace ix
return std::make_tuple(method, requestUri, httpVersion); 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; HttpRequestPtr httpRequest;
@ -133,7 +134,7 @@ namespace ix
return std::make_tuple(true, "", httpRequest); 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 // Write the response to the socket
std::stringstream ss; std::stringstream ss;

View File

@ -115,8 +115,8 @@ namespace ix
{ {
public: public:
static std::tuple<bool, std::string, HttpRequestPtr> parseRequest( static std::tuple<bool, std::string, HttpRequestPtr> parseRequest(
std::shared_ptr<Socket> socket); std::unique_ptr<Socket>& socket);
static bool sendResponse(HttpResponsePtr response, std::shared_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::pair<std::string, int> parseStatusLine(const std::string& line);
static std::tuple<std::string, std::string, std::string> parseRequestLine( static std::tuple<std::string, std::string, std::string> parseRequestLine(

View File

@ -95,7 +95,7 @@ namespace ix
std::atomic<bool> _stop; std::atomic<bool> _stop;
std::thread _thread; 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) std::mutex _mutex; // to protect accessing the _socket (only one socket per client)
SocketTLSOptions _tlsOptions; SocketTLSOptions _tlsOptions;

View File

@ -69,7 +69,7 @@ namespace ix
_onConnectionCallback = callback; _onConnectionCallback = callback;
} }
void HttpServer::handleConnection(std::shared_ptr<Socket> socket, void HttpServer::handleConnection(std::unique_ptr<Socket> socket,
std::shared_ptr<ConnectionState> connectionState) std::shared_ptr<ConnectionState> connectionState)
{ {
_connectedClientsCount++; _connectedClientsCount++;

View File

@ -43,7 +43,7 @@ namespace ix
std::atomic<int> _connectedClientsCount; std::atomic<int> _connectedClientsCount;
// Methods // Methods
virtual void handleConnection(std::shared_ptr<Socket>, virtual void handleConnection(std::unique_ptr<Socket>,
std::shared_ptr<ConnectionState> connectionState) final; std::shared_ptr<ConnectionState> connectionState) final;
virtual size_t getConnectedClientsCount() final; virtual size_t getConnectedClientsCount() final;

View File

@ -14,12 +14,12 @@
namespace ix namespace ix
{ {
std::shared_ptr<SelectInterrupt> createSelectInterrupt() SelectInterruptPtr createSelectInterrupt()
{ {
#if defined(__linux__) || defined(__APPLE__) #if defined(__linux__) || defined(__APPLE__)
return std::make_shared<SelectInterruptPipe>(); return std::make_unique<SelectInterruptPipe>();
#else #else
return std::make_shared<SelectInterrupt>(); return std::make_unique<SelectInterrupt>();
#endif #endif
} }
} // namespace ix } // namespace ix

View File

@ -11,5 +11,6 @@
namespace ix namespace ix
{ {
class SelectInterrupt; class SelectInterrupt;
std::shared_ptr<SelectInterrupt> createSelectInterrupt(); using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
SelectInterruptPtr createSelectInterrupt();
} // namespace ix } // namespace ix

View File

@ -46,7 +46,7 @@ namespace ix
PollResultType Socket::poll(bool readyToRead, PollResultType Socket::poll(bool readyToRead,
int timeoutMs, int timeoutMs,
int sockfd, 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 // We used to use ::select to poll but on Android 9 we get large fds out of

View File

@ -38,6 +38,7 @@ typedef SSIZE_T ssize_t;
namespace ix namespace ix
{ {
class SelectInterrupt; class SelectInterrupt;
using SelectInterruptPtr = std::unique_ptr<SelectInterrupt>;
enum class PollResultType enum class PollResultType
{ {
@ -66,7 +67,7 @@ namespace ix
// Virtual methods // Virtual methods
virtual bool accept(std::string& errMsg); virtual bool accept(std::string& errMsg);
virtual bool connect(const std::string& url, virtual bool connect(const std::string& host,
int port, int port,
std::string& errMsg, std::string& errMsg,
const CancellationRequest& isCancellationRequested); const CancellationRequest& isCancellationRequested);
@ -93,7 +94,7 @@ namespace ix
static PollResultType poll(bool readyToRead, static PollResultType poll(bool readyToRead,
int timeoutMs, int timeoutMs,
int sockfd, int sockfd,
std::shared_ptr<SelectInterrupt> selectInterrupt = nullptr); const SelectInterruptPtr& selectInterrupt);
// Used as special codes for pipe communication // Used as special codes for pipe communication
@ -112,6 +113,6 @@ namespace ix
std::vector<uint8_t> _readBuffer; std::vector<uint8_t> _readBuffer;
static constexpr size_t kChunkSize = 1 << 15; static constexpr size_t kChunkSize = 1 << 15;
std::shared_ptr<SelectInterrupt> _selectInterrupt; SelectInterruptPtr _selectInterrupt;
}; };
} // namespace ix } // namespace ix

View File

@ -164,6 +164,26 @@ namespace ix
return false; 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 // No wait support
bool SocketAppleSSL::connect(const std::string& host, bool SocketAppleSSL::connect(const std::string& host,
int port, int port,
@ -190,26 +210,17 @@ namespace ix
Boolean option(1); Boolean option(1);
SSLSetSessionOption(_sslContext, kSSLSessionOptionBreakOnServerAuth, option); SSLSetSessionOption(_sslContext, kSSLSessionOptionBreakOnServerAuth, option);
do status = tlsHandShake(errMsg, isCancellationRequested);
{
status = SSLHandshake(_sslContext);
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
if (status == errSSLServerAuthCompleted) if (status == errSSLServerAuthCompleted)
{ {
// proceed with the handshake // proceed with the handshake
do status = tlsHandShake(errMsg, isCancellationRequested);
{
status = SSLHandshake(_sslContext);
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
} }
} }
else else
{ {
do status = tlsHandShake(errMsg, isCancellationRequested);
{
status = SSLHandshake(_sslContext);
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);
} }
} }

View File

@ -37,6 +37,9 @@ namespace ix
static OSStatus writeToSocket(SSLConnectionRef connection, const void* data, size_t* len); static OSStatus writeToSocket(SSLConnectionRef connection, const void* data, size_t* len);
static OSStatus readFromSocket(SSLConnectionRef connection, 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; SSLContextRef _sslContext;
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe mutable std::mutex _mutex; // AppleSSL routines are not thread-safe

View File

@ -8,6 +8,7 @@
#include "IXDNSLookup.h" #include "IXDNSLookup.h"
#include "IXNetSystem.h" #include "IXNetSystem.h"
#include "IXSelectInterrupt.h"
#include "IXSocket.h" #include "IXSocket.h"
#include <fcntl.h> #include <fcntl.h>
#include <string.h> #include <string.h>
@ -64,7 +65,8 @@ namespace ix
int timeoutMs = 10; int timeoutMs = 10;
bool readyToRead = false; 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) if (pollResult == PollResultType::Timeout)
{ {

View File

@ -24,28 +24,28 @@
namespace ix namespace ix
{ {
std::shared_ptr<Socket> createSocket(bool tls, std::unique_ptr<Socket> createSocket(bool tls,
int fd, int fd,
std::string& errorMsg, std::string& errorMsg,
const SocketTLSOptions& tlsOptions) const SocketTLSOptions& tlsOptions)
{ {
(void) tlsOptions; (void) tlsOptions;
errorMsg.clear(); errorMsg.clear();
std::shared_ptr<Socket> socket; std::unique_ptr<Socket> socket;
if (!tls) if (!tls)
{ {
socket = std::make_shared<Socket>(fd); socket = std::make_unique<Socket>(fd);
} }
else else
{ {
#ifdef IXWEBSOCKET_USE_TLS #ifdef IXWEBSOCKET_USE_TLS
#if defined(IXWEBSOCKET_USE_MBED_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) #elif defined(IXWEBSOCKET_USE_OPEN_SSL)
socket = std::make_shared<SocketOpenSSL>(tlsOptions, fd); socket = std::make_unique<SocketOpenSSL>(tlsOptions, fd);
#elif defined(__APPLE__) #elif defined(__APPLE__)
socket = std::make_shared<SocketAppleSSL>(tlsOptions, fd); socket = std::make_unique<SocketAppleSSL>(tlsOptions, fd);
#endif #endif
#else #else
errorMsg = "TLS support is not enabled on this platform."; errorMsg = "TLS support is not enabled on this platform.";

View File

@ -14,7 +14,7 @@
namespace ix namespace ix
{ {
class Socket; class Socket;
std::shared_ptr<Socket> createSocket(bool tls, std::unique_ptr<Socket> createSocket(bool tls,
int fd, int fd,
std::string& errorMsg, std::string& errorMsg,
const SocketTLSOptions& tlsOptions); const SocketTLSOptions& tlsOptions);

View File

@ -195,8 +195,17 @@ namespace ix
int res; int res;
do 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); } while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE);
if (res != 0) if (res != 0)

View File

@ -131,8 +131,14 @@ namespace ix
SSL_CTX_set_mode(ctx, SSL_CTX_set_mode(ctx,
SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_set_options( int options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_CIPHER_SERVER_PREFERENCE;
ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_CIPHER_SERVER_PREFERENCE);
#ifdef SSL_OP_NO_TLSv1_3
// (partially?) work around hang in openssl 1.1.1b, by disabling TLS V1.3
// https://github.com/openssl/openssl/issues/7967
options |= SSL_OP_NO_TLSv1_3;
#endif
SSL_CTX_set_options(ctx, options);
} }
return ctx; return ctx;
} }
@ -218,7 +224,9 @@ namespace ix
return true; 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) while (true)
{ {
@ -227,6 +235,12 @@ namespace ix
return false; return false;
} }
if (isCancellationRequested())
{
errMsg = "Cancellation requested";
return false;
}
ERR_clear_error(); ERR_clear_error();
int connect_result = SSL_connect(_ssl_connection); int connect_result = SSL_connect(_ssl_connection);
if (connect_result == 1) if (connect_result == 1)
@ -571,7 +585,7 @@ namespace ix
X509_VERIFY_PARAM* param = SSL_get0_param(_ssl_connection); X509_VERIFY_PARAM* param = SSL_get0_param(_ssl_connection);
X509_VERIFY_PARAM_set1_host(param, host.c_str(), 0); X509_VERIFY_PARAM_set1_host(param, host.c_str(), 0);
#endif #endif
handshakeSuccessful = openSSLClientHandshake(host, errMsg); handshakeSuccessful = openSSLClientHandshake(host, errMsg, isCancellationRequested);
} }
if (!handshakeSuccessful) if (!handshakeSuccessful)

View File

@ -39,7 +39,9 @@ namespace ix
void openSSLInitialize(); void openSSLInitialize();
std::string getSSLError(int ret); std::string getSSLError(int ret);
SSL_CTX* openSSLCreateContext(std::string& errMsg); 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 openSSLCheckServerCert(SSL* ssl, const std::string& hostname, std::string& errMsg);
bool checkHost(const std::string& host, const char* pattern); bool checkHost(const std::string& host, const char* pattern);
bool handleTLSOptions(std::string& errMsg); bool handleTLSOptions(std::string& errMsg);

View File

@ -7,6 +7,7 @@
#include "IXSocketServer.h" #include "IXSocketServer.h"
#include "IXNetSystem.h" #include "IXNetSystem.h"
#include "IXSelectInterrupt.h"
#include "IXSetThreadName.h" #include "IXSetThreadName.h"
#include "IXSocket.h" #include "IXSocket.h"
#include "IXSocketConnect.h" #include "IXSocketConnect.h"
@ -257,7 +258,9 @@ namespace ix
// Use poll to check whether a new connection is in progress // Use poll to check whether a new connection is in progress
int timeoutMs = 10; int timeoutMs = 10;
bool readyToRead = true; 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) if (pollResult == PollResultType::Error)
{ {
@ -338,7 +341,8 @@ namespace ix
std::lock_guard<std::mutex> lock(_connectionsThreadsMutex); std::lock_guard<std::mutex> lock(_connectionsThreadsMutex);
_connectionsThreads.push_back(std::make_pair( _connectionsThreads.push_back(std::make_pair(
connectionState, connectionState,
std::thread(&SocketServer::handleConnection, this, socket, connectionState))); std::thread(
&SocketServer::handleConnection, this, std::move(socket), connectionState)));
} }
} }

View File

@ -101,7 +101,7 @@ namespace ix
// the factory to create ConnectionState objects // the factory to create ConnectionState objects
ConnectionStateFactory _connectionStateFactory; ConnectionStateFactory _connectionStateFactory;
virtual void handleConnection(std::shared_ptr<Socket>, virtual void handleConnection(std::unique_ptr<Socket>,
std::shared_ptr<ConnectionState> connectionState) = 0; std::shared_ptr<ConnectionState> connectionState) = 0;
virtual size_t getConnectedClientsCount() = 0; virtual size_t getConnectedClientsCount() = 0;

View 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
View 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

View File

@ -71,7 +71,7 @@ namespace ix
#elif defined(IXWEBSOCKET_USE_OPEN_SSL) #elif defined(IXWEBSOCKET_USE_OPEN_SSL)
ss << " ssl/OpenSSL " << OPENSSL_VERSION_TEXT; ss << " ssl/OpenSSL " << OPENSSL_VERSION_TEXT;
#elif __APPLE__ #elif __APPLE__
ss << " ssl/DarwinSSL"; ss << " ssl/SecureTransport";
#endif #endif
#else #else
ss << " nossl"; ss << " nossl";

View File

@ -19,7 +19,6 @@ namespace ix
OnTrafficTrackerCallback WebSocket::_onTrafficTrackerCallback = nullptr; OnTrafficTrackerCallback WebSocket::_onTrafficTrackerCallback = nullptr;
const int WebSocket::kDefaultHandShakeTimeoutSecs(60); const int WebSocket::kDefaultHandShakeTimeoutSecs(60);
const int WebSocket::kDefaultPingIntervalSecs(-1); const int WebSocket::kDefaultPingIntervalSecs(-1);
const int WebSocket::kDefaultPingTimeoutSecs(-1);
const bool WebSocket::kDefaultEnablePong(true); const bool WebSocket::kDefaultEnablePong(true);
const uint32_t WebSocket::kDefaultMaxWaitBetweenReconnectionRetries(10 * 1000); // 10s const uint32_t WebSocket::kDefaultMaxWaitBetweenReconnectionRetries(10 * 1000); // 10s
@ -31,7 +30,6 @@ namespace ix
, _handshakeTimeoutSecs(kDefaultHandShakeTimeoutSecs) , _handshakeTimeoutSecs(kDefaultHandShakeTimeoutSecs)
, _enablePong(kDefaultEnablePong) , _enablePong(kDefaultEnablePong)
, _pingIntervalSecs(kDefaultPingIntervalSecs) , _pingIntervalSecs(kDefaultPingIntervalSecs)
, _pingTimeoutSecs(kDefaultPingTimeoutSecs)
{ {
_ws.setOnCloseCallback( _ws.setOnCloseCallback(
[this](uint16_t code, const std::string& reason, size_t wireSize, bool remote) { [this](uint16_t code, const std::string& reason, size_t wireSize, bool remote) {
@ -86,18 +84,6 @@ namespace ix
return _perMessageDeflateOptions; 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) void WebSocket::setPingInterval(int pingIntervalSecs)
{ {
std::lock_guard<std::mutex> lock(_configMutex); std::lock_guard<std::mutex> lock(_configMutex);
@ -110,18 +96,6 @@ namespace ix
return _pingIntervalSecs; 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() void WebSocket::enablePong()
{ {
std::lock_guard<std::mutex> lock(_configMutex); std::lock_guard<std::mutex> lock(_configMutex);
@ -186,11 +160,8 @@ namespace ix
{ {
{ {
std::lock_guard<std::mutex> lock(_configMutex); std::lock_guard<std::mutex> lock(_configMutex);
_ws.configure(_perMessageDeflateOptions, _ws.configure(
_socketTLSOptions, _perMessageDeflateOptions, _socketTLSOptions, _enablePong, _pingIntervalSecs);
_enablePong,
_pingIntervalSecs,
_pingTimeoutSecs);
} }
WebSocketHttpHeaders headers(_extraHeaders); WebSocketHttpHeaders headers(_extraHeaders);
@ -229,21 +200,25 @@ namespace ix
WebSocketErrorInfo(), WebSocketErrorInfo(),
WebSocketOpenInfo(status.uri, status.headers, status.protocol), WebSocketOpenInfo(status.uri, status.headers, status.protocol),
WebSocketCloseInfo())); WebSocketCloseInfo()));
if (_pingIntervalSecs > 0)
{
// Send a heart beat right away
_ws.sendHeartBeat();
}
return status; 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); std::lock_guard<std::mutex> lock(_configMutex);
_ws.configure(_perMessageDeflateOptions, _ws.configure(
_socketTLSOptions, _perMessageDeflateOptions, _socketTLSOptions, _enablePong, _pingIntervalSecs);
_enablePong,
_pingIntervalSecs,
_pingTimeoutSecs);
} }
WebSocketInitResult status = _ws.connectToSocket(socket, timeoutSecs); WebSocketInitResult status = _ws.connectToSocket(std::move(socket), timeoutSecs);
if (!status.success) if (!status.success)
{ {
return status; return status;
@ -256,6 +231,13 @@ namespace ix
WebSocketErrorInfo(), WebSocketErrorInfo(),
WebSocketOpenInfo(status.uri, status.headers), WebSocketOpenInfo(status.uri, status.headers),
WebSocketCloseInfo())); WebSocketCloseInfo()));
if (_pingIntervalSecs > 0)
{
// Send a heart beat right away
_ws.sendHeartBeat();
}
return status; return status;
} }

View File

@ -52,9 +52,7 @@ namespace ix
void setPerMessageDeflateOptions( void setPerMessageDeflateOptions(
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions); const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
void setTLSOptions(const SocketTLSOptions& socketTLSOptions); void setTLSOptions(const SocketTLSOptions& socketTLSOptions);
void setHeartBeatPeriod(int heartBeatPeriodSecs); void setPingInterval(int pingIntervalSecs);
void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod
void setPingTimeout(int pingTimeoutSecs);
void enablePong(); void enablePong();
void disablePong(); void disablePong();
void enablePerMessageDeflate(); void enablePerMessageDeflate();
@ -94,9 +92,7 @@ namespace ix
const std::string& getUrl() const; const std::string& getUrl() const;
const WebSocketPerMessageDeflateOptions& getPerMessageDeflateOptions() const; const WebSocketPerMessageDeflateOptions& getPerMessageDeflateOptions() const;
int getHeartBeatPeriod() const;
int getPingInterval() const; int getPingInterval() const;
int getPingTimeout() const;
size_t bufferedAmount() const; size_t bufferedAmount() const;
void enableAutomaticReconnection(); void enableAutomaticReconnection();
@ -117,7 +113,7 @@ namespace ix
static void invokeTrafficTrackerCallback(size_t size, bool incoming); static void invokeTrafficTrackerCallback(size_t size, bool incoming);
// Server // Server
WebSocketInitResult connectToSocket(std::shared_ptr<Socket>, int timeoutSecs); WebSocketInitResult connectToSocket(std::unique_ptr<Socket>, int timeoutSecs);
WebSocketTransport _ws; WebSocketTransport _ws;

View File

@ -21,8 +21,8 @@ namespace ix
{ {
WebSocketHandshake::WebSocketHandshake( WebSocketHandshake::WebSocketHandshake(
std::atomic<bool>& requestInitCancellation, std::atomic<bool>& requestInitCancellation,
std::shared_ptr<Socket> socket, std::unique_ptr<Socket>& socket,
WebSocketPerMessageDeflate& perMessageDeflate, WebSocketPerMessageDeflatePtr& perMessageDeflate,
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
std::atomic<bool>& enablePerMessageDeflate) std::atomic<bool>& enablePerMessageDeflate)
: _requestInitCancellation(requestInitCancellation) : _requestInitCancellation(requestInitCancellation)
@ -230,7 +230,7 @@ namespace ix
_enablePerMessageDeflate = false; _enablePerMessageDeflate = false;
} }
// Otherwise try to initialize the deflate engine (zlib) // Otherwise try to initialize the deflate engine (zlib)
else if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions)) else if (!_perMessageDeflate->init(webSocketPerMessageDeflateOptions))
{ {
return WebSocketInitResult( return WebSocketInitResult(
false, 0, "Failed to initialize per message deflate engine"); false, 0, "Failed to initialize per message deflate engine");
@ -341,7 +341,7 @@ namespace ix
{ {
_enablePerMessageDeflate = true; _enablePerMessageDeflate = true;
if (!_perMessageDeflate.init(webSocketPerMessageDeflateOptions)) if (!_perMessageDeflate->init(webSocketPerMessageDeflateOptions))
{ {
return WebSocketInitResult( return WebSocketInitResult(
false, 0, "Failed to initialize per message deflate engine"); false, 0, "Failed to initialize per message deflate engine");

View File

@ -23,8 +23,8 @@ namespace ix
{ {
public: public:
WebSocketHandshake(std::atomic<bool>& requestInitCancellation, WebSocketHandshake(std::atomic<bool>& requestInitCancellation,
std::shared_ptr<Socket> _socket, std::unique_ptr<Socket>& _socket,
WebSocketPerMessageDeflate& perMessageDeflate, WebSocketPerMessageDeflatePtr& perMessageDeflate,
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
std::atomic<bool>& enablePerMessageDeflate); std::atomic<bool>& enablePerMessageDeflate);
@ -46,8 +46,8 @@ namespace ix
bool insensitiveStringCompare(const std::string& a, const std::string& b); bool insensitiveStringCompare(const std::string& a, const std::string& b);
std::atomic<bool>& _requestInitCancellation; std::atomic<bool>& _requestInitCancellation;
std::shared_ptr<Socket> _socket; std::unique_ptr<Socket>& _socket;
WebSocketPerMessageDeflate& _perMessageDeflate; WebSocketPerMessageDeflatePtr& _perMessageDeflate;
WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions; WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions;
std::atomic<bool>& _enablePerMessageDeflate; std::atomic<bool>& _enablePerMessageDeflate;
}; };

View File

@ -32,7 +32,7 @@ namespace ix
} }
std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders( std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders(
std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested) std::unique_ptr<Socket>& socket, const CancellationRequest& isCancellationRequested)
{ {
WebSocketHttpHeaders headers; WebSocketHttpHeaders headers;

View File

@ -29,5 +29,5 @@ namespace ix
using WebSocketHttpHeaders = std::map<std::string, std::string, CaseInsensitiveLess>; using WebSocketHttpHeaders = std::map<std::string, std::string, CaseInsensitiveLess>;
std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders( std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders(
std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested); std::unique_ptr<Socket>& socket, const CancellationRequest& isCancellationRequested);
} // namespace ix } // namespace ix

View File

@ -57,4 +57,6 @@ namespace ix
std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor; std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor;
std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor; std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor;
}; };
using WebSocketPerMessageDeflatePtr = std::unique_ptr<WebSocketPerMessageDeflate>;
} // namespace ix } // namespace ix

View File

@ -89,8 +89,12 @@ namespace ix
if (in.empty()) if (in.empty())
{ {
uint8_t buf[6] = {0x02, 0x00, 0x00, 0x00, 0xff, 0xff}; // See issue #167
out.append((char*) (buf), 6); // 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; return true;
} }

View File

@ -71,7 +71,7 @@ namespace ix
_onConnectionCallback = callback; _onConnectionCallback = callback;
} }
void WebSocketServer::handleConnection(std::shared_ptr<Socket> socket, void WebSocketServer::handleConnection(std::unique_ptr<Socket> socket,
std::shared_ptr<ConnectionState> connectionState) std::shared_ptr<ConnectionState> connectionState)
{ {
setThreadName("WebSocketServer::" + connectionState->getId()); setThreadName("WebSocketServer::" + connectionState->getId());
@ -96,7 +96,7 @@ namespace ix
_clients.insert(webSocket); _clients.insert(webSocket);
} }
auto status = webSocket->connectToSocket(socket, _handshakeTimeoutSecs); auto status = webSocket->connectToSocket(std::move(socket), _handshakeTimeoutSecs);
if (status.success) if (status.success)
{ {
// Process incoming messages and execute callbacks // Process incoming messages and execute callbacks

View File

@ -59,7 +59,7 @@ namespace ix
const static bool kDefaultEnablePong; const static bool kDefaultEnablePong;
// Methods // Methods
virtual void handleConnection(std::shared_ptr<Socket> socket, virtual void handleConnection(std::unique_ptr<Socket> socket,
std::shared_ptr<ConnectionState> connectionState) final; std::shared_ptr<ConnectionState> connectionState) final;
virtual size_t getConnectedClientsCount() final; virtual size_t getConnectedClientsCount() final;
}; };

View File

@ -51,26 +51,10 @@
#include <vector> #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 namespace ix
{ {
const std::string WebSocketTransport::kPingMessage("ixwebsocket::heartbeat"); const std::string WebSocketTransport::kPingMessage("ixwebsocket::heartbeat");
const int WebSocketTransport::kDefaultPingIntervalSecs(-1); const int WebSocketTransport::kDefaultPingIntervalSecs(-1);
const int WebSocketTransport::kDefaultPingTimeoutSecs(-1);
const bool WebSocketTransport::kDefaultEnablePong(true); const bool WebSocketTransport::kDefaultEnablePong(true);
const int WebSocketTransport::kClosingMaximumWaitingDelayInMs(300); const int WebSocketTransport::kClosingMaximumWaitingDelayInMs(300);
constexpr size_t WebSocketTransport::kChunkSize; constexpr size_t WebSocketTransport::kChunkSize;
@ -89,11 +73,8 @@ namespace ix
, _closingTimePoint(std::chrono::steady_clock::now()) , _closingTimePoint(std::chrono::steady_clock::now())
, _enablePong(kDefaultEnablePong) , _enablePong(kDefaultEnablePong)
, _pingIntervalSecs(kDefaultPingIntervalSecs) , _pingIntervalSecs(kDefaultPingIntervalSecs)
, _pingTimeoutSecs(kDefaultPingTimeoutSecs) , _pongReceived(false)
, _pingIntervalOrTimeoutGCDSecs(-1)
, _nextGCDTimePoint(std::chrono::steady_clock::now())
, _lastSendPingTimePoint(std::chrono::steady_clock::now()) , _lastSendPingTimePoint(std::chrono::steady_clock::now())
, _lastReceivePongTimePoint(std::chrono::steady_clock::now())
{ {
_readbuf.resize(kChunkSize); _readbuf.resize(kChunkSize);
} }
@ -107,29 +88,13 @@ namespace ix
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
const SocketTLSOptions& socketTLSOptions, const SocketTLSOptions& socketTLSOptions,
bool enablePong, bool enablePong,
int pingIntervalSecs, int pingIntervalSecs)
int pingTimeoutSecs)
{ {
_perMessageDeflateOptions = perMessageDeflateOptions; _perMessageDeflateOptions = perMessageDeflateOptions;
_enablePerMessageDeflate = _perMessageDeflateOptions.enabled(); _enablePerMessageDeflate = _perMessageDeflateOptions.enabled();
_socketTLSOptions = socketTLSOptions; _socketTLSOptions = socketTLSOptions;
_enablePong = enablePong; _enablePong = enablePong;
_pingIntervalSecs = pingIntervalSecs; _pingIntervalSecs = pingIntervalSecs;
_pingTimeoutSecs = pingTimeoutSecs;
if (pingIntervalSecs > 0 && pingTimeoutSecs > 0)
{
_pingIntervalOrTimeoutGCDSecs =
greatestCommonDivisor(pingIntervalSecs, pingTimeoutSecs);
}
else if (_pingTimeoutSecs > 0)
{
_pingIntervalOrTimeoutGCDSecs = pingTimeoutSecs;
}
else
{
_pingIntervalOrTimeoutGCDSecs = pingIntervalSecs;
}
} }
// Client // Client
@ -152,6 +117,7 @@ namespace ix
std::string errorMsg; std::string errorMsg;
bool tls = protocol == "wss"; bool tls = protocol == "wss";
_socket = createSocket(tls, -1, errorMsg, _socketTLSOptions); _socket = createSocket(tls, -1, errorMsg, _socketTLSOptions);
_perMessageDeflate = std::make_unique<WebSocketPerMessageDeflate>();
if (!_socket) if (!_socket)
{ {
@ -174,7 +140,7 @@ namespace ix
} }
// Server // Server
WebSocketInitResult WebSocketTransport::connectToSocket(std::shared_ptr<Socket> socket, WebSocketInitResult WebSocketTransport::connectToSocket(std::unique_ptr<Socket> socket,
int timeoutSecs) int timeoutSecs)
{ {
std::lock_guard<std::mutex> lock(_socketMutex); std::lock_guard<std::mutex> lock(_socketMutex);
@ -183,7 +149,8 @@ namespace ix
_useMask = false; _useMask = false;
_blockingSend = true; _blockingSend = true;
_socket = socket; _socket = std::move(socket);
_perMessageDeflate = std::make_unique<WebSocketPerMessageDeflate>();
WebSocketHandshake webSocketHandshake(_requestInitCancellation, WebSocketHandshake webSocketHandshake(_requestInitCancellation,
_socket, _socket,
@ -220,7 +187,8 @@ namespace ix
} }
else if (readyState == ReadyState::OPEN) else if (readyState == ReadyState::OPEN)
{ {
initTimePointsAndGCDAfterConnect(); initTimePointsAfterConnect();
_pongReceived = false;
} }
_readyState = readyState; _readyState = readyState;
@ -231,22 +199,12 @@ namespace ix
_onCloseCallback = onCloseCallback; _onCloseCallback = onCloseCallback;
} }
void WebSocketTransport::initTimePointsAndGCDAfterConnect() void WebSocketTransport::initTimePointsAfterConnect()
{ {
{ {
std::lock_guard<std::mutex> lock(_lastSendPingTimePointMutex); std::lock_guard<std::mutex> lock(_lastSendPingTimePointMutex);
_lastSendPingTimePoint = std::chrono::steady_clock::now(); _lastSendPingTimePoint = std::chrono::steady_clock::now();
} }
{
std::lock_guard<std::mutex> lock(_lastReceivePongTimePointMutex);
_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. // Only consider send PING time points for that computation.
@ -259,13 +217,12 @@ namespace ix
return now - _lastSendPingTimePoint > std::chrono::seconds(_pingIntervalSecs); return now - _lastSendPingTimePoint > std::chrono::seconds(_pingIntervalSecs);
} }
bool WebSocketTransport::pingTimeoutExceeded() WebSocketSendInfo WebSocketTransport::sendHeartBeat()
{ {
if (_pingTimeoutSecs <= 0) return false; _pongReceived = false;
std::stringstream ss;
std::lock_guard<std::mutex> lock(_lastReceivePongTimePointMutex); ss << kPingMessage << "::" << _pingIntervalSecs << "s";
auto now = std::chrono::steady_clock::now(); return sendPing(ss.str());
return now - _lastReceivePongTimePoint > std::chrono::seconds(_pingTimeoutSecs);
} }
bool WebSocketTransport::closingDelayExceeded() bool WebSocketTransport::closingDelayExceeded()
@ -279,46 +236,32 @@ namespace ix
{ {
if (_readyState == ReadyState::OPEN) if (_readyState == ReadyState::OPEN)
{ {
// if (1) ping timeout is enabled and (2) duration since last received if (pingIntervalExceeded())
// ping response (PONG) exceeds the maximum delay, then close the connection
if (pingTimeoutExceeded())
{ {
close(WebSocketCloseConstants::kInternalErrorCode, if (!_pongReceived)
WebSocketCloseConstants::kPingTimeoutMessage); {
} // ping response (PONG) exceeds the maximum delay, close the connection
// If ping is enabled and no ping has been sent for a duration close(WebSocketCloseConstants::kInternalErrorCode,
// exceeding our ping interval, send a ping to the server. WebSocketCloseConstants::kPingTimeoutMessage);
else if (pingIntervalExceeded()) }
{ else
std::stringstream ss; {
ss << kPingMessage << "::" << _pingIntervalSecs << "s"; sendHeartBeat();
sendPing(ss.str()); }
} }
} }
// No timeout if state is not OPEN, otherwise computed // No timeout if state is not OPEN, otherwise computed
// pingIntervalOrTimeoutGCD (equals to -1 if no ping and no ping timeout are set) // pingIntervalOrTimeoutGCD (equals to -1 if no ping and no ping timeout are set)
int lastingTimeoutDelayInMs = int lastingTimeoutDelayInMs = (_readyState != ReadyState::OPEN) ? 0 : _pingIntervalSecs;
(_readyState != ReadyState::OPEN) ? 0 : _pingIntervalOrTimeoutGCDSecs;
if (_pingIntervalOrTimeoutGCDSecs > 0) if (_pingIntervalSecs > 0)
{ {
// compute lasting delay to wait for next ping / timeout, if at least one set // compute lasting delay to wait for next ping / timeout, if at least one set
auto now = std::chrono::steady_clock::now(); auto now = std::chrono::steady_clock::now();
lastingTimeoutDelayInMs = (int) std::chrono::duration_cast<std::chrono::milliseconds>(
if (now >= _nextGCDTimePoint) now - _lastSendPingTimePoint)
{ .count();
_nextGCDTimePoint = now + std::chrono::seconds(_pingIntervalOrTimeoutGCDSecs);
lastingTimeoutDelayInMs = _pingIntervalOrTimeoutGCDSecs * 1000;
}
else
{
lastingTimeoutDelayInMs =
(int) std::chrono::duration_cast<std::chrono::milliseconds>(_nextGCDTimePoint -
now)
.count();
}
} }
#ifdef _WIN32 #ifdef _WIN32
@ -626,9 +569,7 @@ namespace ix
} }
else if (ws.opcode == wsheader_type::PONG) else if (ws.opcode == wsheader_type::PONG)
{ {
std::lock_guard<std::mutex> lck(_lastReceivePongTimePointMutex); _pongReceived = true;
_lastReceivePongTimePoint = std::chrono::steady_clock::now();
emitMessage(MessageKind::PONG, frameData, false, onMessageCallback); emitMessage(MessageKind::PONG, frameData, false, onMessageCallback);
} }
else if (ws.opcode == wsheader_type::CLOSE) else if (ws.opcode == wsheader_type::CLOSE)
@ -684,7 +625,7 @@ namespace ix
// send back the CLOSE frame // send back the CLOSE frame
sendCloseFrame(code, reason); sendCloseFrame(code, reason);
_socket->wakeUpFromPoll(Socket::kCloseRequest); wakeUpFromPoll(Socket::kCloseRequest);
bool remote = true; bool remote = true;
closeSocketAndSwitchToClosedState(code, reason, _rxbuf.size(), remote); closeSocketAndSwitchToClosedState(code, reason, _rxbuf.size(), remote);
@ -772,7 +713,7 @@ namespace ix
if (compressedMessage && messageKind != MessageKind::FRAGMENT) if (compressedMessage && messageKind != MessageKind::FRAGMENT)
{ {
std::string decompressedMessage; 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))
{ {
@ -826,7 +767,7 @@ namespace ix
if (compress) if (compress)
{ {
if (!_perMessageDeflate.compress(message, compressedMessage)) if (!_perMessageDeflate->compress(message, compressedMessage))
{ {
bool success = false; bool success = false;
compressionError = true; compressionError = true;
@ -904,7 +845,7 @@ namespace ix
// Request to flush the send buffer on the background thread if it isn't empty // Request to flush the send buffer on the background thread if it isn't empty
if (!isSendBufferEmpty()) if (!isSendBufferEmpty())
{ {
_socket->wakeUpFromPoll(Socket::kSendRequest); wakeUpFromPoll(Socket::kSendRequest);
// FIXME: we should have a timeout when sending large messages: see #131 // FIXME: we should have a timeout when sending large messages: see #131
if (_blockingSend && !flushSendBuffer()) if (_blockingSend && !flushSendBuffer())
@ -1122,6 +1063,12 @@ namespace ix
_socket->close(); _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, void WebSocketTransport::closeSocketAndSwitchToClosedState(uint16_t code,
const std::string& reason, const std::string& reason,
size_t closeWireSize, size_t closeWireSize,
@ -1169,8 +1116,9 @@ namespace ix
setReadyState(ReadyState::CLOSING); setReadyState(ReadyState::CLOSING);
sendCloseFrame(code, reason); sendCloseFrame(code, reason);
// wake up the poll, but do not close yet // wake up the poll, but do not close yet
_socket->wakeUpFromPoll(Socket::kSendRequest); wakeUpFromPoll(Socket::kSendRequest);
} }
size_t WebSocketTransport::bufferedAmount() const size_t WebSocketTransport::bufferedAmount() const

View File

@ -75,8 +75,7 @@ namespace ix
void configure(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions, void configure(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
const SocketTLSOptions& socketTLSOptions, const SocketTLSOptions& socketTLSOptions,
bool enablePong, bool enablePong,
int pingIntervalSecs, int pingIntervalSecs);
int pingTimeoutSecs);
// Client // Client
WebSocketInitResult connectToUrl(const std::string& url, WebSocketInitResult connectToUrl(const std::string& url,
@ -84,7 +83,7 @@ namespace ix
int timeoutSecs); int timeoutSecs);
// Server // Server
WebSocketInitResult connectToSocket(std::shared_ptr<Socket> socket, int timeoutSecs); WebSocketInitResult connectToSocket(std::unique_ptr<Socket> socket, int timeoutSecs);
PollResult poll(); PollResult poll();
WebSocketSendInfo sendBinary(const std::string& message, WebSocketSendInfo sendBinary(const std::string& message,
@ -106,6 +105,9 @@ namespace ix
void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback); void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback);
size_t bufferedAmount() const; size_t bufferedAmount() const;
// internal
WebSocketSendInfo sendHeartBeat();
private: private:
std::string _url; std::string _url;
@ -169,7 +171,7 @@ namespace ix
static constexpr size_t kChunkSize = 1 << 15; static constexpr size_t kChunkSize = 1 << 15;
// Underlying TCP socket // Underlying TCP socket
std::shared_ptr<Socket> _socket; std::unique_ptr<Socket> _socket;
std::mutex _socketMutex; std::mutex _socketMutex;
// Hold the state of the connection (OPEN, CLOSED, etc...) // Hold the state of the connection (OPEN, CLOSED, etc...)
@ -183,7 +185,7 @@ namespace ix
mutable std::mutex _closeDataMutex; mutable std::mutex _closeDataMutex;
// Data used for Per Message Deflate compression (with zlib) // Data used for Per Message Deflate compression (with zlib)
WebSocketPerMessageDeflate _perMessageDeflate; WebSocketPerMessageDeflatePtr _perMessageDeflate;
WebSocketPerMessageDeflateOptions _perMessageDeflateOptions; WebSocketPerMessageDeflateOptions _perMessageDeflateOptions;
std::atomic<bool> _enablePerMessageDeflate; std::atomic<bool> _enablePerMessageDeflate;
@ -202,39 +204,24 @@ namespace ix
static const bool kDefaultEnablePong; static const bool kDefaultEnablePong;
// Optional ping and pong timeout // 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 _pingIntervalSecs;
int _pingTimeoutSecs; std::atomic<bool> _pongReceived;
int _pingIntervalOrTimeoutGCDSecs;
static const int kDefaultPingIntervalSecs; static const int kDefaultPingIntervalSecs;
static const int kDefaultPingTimeoutSecs;
static const std::string kPingMessage; 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 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 _lastSendPingTimePointMutex;
mutable std::mutex _lastReceivePongTimePointMutex;
std::chrono::time_point<std::chrono::steady_clock> _lastSendPingTimePoint; 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 // If this function returns true, it is time to send a new ping
bool pingIntervalExceeded(); bool pingIntervalExceeded();
void initTimePointsAfterConnect();
// No PONG data was received through the socket for longer than ping timeout delay
bool pingTimeoutExceeded();
// after calling close(), if no CLOSE frame answer is received back from the remote, we // after calling close(), if no CLOSE frame answer is received back from the remote, we
// should close the connexion // should close the connexion
bool closingDelayExceeded(); bool closingDelayExceeded();
void initTimePointsAndGCDAfterConnect();
void sendCloseFrame(uint16_t code, const std::string& reason); void sendCloseFrame(uint16_t code, const std::string& reason);
void closeSocketAndSwitchToClosedState(uint16_t code, void closeSocketAndSwitchToClosedState(uint16_t code,
@ -242,6 +229,8 @@ namespace ix
size_t closeWireSize, size_t closeWireSize,
bool remote); bool remote);
bool wakeUpFromPoll(uint64_t wakeUpCode);
bool flushSendBuffer(); bool flushSendBuffer();
bool sendOnSocket(); bool sendOnSocket();
bool receiveFromSocket(); bool receiveFromSocket();

View File

@ -6,4 +6,4 @@
#pragma once #pragma once
#define IX_WEBSOCKET_VERSION "8.1.7" #define IX_WEBSOCKET_VERSION "9.1.9"

View File

@ -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 all: brew
@ -8,14 +16,23 @@ install: brew
# Use -DCMAKE_INSTALL_PREFIX= to install into another location # Use -DCMAKE_INSTALL_PREFIX= to install into another location
# on osx it is good practice to make /usr/local user writable # on osx it is good practice to make /usr/local user writable
# sudo chown -R `whoami`/staff /usr/local # sudo chown -R `whoami`/staff /usr/local
#
# Release, Debug, MinSizeRel, RelWithDebInfo are the build types
#
brew: brew:
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_TEST=1 .. ; make -j 4 install) 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: ws:
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j 4) mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 .. ; make -j 4)
ws_install: 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: 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) 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 ${LATEST}
docker push ${IMG} docker push ${IMG}
deploy: docker docker_push
run: run:
docker run --cap-add sys_ptrace --entrypoint=sh -it bsergean/ws:build docker run --cap-add sys_ptrace --entrypoint=sh -it bsergean/ws:build
@ -87,6 +106,31 @@ test:
mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_WS=1 -DUSE_TEST=1 .. ; make -j 4) 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) (cd test ; python2.7 run.py -r)
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_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_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)
test_openssl: 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) mkdir -p build && (cd build ; cmake -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_OPEN_SSL=1 -DUSE_TEST=1 .. ; make -j 4)
(cd test ; python2.7 run.py -r) (cd test ; python2.7 run.py -r)

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ALL_BUILD
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD:
echo ""
echo Build\ all\ projects

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ALL_BUILD
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD:
echo ""
echo Build\ all\ projects

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ALL_BUILD
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD:
echo ""
echo Build\ all\ projects

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ALL_BUILD
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ALL_BUILD:
echo ""
echo Build\ all\ projects

View File

@ -1,18 +0,0 @@
# Generated by CMake, DO NOT EDIT
TARGETS:=
empty:=
space:= $(empty) $(empty)
spaceplus:= $(empty)\ $(empty)
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Applications/CMake.app/Contents/share/cmake-3.12/Modules/CMakeASMInformation.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Applications/CMake.app/Contents/share/cmake-3.12/Modules/Compiler/AppleClang-ASM.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Applications/CMake.app/Contents/share/cmake-3.12/Modules/Compiler/Clang-ASM.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Applications/CMake.app/Contents/share/cmake-3.12/Modules/Compiler/Clang.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Applications/CMake.app/Contents/share/cmake-3.12/Modules/Platform/Apple-clang.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Users/bsergeant/src/foss/IXWebSocket/CMakeFiles/3.12.3/CMakeASMCompiler.cmake))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Users/bsergeant/src/foss/IXWebSocket/third_party/sentry-native/CMakeLists.txt))
TARGETS += $(subst $(space),$(spaceplus),$(wildcard /Users/bsergeant/src/foss/IXWebSocket/third_party/sentry-native/src/CMakeLists.txt))
/Users/bsergeant/src/foss/IXWebSocket/CMakeFiles/cmake.check_cache: $(TARGETS)
/Applications/CMake.app/Contents/bin/cmake -H/Users/bsergeant/src/foss/IXWebSocket -B/Users/bsergeant/src/foss/IXWebSocket

View File

@ -1,139 +0,0 @@
# DO NOT EDIT
# This makefile makes sure all linkable targets are
# up-to-date with anything they link to
default:
echo "Do not invoke directly"
# Rules to remove targets that are older than anything to which they
# link. This forces Xcode to relink the targets from scratch. It
# does not seem to check these dependencies itself.
PostBuild.example.Debug:
PostBuild.sentry.Debug: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/example:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example
PostBuild.example_crashpad.Debug:
PostBuild.sentry.Debug: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad
PostBuild.sentry.Debug:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
PostBuild.sentry_test_integration.Debug:
PostBuild.sentry.Debug: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration
PostBuild.sentry_test_unit.Debug:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_unit:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_unit
PostBuild.example.Release:
PostBuild.sentry.Release: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/example:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example
PostBuild.example_crashpad.Release:
PostBuild.sentry.Release: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/example_crashpad
PostBuild.sentry.Release:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
PostBuild.sentry_test_integration.Release:
PostBuild.sentry.Release: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_integration
PostBuild.sentry_test_unit.Release:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_unit:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/sentry_test_unit
PostBuild.example.MinSizeRel:
PostBuild.sentry.MinSizeRel: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example
PostBuild.example_crashpad.MinSizeRel:
PostBuild.sentry.MinSizeRel: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example_crashpad
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example_crashpad:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/example_crashpad
PostBuild.sentry.MinSizeRel:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a
PostBuild.sentry_test_integration.MinSizeRel:
PostBuild.sentry.MinSizeRel: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/sentry_test_integration
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/sentry_test_integration:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/sentry_test_integration
PostBuild.sentry_test_unit.MinSizeRel:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/sentry_test_unit:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/sentry_test_unit
PostBuild.example.RelWithDebInfo:
PostBuild.sentry.RelWithDebInfo: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example
PostBuild.example_crashpad.RelWithDebInfo:
PostBuild.sentry.RelWithDebInfo: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example_crashpad
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example_crashpad:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/example_crashpad
PostBuild.sentry.RelWithDebInfo:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a
PostBuild.sentry_test_integration.RelWithDebInfo:
PostBuild.sentry.RelWithDebInfo: /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/sentry_test_integration
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/sentry_test_integration:\
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/sentry_test_integration
PostBuild.sentry_test_unit.RelWithDebInfo:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/sentry_test_unit:
/bin/rm -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/sentry_test_unit
# For each target create a dummy ruleso the target does not have to exist
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.a:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.a:
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.a:

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ZERO_CHECK
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK:
echo ""
make -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeScripts/ReRunCMake.make

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ZERO_CHECK
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK:
echo ""
make -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeScripts/ReRunCMake.make

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ZERO_CHECK
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK:
echo ""
make -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeScripts/ReRunCMake.make

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for ZERO_CHECK
.SUFFIXES:
all: \
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK
/Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeFiles/ZERO_CHECK:
echo ""
make -f /Users/bsergeant/src/foss/IXWebSocket/sentry-native/CMakeScripts/ReRunCMake.make

View File

@ -1,9 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for install
.SUFFIXES:
all: \
install_buildpart_0
install_buildpart_0:
/Applications/CMake.app/Contents/bin/cmake -DBUILD_TYPE=$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -P cmake_install.cmake

View File

@ -1,9 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for install
.SUFFIXES:
all: \
install_buildpart_0
install_buildpart_0:
/Applications/CMake.app/Contents/bin/cmake -DBUILD_TYPE=$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -P cmake_install.cmake

View File

@ -1,9 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for install
.SUFFIXES:
all: \
install_buildpart_0
install_buildpart_0:
/Applications/CMake.app/Contents/bin/cmake -DBUILD_TYPE=$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -P cmake_install.cmake

View File

@ -1,9 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for install
.SUFFIXES:
all: \
install_buildpart_0
install_buildpart_0:
/Applications/CMake.app/Contents/bin/cmake -DBUILD_TYPE=$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -P cmake_install.cmake

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for sentry
.SUFFIXES:
all: \
sentry_buildpart_0
sentry_buildpart_0:
echo "Creating symlinks"
/Applications/CMake.app/Contents/bin/cmake -E cmake_symlink_library /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for sentry
.SUFFIXES:
all: \
sentry_buildpart_0
sentry_buildpart_0:
echo "Creating symlinks"
/Applications/CMake.app/Contents/bin/cmake -E cmake_symlink_library /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/MinSizeRel/libsentry.dylib

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for sentry
.SUFFIXES:
all: \
sentry_buildpart_0
sentry_buildpart_0:
echo "Creating symlinks"
/Applications/CMake.app/Contents/bin/cmake -E cmake_symlink_library /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/RelWithDebInfo/libsentry.dylib

View File

@ -1,10 +0,0 @@
# Generated by CMake, DO NOT EDIT
# Custom rules for sentry
.SUFFIXES:
all: \
sentry_buildpart_0
sentry_buildpart_0:
echo "Creating symlinks"
/Applications/CMake.app/Contents/bin/cmake -E cmake_symlink_library /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib /Users/bsergeant/src/foss/IXWebSocket/sentry-native/libsentry.dylib

Some files were not shown because too many files have changed in this diff Show More