Loading test/CMakeLists.txt +12 −0 Original line number Diff line number Diff line Loading @@ -165,3 +165,15 @@ else() endif() add_test(httpd_h2_peer_address_test httpd_h2_peer_address_test) add_executable(httpd_connection_handoff_test httpd_connection_handoff_test.cpp ) if(WIN32) target_link_libraries (httpd_connection_handoff_test httppp-static ws2_32) else() target_link_libraries (httpd_connection_handoff_test httppp-static) endif() add_test(httpd_connection_handoff_test httpd_connection_handoff_test) test/httpd_connection_handoff_test.cpp 0 → 100644 +220 −0 Original line number Diff line number Diff line /******************************************************************************* Copyright (c) 2026, Jan Koester jan.koester@gmx.net All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ // Regression test for netplus::detachConnection() (proxyplus's WebSocket // tunnel support needs this: a request handler takes over a connection's // socket for raw byte relay outside the normal HTTP read/dispatch/write // cycle, e.g. after a WebSocket upgrade). Exercises it through a REAL // epoll-driven HttpEvent server, not a mock, since the whole point is // proving the event loop truly stops touching a detached connection's fd // (no double-read race with whatever the handler does with it afterward, // no crash in the framework's own post-RequestEvent code that still // expects a socket) -- see netplus/src/event/epoll.cpp and // libnetplus/src/connection.h's detachConnection() doc comment. // // GET /handoff detaches curreq's socket and spawns a plain thread that // echoes back whatever raw bytes it receives, uppercased, twice, then // closes. No HTTP response is ever sent through the normal path -- the // test client must see the raw echoed bytes appear on the same connection // with no framework interference, and the server process must not crash // or hang afterward (checked by cleanly stopping the whole event loop at // the end, which would deadlock/abort if the framework still held stale // state for the detached connection). #include <chrono> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <thread> #include <vector> #include <netplus/connection.h> #include <netplus/exception.h> #include <netplus/socket.h> #include "http.h" #include "httpd.h" #include "raw_tcp_client.h" using namespace libhttppp; namespace { int g_passed = 0, g_failed = 0; void check(bool ok, const std::string &name) { if (ok) { std::cout << " PASS: " << name << std::endl; ++g_passed; } else { std::cout << " FAIL: " << name << std::endl; ++g_failed; } } void echoThread(std::unique_ptr<netplus::socket> sock) { sock->setBlock(); for (int i = 0; i < 2; ++i) { netplus::buffer buf(256); size_t n = sock->recvData(buf, 0); if (n == 0) break; std::string data(buf.data.buf, n); for (auto &c : data) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c))); netplus::buffer out(data.data(), data.size()); sock->sendData(out, 0); } sock->close(); } class HandoffServer : public HttpEvent { public: explicit HandoffServer(std::vector<netplus::socket *> serversocket) : HttpEvent(serversocket) {} void RequestEvent(HttpRequest &req, const int, ULONG_PTR) override { if (req.getRequestURL() == "/handoff") { auto sock = netplus::detachConnection(req); if (!sock) { std::cerr << "detachConnection returned null" << std::endl; return; } std::thread(echoThread, std::move(sock)).detach(); return; } HttpResponse res; res.setState("404 Not Found"); res.send(req, std::string("not found"), 9); } }; struct RunningServer { std::unique_ptr<netplus::tcp> sock; std::unique_ptr<HandoffServer> server; std::thread thread; RunningServer() = default; RunningServer(RunningServer &&) = default; RunningServer &operator=(RunningServer &&) = default; ~RunningServer() { if (thread.joinable()) { netplus::event::Running = false; thread.join(); } } }; RunningServer startServer(int &port) { RunningServer rs; rs.sock = std::make_unique<netplus::tcp>("127.0.0.1", 0, 16, -1); rs.sock->bind(); port = rawtcp::boundPort(*rs.sock); rs.sock->listen(); rs.server = std::make_unique<HandoffServer>(std::vector<netplus::socket *>{rs.sock.get()}); netplus::event::Running = true; HandoffServer *serverPtr = rs.server.get(); rs.thread = std::thread([serverPtr] { serverPtr->runEventloop(); }); std::this_thread::sleep_for(std::chrono::milliseconds(50)); return rs; } } // namespace int main() { std::cout << "=== Connection Handoff (detachConnection) Test ===" << std::endl; int rc = 0; try { int port = 0; RunningServer rs = startServer(port); std::cout << "Server listening on 127.0.0.1:" << port << std::endl; auto sock = std::make_unique<netplus::tcp>(); rawtcp::connectLocal(*sock, port); std::ostringstream req; req << "GET /handoff HTTP/1.1\r\n" << "Host: 127.0.0.1:" << port << "\r\n" << "Connection: keep-alive\r\n" << "\r\n"; rawtcp::sendAllOrThrow(*sock, req.str()); // No HTTP response is ever sent for /handoff -- the first bytes on // this connection are the echo thread's raw reply to whatever we // send it next, not an HTTP response. A tiny wait lets RequestEvent // (and the detach) actually run before we send. std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto recvExact = [&](size_t want) -> std::string { std::string acc; auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); while (acc.size() < want) { if (std::chrono::steady_clock::now() > deadline) throw std::runtime_error("timed out waiting for echoed bytes"); netplus::buffer buf(256); size_t n; try { n = sock->recvData(buf); } catch (netplus::NetException &) { continue; } if (n > 0) acc.append(buf.data.buf, n); } return acc; }; rawtcp::sendAllOrThrow(*sock, std::string("hello")); std::string echo1 = recvExact(5); check(echo1 == "HELLO", "first raw write after handoff echoes back uppercased, " "untouched by the HTTP framework"); rawtcp::sendAllOrThrow(*sock, std::string("again")); std::string echo2 = recvExact(5); check(echo2 == "AGAIN", "second round-trip on the same detached socket still works " "(no lingering framework interference)"); sock->close(); // rs's destructor (at scope exit below) stops the event loop and // joins its thread. If the framework still held stale state for the // detached connection (e.g. a dangling CONNECTIONS map entry, or a // crash in the post-RequestEvent code path once csock is null), that // shutdown would hang or the process would already have crashed by // the time this test's exit code is checked. } catch (HTTPException &e) { std::cerr << "HTTPException: " << e.what() << std::endl; rc = 1; } catch (netplus::NetException &e) { std::cerr << "NetException: " << e.what() << std::endl; rc = 1; } catch (std::exception &e) { std::cerr << "Exception: " << e.what() << std::endl; rc = 1; } std::cout << "==============================" << std::endl; std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl; std::cout << "==============================" << std::endl; return (rc != 0 || g_failed > 0) ? 1 : 0; } Loading
test/CMakeLists.txt +12 −0 Original line number Diff line number Diff line Loading @@ -165,3 +165,15 @@ else() endif() add_test(httpd_h2_peer_address_test httpd_h2_peer_address_test) add_executable(httpd_connection_handoff_test httpd_connection_handoff_test.cpp ) if(WIN32) target_link_libraries (httpd_connection_handoff_test httppp-static ws2_32) else() target_link_libraries (httpd_connection_handoff_test httppp-static) endif() add_test(httpd_connection_handoff_test httpd_connection_handoff_test)
test/httpd_connection_handoff_test.cpp 0 → 100644 +220 −0 Original line number Diff line number Diff line /******************************************************************************* Copyright (c) 2026, Jan Koester jan.koester@gmx.net All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ // Regression test for netplus::detachConnection() (proxyplus's WebSocket // tunnel support needs this: a request handler takes over a connection's // socket for raw byte relay outside the normal HTTP read/dispatch/write // cycle, e.g. after a WebSocket upgrade). Exercises it through a REAL // epoll-driven HttpEvent server, not a mock, since the whole point is // proving the event loop truly stops touching a detached connection's fd // (no double-read race with whatever the handler does with it afterward, // no crash in the framework's own post-RequestEvent code that still // expects a socket) -- see netplus/src/event/epoll.cpp and // libnetplus/src/connection.h's detachConnection() doc comment. // // GET /handoff detaches curreq's socket and spawns a plain thread that // echoes back whatever raw bytes it receives, uppercased, twice, then // closes. No HTTP response is ever sent through the normal path -- the // test client must see the raw echoed bytes appear on the same connection // with no framework interference, and the server process must not crash // or hang afterward (checked by cleanly stopping the whole event loop at // the end, which would deadlock/abort if the framework still held stale // state for the detached connection). #include <chrono> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <thread> #include <vector> #include <netplus/connection.h> #include <netplus/exception.h> #include <netplus/socket.h> #include "http.h" #include "httpd.h" #include "raw_tcp_client.h" using namespace libhttppp; namespace { int g_passed = 0, g_failed = 0; void check(bool ok, const std::string &name) { if (ok) { std::cout << " PASS: " << name << std::endl; ++g_passed; } else { std::cout << " FAIL: " << name << std::endl; ++g_failed; } } void echoThread(std::unique_ptr<netplus::socket> sock) { sock->setBlock(); for (int i = 0; i < 2; ++i) { netplus::buffer buf(256); size_t n = sock->recvData(buf, 0); if (n == 0) break; std::string data(buf.data.buf, n); for (auto &c : data) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c))); netplus::buffer out(data.data(), data.size()); sock->sendData(out, 0); } sock->close(); } class HandoffServer : public HttpEvent { public: explicit HandoffServer(std::vector<netplus::socket *> serversocket) : HttpEvent(serversocket) {} void RequestEvent(HttpRequest &req, const int, ULONG_PTR) override { if (req.getRequestURL() == "/handoff") { auto sock = netplus::detachConnection(req); if (!sock) { std::cerr << "detachConnection returned null" << std::endl; return; } std::thread(echoThread, std::move(sock)).detach(); return; } HttpResponse res; res.setState("404 Not Found"); res.send(req, std::string("not found"), 9); } }; struct RunningServer { std::unique_ptr<netplus::tcp> sock; std::unique_ptr<HandoffServer> server; std::thread thread; RunningServer() = default; RunningServer(RunningServer &&) = default; RunningServer &operator=(RunningServer &&) = default; ~RunningServer() { if (thread.joinable()) { netplus::event::Running = false; thread.join(); } } }; RunningServer startServer(int &port) { RunningServer rs; rs.sock = std::make_unique<netplus::tcp>("127.0.0.1", 0, 16, -1); rs.sock->bind(); port = rawtcp::boundPort(*rs.sock); rs.sock->listen(); rs.server = std::make_unique<HandoffServer>(std::vector<netplus::socket *>{rs.sock.get()}); netplus::event::Running = true; HandoffServer *serverPtr = rs.server.get(); rs.thread = std::thread([serverPtr] { serverPtr->runEventloop(); }); std::this_thread::sleep_for(std::chrono::milliseconds(50)); return rs; } } // namespace int main() { std::cout << "=== Connection Handoff (detachConnection) Test ===" << std::endl; int rc = 0; try { int port = 0; RunningServer rs = startServer(port); std::cout << "Server listening on 127.0.0.1:" << port << std::endl; auto sock = std::make_unique<netplus::tcp>(); rawtcp::connectLocal(*sock, port); std::ostringstream req; req << "GET /handoff HTTP/1.1\r\n" << "Host: 127.0.0.1:" << port << "\r\n" << "Connection: keep-alive\r\n" << "\r\n"; rawtcp::sendAllOrThrow(*sock, req.str()); // No HTTP response is ever sent for /handoff -- the first bytes on // this connection are the echo thread's raw reply to whatever we // send it next, not an HTTP response. A tiny wait lets RequestEvent // (and the detach) actually run before we send. std::this_thread::sleep_for(std::chrono::milliseconds(100)); auto recvExact = [&](size_t want) -> std::string { std::string acc; auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); while (acc.size() < want) { if (std::chrono::steady_clock::now() > deadline) throw std::runtime_error("timed out waiting for echoed bytes"); netplus::buffer buf(256); size_t n; try { n = sock->recvData(buf); } catch (netplus::NetException &) { continue; } if (n > 0) acc.append(buf.data.buf, n); } return acc; }; rawtcp::sendAllOrThrow(*sock, std::string("hello")); std::string echo1 = recvExact(5); check(echo1 == "HELLO", "first raw write after handoff echoes back uppercased, " "untouched by the HTTP framework"); rawtcp::sendAllOrThrow(*sock, std::string("again")); std::string echo2 = recvExact(5); check(echo2 == "AGAIN", "second round-trip on the same detached socket still works " "(no lingering framework interference)"); sock->close(); // rs's destructor (at scope exit below) stops the event loop and // joins its thread. If the framework still held stale state for the // detached connection (e.g. a dangling CONNECTIONS map entry, or a // crash in the post-RequestEvent code path once csock is null), that // shutdown would hang or the process would already have crashed by // the time this test's exit code is checked. } catch (HTTPException &e) { std::cerr << "HTTPException: " << e.what() << std::endl; rc = 1; } catch (netplus::NetException &e) { std::cerr << "NetException: " << e.what() << std::endl; rc = 1; } catch (std::exception &e) { std::cerr << "Exception: " << e.what() << std::endl; rc = 1; } std::cout << "==============================" << std::endl; std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl; std::cout << "==============================" << std::endl; return (rc != 0 || g_failed > 0) ? 1 : 0; }