diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..b19e59f0 --- /dev/null +++ b/.clang-format @@ -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: '^$' + 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 diff --git a/ixwebsocket/IXCancellationRequest.h b/ixwebsocket/IXCancellationRequest.h index ed7eb013..8b0547d8 100644 --- a/ixwebsocket/IXCancellationRequest.h +++ b/ixwebsocket/IXCancellationRequest.h @@ -6,14 +6,13 @@ #pragma once -#include #include +#include namespace ix { using CancellationRequest = std::function; - CancellationRequest makeCancellationRequestWithTimeout(int seconds, - std::atomic& requestInitCancellation); -} - + CancellationRequest makeCancellationRequestWithTimeout( + int seconds, std::atomic& requestInitCancellation); +} // namespace ix diff --git a/ixwebsocket/IXConnectionState.h b/ixwebsocket/IXConnectionState.h index e9b1affc..17df5bca 100644 --- a/ixwebsocket/IXConnectionState.h +++ b/ixwebsocket/IXConnectionState.h @@ -6,14 +6,15 @@ #pragma once -#include -#include #include #include +#include +#include namespace ix { - class ConnectionState { + class ConnectionState + { public: ConnectionState(); virtual ~ConnectionState() = default; @@ -32,6 +33,4 @@ namespace ix static std::atomic _globalId; }; -} - - +} // namespace ix diff --git a/ixwebsocket/IXDNSLookup.h b/ixwebsocket/IXDNSLookup.h index 7b418788..bc502309 100644 --- a/ixwebsocket/IXDNSLookup.h +++ b/ixwebsocket/IXDNSLookup.h @@ -11,22 +11,20 @@ #pragma once #include "IXCancellationRequest.h" - -#include -#include #include #include #include +#include +#include struct addrinfo; namespace ix { - class DNSLookup { + class DNSLookup + { public: - DNSLookup(const std::string& hostname, - int port, - int64_t wait = DNSLookup::kDefaultWait); + DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait); ~DNSLookup(); struct addrinfo* resolve(std::string& errMsg, @@ -78,4 +76,4 @@ namespace ix const static int64_t kDefaultWait; }; -} +} // namespace ix diff --git a/ixwebsocket/IXHttpClient.h b/ixwebsocket/IXHttpClient.h index fe34ac0e..45c0ffb1 100644 --- a/ixwebsocket/IXHttpClient.h +++ b/ixwebsocket/IXHttpClient.h @@ -6,39 +6,38 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include - #include "IXSocket.h" #include "IXWebSocketHttpHeaders.h" +#include +#include +#include +#include +#include +#include +#include namespace ix { enum class HttpErrorCode : int { - Ok = 0, - CannotConnect = 1, - Timeout = 2, - Gzip = 3, - UrlMalformed = 4, - CannotCreateSocket = 5, - SendError = 6, - ReadError = 7, - CannotReadStatusLine = 8, - MissingStatus = 9, - HeaderParsingError = 10, - MissingLocation = 11, - TooManyRedirects = 12, - ChunkReadError = 13, - CannotReadBody = 14 + Ok = 0, + CannotConnect = 1, + Timeout = 2, + Gzip = 3, + UrlMalformed = 4, + CannotCreateSocket = 5, + SendError = 6, + ReadError = 7, + CannotReadStatusLine = 8, + MissingStatus = 9, + HeaderParsingError = 10, + MissingLocation = 11, + TooManyRedirects = 12, + ChunkReadError = 13, + CannotReadBody = 14 }; - using HttpResponse = std::tuple _socket; @@ -104,4 +100,4 @@ namespace ix const static std::string kGet; const static std::string kHead; }; -} +} // namespace ix diff --git a/ixwebsocket/IXNetSystem.h b/ixwebsocket/IXNetSystem.h index e8993e1a..52b785a4 100644 --- a/ixwebsocket/IXNetSystem.h +++ b/ixwebsocket/IXNetSystem.h @@ -7,25 +7,25 @@ #pragma once #ifdef _WIN32 -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #else -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #endif namespace ix { bool initNetSystem(); bool uninitNetSystem(); -} +} // namespace ix diff --git a/ixwebsocket/IXSelectInterrupt.h b/ixwebsocket/IXSelectInterrupt.h index 4a720c1e..6d03f32d 100644 --- a/ixwebsocket/IXSelectInterrupt.h +++ b/ixwebsocket/IXSelectInterrupt.h @@ -11,7 +11,8 @@ namespace ix { - class SelectInterrupt { + class SelectInterrupt + { public: SelectInterrupt(); virtual ~SelectInterrupt(); @@ -23,6 +24,4 @@ namespace ix virtual uint64_t read(); virtual int getFd() const; }; -} - - +} // namespace ix diff --git a/ixwebsocket/IXSelectInterruptEventFd.h b/ixwebsocket/IXSelectInterruptEventFd.h index 5d957b0d..6de6ba35 100644 --- a/ixwebsocket/IXSelectInterruptEventFd.h +++ b/ixwebsocket/IXSelectInterruptEventFd.h @@ -7,13 +7,13 @@ #pragma once #include "IXSelectInterrupt.h" - #include #include namespace ix { - class SelectInterruptEventFd final : public SelectInterrupt { + class SelectInterruptEventFd final : public SelectInterrupt + { public: SelectInterruptEventFd(); virtual ~SelectInterruptEventFd(); @@ -28,5 +28,4 @@ namespace ix private: int _eventfd; }; -} - +} // namespace ix diff --git a/ixwebsocket/IXSelectInterruptFactory.h b/ixwebsocket/IXSelectInterruptFactory.h index 11c307e0..f3e83b8f 100644 --- a/ixwebsocket/IXSelectInterruptFactory.h +++ b/ixwebsocket/IXSelectInterruptFactory.h @@ -12,4 +12,4 @@ namespace ix { class SelectInterrupt; std::shared_ptr createSelectInterrupt(); -} +} // namespace ix diff --git a/ixwebsocket/IXSelectInterruptPipe.h b/ixwebsocket/IXSelectInterruptPipe.h index dfac989a..76689151 100644 --- a/ixwebsocket/IXSelectInterruptPipe.h +++ b/ixwebsocket/IXSelectInterruptPipe.h @@ -7,14 +7,14 @@ #pragma once #include "IXSelectInterrupt.h" - +#include #include #include -#include namespace ix { - class SelectInterruptPipe final : public SelectInterrupt { + class SelectInterruptPipe final : public SelectInterrupt + { public: SelectInterruptPipe(); virtual ~SelectInterruptPipe(); @@ -37,5 +37,4 @@ namespace ix static const int kPipeReadIndex; static const int kPipeWriteIndex; }; -} - +} // namespace ix diff --git a/ixwebsocket/IXSetThreadName.h b/ixwebsocket/IXSetThreadName.h index 4493c736..de57c4ae 100644 --- a/ixwebsocket/IXSetThreadName.h +++ b/ixwebsocket/IXSetThreadName.h @@ -10,4 +10,3 @@ namespace ix { void setThreadName(const std::string& name); } - diff --git a/ixwebsocket/IXSocket.h b/ixwebsocket/IXSocket.h index e2c0da5e..193d7b10 100644 --- a/ixwebsocket/IXSocket.h +++ b/ixwebsocket/IXSocket.h @@ -6,12 +6,12 @@ #pragma once -#include -#include -#include #include -#include +#include #include +#include +#include +#include #ifdef _WIN32 #include @@ -24,11 +24,11 @@ typedef SSIZE_T ssize_t; #undef EINVAL // map to WSA error codes -#define EWOULDBLOCK WSAEWOULDBLOCK -#define EAGAIN WSATRY_AGAIN -#define EINPROGRESS WSAEINPROGRESS -#define EBADF WSAEBADF -#define EINVAL WSAEINVAL +#define EWOULDBLOCK WSAEWOULDBLOCK +#define EAGAIN WSATRY_AGAIN +#define EINPROGRESS WSAEINPROGRESS +#define EBADF WSAEBADF +#define EINVAL WSAEINVAL #endif @@ -41,15 +41,16 @@ namespace ix enum class PollResultType { - ReadyForRead = 0, - ReadyForWrite = 1, - Timeout = 2, - Error = 3, - SendRequest = 4, - CloseRequest = 5 + ReadyForRead = 0, + ReadyForWrite = 1, + Timeout = 2, + Error = 3, + SendRequest = 4, + CloseRequest = 5 }; - class Socket { + class Socket + { public: Socket(int fd = -1); virtual ~Socket(); @@ -75,17 +76,13 @@ namespace ix // Blocking and cancellable versions, working with socket that can be set // to non blocking mode. Used during HTTP upgrade. - bool readByte(void* buffer, - const CancellationRequest& isCancellationRequested); - bool writeBytes(const std::string& str, - const CancellationRequest& isCancellationRequested); + bool readByte(void* buffer, const CancellationRequest& isCancellationRequested); + bool writeBytes(const std::string& str, const CancellationRequest& isCancellationRequested); - std::pair readLine( - const CancellationRequest& isCancellationRequested); - std::pair readBytes( - size_t length, - const OnProgressCallback& onProgressCallback, - const CancellationRequest& isCancellationRequested); + std::pair readLine(const CancellationRequest& isCancellationRequested); + std::pair readBytes(size_t length, + const OnProgressCallback& onProgressCallback, + const CancellationRequest& isCancellationRequested); static int getErrno(); static bool isWaitNeeded(); @@ -111,4 +108,4 @@ namespace ix std::shared_ptr _selectInterrupt; }; -} +} // namespace ix diff --git a/ixwebsocket/IXSocketAppleSSL.h b/ixwebsocket/IXSocketAppleSSL.h index 58e4dcb5..2fdc30d8 100644 --- a/ixwebsocket/IXSocketAppleSSL.h +++ b/ixwebsocket/IXSocketAppleSSL.h @@ -6,12 +6,10 @@ #pragma once -#include "IXSocket.h" #include "IXCancellationRequest.h" - -#include +#include "IXSocket.h" #include - +#include #include namespace ix @@ -34,7 +32,7 @@ namespace ix private: SSLContextRef _sslContext; - mutable std::mutex _mutex; // AppleSSL routines are not thread-safe + mutable std::mutex _mutex; // AppleSSL routines are not thread-safe }; -} +} // namespace ix diff --git a/ixwebsocket/IXSocketConnect.h b/ixwebsocket/IXSocketConnect.h index fa09eb9a..84a0858e 100644 --- a/ixwebsocket/IXSocketConnect.h +++ b/ixwebsocket/IXSocketConnect.h @@ -7,14 +7,14 @@ #pragma once #include "IXCancellationRequest.h" - #include struct addrinfo; namespace ix { - class SocketConnect { + class SocketConnect + { public: static int connect(const std::string& hostname, int port, @@ -24,9 +24,8 @@ namespace ix static void configure(int sockfd); private: - static int connectToAddress(const struct addrinfo *address, + static int connectToAddress(const struct addrinfo* address, std::string& errMsg, const CancellationRequest& isCancellationRequested); }; -} - +} // namespace ix diff --git a/ixwebsocket/IXSocketFactory.h b/ixwebsocket/IXSocketFactory.h index 396bc457..09724450 100644 --- a/ixwebsocket/IXSocketFactory.h +++ b/ixwebsocket/IXSocketFactory.h @@ -13,9 +13,7 @@ namespace ix { class Socket; - std::shared_ptr createSocket(bool tls, - std::string& errorMsg); + std::shared_ptr createSocket(bool tls, std::string& errorMsg); - std::shared_ptr createSocket(int fd, - std::string& errorMsg); -} + std::shared_ptr createSocket(int fd, std::string& errorMsg); +} // namespace ix diff --git a/ixwebsocket/IXSocketOpenSSL.h b/ixwebsocket/IXSocketOpenSSL.h index d52ba1d5..5afe4125 100644 --- a/ixwebsocket/IXSocketOpenSSL.h +++ b/ixwebsocket/IXSocketOpenSSL.h @@ -6,17 +6,15 @@ #pragma once -#include "IXSocket.h" #include "IXCancellationRequest.h" - +#include "IXSocket.h" +#include #include -#include #include #include +#include #include -#include - namespace ix { class SocketOpenSSL final : public Socket @@ -40,18 +38,16 @@ namespace ix std::string getSSLError(int ret); SSL_CTX* openSSLCreateContext(std::string& errMsg); bool openSSLHandshake(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 openSSLCheckServerCert(SSL* ssl, const std::string& hostname, std::string& errMsg); + bool checkHost(const std::string& host, const char* pattern); SSL* _ssl_connection; SSL_CTX* _ssl_context; 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::atomic _openSSLInitializationSuccessful; }; -} +} // namespace ix diff --git a/ixwebsocket/IXSocketSChannel.h b/ixwebsocket/IXSocketSChannel.h index 5394600c..4aab9e83 100644 --- a/ixwebsocket/IXSocketSChannel.h +++ b/ixwebsocket/IXSocketSChannel.h @@ -16,9 +16,7 @@ namespace ix SocketSChannel(); ~SocketSChannel(); - virtual bool connect(const std::string& host, - int port, - std::string& errMsg) final; + virtual bool connect(const std::string& host, int port, std::string& errMsg) final; virtual void close() final; // The important override @@ -31,4 +29,4 @@ namespace ix private: }; -} +} // namespace ix diff --git a/ixwebsocket/IXSocketServer.h b/ixwebsocket/IXSocketServer.h index 0472e93c..b8e74126 100644 --- a/ixwebsocket/IXSocketServer.h +++ b/ixwebsocket/IXSocketServer.h @@ -7,28 +7,28 @@ #pragma once #include "IXConnectionState.h" - -#include // pair -#include -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include // pair namespace ix { - class SocketServer { + class SocketServer + { public: using ConnectionStateFactory = std::function()>; // Each connection is handled by its own worker thread. // We use a list as we only care about remove and append operations. - using ConnectionThreads = std::list, - std::thread>>; + using ConnectionThreads = + std::list, std::thread>>; SocketServer(int port = SocketServer::kDefaultPort, const std::string& host = SocketServer::kDefaultHost, @@ -52,7 +52,6 @@ namespace ix void wait(); protected: - // Logging void logError(const std::string& str); void logInfo(const std::string& str); @@ -93,12 +92,11 @@ namespace ix // the factory to create ConnectionState objects ConnectionStateFactory _connectionStateFactory; - virtual void handleConnection(int fd, - std::shared_ptr connectionState) = 0; + virtual void handleConnection(int fd, std::shared_ptr connectionState) = 0; virtual size_t getConnectedClientsCount() = 0; // Returns true if all connection threads are joined void closeTerminatedThreads(); size_t getConnectionsThreadsCount(); }; -} +} // namespace ix diff --git a/ixwebsocket/IXUrlParser.h b/ixwebsocket/IXUrlParser.h index 3ec190c3..40e6b6e9 100644 --- a/ixwebsocket/IXUrlParser.h +++ b/ixwebsocket/IXUrlParser.h @@ -20,4 +20,4 @@ namespace ix std::string& query, int& port); }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocket.h b/ixwebsocket/IXWebSocket.h index 331923ca..0eaf3ba3 100644 --- a/ixwebsocket/IXWebSocket.h +++ b/ixwebsocket/IXWebSocket.h @@ -9,39 +9,38 @@ #pragma once +#include "IXProgressCallback.h" +#include "IXWebSocketCloseConstants.h" +#include "IXWebSocketErrorInfo.h" +#include "IXWebSocketHttpHeaders.h" +#include "IXWebSocketPerMessageDeflateOptions.h" +#include "IXWebSocketSendInfo.h" +#include "IXWebSocketTransport.h" +#include +#include #include #include -#include -#include - -#include "IXWebSocketTransport.h" -#include "IXWebSocketErrorInfo.h" -#include "IXWebSocketSendInfo.h" -#include "IXWebSocketPerMessageDeflateOptions.h" -#include "IXWebSocketHttpHeaders.h" -#include "IXWebSocketCloseConstants.h" -#include "IXProgressCallback.h" namespace ix { // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Ready_state_constants enum class ReadyState { - Connecting = 0, - Open = 1, - Closing = 2, - Closed = 3 + Connecting = 0, + Open = 1, + Closing = 2, + Closed = 3 }; enum class WebSocketMessageType { - Message = 0, - Open = 1, - Close = 2, - Error = 3, - Ping = 4, - Pong = 5, - Fragment = 6 + Message = 0, + Open = 1, + Close = 2, + Error = 3, + Ping = 4, + Pong = 5, + Fragment = 6 }; struct WebSocketOpenInfo @@ -64,9 +63,7 @@ namespace ix std::string reason; bool remote; - WebSocketCloseInfo(uint16_t c = 0, - const std::string& r = std::string(), - bool rem = false) + WebSocketCloseInfo(uint16_t c = 0, const std::string& r = std::string(), bool rem = false) : code(c) , reason(r) , remote(rem) @@ -91,7 +88,8 @@ namespace ix ~WebSocket(); void setUrl(const std::string& url); - void setPerMessageDeflateOptions(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions); + void setPerMessageDeflateOptions( + const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions); void setHeartBeatPeriod(int heartBeatPeriodSecs); void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod void setPingTimeout(int pingTimeoutSecs); @@ -116,8 +114,7 @@ namespace ix const OnProgressCallback& onProgressCallback = nullptr); WebSocketSendInfo ping(const std::string& text); - void close(uint16_t code = 1000, - const std::string& reason = "Normal closure"); + void close(uint16_t code = 1000, const std::string& reason = "Normal closure"); void setOnMessageCallback(const OnMessageCallback& callback); static void setTrafficTrackerCallback(const OnTrafficTrackerCallback& callback); @@ -138,7 +135,6 @@ namespace ix bool isAutomaticReconnectionEnabled() const; private: - WebSocketSendInfo sendMessage(const std::string& text, SendMessageKind sendMessageKind, const OnProgressCallback& callback = nullptr); @@ -180,4 +176,4 @@ namespace ix friend class WebSocketServer; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketCloseConstants.h b/ixwebsocket/IXWebSocketCloseConstants.h index 81ac531b..572a71b7 100644 --- a/ixwebsocket/IXWebSocketCloseConstants.h +++ b/ixwebsocket/IXWebSocketCloseConstants.h @@ -26,4 +26,4 @@ namespace ix static const std::string kProtocolErrorMessage; static const std::string kNoStatusCodeErrorMessage; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketErrorInfo.h b/ixwebsocket/IXWebSocketErrorInfo.h index e8f16c62..03c074cc 100644 --- a/ixwebsocket/IXWebSocketErrorInfo.h +++ b/ixwebsocket/IXWebSocketErrorInfo.h @@ -18,4 +18,4 @@ namespace ix std::string reason; bool decompressionError = false; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketHandshake.h b/ixwebsocket/IXWebSocketHandshake.h index 468f0629..1424b7c2 100644 --- a/ixwebsocket/IXWebSocketHandshake.h +++ b/ixwebsocket/IXWebSocketHandshake.h @@ -7,15 +7,14 @@ #pragma once #include "IXCancellationRequest.h" +#include "IXSocket.h" #include "IXWebSocketHttpHeaders.h" #include "IXWebSocketPerMessageDeflate.h" #include "IXWebSocketPerMessageDeflateOptions.h" -#include "IXSocket.h" - -#include #include #include #include +#include #include namespace ix @@ -42,7 +41,8 @@ namespace ix } }; - class WebSocketHandshake { + class WebSocketHandshake + { public: WebSocketHandshake(std::atomic& requestInitCancellation, std::shared_ptr _socket, @@ -56,8 +56,7 @@ namespace ix int port, int timeoutSecs); - WebSocketInitResult serverHandshake(int fd, - int timeoutSecs); + WebSocketInitResult serverHandshake(int fd, int timeoutSecs); private: std::string genRandomString(const int len); @@ -75,4 +74,4 @@ namespace ix WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions; std::atomic& _enablePerMessageDeflate; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketHttpHeaders.h b/ixwebsocket/IXWebSocketHttpHeaders.h index b8422e56..99cb1242 100644 --- a/ixwebsocket/IXWebSocketHttpHeaders.h +++ b/ixwebsocket/IXWebSocketHttpHeaders.h @@ -7,10 +7,9 @@ #pragma once #include "IXCancellationRequest.h" - -#include #include #include +#include namespace ix { @@ -21,15 +20,14 @@ namespace ix // Case Insensitive compare_less binary function 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::pair parseHttpHeaders( - std::shared_ptr socket, - const CancellationRequest& isCancellationRequested); -} + std::shared_ptr socket, const CancellationRequest& isCancellationRequested); +} // namespace ix diff --git a/ixwebsocket/IXWebSocketMessageQueue.h b/ixwebsocket/IXWebSocketMessageQueue.h index b8b85c25..d2e7dbc1 100644 --- a/ixwebsocket/IXWebSocketMessageQueue.h +++ b/ixwebsocket/IXWebSocketMessageQueue.h @@ -7,9 +7,9 @@ #pragma once #include "IXWebSocket.h" -#include #include #include +#include namespace ix { @@ -50,4 +50,4 @@ namespace ix std::mutex _messagesMutex; std::list _messages; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketPerMessageDeflate.h b/ixwebsocket/IXWebSocketPerMessageDeflate.h index 936714c4..512868ec 100644 --- a/ixwebsocket/IXWebSocketPerMessageDeflate.h +++ b/ixwebsocket/IXWebSocketPerMessageDeflate.h @@ -34,8 +34,8 @@ #pragma once -#include #include +#include namespace ix { @@ -57,4 +57,4 @@ namespace ix std::unique_ptr _compressor; std::unique_ptr _decompressor; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketPerMessageDeflateCodec.h b/ixwebsocket/IXWebSocketPerMessageDeflateCodec.h index 78521c62..3e70fa54 100644 --- a/ixwebsocket/IXWebSocketPerMessageDeflateCodec.h +++ b/ixwebsocket/IXWebSocketPerMessageDeflateCodec.h @@ -7,8 +7,8 @@ #pragma once #include "zlib.h" -#include #include +#include namespace ix { @@ -46,5 +46,4 @@ namespace ix z_stream _inflateState; }; -} - +} // namespace ix diff --git a/ixwebsocket/IXWebSocketPerMessageDeflateOptions.h b/ixwebsocket/IXWebSocketPerMessageDeflateOptions.h index e56c45bb..5cf5ee90 100644 --- a/ixwebsocket/IXWebSocketPerMessageDeflateOptions.h +++ b/ixwebsocket/IXWebSocketPerMessageDeflateOptions.h @@ -42,4 +42,4 @@ namespace ix int _clientMaxWindowBits; int _serverMaxWindowBits; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketSendInfo.h b/ixwebsocket/IXWebSocketSendInfo.h index 8258657a..c66d4a63 100644 --- a/ixwebsocket/IXWebSocketSendInfo.h +++ b/ixwebsocket/IXWebSocketSendInfo.h @@ -15,8 +15,7 @@ namespace ix size_t payloadSize; size_t wireSize; - WebSocketSendInfo(bool s = false, bool c = false, - size_t p = 0, size_t w = 0) + WebSocketSendInfo(bool s = false, bool c = false, size_t p = 0, size_t w = 0) : success(s) , compressionError(c) , payloadSize(p) @@ -25,4 +24,4 @@ namespace ix ; } }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketServer.h b/ixwebsocket/IXWebSocketServer.h index 67f4c606..f14cff72 100644 --- a/ixwebsocket/IXWebSocketServer.h +++ b/ixwebsocket/IXWebSocketServer.h @@ -6,24 +6,24 @@ #pragma once -#include // pair -#include -#include -#include -#include +#include "IXSocketServer.h" +#include "IXWebSocket.h" +#include #include #include -#include - -#include "IXWebSocket.h" -#include "IXSocketServer.h" +#include +#include +#include +#include +#include // pair namespace ix { - using OnConnectionCallback = std::function, - std::shared_ptr)>; + using OnConnectionCallback = + std::function, std::shared_ptr)>; - class WebSocketServer final : public SocketServer { + class WebSocketServer final : public SocketServer + { public: WebSocketServer(int port = SocketServer::kDefaultPort, const std::string& host = SocketServer::kDefaultHost, @@ -59,4 +59,4 @@ namespace ix std::shared_ptr connectionState) final; virtual size_t getConnectedClientsCount() final; }; -} +} // namespace ix diff --git a/ixwebsocket/IXWebSocketTransport.h b/ixwebsocket/IXWebSocketTransport.h index 96d8cae0..aa432319 100644 --- a/ixwebsocket/IXWebSocketTransport.h +++ b/ixwebsocket/IXWebSocketTransport.h @@ -10,22 +10,21 @@ // Adapted from https://github.com/dhbaird/easywsclient // -#include -#include -#include -#include -#include -#include -#include - -#include "IXWebSocketSendInfo.h" -#include "IXWebSocketPerMessageDeflate.h" -#include "IXWebSocketPerMessageDeflateOptions.h" -#include "IXWebSocketHttpHeaders.h" #include "IXCancellationRequest.h" -#include "IXWebSocketHandshake.h" #include "IXProgressCallback.h" #include "IXWebSocketCloseConstants.h" +#include "IXWebSocketHandshake.h" +#include "IXWebSocketHttpHeaders.h" +#include "IXWebSocketPerMessageDeflate.h" +#include "IXWebSocketPerMessageDeflateOptions.h" +#include "IXWebSocketSendInfo.h" +#include +#include +#include +#include +#include +#include +#include namespace ix { @@ -63,14 +62,9 @@ namespace ix AbnormalClose }; - using OnMessageCallback = std::function; - using OnCloseCallback = std::function; + using OnMessageCallback = + std::function; + using OnCloseCallback = std::function; WebSocketTransport(); ~WebSocketTransport(); @@ -82,7 +76,7 @@ namespace ix WebSocketInitResult connectToUrl(const std::string& url, // Client int timeoutSecs); - WebSocketInitResult connectToSocket(int fd, // Server + WebSocketInitResult connectToSocket(int fd, // Server int timeoutSecs); PollResult poll(); @@ -103,25 +97,26 @@ namespace ix ReadyState getReadyState() const; void setReadyState(ReadyState readyState); void setOnCloseCallback(const OnCloseCallback& onCloseCallback); - void dispatch(PollResult pollResult, - const OnMessageCallback& onMessageCallback); + void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback); size_t bufferedAmount() const; private: std::string _url; - struct wsheader_type { + struct wsheader_type + { unsigned header_size; bool fin; bool rsv1; bool mask; - enum opcode_type { + enum opcode_type + { CONTINUATION = 0x0, - TEXT_FRAME = 0x1, + TEXT_FRAME = 0x1, BINARY_FRAME = 0x2, - CLOSE = 8, - PING = 9, - PONG = 0xa, + CLOSE = 8, + PING = 9, + PONG = 0xa, } opcode; int N0; uint64_t N; @@ -176,7 +171,7 @@ namespace ix std::atomic _requestInitCancellation; mutable std::mutex _closingTimePointMutex; - std::chrono::time_point_closingTimePoint; + std::chrono::time_point _closingTimePoint; static const int kClosingMaximumWaitingDelayInMs; // 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 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(); void initTimePointsAndGCDAfterConnect(); @@ -252,4 +248,4 @@ namespace ix std::string getMergedChunks() const; }; -} +} // namespace ix diff --git a/ixwebsocket/LUrlParser.h b/ixwebsocket/LUrlParser.h index 06bd3d20..0298ceb2 100644 --- a/ixwebsocket/LUrlParser.h +++ b/ixwebsocket/LUrlParser.h @@ -31,48 +31,54 @@ namespace LUrlParser { - enum LUrlParserError - { - LUrlParserError_Ok = 0, - LUrlParserError_Uninitialized = 1, - LUrlParserError_NoUrlCharacter = 2, - LUrlParserError_InvalidSchemeName = 3, - LUrlParserError_NoDoubleSlash = 4, - LUrlParserError_NoAtSign = 5, - LUrlParserError_UnexpectedEndOfLine = 6, - LUrlParserError_NoSlash = 7, - }; + enum LUrlParserError + { + LUrlParserError_Ok = 0, + LUrlParserError_Uninitialized = 1, + LUrlParserError_NoUrlCharacter = 2, + LUrlParserError_InvalidSchemeName = 3, + LUrlParserError_NoDoubleSlash = 4, + LUrlParserError_NoAtSign = 5, + LUrlParserError_UnexpectedEndOfLine = 6, + LUrlParserError_NoSlash = 7, + }; - class clParseURL - { - public: - LUrlParserError m_ErrorCode; - std::string m_Scheme; - std::string m_Host; - std::string m_Port; - std::string m_Path; - std::string m_Query; - std::string m_Fragment; - std::string m_UserName; - std::string m_Password; + class clParseURL + { + public: + LUrlParserError m_ErrorCode; + std::string m_Scheme; + std::string m_Host; + std::string m_Port; + std::string m_Path; + std::string m_Query; + std::string m_Fragment; + std::string m_UserName; + std::string m_Password; - clParseURL() - : m_ErrorCode( LUrlParserError_Uninitialized ) - {} + clParseURL() + : m_ErrorCode(LUrlParserError_Uninitialized) + { + } - /// return 'true' if the parsing was successful - bool IsValid() const { return m_ErrorCode == LUrlParserError_Ok; } + /// return 'true' if the parsing was successful + 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) - bool GetPort( int* OutPort ) const; + /// helper to convert the port number to int, return 'true' if the port is valid (within the + /// 0..65535 range) + bool GetPort(int* OutPort) const; - /// parse the URL - static clParseURL ParseURL( const std::string& URL ); + /// parse the URL + static clParseURL ParseURL(const std::string& URL); - private: - explicit clParseURL( LUrlParserError ErrorCode ) - : m_ErrorCode( ErrorCode ) - {} - }; + private: + explicit clParseURL(LUrlParserError ErrorCode) + : m_ErrorCode(ErrorCode) + { + } + }; } // namespace LUrlParser diff --git a/makefile b/makefile index caa57211..044ae6d5 100644 --- a/makefile +++ b/makefile @@ -40,6 +40,9 @@ run: trail: 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 # a builtin C++ server started in the unittest now test_server: diff --git a/ws/IXRedisClient.h b/ws/IXRedisClient.h index 8148f803..25f6793b 100644 --- a/ws/IXRedisClient.h +++ b/ws/IXRedisClient.h @@ -6,14 +6,15 @@ #pragma once -#include #include +#include namespace ix { class Socket; - class RedisClient { + class RedisClient + { public: using OnRedisSubscribeResponseCallback = std::function; using OnRedisSubscribeCallback = std::function; @@ -21,15 +22,11 @@ namespace ix RedisClient() = default; ~RedisClient() = default; - bool connect(const std::string& hostname, - int port); + bool connect(const std::string& hostname, int port); - bool auth(const std::string& password, - std::string& response); + bool auth(const std::string& password, std::string& response); - bool publish(const std::string& channel, - const std::string& message, - std::string& errMsg); + bool publish(const std::string& channel, const std::string& message, std::string& errMsg); bool subscribe(const std::string& channel, const OnRedisSubscribeResponseCallback& responseCallback, @@ -40,5 +37,4 @@ namespace ix std::shared_ptr _socket; }; -} - +} // namespace ix diff --git a/ws/IXSentryClient.h b/ws/IXSentryClient.h index 76e36036..5ab47be9 100644 --- a/ws/IXSentryClient.h +++ b/ws/IXSentryClient.h @@ -6,11 +6,10 @@ #pragma once +#include #include #include -#include - namespace ix { class SentryClient diff --git a/ws/ixcobra/IXCobraConnection.h b/ws/ixcobra/IXCobraConnection.h index fc2e8e7b..f1f0f24a 100644 --- a/ws/ixcobra/IXCobraConnection.h +++ b/ws/ixcobra/IXCobraConnection.h @@ -6,16 +6,15 @@ #pragma once +#include +#include +#include +#include #include #include #include #include #include -#include - -#include -#include -#include namespace ix { @@ -72,8 +71,7 @@ namespace ix /// Publish a message to a channel /// /// No-op if the connection is not established - bool publish(const Json::Value& channels, - const Json::Value& msg); + bool publish(const Json::Value& channels, const Json::Value& msg); // Subscribe to a channel, and execute a callback when an incoming // message arrives. @@ -126,8 +124,7 @@ namespace ix const std::string& errorMsg = std::string(), const WebSocketHttpHeaders& headers = WebSocketHttpHeaders(), const std::string& subscriptionId = std::string()); - void invokeErrorCallback(const std::string& errorMsg, - const std::string& serializedPdu); + void invokeErrorCallback(const std::string& errorMsg, const std::string& serializedPdu); /// /// Member variables diff --git a/ws/ixcobra/IXCobraMetricsPublisher.h b/ws/ixcobra/IXCobraMetricsPublisher.h index 1d2fa369..e0ab7ff4 100644 --- a/ws/ixcobra/IXCobraMetricsPublisher.h +++ b/ws/ixcobra/IXCobraMetricsPublisher.h @@ -7,12 +7,10 @@ #pragma once #include "IXCobraMetricsThreadedPublisher.h" - +#include #include - #include #include -#include namespace ix { @@ -28,10 +26,11 @@ namespace ix /// to make shouldPush as fast as possible. _enabled default to false. /// /// 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, - /// so there shouldn't be any race condition. + /// the last value to be set is _enabled, which is also the first value checked in + /// 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. /// @@ -62,40 +61,44 @@ namespace ix void push(const std::string& id, 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 - /// for places where we want to be as lightweight as possible when collecting metrics. When set to false, - /// it is used so that we don't do double work when computing whether a metrics should be sent or not. - void push(const std::string& id, - const Json::Value& data, - bool shouldPushTest = true); + /// The shouldPushTest argument should be set to false, and used in combination with the + /// shouldPush method for places where we want to be as lightweight as possible when + /// collecting metrics. When set to false, it is used so that we don't do double work when + /// computing whether a metrics should be sent or not. + void push(const std::string& id, const Json::Value& data, bool shouldPushTest = true); /// Interface used by lua. msg is a json encoded string. - void push(const std::string& id, - const std::string& data, - bool shouldPushTest = true); + void push(const std::string& id, const std::string& data, bool shouldPushTest = true); /// Tells whether a metric can be pushed. /// A metric can be pushed if it satisfies those conditions: /// /// 1. the metrics system should be enabled /// 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; /// Get generic information json object Json::Value& getGenericAttributes(); /// Set generic information values - void setGenericAttributes(const std::string& attrName, - const Json::Value& value); + void setGenericAttributes(const std::string& attrName, const Json::Value& value); /// 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 - const std::string& getSession() const { return _session; } + const std::string& getSession() const + { + return _session; + } /// Return the number of milliseconds since the epoch (~1970) uint64_t getMillisecondsSinceEpoch() const; @@ -117,7 +120,6 @@ namespace ix bool isAuthenticated() const; private: - /// Lookup an id in our metrics to see whether it is blacklisted /// Complexity is logarithmic bool isMetricBlacklisted(const std::string& id) const; @@ -150,15 +152,16 @@ namespace ix /// Metrics control (black list + rate control) std::vector _blacklist; std::unordered_map _rate_control; - std::unordered_map> _last_update; + std::unordered_map> + _last_update; mutable std::mutex _last_update_mutex; // protect access to _last_update // const strings for internal ids static const std::string kSetRateControlId; static const std::string kSetBlacklistId; - /// Our protocol version. Can be used by subscribers who would want to be backward compatible - /// if we change the way we arrange data + /// Our protocol version. Can be used by subscribers who would want to be backward + /// compatible if we change the way we arrange data static const int kVersion; }; diff --git a/ws/ixcobra/IXCobraMetricsThreadedPublisher.h b/ws/ixcobra/IXCobraMetricsThreadedPublisher.h index 2e119fca..55c17c59 100644 --- a/ws/ixcobra/IXCobraMetricsThreadedPublisher.h +++ b/ws/ixcobra/IXCobraMetricsThreadedPublisher.h @@ -7,16 +7,14 @@ #pragma once #include "IXCobraConnection.h" - -#include - -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include namespace ix { @@ -67,8 +65,7 @@ namespace ix }; /// Push a message to be processed by the background thread - void pushMessage(MessageKind messageKind, - const Json::Value& msg); + void pushMessage(MessageKind messageKind, const Json::Value& msg); /// Get a wait time which is increasing exponentially based on the number of retries uint64_t getWaitTimeExp(int retry_count); diff --git a/ws/ixcore/utils/IXCoreLogger.h b/ws/ixcore/utils/IXCoreLogger.h index ae263fce..e140dfc3 100644 --- a/ws/ixcore/utils/IXCoreLogger.h +++ b/ws/ixcore/utils/IXCoreLogger.h @@ -3,20 +3,19 @@ namespace ix { + class IXCoreLogger + { + public: + using LogFunc = std::function; + static void Log(const char* msg); -class IXCoreLogger -{ -public: - using LogFunc = std::function; - static void Log(const char* msg); + static void setLogFunction(LogFunc& func) + { + _currentLogger = func; + } - static void setLogFunction(LogFunc& func) { - _currentLogger = func; - } + private: + static LogFunc _currentLogger; + }; -private: - static LogFunc _currentLogger; - -}; - -} // ix +} // namespace ix diff --git a/ws/ixcrypto/IXBase64.h b/ws/ixcrypto/IXBase64.h index 524e8128..38527ea2 100644 --- a/ws/ixcrypto/IXBase64.h +++ b/ws/ixcrypto/IXBase64.h @@ -12,4 +12,4 @@ namespace ix { std::string base64_encode(const std::string& data, size_t len); std::string base64_decode(const std::string& encoded_string); -} +} // namespace ix diff --git a/ws/ixcrypto/IXHash.h b/ws/ixcrypto/IXHash.h index 5d19571a..98d660e1 100644 --- a/ws/ixcrypto/IXHash.h +++ b/ws/ixcrypto/IXHash.h @@ -13,4 +13,3 @@ namespace ix { uint64_t djb2Hash(const std::vector& data); } - diff --git a/ws/ixcrypto/IXUuid.h b/ws/ixcrypto/IXUuid.h index cd248f9f..10004366 100644 --- a/ws/ixcrypto/IXUuid.h +++ b/ws/ixcrypto/IXUuid.h @@ -9,9 +9,9 @@ namespace ix { - /** - * Generate a random uuid - */ - std::string uuid4(); + /** + * Generate a random uuid + */ + std::string uuid4(); -} +} // namespace ix diff --git a/ws/snake/IXAppConfig.h b/ws/snake/IXAppConfig.h index 6d8b345c..e2f9081b 100644 --- a/ws/snake/IXAppConfig.h +++ b/ws/snake/IXAppConfig.h @@ -6,11 +6,10 @@ #pragma once +#include "nlohmann/json.hpp" #include #include -#include "nlohmann/json.hpp" - namespace snake { struct AppConfig @@ -31,16 +30,11 @@ namespace snake bool verbose; }; - bool isAppKeyValid( - const AppConfig& appConfig, - std::string appkey); + bool isAppKeyValid(const AppConfig& appConfig, std::string appkey); - std::string getRoleSecret( - const AppConfig& appConfig, - std::string appkey, - std::string role); + std::string getRoleSecret(const AppConfig& appConfig, std::string appkey, std::string role); std::string generateNonce(); void dumpConfig(const AppConfig& appConfig); -} +} // namespace snake diff --git a/ws/snake/IXSnakeConnectionState.h b/ws/snake/IXSnakeConnectionState.h index 72772b42..713aad32 100644 --- a/ws/snake/IXSnakeConnectionState.h +++ b/ws/snake/IXSnakeConnectionState.h @@ -6,27 +6,47 @@ #pragma once -#include -#include - -#include #include "IXRedisClient.h" +#include +#include +#include namespace snake { class SnakeConnectionState : public ix::ConnectionState { public: - std::string getNonce() { return _nonce; } - void setNonce(const std::string& nonce) { _nonce = nonce; } + std::string getNonce() + { + return _nonce; + } + void setNonce(const std::string& nonce) + { + _nonce = nonce; + } - std::string appkey() { return _appkey; } - void setAppkey(const std::string& appkey) { _appkey = appkey; } + std::string appkey() + { + return _appkey; + } + void setAppkey(const std::string& appkey) + { + _appkey = appkey; + } - std::string role() { return _role; } - void setRole(const std::string& role) { _role = role; } + std::string role() + { + return _role; + } + void setRole(const std::string& role) + { + _role = role; + } - ix::RedisClient& redisClient() { return _redisClient; } + ix::RedisClient& redisClient() + { + return _redisClient; + } std::future fut; @@ -37,4 +57,4 @@ namespace snake ix::RedisClient _redisClient; }; -} +} // namespace snake diff --git a/ws/snake/IXSnakeProtocol.h b/ws/snake/IXSnakeProtocol.h index 636eabfa..16d2e7b1 100644 --- a/ws/snake/IXSnakeProtocol.h +++ b/ws/snake/IXSnakeProtocol.h @@ -18,9 +18,8 @@ namespace snake class SnakeConnectionState; struct AppConfig; - void processCobraMessage( - std::shared_ptr state, - std::shared_ptr ws, - const AppConfig& appConfig, - const std::string& str); -} + void processCobraMessage(std::shared_ptr state, + std::shared_ptr ws, + const AppConfig& appConfig, + const std::string& str); +} // namespace snake diff --git a/ws/snake/IXSnakeServer.h b/ws/snake/IXSnakeServer.h index 0cc7f1dc..49fed587 100644 --- a/ws/snake/IXSnakeServer.h +++ b/ws/snake/IXSnakeServer.h @@ -6,10 +6,9 @@ #pragma once -#include - -#include #include "IXAppConfig.h" +#include +#include namespace snake { @@ -27,4 +26,4 @@ namespace snake AppConfig _appConfig; ix::WebSocketServer _server; }; -} +} // namespace snake diff --git a/ws/ws.h b/ws/ws.h index db72d72c..a6718c9c 100644 --- a/ws/ws.h +++ b/ws/ws.h @@ -28,17 +28,13 @@ namespace ix int ws_broadcast_server_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, - const std::string& user); + int ws_chat_main(const std::string& url, const std::string& user); int ws_connect_main(const std::string& url, bool disableAutomaticReconnection); - int ws_receive_main(const std::string& url, - bool enablePerMessageDeflate, - int delayMs); + int ws_receive_main(const std::string& url, bool enablePerMessageDeflate, int delayMs); - int ws_send_main(const std::string& url, - const std::string& path); + int ws_send_main(const std::string& url, const std::string& path); int ws_redis_publish_main(const std::string& hostname, int port, @@ -95,4 +91,4 @@ namespace ix const std::string& redisPassword, bool verbose, const std::string& appsConfigPath); -} +} // namespace ix