Loading src/.CMakeLists.txt.kate-swpdeleted 100644 → 0 +0 −0 Empty file deleted. src/event/epoll.cpp +6 −17 Changes for src/event/epoll.cpp: 6 added lines, 17 removed lines. Original line number Diff line number Diff line Loading @@ -217,26 +217,15 @@ namespace netplus { // ✅ Pass the certificate bundle map (SNI will select appropriate cert per connection) ccon->csock = std::make_unique<ssl>(srv->_tls.cert_map, -1); } else if (_ServerSocket->_Type == sockettype::QUIC) { // QUIC: All child connections share the parent's UDP socket. // accept() receives one UDP datagram per call and routes it // to existing children or creates a new connection. // Drain all queued datagrams by peeking for more. // Use udp::recvData (base class) with MSG_PEEK|MSG_DONTWAIT // — quic::recvData would throw "connection not established" // on the listener socket. // QUIC: Process ONE UDP datagram per epoll event. // The server socket uses level-triggered EPOLLIN, // so epoll_wait fires again immediately if more // datagrams are queued. This lets the event loop // interleave other work (e.g. PING ACK processing) // between datagrams. { udp* usock = static_cast<udp*>(_ServerSocket); do { std::unique_ptr<socket> quic_csock; _ServerSocket->accept(quic_csock, true); // Peek via UDP layer for more queued datagrams try { buffer peek(1); usock->udp::recvData(peek, MSG_PEEK | MSG_DONTWAIT); } catch (...) { break; } } while (true); } return; } Loading src/posix/udp.cpp +1 −0 Changes for src/posix/udp.cpp: 1 added line, 0 removed lines. Original line number Diff line number Diff line Loading @@ -104,6 +104,7 @@ udp::udp(const std::string& addr, int port, int maxconnections, int sockopts) if (sockopts & SO_REUSEPORT) ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); #endif } udp::udp(const std::string& uxsocket, int maxconnections, int sockopts) Loading src/quic.cpp +158 −89 Changes for src/quic.cpp: 158 added lines, 89 removed lines. Original line number Diff line number Diff line Loading @@ -78,6 +78,12 @@ quic::quic(const std::string& addr, int port, int maxconnections, int sockopts) _handshake_complete = false; _version = QUIC_VERSION_1; // Enlarge the receive buffer so high-throughput clients don't // overrun the kernel queue between epoll_wait cycles. 4 MB keeps // up with ~3000 in-flight 1200-byte QUIC datagrams. int rcvbuf = 4 * 1024 * 1024; ::setsockopt(_Socket, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); // Generate local connection ID for server generateConnectionId(_local_cid, 8); } Loading @@ -92,6 +98,11 @@ quic::quic(const std::map<std::string, ssl::CertificateBundle>& certs, _version = QUIC_VERSION_1; _cert_map = certs; // Enlarge the receive buffer so high-throughput clients don't // overrun the kernel queue between epoll_wait cycles. 4 MB keeps // up with ~3000 in-flight 1200-byte QUIC datagrams. int rcvbuf = 4 * 1024 * 1024; ::setsockopt(_Socket, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); // Generate local connection ID for server generateConnectionId(_local_cid, 8); Loading Loading @@ -934,6 +945,19 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { return; } // Drain up to 512 datagrams per call. On high-throughput links (esp. // localhost) the client may burst many QUIC packets between epoll_wait // cycles. If we only read one datagram per cycle the kernel UDP // receive buffer overflows, the client detects packet loss and its // congestion window collapses. Draining here keeps up with the // sender. For packets belonging to *existing* connections we process // and ACK immediately, then loop back for the next datagram. A new // Initial packet (new connection) exits the loop so the caller can // register it. static constexpr int MAX_DRAIN = 512; for (int drain_i = 0; drain_i < MAX_DRAIN; ++drain_i) { // Allocate receive buffer for incoming UDP datagram std::vector<uint8_t> dgram(65535); sockaddr_storage peer_addr{}; Loading Loading @@ -981,8 +1005,8 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // We assume 8-byte CID (configurable) size_t cid_len = 8; // Default CID length if (dgram.size() < 1 + cid_len) { csock = nullptr; return; // Malformed — skip and try next datagram continue; } std::vector<uint8_t> dcid(dgram.begin() + 1, dgram.begin() + 1 + cid_len); Loading @@ -1004,18 +1028,35 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); existing->processIncomingPacket(dgram.data(), dgram.size()); } // Dispatch stream callbacks in a background thread so // the drain loop continues without delay. { std::vector<PendingDispatch> dispatches; { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); dispatches = std::move(existing->_pending_dispatches); existing->_pending_dispatches.clear(); } if (!dispatches.empty() && existing->_stream_callback) { auto cb = existing->_stream_callback; std::thread([cb, existing, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(existing, pd.stream_id, pd.data, pd.fin); } }).detach(); } } } } else { } csock = nullptr; return; // Re-lock parent and drain next datagram lock.lock(); continue; } // Parse long header to extract connection IDs if (dgram.size() < 7) { csock = nullptr; return; continue; // Malformed — skip } // Extract version Loading @@ -1026,21 +1067,18 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Check for version negotiation (version == 0 means VN) if (version == 0) { csock = nullptr; return; continue; // Skip VN packets } // Parse DCID (Destination Connection ID - this is our CID) size_t offset = 5; if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } uint8_t dcid_len = dgram[offset++]; if (dcid_len > 20 || offset + dcid_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> dcid(dgram.begin() + offset, dgram.begin() + offset + dcid_len); Loading @@ -1049,14 +1087,12 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Parse SCID (Source Connection ID - client's CID) if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } uint8_t scid_len = dgram[offset++]; if (scid_len > 20 || offset + scid_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> scid(dgram.begin() + offset, dgram.begin() + offset + scid_len); Loading Loading @@ -1097,32 +1133,48 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); existing->processIncomingPacket(dgram.data(), dgram.size()); } // Dispatch stream callbacks in a background thread so // the drain loop continues without delay. { std::vector<PendingDispatch> dispatches; { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); dispatches = std::move(existing->_pending_dispatches); existing->_pending_dispatches.clear(); } if (!dispatches.empty() && existing->_stream_callback) { auto cb = existing->_stream_callback; std::thread([cb, existing, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(existing, pd.stream_id, pd.data, pd.fin); } }).detach(); } } csock = nullptr; // Don't create a new connection return; // Re-lock parent and drain next datagram lock.lock(); continue; } } // Check packet type - must be Initial (0x00) for new connections uint8_t packet_type = (dgram[0] & 0x30) >> 4; if (packet_type != 0x00) { // Not an Initial packet and no existing connection found - ignore csock = nullptr; return; // Not an Initial packet and no existing connection found - skip continue; } // Verify supported version if (version != QUIC_VERSION_1 && version != QUIC_VERSION_2) { // Send Version Negotiation packet // TODO: Implement version negotiation csock = nullptr; return; continue; } // Parse token (for Initial packets) if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } size_t tok_bytes; Loading @@ -1130,8 +1182,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { offset += tok_bytes; if (offset + token_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> token(dgram.begin() + offset, dgram.begin() + offset + token_len); Loading Loading @@ -1202,6 +1253,12 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Don't transfer ownership to csock (would cause double-free). // QUIC connections share the parent socket and are routed via accept(). csock = nullptr; return; // New connection created — exit drain loop } // end drain loop (for drain_i) // Reached MAX_DRAIN limit — will be called again by epoll csock = nullptr; } // ============================================================================ Loading Loading @@ -1480,14 +1537,15 @@ void quic::processApplicationPacket(const uint8_t* data, size_t len) { } } // Send ACK immediately — before processing frames — so the peer // does not time out if a stream callback (e.g. RequestEvent) blocks // for a long time during heavy request handling. sendAppAck(); size_t offset = 0; while (offset < payload.size()) { processFrame(payload.data(), payload.size(), offset); } // Send ACK for received 1-RTT packets so the peer's congestion // controller can open its window and continue sending data. sendAppAck(); } // ============================================================================ Loading Loading @@ -2159,6 +2217,10 @@ void quic::completeHandshake() { // ============================================================================ size_t quic::recvData(buffer& data, int flags) { std::vector<PendingDispatch> dispatches; size_t result = 0; { // Scoped lock — released before invoking stream callbacks std::lock_guard<std::mutex> lock(_quic_mutex); // Check connection state Loading @@ -2175,84 +2237,86 @@ size_t quic::recvData(buffer& data, int flags) { } // First, check if we have buffered data from any stream // For simplicity, we use stream 0 as the default data stream uint64_t default_stream = _is_server ? 1 : 0; // Client-initiated bidi stream // Check if there's data in our default stream auto it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { // Copy data from stream buffer to output buffer size_t to_copy = std::min(data.size, it->second.recv_buffer.size()); std::memcpy(data.data.buf, it->second.recv_buffer.data(), to_copy); // Remove copied data from stream buffer it->second.recv_buffer.erase( it->second.recv_buffer.begin(), it->second.recv_buffer.begin() + to_copy); it->second.recv_offset += to_copy; uint64_t default_stream = _is_server ? 1 : 0; auto check_stream = [&](auto& stream_ref) -> bool { size_t to_copy = std::min(data.size, stream_ref.recv_buffer.size()); std::memcpy(data.data.buf, stream_ref.recv_buffer.data(), to_copy); stream_ref.recv_buffer.erase( stream_ref.recv_buffer.begin(), stream_ref.recv_buffer.begin() + to_copy); stream_ref.recv_offset += to_copy; _data_recv += to_copy; data.size = to_copy; return to_copy; } result = to_copy; return true; }; auto it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { check_stream(it->second); } else { // No buffered data, try to receive from network int recv_flags = (flags & MSG_DONTWAIT) ? MSG_DONTWAIT : 0; size_t recv_len; buffer recv_buf_wrapper(65535); size_t recv_len; try { recv_len = udp::recvData(recv_buf_wrapper, recv_flags); } catch (NetException&) { // EAGAIN/EWOULDBLOCK - propagate as-is throw; } if (recv_len == 0) { // Connection closed by peer data.size = 0; return 0; } // Process the received packet result = 0; } else { processIncomingPacket(reinterpret_cast<const uint8_t*>(recv_buf_wrapper.data.buf), recv_len); // After processing, check again for buffered stream data // After processing, check for buffered stream data bool found = false; it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { size_t to_copy = std::min(data.size, it->second.recv_buffer.size()); std::memcpy(data.data.buf, it->second.recv_buffer.data(), to_copy); check_stream(it->second); found = true; } it->second.recv_buffer.erase( it->second.recv_buffer.begin(), it->second.recv_buffer.begin() + to_copy); it->second.recv_offset += to_copy; _data_recv += to_copy; if (!found) { // Check all streams for (auto& [sid, stream] : _streams) { if (!stream.recv_buffer.empty()) { check_stream(stream); found = true; break; } } } data.size = to_copy; return to_copy; if (!found) { data.size = 0; result = 0; } } } // Check all streams for data if default stream has none for (auto& [stream_id, stream] : _streams) { if (!stream.recv_buffer.empty()) { size_t to_copy = std::min(data.size, stream.recv_buffer.size()); std::memcpy(data.data.buf, stream.recv_buffer.data(), to_copy); // Collect pending dispatches before releasing lock dispatches = std::move(_pending_dispatches); _pending_dispatches.clear(); stream.recv_buffer.erase( stream.recv_buffer.begin(), stream.recv_buffer.begin() + to_copy); stream.recv_offset += to_copy; _data_recv += to_copy; } // mutex released data.size = to_copy; return to_copy; // Dispatch stream callbacks in a background thread so the // caller returns immediately — prevents PING timeout. if (!dispatches.empty() && _stream_callback) { auto cb = _stream_callback; auto self = this; std::thread([cb, self, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(self, pd.stream_id, pd.data, pd.fin); } }).detach(); } // No data available yet (packet might have been handshake, ACK, etc.) data.size = 0; return 0; return result; } // ============================================================================ Loading Loading @@ -2736,22 +2800,25 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { stream.recv_complete = true; } // Notify application layer via callback // Queue stream dispatch — will be invoked OUTSIDE _quic_mutex // so that long-running callbacks (e.g. import) don't block PING ACKs. // For bidirectional request streams (stream_id % 4 == 0): wait until complete // For unidirectional streams: notify immediately (control/QPACK streams) if (_is_server && _stream_callback) { bool is_bidi_request = (stream_id % 4 == 0); if (is_bidi_request && stream.recv_complete && !stream.recv_dispatched) { std::cerr << "[QUIC-FC] Dispatching bidi stream " << stream_id << " to app, size=" << stream.recv_buffer.size() << std::endl; std::cerr << "[QUIC-FC] Queuing bidi stream " << stream_id << " for dispatch, size=" << stream.recv_buffer.size() << std::endl; stream.recv_dispatched = true; _stream_callback(this, stream_id, stream.recv_buffer, true); // Free memory — data has been delivered to application _pending_dispatches.push_back({stream_id, std::move(stream.recv_buffer), true}); // Free memory — data has been moved to pending dispatch stream.recv_buffer.clear(); stream.recv_buffer.shrink_to_fit(); stream.recv_ranges.clear(); } else if (!is_bidi_request) { // Unidirectional stream - notify for control stream setup // Unidirectional stream - notify immediately (control/QPACK, small) _stream_callback(this, stream_id, stream.recv_buffer, stream.recv_fin); } } Loading Loading @@ -2805,6 +2872,8 @@ void quic::processAckFrame(const uint8_t* data, size_t len, size_t& offset) { // ============================================================================ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data, bool fin) { std::lock_guard<std::mutex> lock(_quic_mutex); // Maximum QUIC datagram size minus short header overhead: // 1 (flags) + dcid_len + 4 (PN) + 16 (GCM tag) + frame header (~11 max) const size_t header_overhead = 1 + _remote_cid.size() + 4 + 16; Loading src/socket.h +10 −0 Changes for src/socket.h: 10 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -828,6 +828,16 @@ namespace netplus { using QuicStreamCallback = std::function<void(quic*, uint64_t, const std::vector<uint8_t>&, bool)>; QuicStreamCallback _stream_callback; // Deferred stream dispatches — filled inside _quic_mutex, // invoked AFTER releasing it so callbacks can't block the // QUIC packet processing loop (prevents PING timeouts). struct PendingDispatch { uint64_t stream_id; std::vector<uint8_t> data; bool fin; }; std::vector<PendingDispatch> _pending_dispatches; // Handshake timeout tracking // Detects when client sends incomplete ClientHello with large gaps (likely packet loss) std::chrono::steady_clock::time_point _handshake_start_time; Loading Loading
src/event/epoll.cpp +6 −17 Changes for src/event/epoll.cpp: 6 added lines, 17 removed lines. Original line number Diff line number Diff line Loading @@ -217,26 +217,15 @@ namespace netplus { // ✅ Pass the certificate bundle map (SNI will select appropriate cert per connection) ccon->csock = std::make_unique<ssl>(srv->_tls.cert_map, -1); } else if (_ServerSocket->_Type == sockettype::QUIC) { // QUIC: All child connections share the parent's UDP socket. // accept() receives one UDP datagram per call and routes it // to existing children or creates a new connection. // Drain all queued datagrams by peeking for more. // Use udp::recvData (base class) with MSG_PEEK|MSG_DONTWAIT // — quic::recvData would throw "connection not established" // on the listener socket. // QUIC: Process ONE UDP datagram per epoll event. // The server socket uses level-triggered EPOLLIN, // so epoll_wait fires again immediately if more // datagrams are queued. This lets the event loop // interleave other work (e.g. PING ACK processing) // between datagrams. { udp* usock = static_cast<udp*>(_ServerSocket); do { std::unique_ptr<socket> quic_csock; _ServerSocket->accept(quic_csock, true); // Peek via UDP layer for more queued datagrams try { buffer peek(1); usock->udp::recvData(peek, MSG_PEEK | MSG_DONTWAIT); } catch (...) { break; } } while (true); } return; } Loading
src/posix/udp.cpp +1 −0 Changes for src/posix/udp.cpp: 1 added line, 0 removed lines. Original line number Diff line number Diff line Loading @@ -104,6 +104,7 @@ udp::udp(const std::string& addr, int port, int maxconnections, int sockopts) if (sockopts & SO_REUSEPORT) ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); #endif } udp::udp(const std::string& uxsocket, int maxconnections, int sockopts) Loading
src/quic.cpp +158 −89 Changes for src/quic.cpp: 158 added lines, 89 removed lines. Original line number Diff line number Diff line Loading @@ -78,6 +78,12 @@ quic::quic(const std::string& addr, int port, int maxconnections, int sockopts) _handshake_complete = false; _version = QUIC_VERSION_1; // Enlarge the receive buffer so high-throughput clients don't // overrun the kernel queue between epoll_wait cycles. 4 MB keeps // up with ~3000 in-flight 1200-byte QUIC datagrams. int rcvbuf = 4 * 1024 * 1024; ::setsockopt(_Socket, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); // Generate local connection ID for server generateConnectionId(_local_cid, 8); } Loading @@ -92,6 +98,11 @@ quic::quic(const std::map<std::string, ssl::CertificateBundle>& certs, _version = QUIC_VERSION_1; _cert_map = certs; // Enlarge the receive buffer so high-throughput clients don't // overrun the kernel queue between epoll_wait cycles. 4 MB keeps // up with ~3000 in-flight 1200-byte QUIC datagrams. int rcvbuf = 4 * 1024 * 1024; ::setsockopt(_Socket, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)); // Generate local connection ID for server generateConnectionId(_local_cid, 8); Loading Loading @@ -934,6 +945,19 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { return; } // Drain up to 512 datagrams per call. On high-throughput links (esp. // localhost) the client may burst many QUIC packets between epoll_wait // cycles. If we only read one datagram per cycle the kernel UDP // receive buffer overflows, the client detects packet loss and its // congestion window collapses. Draining here keeps up with the // sender. For packets belonging to *existing* connections we process // and ACK immediately, then loop back for the next datagram. A new // Initial packet (new connection) exits the loop so the caller can // register it. static constexpr int MAX_DRAIN = 512; for (int drain_i = 0; drain_i < MAX_DRAIN; ++drain_i) { // Allocate receive buffer for incoming UDP datagram std::vector<uint8_t> dgram(65535); sockaddr_storage peer_addr{}; Loading Loading @@ -981,8 +1005,8 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // We assume 8-byte CID (configurable) size_t cid_len = 8; // Default CID length if (dgram.size() < 1 + cid_len) { csock = nullptr; return; // Malformed — skip and try next datagram continue; } std::vector<uint8_t> dcid(dgram.begin() + 1, dgram.begin() + 1 + cid_len); Loading @@ -1004,18 +1028,35 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); existing->processIncomingPacket(dgram.data(), dgram.size()); } // Dispatch stream callbacks in a background thread so // the drain loop continues without delay. { std::vector<PendingDispatch> dispatches; { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); dispatches = std::move(existing->_pending_dispatches); existing->_pending_dispatches.clear(); } if (!dispatches.empty() && existing->_stream_callback) { auto cb = existing->_stream_callback; std::thread([cb, existing, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(existing, pd.stream_id, pd.data, pd.fin); } }).detach(); } } } } else { } csock = nullptr; return; // Re-lock parent and drain next datagram lock.lock(); continue; } // Parse long header to extract connection IDs if (dgram.size() < 7) { csock = nullptr; return; continue; // Malformed — skip } // Extract version Loading @@ -1026,21 +1067,18 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Check for version negotiation (version == 0 means VN) if (version == 0) { csock = nullptr; return; continue; // Skip VN packets } // Parse DCID (Destination Connection ID - this is our CID) size_t offset = 5; if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } uint8_t dcid_len = dgram[offset++]; if (dcid_len > 20 || offset + dcid_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> dcid(dgram.begin() + offset, dgram.begin() + offset + dcid_len); Loading @@ -1049,14 +1087,12 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Parse SCID (Source Connection ID - client's CID) if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } uint8_t scid_len = dgram[offset++]; if (scid_len > 20 || offset + scid_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> scid(dgram.begin() + offset, dgram.begin() + offset + scid_len); Loading Loading @@ -1097,32 +1133,48 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); existing->processIncomingPacket(dgram.data(), dgram.size()); } // Dispatch stream callbacks in a background thread so // the drain loop continues without delay. { std::vector<PendingDispatch> dispatches; { std::lock_guard<std::mutex> child_lock(existing->_quic_mutex); dispatches = std::move(existing->_pending_dispatches); existing->_pending_dispatches.clear(); } if (!dispatches.empty() && existing->_stream_callback) { auto cb = existing->_stream_callback; std::thread([cb, existing, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(existing, pd.stream_id, pd.data, pd.fin); } }).detach(); } } csock = nullptr; // Don't create a new connection return; // Re-lock parent and drain next datagram lock.lock(); continue; } } // Check packet type - must be Initial (0x00) for new connections uint8_t packet_type = (dgram[0] & 0x30) >> 4; if (packet_type != 0x00) { // Not an Initial packet and no existing connection found - ignore csock = nullptr; return; // Not an Initial packet and no existing connection found - skip continue; } // Verify supported version if (version != QUIC_VERSION_1 && version != QUIC_VERSION_2) { // Send Version Negotiation packet // TODO: Implement version negotiation csock = nullptr; return; continue; } // Parse token (for Initial packets) if (offset >= dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } size_t tok_bytes; Loading @@ -1130,8 +1182,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { offset += tok_bytes; if (offset + token_len > dgram.size()) { csock = nullptr; return; continue; // Malformed — skip } std::vector<uint8_t> token(dgram.begin() + offset, dgram.begin() + offset + token_len); Loading Loading @@ -1202,6 +1253,12 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) { // Don't transfer ownership to csock (would cause double-free). // QUIC connections share the parent socket and are routed via accept(). csock = nullptr; return; // New connection created — exit drain loop } // end drain loop (for drain_i) // Reached MAX_DRAIN limit — will be called again by epoll csock = nullptr; } // ============================================================================ Loading Loading @@ -1480,14 +1537,15 @@ void quic::processApplicationPacket(const uint8_t* data, size_t len) { } } // Send ACK immediately — before processing frames — so the peer // does not time out if a stream callback (e.g. RequestEvent) blocks // for a long time during heavy request handling. sendAppAck(); size_t offset = 0; while (offset < payload.size()) { processFrame(payload.data(), payload.size(), offset); } // Send ACK for received 1-RTT packets so the peer's congestion // controller can open its window and continue sending data. sendAppAck(); } // ============================================================================ Loading Loading @@ -2159,6 +2217,10 @@ void quic::completeHandshake() { // ============================================================================ size_t quic::recvData(buffer& data, int flags) { std::vector<PendingDispatch> dispatches; size_t result = 0; { // Scoped lock — released before invoking stream callbacks std::lock_guard<std::mutex> lock(_quic_mutex); // Check connection state Loading @@ -2175,84 +2237,86 @@ size_t quic::recvData(buffer& data, int flags) { } // First, check if we have buffered data from any stream // For simplicity, we use stream 0 as the default data stream uint64_t default_stream = _is_server ? 1 : 0; // Client-initiated bidi stream // Check if there's data in our default stream auto it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { // Copy data from stream buffer to output buffer size_t to_copy = std::min(data.size, it->second.recv_buffer.size()); std::memcpy(data.data.buf, it->second.recv_buffer.data(), to_copy); // Remove copied data from stream buffer it->second.recv_buffer.erase( it->second.recv_buffer.begin(), it->second.recv_buffer.begin() + to_copy); it->second.recv_offset += to_copy; uint64_t default_stream = _is_server ? 1 : 0; auto check_stream = [&](auto& stream_ref) -> bool { size_t to_copy = std::min(data.size, stream_ref.recv_buffer.size()); std::memcpy(data.data.buf, stream_ref.recv_buffer.data(), to_copy); stream_ref.recv_buffer.erase( stream_ref.recv_buffer.begin(), stream_ref.recv_buffer.begin() + to_copy); stream_ref.recv_offset += to_copy; _data_recv += to_copy; data.size = to_copy; return to_copy; } result = to_copy; return true; }; auto it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { check_stream(it->second); } else { // No buffered data, try to receive from network int recv_flags = (flags & MSG_DONTWAIT) ? MSG_DONTWAIT : 0; size_t recv_len; buffer recv_buf_wrapper(65535); size_t recv_len; try { recv_len = udp::recvData(recv_buf_wrapper, recv_flags); } catch (NetException&) { // EAGAIN/EWOULDBLOCK - propagate as-is throw; } if (recv_len == 0) { // Connection closed by peer data.size = 0; return 0; } // Process the received packet result = 0; } else { processIncomingPacket(reinterpret_cast<const uint8_t*>(recv_buf_wrapper.data.buf), recv_len); // After processing, check again for buffered stream data // After processing, check for buffered stream data bool found = false; it = _streams.find(default_stream); if (it != _streams.end() && !it->second.recv_buffer.empty()) { size_t to_copy = std::min(data.size, it->second.recv_buffer.size()); std::memcpy(data.data.buf, it->second.recv_buffer.data(), to_copy); check_stream(it->second); found = true; } it->second.recv_buffer.erase( it->second.recv_buffer.begin(), it->second.recv_buffer.begin() + to_copy); it->second.recv_offset += to_copy; _data_recv += to_copy; if (!found) { // Check all streams for (auto& [sid, stream] : _streams) { if (!stream.recv_buffer.empty()) { check_stream(stream); found = true; break; } } } data.size = to_copy; return to_copy; if (!found) { data.size = 0; result = 0; } } } // Check all streams for data if default stream has none for (auto& [stream_id, stream] : _streams) { if (!stream.recv_buffer.empty()) { size_t to_copy = std::min(data.size, stream.recv_buffer.size()); std::memcpy(data.data.buf, stream.recv_buffer.data(), to_copy); // Collect pending dispatches before releasing lock dispatches = std::move(_pending_dispatches); _pending_dispatches.clear(); stream.recv_buffer.erase( stream.recv_buffer.begin(), stream.recv_buffer.begin() + to_copy); stream.recv_offset += to_copy; _data_recv += to_copy; } // mutex released data.size = to_copy; return to_copy; // Dispatch stream callbacks in a background thread so the // caller returns immediately — prevents PING timeout. if (!dispatches.empty() && _stream_callback) { auto cb = _stream_callback; auto self = this; std::thread([cb, self, ds = std::move(dispatches)]() { for (auto& pd : ds) { cb(self, pd.stream_id, pd.data, pd.fin); } }).detach(); } // No data available yet (packet might have been handshake, ACK, etc.) data.size = 0; return 0; return result; } // ============================================================================ Loading Loading @@ -2736,22 +2800,25 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { stream.recv_complete = true; } // Notify application layer via callback // Queue stream dispatch — will be invoked OUTSIDE _quic_mutex // so that long-running callbacks (e.g. import) don't block PING ACKs. // For bidirectional request streams (stream_id % 4 == 0): wait until complete // For unidirectional streams: notify immediately (control/QPACK streams) if (_is_server && _stream_callback) { bool is_bidi_request = (stream_id % 4 == 0); if (is_bidi_request && stream.recv_complete && !stream.recv_dispatched) { std::cerr << "[QUIC-FC] Dispatching bidi stream " << stream_id << " to app, size=" << stream.recv_buffer.size() << std::endl; std::cerr << "[QUIC-FC] Queuing bidi stream " << stream_id << " for dispatch, size=" << stream.recv_buffer.size() << std::endl; stream.recv_dispatched = true; _stream_callback(this, stream_id, stream.recv_buffer, true); // Free memory — data has been delivered to application _pending_dispatches.push_back({stream_id, std::move(stream.recv_buffer), true}); // Free memory — data has been moved to pending dispatch stream.recv_buffer.clear(); stream.recv_buffer.shrink_to_fit(); stream.recv_ranges.clear(); } else if (!is_bidi_request) { // Unidirectional stream - notify for control stream setup // Unidirectional stream - notify immediately (control/QPACK, small) _stream_callback(this, stream_id, stream.recv_buffer, stream.recv_fin); } } Loading Loading @@ -2805,6 +2872,8 @@ void quic::processAckFrame(const uint8_t* data, size_t len, size_t& offset) { // ============================================================================ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data, bool fin) { std::lock_guard<std::mutex> lock(_quic_mutex); // Maximum QUIC datagram size minus short header overhead: // 1 (flags) + dcid_len + 4 (PN) + 16 (GCM tag) + frame header (~11 max) const size_t header_overhead = 1 + _remote_cid.size() + 4 + 16; Loading
src/socket.h +10 −0 Changes for src/socket.h: 10 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -828,6 +828,16 @@ namespace netplus { using QuicStreamCallback = std::function<void(quic*, uint64_t, const std::vector<uint8_t>&, bool)>; QuicStreamCallback _stream_callback; // Deferred stream dispatches — filled inside _quic_mutex, // invoked AFTER releasing it so callbacks can't block the // QUIC packet processing loop (prevents PING timeouts). struct PendingDispatch { uint64_t stream_id; std::vector<uint8_t> data; bool fin; }; std::vector<PendingDispatch> _pending_dispatches; // Handshake timeout tracking // Detects when client sends incomplete ClientHello with large gaps (likely packet loss) std::chrono::steady_clock::time_point _handshake_start_time; Loading