websocket.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. PLOG_VERBOSE << "Opening WebSocket to URL: " << url;
  44. if (mState != State::Closed)
  45. throw std::logic_error("WebSocket must be closed before opening");
  46. // Modified regex from RFC 3986, see https://tools.ietf.org/html/rfc3986#appendix-B
  47. static const char *rs =
  48. R"(^(([^:.@/?#]+):)?(/{0,2}((([^:@]*)(:([^@]*))?)@)?(([^:/?#]*)(:([^/?#]*))?))?([^?#]*)(\?([^#]*))?(#(.*))?)";
  49. static const std::regex r(rs, std::regex::extended);
  50. std::smatch m;
  51. if (!std::regex_match(url, m, r) || m[10].length() == 0)
  52. throw std::invalid_argument("Invalid WebSocket URL: " + url);
  53. mScheme = m[2];
  54. if (mScheme.empty())
  55. mScheme = "ws";
  56. else if (mScheme != "ws" && mScheme != "wss")
  57. throw std::invalid_argument("Invalid WebSocket scheme: " + mScheme);
  58. mHostname = m[10];
  59. mService = m[12];
  60. if (mService.empty()) {
  61. mService = mScheme == "ws" ? "80" : "443";
  62. mHost = mHostname;
  63. } else {
  64. mHost = mHostname + ':' + mService;
  65. }
  66. while (!mHostname.empty() && mHostname.front() == '[')
  67. mHostname.erase(mHostname.begin());
  68. while (!mHostname.empty() && mHostname.back() == ']')
  69. mHostname.pop_back();
  70. mPath = m[13];
  71. if (mPath.empty())
  72. mPath += '/';
  73. if (string query = m[15]; !query.empty())
  74. mPath += "?" + query;
  75. changeState(State::Connecting);
  76. initTcpTransport();
  77. }
  78. void WebSocket::close() {
  79. auto state = mState.load();
  80. if (state == State::Connecting || state == State::Open) {
  81. PLOG_VERBOSE << "Closing WebSocket";
  82. changeState(State::Closing);
  83. if (auto transport = std::atomic_load(&mWsTransport))
  84. transport->close();
  85. else
  86. changeState(State::Closed);
  87. }
  88. }
  89. void WebSocket::remoteClose() {
  90. if (mState.load() != State::Closed) {
  91. close();
  92. closeTransports();
  93. }
  94. }
  95. bool WebSocket::send(message_variant data) { return outgoing(make_message(std::move(data))); }
  96. bool WebSocket::isOpen() const { return mState == State::Open; }
  97. bool WebSocket::isClosed() const { return mState == State::Closed; }
  98. size_t WebSocket::maxMessageSize() const { return DEFAULT_MAX_MESSAGE_SIZE; }
  99. std::optional<message_variant> WebSocket::receive() {
  100. while (auto next = mRecvQueue.tryPop()) {
  101. message_ptr message = std::move(*next);
  102. if (message->type != Message::Control)
  103. return to_variant(std::move(*message));
  104. }
  105. return nullopt;
  106. }
  107. size_t WebSocket::availableAmount() const { return mRecvQueue.amount(); }
  108. bool WebSocket::changeState(State state) { return mState.exchange(state) != state; }
  109. bool WebSocket::outgoing(message_ptr message) {
  110. if (mState != State::Open || !mWsTransport)
  111. throw std::runtime_error("WebSocket is not open");
  112. if (message->size() > maxMessageSize())
  113. throw std::runtime_error("Message size exceeds limit");
  114. return mWsTransport->send(message);
  115. }
  116. void WebSocket::incoming(message_ptr message) {
  117. if (!message) {
  118. remoteClose();
  119. return;
  120. }
  121. if (message->type == Message::String || message->type == Message::Binary) {
  122. mRecvQueue.push(message);
  123. triggerAvailable(mRecvQueue.size());
  124. }
  125. }
  126. shared_ptr<TcpTransport> WebSocket::initTcpTransport() {
  127. PLOG_VERBOSE << "Starting TCP transport";
  128. using State = TcpTransport::State;
  129. try {
  130. std::lock_guard lock(mInitMutex);
  131. if (auto transport = std::atomic_load(&mTcpTransport))
  132. return transport;
  133. auto transport = std::make_shared<TcpTransport>(
  134. mHostname, mService, [this, weak_this = weak_from_this()](State state) {
  135. auto shared_this = weak_this.lock();
  136. if (!shared_this)
  137. return;
  138. switch (state) {
  139. case State::Connected:
  140. if (mScheme == "ws")
  141. initWsTransport();
  142. else
  143. initTlsTransport();
  144. break;
  145. case State::Failed:
  146. triggerError("TCP connection failed");
  147. remoteClose();
  148. break;
  149. case State::Disconnected:
  150. remoteClose();
  151. break;
  152. default:
  153. // Ignore
  154. break;
  155. }
  156. });
  157. std::atomic_store(&mTcpTransport, transport);
  158. if (mState == WebSocket::State::Closed) {
  159. mTcpTransport.reset();
  160. throw std::runtime_error("Connection is closed");
  161. }
  162. transport->start();
  163. return transport;
  164. } catch (const std::exception &e) {
  165. PLOG_ERROR << e.what();
  166. remoteClose();
  167. throw std::runtime_error("TCP transport initialization failed");
  168. }
  169. }
  170. shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
  171. PLOG_VERBOSE << "Starting TLS transport";
  172. using State = TlsTransport::State;
  173. try {
  174. std::lock_guard lock(mInitMutex);
  175. if (auto transport = std::atomic_load(&mTlsTransport))
  176. return transport;
  177. auto lower = std::atomic_load(&mTcpTransport);
  178. auto stateChangeCallback = [this, weak_this = weak_from_this()](State state) {
  179. auto shared_this = weak_this.lock();
  180. if (!shared_this)
  181. return;
  182. switch (state) {
  183. case State::Connected:
  184. initWsTransport();
  185. break;
  186. case State::Failed:
  187. triggerError("TCP connection failed");
  188. remoteClose();
  189. break;
  190. case State::Disconnected:
  191. remoteClose();
  192. break;
  193. default:
  194. // Ignore
  195. break;
  196. }
  197. };
  198. shared_ptr<TlsTransport> transport;
  199. #ifdef _WIN32
  200. if (!mConfig.disableTlsVerification) {
  201. PLOG_WARNING << "TLS certificate verification with root CA is not supported on Windows";
  202. }
  203. transport = std::make_shared<TlsTransport>(lower, mHost, stateChangeCallback);
  204. #else
  205. if (mConfig.disableTlsVerification)
  206. transport = std::make_shared<TlsTransport>(lower, mHost, stateChangeCallback);
  207. else
  208. transport = std::make_shared<VerifiedTlsTransport>(lower, mHost, stateChangeCallback);
  209. #endif
  210. std::atomic_store(&mTlsTransport, transport);
  211. if (mState == WebSocket::State::Closed) {
  212. mTlsTransport.reset();
  213. throw std::runtime_error("Connection is closed");
  214. }
  215. transport->start();
  216. return transport;
  217. } catch (const std::exception &e) {
  218. PLOG_ERROR << e.what();
  219. remoteClose();
  220. throw std::runtime_error("TLS transport initialization failed");
  221. }
  222. }
  223. shared_ptr<WsTransport> WebSocket::initWsTransport() {
  224. PLOG_VERBOSE << "Starting WebSocket transport";
  225. using State = WsTransport::State;
  226. try {
  227. std::lock_guard lock(mInitMutex);
  228. if (auto transport = std::atomic_load(&mWsTransport))
  229. return transport;
  230. shared_ptr<Transport> lower = std::atomic_load(&mTlsTransport);
  231. if (!lower)
  232. lower = std::atomic_load(&mTcpTransport);
  233. auto transport = std::make_shared<WsTransport>(
  234. lower, mHost, mPath, weak_bind(&WebSocket::incoming, this, _1),
  235. [this, weak_this = weak_from_this()](State state) {
  236. auto shared_this = weak_this.lock();
  237. if (!shared_this)
  238. return;
  239. switch (state) {
  240. case State::Connected:
  241. if (mState == WebSocket::State::Connecting) {
  242. PLOG_DEBUG << "WebSocket open";
  243. changeState(WebSocket::State::Open);
  244. triggerOpen();
  245. }
  246. break;
  247. case State::Failed:
  248. triggerError("WebSocket connection failed");
  249. remoteClose();
  250. break;
  251. case State::Disconnected:
  252. remoteClose();
  253. break;
  254. default:
  255. // Ignore
  256. break;
  257. }
  258. });
  259. std::atomic_store(&mWsTransport, transport);
  260. if (mState == WebSocket::State::Closed) {
  261. mWsTransport.reset();
  262. throw std::runtime_error("Connection is closed");
  263. }
  264. transport->start();
  265. return transport;
  266. } catch (const std::exception &e) {
  267. PLOG_ERROR << e.what();
  268. remoteClose();
  269. throw std::runtime_error("WebSocket transport initialization failed");
  270. }
  271. }
  272. void WebSocket::closeTransports() {
  273. PLOG_VERBOSE << "Closing transports";
  274. if (mState.load() != State::Closed) {
  275. changeState(State::Closed);
  276. triggerClosed();
  277. }
  278. // Reset callbacks now that state is changed
  279. resetCallbacks();
  280. // Pass the pointers to a thread, allowing to terminate a transport from its own thread
  281. auto ws = std::atomic_exchange(&mWsTransport, decltype(mWsTransport)(nullptr));
  282. auto tls = std::atomic_exchange(&mTlsTransport, decltype(mTlsTransport)(nullptr));
  283. auto tcp = std::atomic_exchange(&mTcpTransport, decltype(mTcpTransport)(nullptr));
  284. ThreadPool::Instance().enqueue([ws, tls, tcp]() mutable {
  285. if (ws)
  286. ws->stop();
  287. if (tls)
  288. tls->stop();
  289. if (tcp)
  290. tcp->stop();
  291. ws.reset();
  292. tls.reset();
  293. tcp.reset();
  294. });
  295. }
  296. } // namespace rtc
  297. #endif