websocket.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /**
  2. * Copyright (c) 2020-2021 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #if RTC_ENABLE_WEBSOCKET
  9. #include "websocket.hpp"
  10. #include "common.hpp"
  11. #include "internals.hpp"
  12. #include "processor.hpp"
  13. #include "utils.hpp"
  14. #include "httpproxytransport.hpp"
  15. #include "tcptransport.hpp"
  16. #include "tlstransport.hpp"
  17. #include "verifiedtlstransport.hpp"
  18. #include "wstransport.hpp"
  19. #include <array>
  20. #include <chrono>
  21. #include <regex>
  22. #ifdef _WIN32
  23. #include <winsock2.h>
  24. #endif
  25. namespace rtc::impl {
  26. using namespace std::placeholders;
  27. using namespace std::chrono_literals;
  28. using std::chrono::milliseconds;
  29. WebSocket::WebSocket(optional<Configuration> optConfig, certificate_ptr certificate)
  30. : config(optConfig ? std::move(*optConfig) : Configuration()),
  31. mCertificate(std::move(certificate)), mIsSecure(mCertificate != nullptr),
  32. mRecvQueue(RECV_QUEUE_LIMIT, message_size_func) {
  33. PLOG_VERBOSE << "Creating WebSocket";
  34. if (config.proxyServer) {
  35. if (config.proxyServer->type == ProxyServer::Type::Socks5)
  36. throw std::invalid_argument(
  37. "Proxy server support for WebSocket is not implemented for Socks5");
  38. if (config.proxyServer->username || config.proxyServer->password) {
  39. PLOG_WARNING << "HTTP authentication support for proxy is not implemented";
  40. }
  41. }
  42. }
  43. WebSocket::~WebSocket() { PLOG_VERBOSE << "Destroying WebSocket"; }
  44. void WebSocket::open(const string &url) {
  45. PLOG_VERBOSE << "Opening WebSocket to URL: " << url;
  46. if (state != State::Closed)
  47. throw std::logic_error("WebSocket must be closed before opening");
  48. // Modified regex from RFC 3986, see https://www.rfc-editor.org/rfc/rfc3986.html#appendix-B
  49. static const char *rs =
  50. R"(^(([^:.@/?#]+):)?(/{0,2}((([^:@]*)(:([^@]*))?)@)?(([^:/?#]*)(:([^/?#]*))?))?([^?#]*)(\?([^#]*))?(#(.*))?)";
  51. static const std::regex r(rs, std::regex::extended);
  52. std::smatch m;
  53. if (!std::regex_match(url, m, r) || m[10].length() == 0)
  54. throw std::invalid_argument("Invalid WebSocket URL: " + url);
  55. string scheme = m[2];
  56. if (scheme.empty())
  57. scheme = "ws";
  58. if (scheme != "ws" && scheme != "wss")
  59. throw std::invalid_argument("Invalid WebSocket scheme: " + scheme);
  60. mIsSecure = (scheme != "ws");
  61. string username = utils::url_decode(m[6]);
  62. string password = utils::url_decode(m[8]);
  63. if (!username.empty() || !password.empty()) {
  64. PLOG_WARNING << "HTTP authentication support for WebSocket is not implemented";
  65. }
  66. string host;
  67. string hostname = m[10];
  68. string service = m[12];
  69. if (service.empty()) {
  70. service = mIsSecure ? "443" : "80";
  71. host = hostname;
  72. } else {
  73. host = hostname + ':' + service;
  74. }
  75. if (hostname.front() == '[' && hostname.back() == ']') {
  76. // IPv6 literal
  77. hostname.erase(hostname.begin());
  78. hostname.pop_back();
  79. } else {
  80. hostname = utils::url_decode(hostname);
  81. }
  82. string path = m[13];
  83. if (path.empty())
  84. path += '/';
  85. if (string query = m[15]; !query.empty())
  86. path += "?" + query;
  87. mHostname = hostname; // for TLS SNI and Proxy
  88. mService = service; // For proxy
  89. std::atomic_store(&mWsHandshake, std::make_shared<WsHandshake>(host, path, config.protocols));
  90. changeState(State::Connecting);
  91. if (config.proxyServer) {
  92. setTcpTransport(std::make_shared<TcpTransport>(
  93. config.proxyServer->hostname, std::to_string(config.proxyServer->port), nullptr));
  94. } else {
  95. setTcpTransport(std::make_shared<TcpTransport>(hostname, service, nullptr));
  96. }
  97. }
  98. void WebSocket::close() {
  99. auto s = state.load();
  100. if (s == State::Connecting || s == State::Open) {
  101. PLOG_VERBOSE << "Closing WebSocket";
  102. changeState(State::Closing);
  103. if (auto transport = std::atomic_load(&mWsTransport))
  104. transport->stop();
  105. else
  106. remoteClose();
  107. }
  108. }
  109. void WebSocket::remoteClose() {
  110. close();
  111. if (state.load() != State::Closed)
  112. closeTransports();
  113. }
  114. bool WebSocket::isOpen() const { return state == State::Open; }
  115. bool WebSocket::isClosed() const { return state == State::Closed; }
  116. size_t WebSocket::maxMessageSize() const { return DEFAULT_MAX_MESSAGE_SIZE; }
  117. optional<message_variant> WebSocket::receive() {
  118. while (auto next = mRecvQueue.pop()) {
  119. message_ptr message = *next;
  120. if (message->type != Message::Control)
  121. return to_variant(std::move(*message));
  122. }
  123. return nullopt;
  124. }
  125. optional<message_variant> WebSocket::peek() {
  126. while (auto next = mRecvQueue.peek()) {
  127. message_ptr message = *next;
  128. if (message->type != Message::Control)
  129. return to_variant(std::move(*message));
  130. mRecvQueue.pop();
  131. }
  132. return nullopt;
  133. }
  134. size_t WebSocket::availableAmount() const { return mRecvQueue.amount(); }
  135. bool WebSocket::changeState(State newState) { return state.exchange(newState) != newState; }
  136. bool WebSocket::outgoing(message_ptr message) {
  137. if (state != State::Open || !mWsTransport)
  138. throw std::runtime_error("WebSocket is not open");
  139. if (message->size() > maxMessageSize())
  140. throw std::runtime_error("Message size exceeds limit");
  141. return mWsTransport->send(message);
  142. }
  143. void WebSocket::incoming(message_ptr message) {
  144. if (!message) {
  145. remoteClose();
  146. return;
  147. }
  148. if (message->type == Message::String || message->type == Message::Binary) {
  149. mRecvQueue.push(message);
  150. triggerAvailable(mRecvQueue.size());
  151. }
  152. }
  153. // Helper for WebSocket::initXTransport methods: start and emplace the transport
  154. template <typename T>
  155. shared_ptr<T> emplaceTransport(WebSocket *ws, shared_ptr<T> *member, shared_ptr<T> transport) {
  156. std::atomic_store(member, transport);
  157. try {
  158. transport->start();
  159. } catch (...) {
  160. std::atomic_store(member, decltype(transport)(nullptr));
  161. transport->stop();
  162. throw;
  163. }
  164. if (ws->state == WebSocket::State::Closed) {
  165. std::atomic_store(member, decltype(transport)(nullptr));
  166. transport->stop();
  167. return nullptr;
  168. }
  169. return transport;
  170. }
  171. shared_ptr<TcpTransport> WebSocket::setTcpTransport(shared_ptr<TcpTransport> transport) {
  172. PLOG_VERBOSE << "Starting TCP transport";
  173. if (!transport)
  174. throw std::logic_error("TCP transport is null");
  175. using State = TcpTransport::State;
  176. try {
  177. if (std::atomic_load(&mTcpTransport))
  178. throw std::logic_error("TCP transport is already set");
  179. transport->onBufferedAmount(weak_bind(&WebSocket::triggerBufferedAmount, this, _1));
  180. transport->onStateChange([this, weak_this = weak_from_this()](State transportState) {
  181. auto shared_this = weak_this.lock();
  182. if (!shared_this)
  183. return;
  184. switch (transportState) {
  185. case State::Connected:
  186. if (config.proxyServer)
  187. initProxyTransport();
  188. else if (mIsSecure)
  189. initTlsTransport();
  190. else
  191. initWsTransport();
  192. break;
  193. case State::Failed:
  194. triggerError("TCP connection failed");
  195. remoteClose();
  196. break;
  197. case State::Disconnected:
  198. remoteClose();
  199. break;
  200. default:
  201. // Ignore
  202. break;
  203. }
  204. });
  205. // WS transport sends a ping on read timeout
  206. auto pingInterval = config.pingInterval.value_or(10000ms);
  207. if (pingInterval > milliseconds::zero())
  208. transport->setReadTimeout(pingInterval);
  209. scheduleConnectionTimeout();
  210. return emplaceTransport(this, &mTcpTransport, std::move(transport));
  211. } catch (const std::exception &e) {
  212. PLOG_ERROR << e.what();
  213. remoteClose();
  214. throw std::runtime_error("TCP transport initialization failed");
  215. }
  216. }
  217. shared_ptr<HttpProxyTransport> WebSocket::initProxyTransport() {
  218. PLOG_VERBOSE << "Starting Tcp Proxy transport";
  219. using State = HttpProxyTransport::State;
  220. try {
  221. if (auto transport = std::atomic_load(&mProxyTransport))
  222. return transport;
  223. auto lower = std::atomic_load(&mTcpTransport);
  224. if (!lower)
  225. throw std::logic_error("No underlying TCP transport for Proxy transport");
  226. auto stateChangeCallback = [this, weak_this = weak_from_this()](State transportState) {
  227. auto shared_this = weak_this.lock();
  228. if (!shared_this)
  229. return;
  230. switch (transportState) {
  231. case State::Connected:
  232. if (mIsSecure)
  233. initTlsTransport();
  234. else
  235. initWsTransport();
  236. break;
  237. case State::Failed:
  238. triggerError("Proxy connection failed");
  239. remoteClose();
  240. break;
  241. case State::Disconnected:
  242. remoteClose();
  243. break;
  244. default:
  245. // Ignore
  246. break;
  247. }
  248. };
  249. auto transport = std::make_shared<HttpProxyTransport>(
  250. lower, mHostname.value(), mService.value(), stateChangeCallback);
  251. return emplaceTransport(this, &mProxyTransport, std::move(transport));
  252. } catch (const std::exception &e) {
  253. PLOG_ERROR << e.what();
  254. remoteClose();
  255. throw std::runtime_error("Tcp Proxy transport initialization failed");
  256. }
  257. }
  258. shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
  259. PLOG_VERBOSE << "Starting TLS transport";
  260. using State = TlsTransport::State;
  261. try {
  262. if (auto transport = std::atomic_load(&mTlsTransport))
  263. return transport;
  264. variant<shared_ptr<TcpTransport>, shared_ptr<HttpProxyTransport>> lower;
  265. if (config.proxyServer) {
  266. auto transport = std::atomic_load(&mProxyTransport);
  267. if (!transport)
  268. throw std::logic_error("No underlying proxy transport for TLS transport");
  269. lower = transport;
  270. } else {
  271. auto transport = std::atomic_load(&mTcpTransport);
  272. if (!transport)
  273. throw std::logic_error("No underlying TCP transport for TLS transport");
  274. lower = transport;
  275. }
  276. auto stateChangeCallback = [this, weak_this = weak_from_this()](State transportState) {
  277. auto shared_this = weak_this.lock();
  278. if (!shared_this)
  279. return;
  280. switch (transportState) {
  281. case State::Connected:
  282. initWsTransport();
  283. break;
  284. case State::Failed:
  285. triggerError("TLS connection failed");
  286. remoteClose();
  287. break;
  288. case State::Disconnected:
  289. remoteClose();
  290. break;
  291. default:
  292. // Ignore
  293. break;
  294. }
  295. };
  296. bool verify = mHostname.has_value() && !config.disableTlsVerification;
  297. #ifdef _WIN32
  298. if (std::exchange(verify, false)) {
  299. PLOG_WARNING << "TLS certificate verification with root CA is not supported on Windows";
  300. }
  301. #endif
  302. shared_ptr<TlsTransport> transport;
  303. if (verify)
  304. transport = std::make_shared<VerifiedTlsTransport>(lower, mHostname.value(),
  305. mCertificate, stateChangeCallback);
  306. else
  307. transport =
  308. std::make_shared<TlsTransport>(lower, mHostname, mCertificate, stateChangeCallback);
  309. return emplaceTransport(this, &mTlsTransport, std::move(transport));
  310. } catch (const std::exception &e) {
  311. PLOG_ERROR << e.what();
  312. remoteClose();
  313. throw std::runtime_error("TLS transport initialization failed");
  314. }
  315. }
  316. shared_ptr<WsTransport> WebSocket::initWsTransport() {
  317. PLOG_VERBOSE << "Starting WebSocket transport";
  318. using State = WsTransport::State;
  319. try {
  320. if (auto transport = std::atomic_load(&mWsTransport))
  321. return transport;
  322. variant<shared_ptr<TcpTransport>, shared_ptr<HttpProxyTransport>, shared_ptr<TlsTransport>>
  323. lower;
  324. if (mIsSecure) {
  325. auto transport = std::atomic_load(&mTlsTransport);
  326. if (!transport)
  327. throw std::logic_error("No underlying TLS transport for WebSocket transport");
  328. lower = transport;
  329. } else if (config.proxyServer) {
  330. auto transport = std::atomic_load(&mProxyTransport);
  331. if (!transport)
  332. throw std::logic_error("No underlying proxy transport for WebSocket transport");
  333. lower = transport;
  334. } else {
  335. auto transport = std::atomic_load(&mTcpTransport);
  336. if (!transport)
  337. throw std::logic_error("No underlying TCP transport for WebSocket transport");
  338. lower = transport;
  339. }
  340. if (!atomic_load(&mWsHandshake))
  341. atomic_store(&mWsHandshake, std::make_shared<WsHandshake>());
  342. auto stateChangeCallback = [this, weak_this = weak_from_this()](State transportState) {
  343. auto shared_this = weak_this.lock();
  344. if (!shared_this)
  345. return;
  346. switch (transportState) {
  347. case State::Connected:
  348. if (state == WebSocket::State::Connecting) {
  349. PLOG_DEBUG << "WebSocket open";
  350. if (changeState(WebSocket::State::Open))
  351. triggerOpen();
  352. }
  353. break;
  354. case State::Failed:
  355. triggerError("WebSocket connection failed");
  356. remoteClose();
  357. break;
  358. case State::Disconnected:
  359. remoteClose();
  360. break;
  361. default:
  362. // Ignore
  363. break;
  364. }
  365. };
  366. auto maxOutstandingPings = config.maxOutstandingPings.value_or(0);
  367. auto transport = std::make_shared<WsTransport>(lower, mWsHandshake, maxOutstandingPings,
  368. weak_bind(&WebSocket::incoming, this, _1),
  369. stateChangeCallback);
  370. return emplaceTransport(this, &mWsTransport, std::move(transport));
  371. } catch (const std::exception &e) {
  372. PLOG_ERROR << e.what();
  373. remoteClose();
  374. throw std::runtime_error("WebSocket transport initialization failed");
  375. }
  376. }
  377. shared_ptr<TcpTransport> WebSocket::getTcpTransport() const {
  378. return std::atomic_load(&mTcpTransport);
  379. }
  380. shared_ptr<TlsTransport> WebSocket::getTlsTransport() const {
  381. return std::atomic_load(&mTlsTransport);
  382. }
  383. shared_ptr<WsTransport> WebSocket::getWsTransport() const {
  384. return std::atomic_load(&mWsTransport);
  385. }
  386. shared_ptr<WsHandshake> WebSocket::getWsHandshake() const {
  387. return std::atomic_load(&mWsHandshake);
  388. }
  389. void WebSocket::closeTransports() {
  390. PLOG_VERBOSE << "Closing transports";
  391. if (!changeState(State::Closed))
  392. return; // already closed
  393. // Pass the pointers to a thread, allowing to terminate a transport from its own thread
  394. auto ws = std::atomic_exchange(&mWsTransport, decltype(mWsTransport)(nullptr));
  395. auto tls = std::atomic_exchange(&mTlsTransport, decltype(mTlsTransport)(nullptr));
  396. auto tcp = std::atomic_exchange(&mTcpTransport, decltype(mTcpTransport)(nullptr));
  397. if (ws)
  398. ws->onRecv(nullptr);
  399. if (tcp)
  400. tcp->onBufferedAmount(nullptr);
  401. using array = std::array<shared_ptr<Transport>, 3>;
  402. array transports{std::move(ws), std::move(tls), std::move(tcp)};
  403. for (const auto &t : transports)
  404. if (t)
  405. t->onStateChange(nullptr);
  406. TearDownProcessor::Instance().enqueue(
  407. [transports = std::move(transports), token = Init::Instance().token()]() mutable {
  408. for (const auto &t : transports) {
  409. if (t) {
  410. t->stop();
  411. break;
  412. }
  413. }
  414. for (auto &t : transports)
  415. t.reset();
  416. });
  417. triggerClosed();
  418. }
  419. void WebSocket::scheduleConnectionTimeout() {
  420. auto defaultTimeout = 30s;
  421. auto timeout = config.connectionTimeout.value_or(milliseconds(defaultTimeout));
  422. if (timeout > milliseconds::zero()) {
  423. ThreadPool::Instance().schedule(timeout, [weak_this = weak_from_this()]() {
  424. if (auto locked = weak_this.lock()) {
  425. if (locked->state == WebSocket::State::Connecting) {
  426. PLOG_WARNING << "WebSocket connection timed out";
  427. locked->triggerError("Connection timed out");
  428. locked->remoteClose();
  429. }
  430. }
  431. });
  432. }
  433. }
  434. } // namespace rtc::impl
  435. #endif