clang format, based on cpprest

This commit is contained in:
Benjamin Sergeant 2019-05-30 08:46:50 -07:00
parent 879a4b38aa
commit c65fec7271
47 changed files with 426 additions and 414 deletions

46
.clang-format Normal file
View File

@ -0,0 +1,46 @@
# https://releases.llvm.org/7.0.0/tools/clang/docs/ClangFormatStyleOptions.html
---
Language: Cpp
BasedOnStyle: WebKit
AlignAfterOpenBracket: Align
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 100
ConstructorInitializerAllOnOneLineOrOnePerLine: false
Cpp11BracedListStyle: true
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^["<](stdafx|pch)\.h[">]$'
Priority: -1
- Regex: '^<Windows\.h>$'
Priority: 3
- Regex: '^<(WinIoCtl|winhttp|Shellapi)\.h>$'
Priority: 4
- Regex: '.*'
Priority: 2
IndentCaseLabels: true
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
PenaltyReturnTypeOnItsOwnLine: 1000
PointerAlignment: Left
SpaceAfterTemplateKeyword: false
Standard: Cpp11
UseTab: Never

View File

@ -6,14 +6,13 @@
#pragma once #pragma once
#include <functional>
#include <atomic> #include <atomic>
#include <functional>
namespace ix namespace ix
{ {
using CancellationRequest = std::function<bool()>; using CancellationRequest = std::function<bool()>;
CancellationRequest makeCancellationRequestWithTimeout(int seconds, CancellationRequest makeCancellationRequestWithTimeout(
std::atomic<bool>& requestInitCancellation); int seconds, std::atomic<bool>& requestInitCancellation);
} } // namespace ix

View File

@ -6,14 +6,15 @@
#pragma once #pragma once
#include <stdint.h>
#include <string>
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <stdint.h>
#include <string>
namespace ix namespace ix
{ {
class ConnectionState { class ConnectionState
{
public: public:
ConnectionState(); ConnectionState();
virtual ~ConnectionState() = default; virtual ~ConnectionState() = default;
@ -32,6 +33,4 @@ namespace ix
static std::atomic<uint64_t> _globalId; static std::atomic<uint64_t> _globalId;
}; };
} } // namespace ix

View File

@ -11,22 +11,20 @@
#pragma once #pragma once
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include <string>
#include <thread>
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <set> #include <set>
#include <string>
#include <thread>
struct addrinfo; struct addrinfo;
namespace ix namespace ix
{ {
class DNSLookup { class DNSLookup
{
public: public:
DNSLookup(const std::string& hostname, DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
int port,
int64_t wait = DNSLookup::kDefaultWait);
~DNSLookup(); ~DNSLookup();
struct addrinfo* resolve(std::string& errMsg, struct addrinfo* resolve(std::string& errMsg,
@ -78,4 +76,4 @@ namespace ix
const static int64_t kDefaultWait; const static int64_t kDefaultWait;
}; };
} } // namespace ix

View File

@ -6,39 +6,38 @@
#pragma once #pragma once
#include <algorithm>
#include <functional>
#include <mutex>
#include <atomic>
#include <tuple>
#include <memory>
#include <map>
#include "IXSocket.h" #include "IXSocket.h"
#include "IXWebSocketHttpHeaders.h" #include "IXWebSocketHttpHeaders.h"
#include <algorithm>
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <tuple>
namespace ix namespace ix
{ {
enum class HttpErrorCode : int enum class HttpErrorCode : int
{ {
Ok = 0, Ok = 0,
CannotConnect = 1, CannotConnect = 1,
Timeout = 2, Timeout = 2,
Gzip = 3, Gzip = 3,
UrlMalformed = 4, UrlMalformed = 4,
CannotCreateSocket = 5, CannotCreateSocket = 5,
SendError = 6, SendError = 6,
ReadError = 7, ReadError = 7,
CannotReadStatusLine = 8, CannotReadStatusLine = 8,
MissingStatus = 9, MissingStatus = 9,
HeaderParsingError = 10, HeaderParsingError = 10,
MissingLocation = 11, MissingLocation = 11,
TooManyRedirects = 12, TooManyRedirects = 12,
ChunkReadError = 13, ChunkReadError = 13,
CannotReadBody = 14 CannotReadBody = 14
}; };
using HttpResponse = std::tuple<int, // status using HttpResponse = std::tuple<int, // status
HttpErrorCode, // error code HttpErrorCode, // error code
WebSocketHttpHeaders, WebSocketHttpHeaders,
std::string, // payload std::string, // payload
@ -64,15 +63,14 @@ namespace ix
OnProgressCallback onProgressCallback; OnProgressCallback onProgressCallback;
}; };
class HttpClient { class HttpClient
{
public: public:
HttpClient(); HttpClient();
~HttpClient(); ~HttpClient();
HttpResponse get(const std::string& url, HttpResponse get(const std::string& url, const HttpRequestArgs& args);
const HttpRequestArgs& args); HttpResponse head(const std::string& url, const HttpRequestArgs& args);
HttpResponse head(const std::string& url,
const HttpRequestArgs& args);
HttpResponse post(const std::string& url, HttpResponse post(const std::string& url,
const HttpParameters& httpParameters, const HttpParameters& httpParameters,
@ -94,9 +92,7 @@ namespace ix
void log(const std::string& msg, const HttpRequestArgs& args); void log(const std::string& msg, const HttpRequestArgs& args);
bool gzipInflate( bool gzipInflate(const std::string& in, std::string& out);
const std::string& in,
std::string& out);
std::shared_ptr<Socket> _socket; std::shared_ptr<Socket> _socket;
@ -104,4 +100,4 @@ namespace ix
const static std::string kGet; const static std::string kGet;
const static std::string kHead; const static std::string kHead;
}; };
} } // namespace ix

View File

@ -7,25 +7,25 @@
#pragma once #pragma once
#ifdef _WIN32 #ifdef _WIN32
# include <WS2tcpip.h> #include <WS2tcpip.h>
# include <WinSock2.h> #include <WinSock2.h>
# include <basetsd.h> #include <basetsd.h>
# include <io.h> #include <io.h>
# include <ws2def.h> #include <ws2def.h>
#else #else
# include <arpa/inet.h> #include <arpa/inet.h>
# include <errno.h> #include <errno.h>
# include <netdb.h> #include <netdb.h>
# include <netinet/tcp.h> #include <netinet/tcp.h>
# include <sys/select.h> #include <sys/select.h>
# include <sys/socket.h> #include <sys/socket.h>
# include <sys/stat.h> #include <sys/stat.h>
# include <sys/time.h> #include <sys/time.h>
# include <unistd.h> #include <unistd.h>
#endif #endif
namespace ix namespace ix
{ {
bool initNetSystem(); bool initNetSystem();
bool uninitNetSystem(); bool uninitNetSystem();
} } // namespace ix

View File

@ -11,7 +11,8 @@
namespace ix namespace ix
{ {
class SelectInterrupt { class SelectInterrupt
{
public: public:
SelectInterrupt(); SelectInterrupt();
virtual ~SelectInterrupt(); virtual ~SelectInterrupt();
@ -23,6 +24,4 @@ namespace ix
virtual uint64_t read(); virtual uint64_t read();
virtual int getFd() const; virtual int getFd() const;
}; };
} } // namespace ix

View File

@ -7,13 +7,13 @@
#pragma once #pragma once
#include "IXSelectInterrupt.h" #include "IXSelectInterrupt.h"
#include <stdint.h> #include <stdint.h>
#include <string> #include <string>
namespace ix namespace ix
{ {
class SelectInterruptEventFd final : public SelectInterrupt { class SelectInterruptEventFd final : public SelectInterrupt
{
public: public:
SelectInterruptEventFd(); SelectInterruptEventFd();
virtual ~SelectInterruptEventFd(); virtual ~SelectInterruptEventFd();
@ -28,5 +28,4 @@ namespace ix
private: private:
int _eventfd; int _eventfd;
}; };
} } // namespace ix

View File

@ -12,4 +12,4 @@ namespace ix
{ {
class SelectInterrupt; class SelectInterrupt;
std::shared_ptr<SelectInterrupt> createSelectInterrupt(); std::shared_ptr<SelectInterrupt> createSelectInterrupt();
} } // namespace ix

View File

@ -7,14 +7,14 @@
#pragma once #pragma once
#include "IXSelectInterrupt.h" #include "IXSelectInterrupt.h"
#include <mutex>
#include <stdint.h> #include <stdint.h>
#include <string> #include <string>
#include <mutex>
namespace ix namespace ix
{ {
class SelectInterruptPipe final : public SelectInterrupt { class SelectInterruptPipe final : public SelectInterrupt
{
public: public:
SelectInterruptPipe(); SelectInterruptPipe();
virtual ~SelectInterruptPipe(); virtual ~SelectInterruptPipe();
@ -37,5 +37,4 @@ namespace ix
static const int kPipeReadIndex; static const int kPipeReadIndex;
static const int kPipeWriteIndex; static const int kPipeWriteIndex;
}; };
} } // namespace ix

View File

@ -10,4 +10,3 @@ namespace ix
{ {
void setThreadName(const std::string& name); void setThreadName(const std::string& name);
} }

View File

@ -6,12 +6,12 @@
#pragma once #pragma once
#include <string>
#include <functional>
#include <mutex>
#include <atomic> #include <atomic>
#include <vector> #include <functional>
#include <memory> #include <memory>
#include <mutex>
#include <string>
#include <vector>
#ifdef _WIN32 #ifdef _WIN32
#include <BaseTsd.h> #include <BaseTsd.h>
@ -24,11 +24,11 @@ typedef SSIZE_T ssize_t;
#undef EINVAL #undef EINVAL
// map to WSA error codes // map to WSA error codes
#define EWOULDBLOCK WSAEWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK
#define EAGAIN WSATRY_AGAIN #define EAGAIN WSATRY_AGAIN
#define EINPROGRESS WSAEINPROGRESS #define EINPROGRESS WSAEINPROGRESS
#define EBADF WSAEBADF #define EBADF WSAEBADF
#define EINVAL WSAEINVAL #define EINVAL WSAEINVAL
#endif #endif
@ -41,15 +41,16 @@ namespace ix
enum class PollResultType enum class PollResultType
{ {
ReadyForRead = 0, ReadyForRead = 0,
ReadyForWrite = 1, ReadyForWrite = 1,
Timeout = 2, Timeout = 2,
Error = 3, Error = 3,
SendRequest = 4, SendRequest = 4,
CloseRequest = 5 CloseRequest = 5
}; };
class Socket { class Socket
{
public: public:
Socket(int fd = -1); Socket(int fd = -1);
virtual ~Socket(); virtual ~Socket();
@ -75,17 +76,13 @@ namespace ix
// Blocking and cancellable versions, working with socket that can be set // Blocking and cancellable versions, working with socket that can be set
// to non blocking mode. Used during HTTP upgrade. // to non blocking mode. Used during HTTP upgrade.
bool readByte(void* buffer, bool readByte(void* buffer, const CancellationRequest& isCancellationRequested);
const CancellationRequest& isCancellationRequested); bool writeBytes(const std::string& str, const CancellationRequest& isCancellationRequested);
bool writeBytes(const std::string& str,
const CancellationRequest& isCancellationRequested);
std::pair<bool, std::string> readLine( std::pair<bool, std::string> readLine(const CancellationRequest& isCancellationRequested);
const CancellationRequest& isCancellationRequested); std::pair<bool, std::string> readBytes(size_t length,
std::pair<bool, std::string> readBytes( const OnProgressCallback& onProgressCallback,
size_t length, const CancellationRequest& isCancellationRequested);
const OnProgressCallback& onProgressCallback,
const CancellationRequest& isCancellationRequested);
static int getErrno(); static int getErrno();
static bool isWaitNeeded(); static bool isWaitNeeded();
@ -111,4 +108,4 @@ namespace ix
std::shared_ptr<SelectInterrupt> _selectInterrupt; std::shared_ptr<SelectInterrupt> _selectInterrupt;
}; };
} } // namespace ix

View File

@ -6,12 +6,10 @@
#pragma once #pragma once
#include "IXSocket.h"
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include "IXSocket.h"
#include <Security/Security.h>
#include <Security/SecureTransport.h> #include <Security/SecureTransport.h>
#include <Security/Security.h>
#include <mutex> #include <mutex>
namespace ix namespace ix
@ -34,7 +32,7 @@ namespace ix
private: private:
SSLContextRef _sslContext; SSLContextRef _sslContext;
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe mutable std::mutex _mutex; // AppleSSL routines are not thread-safe
}; };
} } // namespace ix

View File

@ -7,14 +7,14 @@
#pragma once #pragma once
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include <string> #include <string>
struct addrinfo; struct addrinfo;
namespace ix namespace ix
{ {
class SocketConnect { class SocketConnect
{
public: public:
static int connect(const std::string& hostname, static int connect(const std::string& hostname,
int port, int port,
@ -24,9 +24,8 @@ namespace ix
static void configure(int sockfd); static void configure(int sockfd);
private: private:
static int connectToAddress(const struct addrinfo *address, static int connectToAddress(const struct addrinfo* address,
std::string& errMsg, std::string& errMsg,
const CancellationRequest& isCancellationRequested); const CancellationRequest& isCancellationRequested);
}; };
} } // namespace ix

View File

@ -13,9 +13,7 @@
namespace ix namespace ix
{ {
class Socket; class Socket;
std::shared_ptr<Socket> createSocket(bool tls, std::shared_ptr<Socket> createSocket(bool tls, std::string& errorMsg);
std::string& errorMsg);
std::shared_ptr<Socket> createSocket(int fd, std::shared_ptr<Socket> createSocket(int fd, std::string& errorMsg);
std::string& errorMsg); } // namespace ix
}

View File

@ -6,17 +6,15 @@
#pragma once #pragma once
#include "IXSocket.h"
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include "IXSocket.h"
#include <mutex>
#include <openssl/bio.h> #include <openssl/bio.h>
#include <openssl/hmac.h>
#include <openssl/conf.h> #include <openssl/conf.h>
#include <openssl/err.h> #include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/ssl.h> #include <openssl/ssl.h>
#include <mutex>
namespace ix namespace ix
{ {
class SocketOpenSSL final : public Socket class SocketOpenSSL final : public Socket
@ -40,18 +38,16 @@ namespace ix
std::string getSSLError(int ret); std::string getSSLError(int ret);
SSL_CTX* openSSLCreateContext(std::string& errMsg); SSL_CTX* openSSLCreateContext(std::string& errMsg);
bool openSSLHandshake(const std::string& hostname, std::string& errMsg); bool openSSLHandshake(const std::string& hostname, std::string& errMsg);
bool openSSLCheckServerCert(SSL *ssl, bool openSSLCheckServerCert(SSL* ssl, const std::string& hostname, std::string& errMsg);
const std::string& hostname, bool checkHost(const std::string& host, const char* pattern);
std::string& errMsg);
bool checkHost(const std::string& host, const char *pattern);
SSL* _ssl_connection; SSL* _ssl_connection;
SSL_CTX* _ssl_context; SSL_CTX* _ssl_context;
const SSL_METHOD* _ssl_method; const SSL_METHOD* _ssl_method;
mutable std::mutex _mutex; // OpenSSL routines are not thread-safe mutable std::mutex _mutex; // OpenSSL routines are not thread-safe
static std::once_flag _openSSLInitFlag; static std::once_flag _openSSLInitFlag;
static std::atomic<bool> _openSSLInitializationSuccessful; static std::atomic<bool> _openSSLInitializationSuccessful;
}; };
} } // namespace ix

View File

@ -16,9 +16,7 @@ namespace ix
SocketSChannel(); SocketSChannel();
~SocketSChannel(); ~SocketSChannel();
virtual bool connect(const std::string& host, virtual bool connect(const std::string& host, int port, std::string& errMsg) final;
int port,
std::string& errMsg) final;
virtual void close() final; virtual void close() final;
// The important override // The important override
@ -31,4 +29,4 @@ namespace ix
private: private:
}; };
} } // namespace ix

View File

@ -7,28 +7,28 @@
#pragma once #pragma once
#include "IXConnectionState.h" #include "IXConnectionState.h"
#include <utility> // pair
#include <string>
#include <set>
#include <thread>
#include <list>
#include <mutex>
#include <functional>
#include <memory>
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <utility> // pair
namespace ix namespace ix
{ {
class SocketServer { class SocketServer
{
public: public:
using ConnectionStateFactory = std::function<std::shared_ptr<ConnectionState>()>; using ConnectionStateFactory = std::function<std::shared_ptr<ConnectionState>()>;
// Each connection is handled by its own worker thread. // Each connection is handled by its own worker thread.
// We use a list as we only care about remove and append operations. // We use a list as we only care about remove and append operations.
using ConnectionThreads = std::list<std::pair<std::shared_ptr<ConnectionState>, using ConnectionThreads =
std::thread>>; std::list<std::pair<std::shared_ptr<ConnectionState>, std::thread>>;
SocketServer(int port = SocketServer::kDefaultPort, SocketServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
@ -52,7 +52,6 @@ namespace ix
void wait(); void wait();
protected: protected:
// Logging // Logging
void logError(const std::string& str); void logError(const std::string& str);
void logInfo(const std::string& str); void logInfo(const std::string& str);
@ -93,12 +92,11 @@ namespace ix
// the factory to create ConnectionState objects // the factory to create ConnectionState objects
ConnectionStateFactory _connectionStateFactory; ConnectionStateFactory _connectionStateFactory;
virtual void handleConnection(int fd, virtual void handleConnection(int fd, std::shared_ptr<ConnectionState> connectionState) = 0;
std::shared_ptr<ConnectionState> connectionState) = 0;
virtual size_t getConnectedClientsCount() = 0; virtual size_t getConnectedClientsCount() = 0;
// Returns true if all connection threads are joined // Returns true if all connection threads are joined
void closeTerminatedThreads(); void closeTerminatedThreads();
size_t getConnectionsThreadsCount(); size_t getConnectionsThreadsCount();
}; };
} } // namespace ix

View File

@ -20,4 +20,4 @@ namespace ix
std::string& query, std::string& query,
int& port); int& port);
}; };
} } // namespace ix

View File

@ -9,39 +9,38 @@
#pragma once #pragma once
#include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h"
#include "IXWebSocketErrorInfo.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketTransport.h"
#include <atomic>
#include <mutex>
#include <string> #include <string>
#include <thread> #include <thread>
#include <mutex>
#include <atomic>
#include "IXWebSocketTransport.h"
#include "IXWebSocketErrorInfo.h"
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketCloseConstants.h"
#include "IXProgressCallback.h"
namespace ix namespace ix
{ {
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Ready_state_constants // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Ready_state_constants
enum class ReadyState enum class ReadyState
{ {
Connecting = 0, Connecting = 0,
Open = 1, Open = 1,
Closing = 2, Closing = 2,
Closed = 3 Closed = 3
}; };
enum class WebSocketMessageType enum class WebSocketMessageType
{ {
Message = 0, Message = 0,
Open = 1, Open = 1,
Close = 2, Close = 2,
Error = 3, Error = 3,
Ping = 4, Ping = 4,
Pong = 5, Pong = 5,
Fragment = 6 Fragment = 6
}; };
struct WebSocketOpenInfo struct WebSocketOpenInfo
@ -64,9 +63,7 @@ namespace ix
std::string reason; std::string reason;
bool remote; bool remote;
WebSocketCloseInfo(uint16_t c = 0, WebSocketCloseInfo(uint16_t c = 0, const std::string& r = std::string(), bool rem = false)
const std::string& r = std::string(),
bool rem = false)
: code(c) : code(c)
, reason(r) , reason(r)
, remote(rem) , remote(rem)
@ -91,7 +88,8 @@ namespace ix
~WebSocket(); ~WebSocket();
void setUrl(const std::string& url); void setUrl(const std::string& url);
void setPerMessageDeflateOptions(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions); void setPerMessageDeflateOptions(
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
void setHeartBeatPeriod(int heartBeatPeriodSecs); void setHeartBeatPeriod(int heartBeatPeriodSecs);
void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod
void setPingTimeout(int pingTimeoutSecs); void setPingTimeout(int pingTimeoutSecs);
@ -116,8 +114,7 @@ namespace ix
const OnProgressCallback& onProgressCallback = nullptr); const OnProgressCallback& onProgressCallback = nullptr);
WebSocketSendInfo ping(const std::string& text); WebSocketSendInfo ping(const std::string& text);
void close(uint16_t code = 1000, void close(uint16_t code = 1000, const std::string& reason = "Normal closure");
const std::string& reason = "Normal closure");
void setOnMessageCallback(const OnMessageCallback& callback); void setOnMessageCallback(const OnMessageCallback& callback);
static void setTrafficTrackerCallback(const OnTrafficTrackerCallback& callback); static void setTrafficTrackerCallback(const OnTrafficTrackerCallback& callback);
@ -138,7 +135,6 @@ namespace ix
bool isAutomaticReconnectionEnabled() const; bool isAutomaticReconnectionEnabled() const;
private: private:
WebSocketSendInfo sendMessage(const std::string& text, WebSocketSendInfo sendMessage(const std::string& text,
SendMessageKind sendMessageKind, SendMessageKind sendMessageKind,
const OnProgressCallback& callback = nullptr); const OnProgressCallback& callback = nullptr);
@ -180,4 +176,4 @@ namespace ix
friend class WebSocketServer; friend class WebSocketServer;
}; };
} } // namespace ix

View File

@ -26,4 +26,4 @@ namespace ix
static const std::string kProtocolErrorMessage; static const std::string kProtocolErrorMessage;
static const std::string kNoStatusCodeErrorMessage; static const std::string kNoStatusCodeErrorMessage;
}; };
} } // namespace ix

View File

@ -18,4 +18,4 @@ namespace ix
std::string reason; std::string reason;
bool decompressionError = false; bool decompressionError = false;
}; };
} } // namespace ix

View File

@ -7,15 +7,14 @@
#pragma once #pragma once
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include "IXSocket.h"
#include "IXWebSocketHttpHeaders.h" #include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflate.h" #include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h" #include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXSocket.h"
#include <string>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <memory> #include <memory>
#include <string>
#include <tuple> #include <tuple>
namespace ix namespace ix
@ -42,7 +41,8 @@ namespace ix
} }
}; };
class WebSocketHandshake { class WebSocketHandshake
{
public: public:
WebSocketHandshake(std::atomic<bool>& requestInitCancellation, WebSocketHandshake(std::atomic<bool>& requestInitCancellation,
std::shared_ptr<Socket> _socket, std::shared_ptr<Socket> _socket,
@ -56,8 +56,7 @@ namespace ix
int port, int port,
int timeoutSecs); int timeoutSecs);
WebSocketInitResult serverHandshake(int fd, WebSocketInitResult serverHandshake(int fd, int timeoutSecs);
int timeoutSecs);
private: private:
std::string genRandomString(const int len); std::string genRandomString(const int len);
@ -75,4 +74,4 @@ namespace ix
WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions; WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions;
std::atomic<bool>& _enablePerMessageDeflate; std::atomic<bool>& _enablePerMessageDeflate;
}; };
} } // namespace ix

View File

@ -7,10 +7,9 @@
#pragma once #pragma once
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include <string>
#include <map> #include <map>
#include <memory> #include <memory>
#include <string>
namespace ix namespace ix
{ {
@ -21,15 +20,14 @@ namespace ix
// Case Insensitive compare_less binary function // Case Insensitive compare_less binary function
struct NocaseCompare struct NocaseCompare
{ {
bool operator() (const unsigned char& c1, const unsigned char& c2) const; bool operator()(const unsigned char& c1, const unsigned char& c2) const;
}; };
bool operator() (const std::string & s1, const std::string & s2) const; bool operator()(const std::string& s1, const std::string& s2) const;
}; };
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, std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested);
const CancellationRequest& isCancellationRequested); } // namespace ix
}

View File

@ -7,9 +7,9 @@
#pragma once #pragma once
#include "IXWebSocket.h" #include "IXWebSocket.h"
#include <thread>
#include <list> #include <list>
#include <memory> #include <memory>
#include <thread>
namespace ix namespace ix
{ {
@ -50,4 +50,4 @@ namespace ix
std::mutex _messagesMutex; std::mutex _messagesMutex;
std::list<MessagePtr> _messages; std::list<MessagePtr> _messages;
}; };
} } // namespace ix

View File

@ -34,8 +34,8 @@
#pragma once #pragma once
#include <string>
#include <memory> #include <memory>
#include <string>
namespace ix namespace ix
{ {
@ -57,4 +57,4 @@ namespace ix
std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor; std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor;
std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor; std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor;
}; };
} } // namespace ix

View File

@ -7,8 +7,8 @@
#pragma once #pragma once
#include "zlib.h" #include "zlib.h"
#include <string>
#include <memory> #include <memory>
#include <string>
namespace ix namespace ix
{ {
@ -46,5 +46,4 @@ namespace ix
z_stream _inflateState; z_stream _inflateState;
}; };
} } // namespace ix

View File

@ -42,4 +42,4 @@ namespace ix
int _clientMaxWindowBits; int _clientMaxWindowBits;
int _serverMaxWindowBits; int _serverMaxWindowBits;
}; };
} } // namespace ix

View File

@ -15,8 +15,7 @@ namespace ix
size_t payloadSize; size_t payloadSize;
size_t wireSize; size_t wireSize;
WebSocketSendInfo(bool s = false, bool c = false, WebSocketSendInfo(bool s = false, bool c = false, size_t p = 0, size_t w = 0)
size_t p = 0, size_t w = 0)
: success(s) : success(s)
, compressionError(c) , compressionError(c)
, payloadSize(p) , payloadSize(p)
@ -25,4 +24,4 @@ namespace ix
; ;
} }
}; };
} } // namespace ix

View File

@ -6,24 +6,24 @@
#pragma once #pragma once
#include <utility> // pair #include "IXSocketServer.h"
#include <string> #include "IXWebSocket.h"
#include <set> #include <condition_variable>
#include <thread>
#include <mutex>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <condition_variable> #include <mutex>
#include <set>
#include "IXWebSocket.h" #include <string>
#include "IXSocketServer.h" #include <thread>
#include <utility> // pair
namespace ix namespace ix
{ {
using OnConnectionCallback = std::function<void(std::shared_ptr<WebSocket>, using OnConnectionCallback =
std::shared_ptr<ConnectionState>)>; std::function<void(std::shared_ptr<WebSocket>, std::shared_ptr<ConnectionState>)>;
class WebSocketServer final : public SocketServer { class WebSocketServer final : public SocketServer
{
public: public:
WebSocketServer(int port = SocketServer::kDefaultPort, WebSocketServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost, const std::string& host = SocketServer::kDefaultHost,
@ -59,4 +59,4 @@ namespace ix
std::shared_ptr<ConnectionState> connectionState) final; std::shared_ptr<ConnectionState> connectionState) final;
virtual size_t getConnectedClientsCount() final; virtual size_t getConnectedClientsCount() final;
}; };
} } // namespace ix

View File

@ -10,22 +10,21 @@
// Adapted from https://github.com/dhbaird/easywsclient // Adapted from https://github.com/dhbaird/easywsclient
// //
#include <string>
#include <vector>
#include <functional>
#include <memory>
#include <mutex>
#include <atomic>
#include <list>
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXCancellationRequest.h" #include "IXCancellationRequest.h"
#include "IXWebSocketHandshake.h"
#include "IXProgressCallback.h" #include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h" #include "IXWebSocketCloseConstants.h"
#include "IXWebSocketHandshake.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketSendInfo.h"
#include <atomic>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace ix namespace ix
{ {
@ -63,14 +62,9 @@ namespace ix
AbnormalClose AbnormalClose
}; };
using OnMessageCallback = std::function<void(const std::string&, using OnMessageCallback =
size_t, std::function<void(const std::string&, size_t, bool, MessageKind)>;
bool, using OnCloseCallback = std::function<void(uint16_t, const std::string&, size_t, bool)>;
MessageKind)>;
using OnCloseCallback = std::function<void(uint16_t,
const std::string&,
size_t,
bool)>;
WebSocketTransport(); WebSocketTransport();
~WebSocketTransport(); ~WebSocketTransport();
@ -82,7 +76,7 @@ namespace ix
WebSocketInitResult connectToUrl(const std::string& url, // Client WebSocketInitResult connectToUrl(const std::string& url, // Client
int timeoutSecs); int timeoutSecs);
WebSocketInitResult connectToSocket(int fd, // Server WebSocketInitResult connectToSocket(int fd, // Server
int timeoutSecs); int timeoutSecs);
PollResult poll(); PollResult poll();
@ -103,25 +97,26 @@ namespace ix
ReadyState getReadyState() const; ReadyState getReadyState() const;
void setReadyState(ReadyState readyState); void setReadyState(ReadyState readyState);
void setOnCloseCallback(const OnCloseCallback& onCloseCallback); void setOnCloseCallback(const OnCloseCallback& onCloseCallback);
void dispatch(PollResult pollResult, void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback);
const OnMessageCallback& onMessageCallback);
size_t bufferedAmount() const; size_t bufferedAmount() const;
private: private:
std::string _url; std::string _url;
struct wsheader_type { struct wsheader_type
{
unsigned header_size; unsigned header_size;
bool fin; bool fin;
bool rsv1; bool rsv1;
bool mask; bool mask;
enum opcode_type { enum opcode_type
{
CONTINUATION = 0x0, CONTINUATION = 0x0,
TEXT_FRAME = 0x1, TEXT_FRAME = 0x1,
BINARY_FRAME = 0x2, BINARY_FRAME = 0x2,
CLOSE = 8, CLOSE = 8,
PING = 9, PING = 9,
PONG = 0xa, PONG = 0xa,
} opcode; } opcode;
int N0; int N0;
uint64_t N; uint64_t N;
@ -176,7 +171,7 @@ namespace ix
std::atomic<bool> _requestInitCancellation; std::atomic<bool> _requestInitCancellation;
mutable std::mutex _closingTimePointMutex; mutable std::mutex _closingTimePointMutex;
std::chrono::time_point<std::chrono::steady_clock>_closingTimePoint; std::chrono::time_point<std::chrono::steady_clock> _closingTimePoint;
static const int kClosingMaximumWaitingDelayInMs; static const int kClosingMaximumWaitingDelayInMs;
// enable auto response to ping // enable auto response to ping
@ -211,7 +206,8 @@ namespace ix
// No PONG data was received through the socket for longer than ping timeout delay // No PONG data was received through the socket for longer than ping timeout delay
bool pingTimeoutExceeded(); bool pingTimeoutExceeded();
// after calling close(), if no CLOSE frame answer is received back from the remote, we should close the connexion // after calling close(), if no CLOSE frame answer is received back from the remote, we
// should close the connexion
bool closingDelayExceeded(); bool closingDelayExceeded();
void initTimePointsAndGCDAfterConnect(); void initTimePointsAndGCDAfterConnect();
@ -252,4 +248,4 @@ namespace ix
std::string getMergedChunks() const; std::string getMergedChunks() const;
}; };
} } // namespace ix

View File

@ -31,48 +31,54 @@
namespace LUrlParser namespace LUrlParser
{ {
enum LUrlParserError enum LUrlParserError
{ {
LUrlParserError_Ok = 0, LUrlParserError_Ok = 0,
LUrlParserError_Uninitialized = 1, LUrlParserError_Uninitialized = 1,
LUrlParserError_NoUrlCharacter = 2, LUrlParserError_NoUrlCharacter = 2,
LUrlParserError_InvalidSchemeName = 3, LUrlParserError_InvalidSchemeName = 3,
LUrlParserError_NoDoubleSlash = 4, LUrlParserError_NoDoubleSlash = 4,
LUrlParserError_NoAtSign = 5, LUrlParserError_NoAtSign = 5,
LUrlParserError_UnexpectedEndOfLine = 6, LUrlParserError_UnexpectedEndOfLine = 6,
LUrlParserError_NoSlash = 7, LUrlParserError_NoSlash = 7,
}; };
class clParseURL class clParseURL
{ {
public: public:
LUrlParserError m_ErrorCode; LUrlParserError m_ErrorCode;
std::string m_Scheme; std::string m_Scheme;
std::string m_Host; std::string m_Host;
std::string m_Port; std::string m_Port;
std::string m_Path; std::string m_Path;
std::string m_Query; std::string m_Query;
std::string m_Fragment; std::string m_Fragment;
std::string m_UserName; std::string m_UserName;
std::string m_Password; std::string m_Password;
clParseURL() clParseURL()
: m_ErrorCode( LUrlParserError_Uninitialized ) : m_ErrorCode(LUrlParserError_Uninitialized)
{} {
}
/// return 'true' if the parsing was successful /// return 'true' if the parsing was successful
bool IsValid() const { return m_ErrorCode == LUrlParserError_Ok; } bool IsValid() const
{
return m_ErrorCode == LUrlParserError_Ok;
}
/// helper to convert the port number to int, return 'true' if the port is valid (within the 0..65535 range) /// helper to convert the port number to int, return 'true' if the port is valid (within the
bool GetPort( int* OutPort ) const; /// 0..65535 range)
bool GetPort(int* OutPort) const;
/// parse the URL /// parse the URL
static clParseURL ParseURL( const std::string& URL ); static clParseURL ParseURL(const std::string& URL);
private: private:
explicit clParseURL( LUrlParserError ErrorCode ) explicit clParseURL(LUrlParserError ErrorCode)
: m_ErrorCode( ErrorCode ) : m_ErrorCode(ErrorCode)
{} {
}; }
};
} // namespace LUrlParser } // namespace LUrlParser

View File

@ -40,6 +40,9 @@ run:
trail: trail:
sh third_party/remote_trailing_whitespaces.sh sh third_party/remote_trailing_whitespaces.sh
format:
sh third_party/indent.sh
# That target is used to start a node server, but isn't required as we have # That target is used to start a node server, but isn't required as we have
# a builtin C++ server started in the unittest now # a builtin C++ server started in the unittest now
test_server: test_server:

View File

@ -6,14 +6,15 @@
#pragma once #pragma once
#include <memory>
#include <functional> #include <functional>
#include <memory>
namespace ix namespace ix
{ {
class Socket; class Socket;
class RedisClient { class RedisClient
{
public: public:
using OnRedisSubscribeResponseCallback = std::function<void(const std::string&)>; using OnRedisSubscribeResponseCallback = std::function<void(const std::string&)>;
using OnRedisSubscribeCallback = std::function<void(const std::string&)>; using OnRedisSubscribeCallback = std::function<void(const std::string&)>;
@ -21,15 +22,11 @@ namespace ix
RedisClient() = default; RedisClient() = default;
~RedisClient() = default; ~RedisClient() = default;
bool connect(const std::string& hostname, bool connect(const std::string& hostname, int port);
int port);
bool auth(const std::string& password, bool auth(const std::string& password, std::string& response);
std::string& response);
bool publish(const std::string& channel, bool publish(const std::string& channel, const std::string& message, std::string& errMsg);
const std::string& message,
std::string& errMsg);
bool subscribe(const std::string& channel, bool subscribe(const std::string& channel,
const OnRedisSubscribeResponseCallback& responseCallback, const OnRedisSubscribeResponseCallback& responseCallback,
@ -40,5 +37,4 @@ namespace ix
std::shared_ptr<Socket> _socket; std::shared_ptr<Socket> _socket;
}; };
} } // namespace ix

View File

@ -6,11 +6,10 @@
#pragma once #pragma once
#include <ixwebsocket/IXHttpClient.h>
#include <jsoncpp/json/json.h> #include <jsoncpp/json/json.h>
#include <regex> #include <regex>
#include <ixwebsocket/IXHttpClient.h>
namespace ix namespace ix
{ {
class SentryClient class SentryClient

View File

@ -6,16 +6,15 @@
#pragma once #pragma once
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
#include <jsoncpp/json/json.h>
#include <memory>
#include <mutex> #include <mutex>
#include <queue> #include <queue>
#include <string> #include <string>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
#include <memory>
#include <jsoncpp/json/json.h>
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
namespace ix namespace ix
{ {
@ -72,8 +71,7 @@ namespace ix
/// Publish a message to a channel /// Publish a message to a channel
/// ///
/// No-op if the connection is not established /// No-op if the connection is not established
bool publish(const Json::Value& channels, bool publish(const Json::Value& channels, const Json::Value& msg);
const Json::Value& msg);
// Subscribe to a channel, and execute a callback when an incoming // Subscribe to a channel, and execute a callback when an incoming
// message arrives. // message arrives.
@ -126,8 +124,7 @@ namespace ix
const std::string& errorMsg = std::string(), const std::string& errorMsg = std::string(),
const WebSocketHttpHeaders& headers = WebSocketHttpHeaders(), const WebSocketHttpHeaders& headers = WebSocketHttpHeaders(),
const std::string& subscriptionId = std::string()); const std::string& subscriptionId = std::string());
void invokeErrorCallback(const std::string& errorMsg, void invokeErrorCallback(const std::string& errorMsg, const std::string& serializedPdu);
const std::string& serializedPdu);
/// ///
/// Member variables /// Member variables

View File

@ -7,12 +7,10 @@
#pragma once #pragma once
#include "IXCobraMetricsThreadedPublisher.h" #include "IXCobraMetricsThreadedPublisher.h"
#include <chrono>
#include <jsoncpp/json/json.h> #include <jsoncpp/json/json.h>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <chrono>
namespace ix namespace ix
{ {
@ -28,10 +26,11 @@ namespace ix
/// to make shouldPush as fast as possible. _enabled default to false. /// to make shouldPush as fast as possible. _enabled default to false.
/// ///
/// The code that set those is ran only once at init, and /// The code that set those is ran only once at init, and
/// the last value to be set is _enabled, which is also the first value checked in shouldPush, /// the last value to be set is _enabled, which is also the first value checked in
/// so there shouldn't be any race condition. /// shouldPush, so there shouldn't be any race condition.
/// ///
/// 2. The queue of messages is thread safe, so multiple metrics can be safely pushed on multiple threads /// 2. The queue of messages is thread safe, so multiple metrics can be safely pushed on
/// multiple threads
/// ///
/// 3. Access to _last_update is protected as it needs to be read/write. /// 3. Access to _last_update is protected as it needs to be read/write.
/// ///
@ -62,40 +61,44 @@ namespace ix
void push(const std::string& id, void push(const std::string& id,
const CobraMetricsPublisher::Message& data = CobraMetricsPublisher::Message()); const CobraMetricsPublisher::Message& data = CobraMetricsPublisher::Message());
/// Richer interface using json, which supports types (bool, int, float) and hierarchies of elements /// Richer interface using json, which supports types (bool, int, float) and hierarchies of
/// elements
/// ///
/// The shouldPushTest argument should be set to false, and used in combination with the shouldPush method /// The shouldPushTest argument should be set to false, and used in combination with the
/// for places where we want to be as lightweight as possible when collecting metrics. When set to false, /// shouldPush method for places where we want to be as lightweight as possible when
/// it is used so that we don't do double work when computing whether a metrics should be sent or not. /// collecting metrics. When set to false, it is used so that we don't do double work when
void push(const std::string& id, /// computing whether a metrics should be sent or not.
const Json::Value& data, void push(const std::string& id, const Json::Value& data, bool shouldPushTest = true);
bool shouldPushTest = true);
/// Interface used by lua. msg is a json encoded string. /// Interface used by lua. msg is a json encoded string.
void push(const std::string& id, void push(const std::string& id, const std::string& data, bool shouldPushTest = true);
const std::string& data,
bool shouldPushTest = true);
/// Tells whether a metric can be pushed. /// Tells whether a metric can be pushed.
/// A metric can be pushed if it satisfies those conditions: /// A metric can be pushed if it satisfies those conditions:
/// ///
/// 1. the metrics system should be enabled /// 1. the metrics system should be enabled
/// 2. the metrics shouldn't be black-listed /// 2. the metrics shouldn't be black-listed
/// 3. the metrics shouldn't have reached its rate control limit at this "sampling"/"calling" time /// 3. the metrics shouldn't have reached its rate control limit at this
/// "sampling"/"calling" time
bool shouldPush(const std::string& id) const; bool shouldPush(const std::string& id) const;
/// Get generic information json object /// Get generic information json object
Json::Value& getGenericAttributes(); Json::Value& getGenericAttributes();
/// Set generic information values /// Set generic information values
void setGenericAttributes(const std::string& attrName, void setGenericAttributes(const std::string& attrName, const Json::Value& value);
const Json::Value& value);
/// Set a unique id for the session. A uuid can be used. /// Set a unique id for the session. A uuid can be used.
void setSession(const std::string& session) { _session = session; } void setSession(const std::string& session)
{
_session = session;
}
/// Get the unique id used to identify the current session /// Get the unique id used to identify the current session
const std::string& getSession() const { return _session; } const std::string& getSession() const
{
return _session;
}
/// Return the number of milliseconds since the epoch (~1970) /// Return the number of milliseconds since the epoch (~1970)
uint64_t getMillisecondsSinceEpoch() const; uint64_t getMillisecondsSinceEpoch() const;
@ -117,7 +120,6 @@ namespace ix
bool isAuthenticated() const; bool isAuthenticated() const;
private: private:
/// Lookup an id in our metrics to see whether it is blacklisted /// Lookup an id in our metrics to see whether it is blacklisted
/// Complexity is logarithmic /// Complexity is logarithmic
bool isMetricBlacklisted(const std::string& id) const; bool isMetricBlacklisted(const std::string& id) const;
@ -150,15 +152,16 @@ namespace ix
/// Metrics control (black list + rate control) /// Metrics control (black list + rate control)
std::vector<std::string> _blacklist; std::vector<std::string> _blacklist;
std::unordered_map<std::string, int> _rate_control; std::unordered_map<std::string, int> _rate_control;
std::unordered_map<std::string, std::chrono::time_point<std::chrono::steady_clock>> _last_update; std::unordered_map<std::string, std::chrono::time_point<std::chrono::steady_clock>>
_last_update;
mutable std::mutex _last_update_mutex; // protect access to _last_update mutable std::mutex _last_update_mutex; // protect access to _last_update
// const strings for internal ids // const strings for internal ids
static const std::string kSetRateControlId; static const std::string kSetRateControlId;
static const std::string kSetBlacklistId; static const std::string kSetBlacklistId;
/// Our protocol version. Can be used by subscribers who would want to be backward compatible /// Our protocol version. Can be used by subscribers who would want to be backward
/// if we change the way we arrange data /// compatible if we change the way we arrange data
static const int kVersion; static const int kVersion;
}; };

View File

@ -7,16 +7,14 @@
#pragma once #pragma once
#include "IXCobraConnection.h" #include "IXCobraConnection.h"
#include <jsoncpp/json/json.h>
#include <string>
#include <queue>
#include <mutex>
#include <thread>
#include <map>
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <jsoncpp/json/json.h>
#include <map>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
namespace ix namespace ix
{ {
@ -67,8 +65,7 @@ namespace ix
}; };
/// Push a message to be processed by the background thread /// Push a message to be processed by the background thread
void pushMessage(MessageKind messageKind, void pushMessage(MessageKind messageKind, const Json::Value& msg);
const Json::Value& msg);
/// Get a wait time which is increasing exponentially based on the number of retries /// Get a wait time which is increasing exponentially based on the number of retries
uint64_t getWaitTimeExp(int retry_count); uint64_t getWaitTimeExp(int retry_count);

View File

@ -3,20 +3,19 @@
namespace ix namespace ix
{ {
class IXCoreLogger
{
public:
using LogFunc = std::function<void(const char*)>;
static void Log(const char* msg);
class IXCoreLogger static void setLogFunction(LogFunc& func)
{ {
public: _currentLogger = func;
using LogFunc = std::function<void(const char*)>; }
static void Log(const char* msg);
static void setLogFunction(LogFunc& func) { private:
_currentLogger = func; static LogFunc _currentLogger;
} };
private: } // namespace ix
static LogFunc _currentLogger;
};
} // ix

View File

@ -12,4 +12,4 @@ namespace ix
{ {
std::string base64_encode(const std::string& data, size_t len); std::string base64_encode(const std::string& data, size_t len);
std::string base64_decode(const std::string& encoded_string); std::string base64_decode(const std::string& encoded_string);
} } // namespace ix

View File

@ -13,4 +13,3 @@ namespace ix
{ {
uint64_t djb2Hash(const std::vector<uint8_t>& data); uint64_t djb2Hash(const std::vector<uint8_t>& data);
} }

View File

@ -9,9 +9,9 @@
namespace ix namespace ix
{ {
/** /**
* Generate a random uuid * Generate a random uuid
*/ */
std::string uuid4(); std::string uuid4();
} } // namespace ix

View File

@ -6,11 +6,10 @@
#pragma once #pragma once
#include "nlohmann/json.hpp"
#include <string> #include <string>
#include <vector> #include <vector>
#include "nlohmann/json.hpp"
namespace snake namespace snake
{ {
struct AppConfig struct AppConfig
@ -31,16 +30,11 @@ namespace snake
bool verbose; bool verbose;
}; };
bool isAppKeyValid( bool isAppKeyValid(const AppConfig& appConfig, std::string appkey);
const AppConfig& appConfig,
std::string appkey);
std::string getRoleSecret( std::string getRoleSecret(const AppConfig& appConfig, std::string appkey, std::string role);
const AppConfig& appConfig,
std::string appkey,
std::string role);
std::string generateNonce(); std::string generateNonce();
void dumpConfig(const AppConfig& appConfig); void dumpConfig(const AppConfig& appConfig);
} } // namespace snake

View File

@ -6,27 +6,47 @@
#pragma once #pragma once
#include <string>
#include <future>
#include <ixwebsocket/IXConnectionState.h>
#include "IXRedisClient.h" #include "IXRedisClient.h"
#include <future>
#include <ixwebsocket/IXConnectionState.h>
#include <string>
namespace snake namespace snake
{ {
class SnakeConnectionState : public ix::ConnectionState class SnakeConnectionState : public ix::ConnectionState
{ {
public: public:
std::string getNonce() { return _nonce; } std::string getNonce()
void setNonce(const std::string& nonce) { _nonce = nonce; } {
return _nonce;
}
void setNonce(const std::string& nonce)
{
_nonce = nonce;
}
std::string appkey() { return _appkey; } std::string appkey()
void setAppkey(const std::string& appkey) { _appkey = appkey; } {
return _appkey;
}
void setAppkey(const std::string& appkey)
{
_appkey = appkey;
}
std::string role() { return _role; } std::string role()
void setRole(const std::string& role) { _role = role; } {
return _role;
}
void setRole(const std::string& role)
{
_role = role;
}
ix::RedisClient& redisClient() { return _redisClient; } ix::RedisClient& redisClient()
{
return _redisClient;
}
std::future<void> fut; std::future<void> fut;
@ -37,4 +57,4 @@ namespace snake
ix::RedisClient _redisClient; ix::RedisClient _redisClient;
}; };
} } // namespace snake

View File

@ -18,9 +18,8 @@ namespace snake
class SnakeConnectionState; class SnakeConnectionState;
struct AppConfig; struct AppConfig;
void processCobraMessage( void processCobraMessage(std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<SnakeConnectionState> state, std::shared_ptr<ix::WebSocket> ws,
std::shared_ptr<ix::WebSocket> ws, const AppConfig& appConfig,
const AppConfig& appConfig, const std::string& str);
const std::string& str); } // namespace snake
}

View File

@ -6,10 +6,9 @@
#pragma once #pragma once
#include <string>
#include <ixwebsocket/IXWebSocketServer.h>
#include "IXAppConfig.h" #include "IXAppConfig.h"
#include <ixwebsocket/IXWebSocketServer.h>
#include <string>
namespace snake namespace snake
{ {
@ -27,4 +26,4 @@ namespace snake
AppConfig _appConfig; AppConfig _appConfig;
ix::WebSocketServer _server; ix::WebSocketServer _server;
}; };
} } // namespace snake

12
ws/ws.h
View File

@ -28,17 +28,13 @@ namespace ix
int ws_broadcast_server_main(int port, const std::string& hostname); int ws_broadcast_server_main(int port, const std::string& hostname);
int ws_transfer_main(int port, const std::string& hostname); int ws_transfer_main(int port, const std::string& hostname);
int ws_chat_main(const std::string& url, int ws_chat_main(const std::string& url, const std::string& user);
const std::string& user);
int ws_connect_main(const std::string& url, bool disableAutomaticReconnection); int ws_connect_main(const std::string& url, bool disableAutomaticReconnection);
int ws_receive_main(const std::string& url, int ws_receive_main(const std::string& url, bool enablePerMessageDeflate, int delayMs);
bool enablePerMessageDeflate,
int delayMs);
int ws_send_main(const std::string& url, int ws_send_main(const std::string& url, const std::string& path);
const std::string& path);
int ws_redis_publish_main(const std::string& hostname, int ws_redis_publish_main(const std::string& hostname,
int port, int port,
@ -95,4 +91,4 @@ namespace ix
const std::string& redisPassword, const std::string& redisPassword,
bool verbose, bool verbose,
const std::string& appsConfigPath); const std::string& appsConfigPath);
} } // namespace ix