websocket.cpp 9.9 KB

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