websocket.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /**
  2. * Copyright (c) 2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #if RTC_ENABLE_WEBSOCKET
  19. #include "websocket.hpp"
  20. #include "include.hpp"
  21. #include "threadpool.hpp"
  22. #include "tcptransport.hpp"
  23. #include "tlstransport.hpp"
  24. #include "verifiedtlstransport.hpp"
  25. #include "wstransport.hpp"
  26. #include <regex>
  27. #ifdef _WIN32
  28. #include <winsock2.h>
  29. #endif
  30. namespace rtc {
  31. using std::shared_ptr;
  32. WebSocket::WebSocket(std::optional<Configuration> config)
  33. : mConfig(config ? std::move(*config) : Configuration()),
  34. mRecvQueue(RECV_QUEUE_LIMIT, message_size_func) {
  35. PLOG_VERBOSE << "Creating WebSocket";
  36. }
  37. WebSocket::~WebSocket() {
  38. PLOG_VERBOSE << "Destroying WebSocket";
  39. remoteClose();
  40. }
  41. WebSocket::State WebSocket::readyState() const { return mState; }
  42. void WebSocket::open(const string &url) {
  43. if (mState != State::Closed)
  44. throw std::runtime_error("WebSocket must be closed before opening");
  45. static const char *rs = R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)";
  46. static std::regex regex(rs, std::regex::extended);
  47. std::smatch match;
  48. if (!std::regex_match(url, match, regex))
  49. throw std::invalid_argument("Malformed WebSocket URL: " + url);
  50. mScheme = match[2];
  51. if (mScheme != "ws" && mScheme != "wss")
  52. throw std::invalid_argument("Invalid WebSocket scheme: " + mScheme);
  53. mHost = match[4];
  54. if (auto pos = mHost.find(':'); pos != string::npos) {
  55. mHostname = mHost.substr(0, pos);
  56. mService = mHost.substr(pos + 1);
  57. } else {
  58. mHostname = mHost;
  59. mService = mScheme == "ws" ? "80" : "443";
  60. }
  61. mPath = match[5];
  62. if (string query = match[7]; !query.empty())
  63. mPath += "?" + query;
  64. changeState(State::Connecting);
  65. initTcpTransport();
  66. }
  67. void WebSocket::close() {
  68. auto state = mState.load();
  69. if (state == State::Connecting || state == State::Open) {
  70. PLOG_VERBOSE << "Closing WebSocket";
  71. changeState(State::Closing);
  72. if (auto transport = std::atomic_load(&mWsTransport))
  73. transport->close();
  74. else
  75. changeState(State::Closed);
  76. }
  77. }
  78. void WebSocket::remoteClose() {
  79. if (mState.load() != State::Closed) {
  80. close();
  81. closeTransports();
  82. }
  83. }
  84. bool WebSocket::send(message_variant data) { return outgoing(make_message(std::move(data))); }
  85. bool WebSocket::isOpen() const { return mState == State::Open; }
  86. bool WebSocket::isClosed() const { return mState == State::Closed; }
  87. size_t WebSocket::maxMessageSize() const { return DEFAULT_MAX_MESSAGE_SIZE; }
  88. std::optional<message_variant> WebSocket::receive() {
  89. while (!mRecvQueue.empty()) {
  90. auto message = *mRecvQueue.pop();
  91. if (message->type != Message::Control)
  92. return to_variant(std::move(*message));
  93. }
  94. return nullopt;
  95. }
  96. size_t WebSocket::availableAmount() const { return mRecvQueue.amount(); }
  97. bool WebSocket::changeState(State state) { return mState.exchange(state) != state; }
  98. bool WebSocket::outgoing(message_ptr message) {
  99. if (mState != State::Open || !mWsTransport)
  100. throw std::runtime_error("WebSocket is not open");
  101. if (message->size() > maxMessageSize())
  102. throw std::runtime_error("Message size exceeds limit");
  103. return mWsTransport->send(message);
  104. }
  105. void WebSocket::incoming(message_ptr message) {
  106. if (message->type == Message::String || message->type == Message::Binary) {
  107. mRecvQueue.push(message);
  108. triggerAvailable(mRecvQueue.size());
  109. }
  110. }
  111. shared_ptr<TcpTransport> WebSocket::initTcpTransport() {
  112. using State = TcpTransport::State;
  113. try {
  114. std::lock_guard lock(mInitMutex);
  115. if (auto transport = std::atomic_load(&mTcpTransport))
  116. return transport;
  117. auto transport = std::make_shared<TcpTransport>(
  118. mHostname, mService, [this, weak_this = weak_from_this()](State state) {
  119. auto shared_this = weak_this.lock();
  120. if (!shared_this)
  121. return;
  122. switch (state) {
  123. case State::Connected:
  124. if (mScheme == "ws")
  125. initWsTransport();
  126. else
  127. initTlsTransport();
  128. break;
  129. case State::Failed:
  130. triggerError("TCP connection failed");
  131. remoteClose();
  132. break;
  133. case State::Disconnected:
  134. remoteClose();
  135. break;
  136. default:
  137. // Ignore
  138. break;
  139. }
  140. });
  141. std::atomic_store(&mTcpTransport, transport);
  142. if (mState == WebSocket::State::Closed) {
  143. mTcpTransport.reset();
  144. throw std::runtime_error("Connection is closed");
  145. }
  146. transport->start();
  147. return transport;
  148. } catch (const std::exception &e) {
  149. PLOG_ERROR << e.what();
  150. remoteClose();
  151. throw std::runtime_error("TCP transport initialization failed");
  152. }
  153. }
  154. shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
  155. using State = TlsTransport::State;
  156. try {
  157. std::lock_guard lock(mInitMutex);
  158. if (auto transport = std::atomic_load(&mTlsTransport))
  159. return transport;
  160. auto lower = std::atomic_load(&mTcpTransport);
  161. auto stateChangeCallback = [this, weak_this = weak_from_this()](State state) {
  162. auto shared_this = weak_this.lock();
  163. if (!shared_this)
  164. return;
  165. switch (state) {
  166. case State::Connected:
  167. initWsTransport();
  168. break;
  169. case State::Failed:
  170. triggerError("TCP connection failed");
  171. remoteClose();
  172. break;
  173. case State::Disconnected:
  174. remoteClose();
  175. break;
  176. default:
  177. // Ignore
  178. break;
  179. }
  180. };
  181. shared_ptr<TlsTransport> transport;
  182. #ifdef _WIN32
  183. if (!mConfig.disableTlsVerification) {
  184. PLOG_WARNING << "TLS certificate verification with root CA is not supported on Windows";
  185. }
  186. transport = std::make_shared<TlsTransport>(lower, mHost, stateChangeCallback);
  187. #else
  188. if (mConfig.disableTlsVerification)
  189. transport = std::make_shared<TlsTransport>(lower, mHost, stateChangeCallback);
  190. else
  191. transport = std::make_shared<VerifiedTlsTransport>(lower, mHost, stateChangeCallback);
  192. #endif
  193. std::atomic_store(&mTlsTransport, transport);
  194. if (mState == WebSocket::State::Closed) {
  195. mTlsTransport.reset();
  196. throw std::runtime_error("Connection is closed");
  197. }
  198. transport->start();
  199. return transport;
  200. } catch (const std::exception &e) {
  201. PLOG_ERROR << e.what();
  202. remoteClose();
  203. throw std::runtime_error("TLS transport initialization failed");
  204. }
  205. }
  206. shared_ptr<WsTransport> WebSocket::initWsTransport() {
  207. using State = WsTransport::State;
  208. try {
  209. std::lock_guard lock(mInitMutex);
  210. if (auto transport = std::atomic_load(&mWsTransport))
  211. return transport;
  212. shared_ptr<Transport> lower = std::atomic_load(&mTlsTransport);
  213. if (!lower)
  214. lower = std::atomic_load(&mTcpTransport);
  215. auto transport = std::make_shared<WsTransport>(
  216. lower, mHost, mPath, weak_bind(&WebSocket::incoming, this, _1),
  217. [this, weak_this = weak_from_this()](State state) {
  218. auto shared_this = weak_this.lock();
  219. if (!shared_this)
  220. return;
  221. switch (state) {
  222. case State::Connected:
  223. if (mState == WebSocket::State::Connecting) {
  224. PLOG_DEBUG << "WebSocket open";
  225. changeState(WebSocket::State::Open);
  226. triggerOpen();
  227. }
  228. break;
  229. case State::Failed:
  230. triggerError("WebSocket connection failed");
  231. remoteClose();
  232. break;
  233. case State::Disconnected:
  234. remoteClose();
  235. break;
  236. default:
  237. // Ignore
  238. break;
  239. }
  240. });
  241. std::atomic_store(&mWsTransport, transport);
  242. if (mState == WebSocket::State::Closed) {
  243. mWsTransport.reset();
  244. throw std::runtime_error("Connection is closed");
  245. }
  246. transport->start();
  247. return transport;
  248. } catch (const std::exception &e) {
  249. PLOG_ERROR << e.what();
  250. remoteClose();
  251. throw std::runtime_error("WebSocket transport initialization failed");
  252. }
  253. }
  254. void WebSocket::closeTransports() {
  255. PLOG_VERBOSE << "Closing transports";
  256. if (mState.load() != State::Closed) {
  257. changeState(State::Closed);
  258. triggerClosed();
  259. }
  260. // Reset callbacks now that state is changed
  261. resetCallbacks();
  262. // Pass the pointers to a thread, allowing to terminate a transport from its own thread
  263. auto ws = std::atomic_exchange(&mWsTransport, decltype(mWsTransport)(nullptr));
  264. auto tls = std::atomic_exchange(&mTlsTransport, decltype(mTlsTransport)(nullptr));
  265. auto tcp = std::atomic_exchange(&mTcpTransport, decltype(mTcpTransport)(nullptr));
  266. ThreadPool::Instance().enqueue([ws, tls, tcp]() mutable {
  267. if (ws)
  268. ws->stop();
  269. if (tls)
  270. tls->stop();
  271. if (tcp)
  272. tcp->stop();
  273. ws.reset();
  274. tls.reset();
  275. tcp.reset();
  276. });
  277. }
  278. } // namespace rtc
  279. #endif