test_websocket_heartbeat.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // Standalone test for WebSocket heartbeat and close() timing, compiled with
  2. // short intervals and timeouts so the tests don't wait for the defaults.
  3. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 1
  4. #define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 3
  5. #define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 3
  6. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 1
  7. #include <httplib.h>
  8. #include "gtest/gtest.h"
  9. #include <future>
  10. using namespace httplib;
  11. class WebSocketHeartbeatTest : public ::testing::Test {
  12. protected:
  13. void SetUp() override {
  14. svr_.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15. std::string msg;
  16. while (ws.read(msg)) {
  17. ws.send(msg);
  18. }
  19. });
  20. port_ = svr_.bind_to_any_port("localhost");
  21. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22. svr_.wait_until_ready();
  23. }
  24. void TearDown() override {
  25. svr_.stop();
  26. thread_.join();
  27. }
  28. Server svr_;
  29. int port_;
  30. std::thread thread_;
  31. };
  32. // Verify that an idle connection stays alive beyond the read timeout
  33. // thanks to automatic heartbeat pings.
  34. TEST_F(WebSocketHeartbeatTest, IdleConnectionStaysAlive) {
  35. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  36. ASSERT_TRUE(client.connect());
  37. // Sleep longer than read timeout (3s). Without heartbeat, the connection
  38. // would time out. With heartbeat pings every 1s, it stays alive.
  39. std::this_thread::sleep_for(std::chrono::seconds(5));
  40. // Connection should still be open
  41. ASSERT_TRUE(client.is_open());
  42. // Verify we can still exchange messages
  43. ASSERT_TRUE(client.send("hello after idle"));
  44. std::string msg;
  45. ASSERT_TRUE(client.read(msg));
  46. EXPECT_EQ("hello after idle", msg);
  47. client.close();
  48. }
  49. // Verify that set_websocket_ping_interval overrides the compile-time default
  50. TEST_F(WebSocketHeartbeatTest, RuntimePingIntervalOverride) {
  51. // The server is already using the compile-time default (1s).
  52. // Create a client with a custom runtime interval.
  53. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  54. client.set_websocket_ping_interval(2);
  55. ASSERT_TRUE(client.connect());
  56. // Sleep longer than read timeout (3s). Client heartbeat at 2s keeps alive.
  57. std::this_thread::sleep_for(std::chrono::seconds(5));
  58. ASSERT_TRUE(client.is_open());
  59. ASSERT_TRUE(client.send("runtime interval"));
  60. std::string msg;
  61. ASSERT_TRUE(client.read(msg));
  62. EXPECT_EQ("runtime interval", msg);
  63. client.close();
  64. }
  65. // Verify that ping_interval=0 disables heartbeat without breaking basic I/O.
  66. TEST_F(WebSocketHeartbeatTest, ZeroDisablesHeartbeat) {
  67. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  68. client.set_websocket_ping_interval(0);
  69. ASSERT_TRUE(client.connect());
  70. // Basic send/receive still works with heartbeat disabled
  71. ASSERT_TRUE(client.send("no client ping"));
  72. std::string msg;
  73. ASSERT_TRUE(client.read(msg));
  74. EXPECT_EQ("no client ping", msg);
  75. client.close();
  76. }
  77. // Verify that Server::set_websocket_ping_interval works at runtime
  78. class WebSocketServerPingIntervalTest : public ::testing::Test {
  79. protected:
  80. void SetUp() override {
  81. svr_.set_websocket_ping_interval(2);
  82. svr_.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  83. std::string msg;
  84. while (ws.read(msg)) {
  85. ws.send(msg);
  86. }
  87. });
  88. port_ = svr_.bind_to_any_port("localhost");
  89. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  90. svr_.wait_until_ready();
  91. }
  92. void TearDown() override {
  93. svr_.stop();
  94. thread_.join();
  95. }
  96. Server svr_;
  97. int port_;
  98. std::thread thread_;
  99. };
  100. TEST_F(WebSocketServerPingIntervalTest, ServerRuntimeInterval) {
  101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  102. ASSERT_TRUE(client.connect());
  103. // Server ping interval is 2s; client uses compile-time default (1s).
  104. // Both keep the connection alive.
  105. std::this_thread::sleep_for(std::chrono::seconds(5));
  106. ASSERT_TRUE(client.is_open());
  107. ASSERT_TRUE(client.send("server interval"));
  108. std::string msg;
  109. ASSERT_TRUE(client.read(msg));
  110. EXPECT_EQ("server interval", msg);
  111. client.close();
  112. }
  113. // A peer that never sends anything: the server's heartbeat is disabled and its
  114. // handler never calls read(). The pong timeout against such a peer is tested
  115. // in test.cc (WebSocketTest.PongTimeoutEndsABlockedRead), where every CI job
  116. // runs it.
  117. class WebSocketSilentPeerTest : public ::testing::Test {
  118. protected:
  119. void SetUp() override {
  120. svr_.set_websocket_ping_interval(0);
  121. svr_.WebSocket("/ws", [this](const Request &, ws::WebSocket &) {
  122. std::unique_lock<std::mutex> lock(handler_mutex_);
  123. handler_cv_.wait(lock, [this]() { return release_; });
  124. });
  125. port_ = svr_.bind_to_any_port("localhost");
  126. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  127. svr_.wait_until_ready();
  128. }
  129. void TearDown() override {
  130. {
  131. std::lock_guard<std::mutex> lock(handler_mutex_);
  132. release_ = true;
  133. }
  134. handler_cv_.notify_all();
  135. svr_.stop();
  136. thread_.join();
  137. }
  138. Server svr_;
  139. int port_;
  140. std::thread thread_;
  141. std::mutex handler_mutex_;
  142. std::condition_variable handler_cv_;
  143. bool release_ = false;
  144. };
  145. // The compile-time client read timeout (3s here) was never asked for through
  146. // set_read_timeout(), so when it elapses read() reports Fail and closes the
  147. // connection rather than handing back a Timeout on a still-open one.
  148. TEST_F(WebSocketSilentPeerTest, CompileTimeClientReadTimeoutIsFail) {
  149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  150. client.set_websocket_ping_interval(0);
  151. ASSERT_TRUE(client.connect());
  152. // Server pings are off and its handler never sends, so nothing arrives.
  153. std::string msg;
  154. EXPECT_EQ(client.read(msg), ws::Fail);
  155. EXPECT_FALSE(client.is_open());
  156. }
  157. // The compile-time server read timeout (3s here) is a backstop that reclaims
  158. // the worker from a peer gone quiet, not a timeout the handler asked for. When
  159. // it elapses read() must return Fail, so a handler written as
  160. // `while (ws.read(msg))` ends instead of re-running its body with the previous
  161. // message still in `msg`.
  162. class WebSocketServerReadTimeoutTest : public ::testing::Test {
  163. protected:
  164. void SetUp() override {
  165. svr_.set_websocket_ping_interval(0);
  166. svr_.WebSocket("/ws", [this](const Request &, ws::WebSocket &ws) {
  167. std::string msg;
  168. while (ws.read(msg)) {
  169. iterations_++;
  170. ws.send(msg);
  171. }
  172. handler_done_.set_value();
  173. });
  174. port_ = svr_.bind_to_any_port("localhost");
  175. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  176. svr_.wait_until_ready();
  177. }
  178. void TearDown() override {
  179. svr_.stop();
  180. thread_.join();
  181. }
  182. Server svr_;
  183. int port_;
  184. std::thread thread_;
  185. std::atomic<int> iterations_{0};
  186. std::promise<void> handler_done_;
  187. };
  188. TEST_F(WebSocketServerReadTimeoutTest, BackstopEndsHandlerLoop) {
  189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  190. client.set_websocket_ping_interval(0); // nothing reaches the server's read()
  191. client.set_read_timeout(10, 0); // fail rather than hang
  192. ASSERT_TRUE(client.connect());
  193. ASSERT_TRUE(client.send("hello"));
  194. std::string msg;
  195. ASSERT_EQ(client.read(msg), ws::Text);
  196. EXPECT_EQ("hello", msg);
  197. // The client now stays silent. The server's backstop elapses and the
  198. // handler returns, having run its loop body exactly once.
  199. auto done = handler_done_.get_future();
  200. ASSERT_EQ(done.wait_for(std::chrono::seconds(6)), std::future_status::ready);
  201. EXPECT_EQ(1, iterations_.load());
  202. EXPECT_EQ(client.read(msg), ws::Fail);
  203. EXPECT_FALSE(client.is_open());
  204. }
  205. // Verify that a responsive peer does NOT trigger the pong-timeout mechanism,
  206. // even with a small max_missed_pongs budget. This is the positive counterpart
  207. // of WebSocketTest.PongTimeoutEndsABlockedRead in test.cc: the client must
  208. // actively drive read() so that incoming Pong frames are consumed and the
  209. // unacked counter is reset.
  210. TEST_F(WebSocketHeartbeatTest, ResponsivePeerNeverTimesOut) {
  211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  212. client.set_websocket_max_missed_pongs(2);
  213. ASSERT_TRUE(client.connect());
  214. // Interactive loop over ~6s, longer than 2 ping intervals, so the
  215. // pong-timeout mechanism would trigger if pongs weren't being consumed.
  216. // Each iteration's read() also drains any pending Pong frame.
  217. for (int i = 0; i < 6; i++) {
  218. std::string text = "keepalive" + std::to_string(i);
  219. ASSERT_TRUE(client.send(text));
  220. std::string msg;
  221. ASSERT_TRUE(client.read(msg));
  222. EXPECT_EQ(text, msg);
  223. std::this_thread::sleep_for(std::chrono::seconds(1));
  224. }
  225. EXPECT_TRUE(client.is_open());
  226. client.close();
  227. }
  228. // Verify that multiple heartbeat cycles work
  229. TEST_F(WebSocketHeartbeatTest, MultipleHeartbeatCycles) {
  230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws");
  231. ASSERT_TRUE(client.connect());
  232. // Wait through several heartbeat cycles
  233. for (int i = 0; i < 3; i++) {
  234. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  235. ASSERT_TRUE(client.is_open());
  236. std::string text = "msg" + std::to_string(i);
  237. ASSERT_TRUE(client.send(text));
  238. std::string msg;
  239. ASSERT_TRUE(client.read(msg));
  240. EXPECT_EQ(text, msg);
  241. }
  242. client.close();
  243. }
  244. // A raw client never answers the server's close() and sends `bytes`, `chunk`
  245. // bytes at a time `gap` apart; close() must still return at its 1 s timeout.
  246. static void expect_close_bounded(bool use_tls, const std::string &bytes,
  247. size_t chunk, std::chrono::milliseconds gap) {
  248. std::unique_ptr<Server> svr;
  249. #ifdef CPPHTTPLIB_SSL_ENABLED
  250. if (use_tls) { svr.reset(new SSLServer("cert.pem", "key.pem")); }
  251. #endif
  252. if (!svr) { svr.reset(new Server); }
  253. svr->set_websocket_ping_interval(0);
  254. std::atomic<bool> upgraded{false};
  255. std::atomic<bool> closed{false};
  256. std::chrono::steady_clock::duration close_took{};
  257. svr->WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  258. while (!upgraded) {
  259. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  260. }
  261. auto start = std::chrono::steady_clock::now();
  262. ws.close();
  263. close_took = std::chrono::steady_clock::now() - start;
  264. closed = true;
  265. });
  266. auto port = svr->bind_to_any_port("127.0.0.1");
  267. ASSERT_GT(port, 0);
  268. std::thread t([&] { svr->listen_after_bind(); });
  269. auto se = detail::scope_exit([&] {
  270. upgraded = true; // Releases the handler when an assertion bails out early
  271. svr->stop();
  272. t.join();
  273. });
  274. svr->wait_until_ready();
  275. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_NE(INVALID_SOCKET, sock);
  277. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  278. sockaddr_in addr{};
  279. addr.sin_family = AF_INET;
  280. addr.sin_port = htons(static_cast<uint16_t>(port));
  281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  282. ASSERT_EQ(0,
  283. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  284. std::unique_ptr<Stream> strm;
  285. #ifdef CPPHTTPLIB_SSL_ENABLED
  286. tls::ctx_t ctx = nullptr;
  287. tls::session_t session = nullptr;
  288. auto tls_se = detail::scope_exit([&] {
  289. if (session) { tls::free_session(session); }
  290. if (ctx) { tls::free_context(ctx); }
  291. });
  292. if (use_tls) {
  293. ctx = tls::create_client_context();
  294. tls::set_verify_client(ctx, false); // The test certificate is self-signed
  295. session = tls::create_session(ctx, sock);
  296. ASSERT_TRUE(tls::connect_nonblocking(session, sock, 5, 0, nullptr));
  297. strm.reset(new detail::SSLSocketStream(sock, session, 5, 0, 5, 0));
  298. }
  299. #endif
  300. if (!strm) { strm.reset(new detail::SocketStream(sock, 5, 0, 5, 0)); }
  301. const std::string upgrade = "GET /ws HTTP/1.1\r\n"
  302. "Host: 127.0.0.1\r\n"
  303. "Upgrade: websocket\r\n"
  304. "Connection: Upgrade\r\n"
  305. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  306. "Sec-WebSocket-Version: 13\r\n"
  307. "\r\n";
  308. ASSERT_EQ(static_cast<ssize_t>(upgrade.size()),
  309. strm->write(upgrade.data(), upgrade.size()));
  310. std::string response;
  311. char c;
  312. while (response.find("\r\n\r\n") == std::string::npos &&
  313. strm->read(&c, 1) == 1) {
  314. response += c;
  315. }
  316. ASSERT_NE(std::string::npos, response.find(" 101 "));
  317. upgraded = true;
  318. // Without the bound, close() would wait as long as the client sends
  319. auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(4);
  320. while (!closed && std::chrono::steady_clock::now() < give_up) {
  321. for (size_t off = 0; off < bytes.size() && !closed;) {
  322. auto n = strm->write(bytes.data() + off,
  323. (std::min)(chunk, bytes.size() - off));
  324. if (n <= 0) { break; }
  325. off += static_cast<size_t>(n);
  326. auto next = std::chrono::steady_clock::now() + gap;
  327. while (!closed && std::chrono::steady_clock::now() < next) {
  328. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  329. }
  330. }
  331. }
  332. while (!closed) {
  333. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  334. }
  335. EXPECT_LT(close_took, std::chrono::milliseconds(2500));
  336. }
  337. // Empty masked Ping frames, enough to keep the socket full
  338. static std::string ping_flood() {
  339. const std::string ping("\x89\x80\0\0\0\0", 6);
  340. std::string bytes;
  341. while (bytes.size() < 64 * 1024) {
  342. bytes += ping;
  343. }
  344. return bytes;
  345. }
  346. // A masked 20-byte Ping; sent a byte at a time, it outlasts the close timeout
  347. static std::string ping_with_payload() {
  348. return std::string("\x89\x8e\0\0\0\0", 6) + std::string(14, 'x');
  349. }
  350. TEST(WebSocketCloseTest, BoundedAgainstPeerThatKeepsSending) {
  351. expect_close_bounded(/*use_tls=*/false, ping_flood(), ping_flood().size(),
  352. std::chrono::milliseconds(0));
  353. }
  354. TEST(WebSocketCloseTest, BoundedAgainstPeerThatTricklesAFrame) {
  355. expect_close_bounded(/*use_tls=*/false, ping_with_payload(), 1,
  356. std::chrono::milliseconds(300));
  357. }
  358. #ifdef CPPHTTPLIB_SSL_ENABLED
  359. TEST(WebSocketCloseTest, SSLBoundedAgainstPeerThatKeepsSending) {
  360. expect_close_bounded(/*use_tls=*/true, ping_flood(), ping_flood().size(),
  361. std::chrono::milliseconds(0));
  362. }
  363. TEST(WebSocketCloseTest, SSLBoundedAgainstPeerThatTricklesAFrame) {
  364. expect_close_bounded(/*use_tls=*/true, ping_with_payload(), 1,
  365. std::chrono::milliseconds(300));
  366. }
  367. #endif