websocket.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 "common.hpp"
  21. #include "internals.hpp"
  22. #include "threadpool.hpp"
  23. #include "utils.hpp"
  24. #include "tcptransport.hpp"
  25. #include "tlstransport.hpp"
  26. #include "verifiedtlstransport.hpp"
  27. #include "wstransport.hpp"
  28. #include <array>
  29. #include <regex>
  30. #ifdef _WIN32
  31. #include <winsock2.h>
  32. #endif
  33. namespace rtc::impl {
  34. using namespace std::placeholders;
  35. WebSocket::WebSocket(optional<Configuration> optConfig, certificate_ptr certificate)
  36. : config(optConfig ? std::move(*optConfig) : Configuration()),
  37. mCertificate(std::move(certificate)), mIsSecure(mCertificate != nullptr),
  38. mRecvQueue(RECV_QUEUE_LIMIT, message_size_func) {
  39. PLOG_VERBOSE << "Creating WebSocket";
  40. }
  41. WebSocket::~WebSocket() { PLOG_VERBOSE << "Destroying WebSocket"; }
  42. void WebSocket::open(const string &url) {
  43. PLOG_VERBOSE << "Opening WebSocket to URL: " << url;
  44. if (state != State::Closed)
  45. throw std::logic_error("WebSocket must be closed before opening");
  46. if (config.proxyServer) {
  47. PLOG_WARNING << "Proxy server support for WebSocket is not implemented";
  48. }
  49. // Modified regex from RFC 3986, see https://www.rfc-editor.org/rfc/rfc3986.html#appendix-B
  50. static const char *rs =
  51. R"(^(([^:.@/?#]+):)?(/{0,2}((([^:@]*)(:([^@]*))?)@)?(([^:/?#]*)(:([^/?#]*))?))?([^?#]*)(\?([^#]*))?(#(.*))?)";
  52. static const std::regex r(rs, std::regex::extended);
  53. std::smatch m;
  54. if (!std::regex_match(url, m, r) || m[10].length() == 0)
  55. throw std::invalid_argument("Invalid WebSocket URL: " + url);
  56. string scheme = m[2];
  57. if (scheme.empty())
  58. scheme = "ws";
  59. if (scheme != "ws" && scheme != "wss")
  60. throw std::invalid_argument("Invalid WebSocket scheme: " + scheme);
  61. mIsSecure = (scheme != "ws");
  62. string username = utils::url_decode(m[6]);
  63. string password = utils::url_decode(m[8]);
  64. if (!username.empty() || !password.empty()) {
  65. PLOG_WARNING << "HTTP authentication support for WebSocket is not implemented";
  66. }
  67. string host;
  68. string hostname = m[10];
  69. string service = m[12];
  70. if (service.empty()) {
  71. service = mIsSecure ? "443" : "80";
  72. host = hostname;
  73. } else {
  74. host = hostname + ':' + service;
  75. }
  76. if (hostname.front() == '[' && hostname.back() == ']') {
  77. // IPv6 literal
  78. hostname.erase(hostname.begin());
  79. hostname.pop_back();
  80. } else {
  81. hostname = utils::url_decode(hostname);
  82. }
  83. string path = m[13];
  84. if (path.empty())
  85. path += '/';
  86. if (string query = m[15]; !query.empty())
  87. path += "?" + query;
  88. mHostname = hostname; // for TLS SNI
  89. std::atomic_store(&mWsHandshake, std::make_shared<WsHandshake>(host, path, config.protocols));
  90. changeState(State::Connecting);
  91. setTcpTransport(std::make_shared<TcpTransport>(hostname, service, nullptr));
  92. }
  93. void WebSocket::close() {
  94. auto s = state.load();
  95. if (s == State::Connecting || s == State::Open) {
  96. PLOG_VERBOSE << "Closing WebSocket";
  97. changeState(State::Closing);
  98. if (auto transport = std::atomic_load(&mWsTransport))
  99. transport->close();
  100. else
  101. remoteClose();
  102. }
  103. }
  104. void WebSocket::remoteClose() {
  105. if (state != State::Closed) {
  106. close();
  107. closeTransports();
  108. }
  109. }
  110. bool WebSocket::isOpen() const { return state == State::Open; }
  111. bool WebSocket::isClosed() const { return state == State::Closed; }
  112. size_t WebSocket::maxMessageSize() const { return DEFAULT_MAX_MESSAGE_SIZE; }
  113. optional<message_variant> WebSocket::receive() {
  114. while (auto next = mRecvQueue.tryPop()) {
  115. message_ptr message = *next;
  116. if (message->type != Message::Control)
  117. return to_variant(std::move(*message));
  118. }
  119. return nullopt;
  120. }
  121. optional<message_variant> WebSocket::peek() {
  122. while (auto next = mRecvQueue.peek()) {
  123. message_ptr message = *next;
  124. if (message->type != Message::Control)
  125. return to_variant(std::move(*message));
  126. mRecvQueue.tryPop();
  127. }
  128. return nullopt;
  129. }
  130. size_t WebSocket::availableAmount() const { return mRecvQueue.amount(); }
  131. bool WebSocket::changeState(State newState) { return state.exchange(newState) != newState; }
  132. bool WebSocket::outgoing(message_ptr message) {
  133. if (state != State::Open || !mWsTransport)
  134. throw std::runtime_error("WebSocket is not open");
  135. if (message->size() > maxMessageSize())
  136. throw std::runtime_error("Message size exceeds limit");
  137. return mWsTransport->send(message);
  138. }
  139. void WebSocket::incoming(message_ptr message) {
  140. if (!message) {
  141. remoteClose();
  142. return;
  143. }
  144. if (message->type == Message::String || message->type == Message::Binary) {
  145. mRecvQueue.push(message);
  146. triggerAvailable(mRecvQueue.size());
  147. }
  148. }
  149. // Helper for WebSocket::initXTransport methods: start and emplace the transport
  150. template <typename T>
  151. shared_ptr<T> emplaceTransport(WebSocket *ws, shared_ptr<T> *member, shared_ptr<T> transport) {
  152. std::atomic_store(member, transport);
  153. try {
  154. transport->start();
  155. } catch (...) {
  156. std::atomic_store(member, decltype(transport)(nullptr));
  157. transport->stop();
  158. throw;
  159. }
  160. if (ws->state == WebSocket::State::Closed) {
  161. std::atomic_store(member, decltype(transport)(nullptr));
  162. transport->stop();
  163. return nullptr;
  164. }
  165. return transport;
  166. }
  167. shared_ptr<TcpTransport> WebSocket::setTcpTransport(shared_ptr<TcpTransport> transport) {
  168. PLOG_VERBOSE << "Starting TCP transport";
  169. if (!transport)
  170. throw std::logic_error("TCP transport is null");
  171. using State = TcpTransport::State;
  172. try {
  173. if (std::atomic_load(&mTcpTransport))
  174. throw std::logic_error("TCP transport is already set");
  175. transport->onStateChange([this, weak_this = weak_from_this()](State transportState) {
  176. auto shared_this = weak_this.lock();
  177. if (!shared_this)
  178. return;
  179. switch (transportState) {
  180. case State::Connected:
  181. if (mIsSecure)
  182. initTlsTransport();
  183. else
  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. return emplaceTransport(this, &mTcpTransport, std::move(transport));
  199. } catch (const std::exception &e) {
  200. PLOG_ERROR << e.what();
  201. remoteClose();
  202. throw std::runtime_error("TCP transport initialization failed");
  203. }
  204. }
  205. shared_ptr<TlsTransport> WebSocket::initTlsTransport() {
  206. PLOG_VERBOSE << "Starting TLS transport";
  207. using State = TlsTransport::State;
  208. try {
  209. if (auto transport = std::atomic_load(&mTlsTransport))
  210. return transport;
  211. auto lower = std::atomic_load(&mTcpTransport);
  212. if (!lower)
  213. throw std::logic_error("No underlying TCP transport for TLS transport");
  214. auto stateChangeCallback = [this, weak_this = weak_from_this()](State transportState) {
  215. auto shared_this = weak_this.lock();
  216. if (!shared_this)
  217. return;
  218. switch (transportState) {
  219. case State::Connected:
  220. initWsTransport();
  221. break;
  222. case State::Failed:
  223. triggerError("TLS connection failed");
  224. remoteClose();
  225. break;
  226. case State::Disconnected:
  227. remoteClose();
  228. break;
  229. default:
  230. // Ignore
  231. break;
  232. }
  233. };
  234. bool verify = mHostname.has_value() && !config.disableTlsVerification;
  235. #ifdef _WIN32
  236. if (std::exchange(verify, false)) {
  237. PLOG_WARNING << "TLS certificate verification with root CA is not supported on Windows";
  238. }
  239. #endif
  240. shared_ptr<TlsTransport> transport;
  241. if (verify)
  242. transport = std::make_shared<VerifiedTlsTransport>(lower, mHostname.value(),
  243. mCertificate, stateChangeCallback);
  244. else
  245. transport =
  246. std::make_shared<TlsTransport>(lower, mHostname, mCertificate, stateChangeCallback);
  247. return emplaceTransport(this, &mTlsTransport, std::move(transport));
  248. } catch (const std::exception &e) {
  249. PLOG_ERROR << e.what();
  250. remoteClose();
  251. throw std::runtime_error("TLS transport initialization failed");
  252. }
  253. }
  254. shared_ptr<WsTransport> WebSocket::initWsTransport() {
  255. PLOG_VERBOSE << "Starting WebSocket transport";
  256. using State = WsTransport::State;
  257. try {
  258. if (auto transport = std::atomic_load(&mWsTransport))
  259. return transport;
  260. variant<shared_ptr<TcpTransport>, shared_ptr<TlsTransport>> lower;
  261. if (mIsSecure) {
  262. auto transport = std::atomic_load(&mTlsTransport);
  263. if (!transport)
  264. throw std::logic_error("No underlying TLS transport for WebSocket transport");
  265. lower = transport;
  266. } else {
  267. auto transport = std::atomic_load(&mTcpTransport);
  268. if (!transport)
  269. throw std::logic_error("No underlying TCP transport for WebSocket transport");
  270. lower = transport;
  271. }
  272. if (!atomic_load(&mWsHandshake))
  273. atomic_store(&mWsHandshake, std::make_shared<WsHandshake>());
  274. auto stateChangeCallback = [this, weak_this = weak_from_this()](State transportState) {
  275. auto shared_this = weak_this.lock();
  276. if (!shared_this)
  277. return;
  278. switch (transportState) {
  279. case State::Connected:
  280. if (state == WebSocket::State::Connecting) {
  281. PLOG_DEBUG << "WebSocket open";
  282. if (changeState(WebSocket::State::Open))
  283. triggerOpen();
  284. }
  285. break;
  286. case State::Failed:
  287. triggerError("WebSocket connection failed");
  288. remoteClose();
  289. break;
  290. case State::Disconnected:
  291. remoteClose();
  292. break;
  293. default:
  294. // Ignore
  295. break;
  296. }
  297. };
  298. auto transport = std::make_shared<WsTransport>(
  299. lower, mWsHandshake, weak_bind(&WebSocket::incoming, this, _1), stateChangeCallback);
  300. return emplaceTransport(this, &mWsTransport, std::move(transport));
  301. } catch (const std::exception &e) {
  302. PLOG_ERROR << e.what();
  303. remoteClose();
  304. throw std::runtime_error("WebSocket transport initialization failed");
  305. }
  306. }
  307. shared_ptr<TcpTransport> WebSocket::getTcpTransport() const {
  308. return std::atomic_load(&mTcpTransport);
  309. }
  310. shared_ptr<TlsTransport> WebSocket::getTlsTransport() const {
  311. return std::atomic_load(&mTlsTransport);
  312. }
  313. shared_ptr<WsTransport> WebSocket::getWsTransport() const {
  314. return std::atomic_load(&mWsTransport);
  315. }
  316. shared_ptr<WsHandshake> WebSocket::getWsHandshake() const {
  317. return std::atomic_load(&mWsHandshake);
  318. }
  319. void WebSocket::closeTransports() {
  320. PLOG_VERBOSE << "Closing transports";
  321. if (!changeState(State::Closed))
  322. return; // already closed
  323. // Pass the pointers to a thread, allowing to terminate a transport from its own thread
  324. auto ws = std::atomic_exchange(&mWsTransport, decltype(mWsTransport)(nullptr));
  325. auto tls = std::atomic_exchange(&mTlsTransport, decltype(mTlsTransport)(nullptr));
  326. auto tcp = std::atomic_exchange(&mTcpTransport, decltype(mTcpTransport)(nullptr));
  327. if (ws)
  328. ws->onRecv(nullptr);
  329. using array = std::array<shared_ptr<Transport>, 3>;
  330. array transports{std::move(ws), std::move(tls), std::move(tcp)};
  331. for (const auto &t : transports)
  332. if (t)
  333. t->onStateChange(nullptr);
  334. ThreadPool::Instance().enqueue([transports = std::move(transports)]() mutable {
  335. for (const auto &t : transports)
  336. if (t)
  337. t->stop();
  338. for (auto &t : transports)
  339. t.reset();
  340. });
  341. triggerClosed();
  342. }
  343. } // namespace rtc::impl
  344. #endif