Commit b2b82e3b authored by jan.koester's avatar jan.koester
Browse files

teset

parent bf2d3be8
Loading
Loading
Loading
Loading
+1 −0
Changes for .gitignore: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
build/
build*
/.vs
/out/install/x64-Debug
/out/install/x64-Release
+19 −72
Changes for src/event/epoll.cpp: 19 added lines, 72 removed lines.
Original line number Diff line number Diff line
@@ -145,7 +145,10 @@ namespace netplus {
              _Events(new epoll_event[serversocket->getMaxconnections()]),
              _ServerSocket(serversocket)
        {
            {
                std::lock_guard<std::mutex> lk(POLL_HANDLER_MUTEX);
                SSOCKETS.emplace_back(_ServerSocket);
            }

            for (int i = 0; i < _ServerSocket->getMaxconnections(); ++i) {
                _Events[i].events = -1;
@@ -254,7 +257,7 @@ namespace netplus {
        }

        // ------------------------------------------------------------
        // IO handling (NO DEADLOCK!)
        // IO handling (unified for TCP/SSL/QUIC)
        // ------------------------------------------------------------
        void IoEventHandler(int fd, int events, const int tid, ULONG_PTR args) override {
            std::shared_ptr<con> c = getConByFd(fd);
@@ -263,11 +266,8 @@ namespace netplus {
            }

            EpollArmGuard rearm(fd, c, this);

            bool needClose = false;

            // IMPORTANT:
            // Hold per-connection lock only for IO state modifications
            {
                std::lock_guard<std::mutex> lk(c->event_mutex);
                if (!c->csock) return;
@@ -278,97 +278,49 @@ namespace netplus {
                        needClose = true;
                    }
                    else {
                        // Step 1: If handshake not done and EPOLLIN, read raw TCP data into TLS buffer
                        if ((events & EPOLLIN) && !c->csock->getHandshakeDone() && !needClose) {
                        // Step 1: EPOLLIN - buffer transport data
                        if ((events & EPOLLIN) && !needClose) {
                            buffer buf(BLOCKSIZE);
                            size_t rcv = 0;

                            try {
                                // Read raw TCP data (don't use recvData which tries to decrypt)
                                rcv = ((netplus::tcp&)*c->csock).tcp::recvData(buf, 0);
                                c->csock->prime_recv(buf, 0);
                            } catch (NetException& e) {
                                if (e.getErrorType() == NetException::Note){
                                    // No data available right now - just continue to handshake
                                    // (it will re-arm socket when needed)
                                    rcv = 0;
                                } else {
                                    throw;
                                }
                            }

                            if (rcv > 0) {
                                // Put raw TLS data into _rx_tcp_buf via pushReceivedData()
                                c->csock->pushReceivedData((const uint8_t*)buf.data.buf, rcv);
                                if (e.getErrorType() != NetException::Note) throw;
                            }
                        }

                        // Step 2: Try handshake (with buffered TLS data)
                        if (!c->csock->getHandshakeDone() && !needClose) {
                        // Step 2: Handshake (if not done)
                        while (!c->csock->getHandshakeDone() && c->csock->hasBufferedData() && !needClose) {
                            try {
                                c->csock->handshake_after_accept();
                            } catch (NetException& e) {
                                if (e.getErrorType() != NetException::Note) throw;
                            }

                            // Flush any pending write data
                            if (c->csock->hasPendingWrite()) {
                                try {
                                    c->csock->flush_out();
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        rearm.disarm();
                                        setpollEventsFd(fd, EPOLLOUT | EPOLLRDHUP | EPOLLONESHOT);
                                    } else {
                                        throw;
                                    }
                                }
                            }

                            // Process any buffered TLS data left in socket buffer
                            while (!c->csock->getHandshakeDone() && c->csock->hasBufferedData()) {
                                try {
                                    c->csock->handshake_after_accept();
                                } catch (NetException& e) {
                                    if (e.getErrorType() != NetException::Note) throw;
                                        return;
                                    }

                                if (c->csock->hasPendingWrite()) {
                                    try {
                                        c->csock->flush_out();
                                    } catch (NetException& e) {
                                        if (e.getErrorType() != NetException::Note) throw;
                                        setpollEventsFd(fd, EPOLLOUT | EPOLLRDHUP | EPOLLONESHOT);
                                        break;
                                    throw;
                                }
                            }
                        }

                            // If handshake still not done, re-arm for more data
                        // Re-arm if handshake still in progress
                        if (!c->csock->getHandshakeDone()) {
                            int ev = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT;
                                if (c->csock->hasPendingWrite())
                                    ev |= EPOLLOUT;
                            if (c->csock->hasPendingWrite()) ev |= EPOLLOUT;
                            rearm.disarm();
                            setpollEventsFd(fd, ev);
                            }
                            return;
                        }

                        // Step 3: Handle application data (only after handshake)
                        // Step 3: Application data (handshake done)
                        if ((events & EPOLLIN) && c->csock->getHandshakeDone() && !needClose) {
                            // First, read raw TCP data into TLS buffer
                            try {
                                buffer buf(BLOCKSIZE);
                                size_t rcv = ((netplus::tcp&)*c->csock).tcp::recvData(buf, 0);
                                if (rcv > 0) {
                                    c->csock->pushReceivedData((const uint8_t*)buf.data.buf, rcv);
                                }
                            } catch (NetException& e) {
                                if (e.getErrorType() != NetException::Note) {
                                    throw;
                                }
                                // No more TCP data available (would block)
                            }

                            // Now try to decrypt application data from the TLS buffer
                            if (c->csock->hasBufferedData()) {
                            buffer buf(BLOCKSIZE);
                            size_t rcv = 0;

@@ -390,11 +342,9 @@ namespace netplus {
                                evconnection->RequestEvent(*c, tid, args);
                            }
                        }
                        }

                        // Step 4: EPOLLOUT: flush + send one chunk
                        // Step 4: EPOLLOUT - flush and send
                        if ((events & EPOLLOUT) && !needClose) {

                            if (c->csock->hasPendingWrite()) {
                                try {
                                    c->csock->flush_out();
@@ -415,10 +365,8 @@ namespace netplus {
                                size_t consumed = 0;
                                try {
                                    consumed = c->csock->sendData(out, 0);

                                    if (c->csock->hasPendingWrite())
                                        c->csock->flush_out();

                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        rearm.disarm();
@@ -441,7 +389,6 @@ namespace netplus {

                } catch (NetException& e) {
                    if (e.getErrorType() == NetException::Note) {
                        // Only set EPOLLOUT if there's actually pending write data
                        int ev = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT;
                        if (c->csock->hasPendingWrite() || !c->SendData.empty())
                            ev |= EPOLLOUT;
+72 −167
Changes for src/event/iocp.cpp: 72 added lines, 167 removed lines.
Original line number Diff line number Diff line
@@ -62,31 +62,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

namespace netplus {

    // -------------------------------------------------------------------------
    // AcceptContext matches socket.h concept: keep accept socket + buffer
    // -------------------------------------------------------------------------
    struct AcceptCtx {
        std::unique_ptr<socket> csock;
    };

    // -------------------------------------------------------------------------
    // Per-event state (because event class has no members for Windows backend)
    // -------------------------------------------------------------------------
    struct EventState {
        HANDLE iocp = nullptr;
        LPFN_ACCEPTEX fnAcceptEx = nullptr;

        std::mutex conMutex;
        std::unordered_map<SOCKET, std::shared_ptr<con>> sockToCon;

        // Recv buffers are now in sockets
        // std::mutex bufMutex;
        // std::unordered_map<con*, std::unique_ptr<buffer>> recvBuf;

        std::mutex accMutex;
        std::unordered_map<OVERLAPPED*, AcceptCtx*> acceptByOv;

        std::vector<std::thread> workers;
        std::thread acceptThread;  // Dedicated accept thread
        int threads = 1;
    };

@@ -101,29 +87,6 @@ namespace netplus {
        return it->second.get();
    }

    // -------------------------------------------------------------------------
    // Load AcceptEx
    // -------------------------------------------------------------------------
    static LPFN_ACCEPTEX loadAcceptEx(SOCKET listenSock) {
        GUID guid = WSAID_ACCEPTEX;
        LPFN_ACCEPTEX fn = nullptr;
        DWORD bytes = 0;

        int rc = WSAIoctl(listenSock,
                          SIO_GET_EXTENSION_FUNCTION_POINTER,
                          &guid, sizeof(guid),
                          &fn, sizeof(fn),
                          &bytes,
                          nullptr, nullptr);

        if (rc == SOCKET_ERROR || !fn) {
            NetException e;
            e[NetException::Critical] << "LoadAcceptEx failed: " << WSAGetLastError();
            throw e;
        }
        return fn;
    }

    // -------------------------------------------------------------------------
    // init EventState for an event instance
    // -------------------------------------------------------------------------
@@ -146,65 +109,82 @@ namespace netplus {
             throw e;
        }

        // bind listening socket
        HANDLE h = CreateIoCompletionPort((HANDLE)serverSock->fd(),
                                          st->iocp,
                                          (ULONG_PTR)serverSock,
                                          0);
        if (!h) {
            NetException e;
            e[NetException::Critical] << "CreateIoCompletionPort(bind listen) failed: " << GetLastError();
            throw e;
        }

        st->fnAcceptEx = loadAcceptEx((SOCKET)serverSock->fd());
        st->threads = ev->threads;

        g_states[ev] = std::move(st);
    }

    // -------------------------------------------------------------------------
    // Post AcceptEx
    // Accept loop - runs in dedicated thread, works for TCP and UDP
    // -------------------------------------------------------------------------
    static void post_accept(EventState* st, socket* serverSock) {
        auto* ctx = new AcceptCtx();
    static void accept_loop(event* ev, socket* serverSock) {
        EventState* st = ST(ev);
        
        while (event::Running) {
            std::unique_ptr<socket> csock;
            
            try {
            // Uses the virtual accept which uses internal buffer
            serverSock->accept(st->fnAcceptEx, ctx->csock);
                // Blocking accept - works for TCP, UDP handles this differently
                serverSock->accept(csock, false);  // blocking
            } catch (NetException& e) {
            std::cerr << "[IOCP] post_accept failed (NetException): " << e.what() << std::endl;
            delete ctx;
            return;
                if (!event::Running) break;
                if (e.getErrorType() == NetException::Note) {
                    continue;  // Would block, retry
                }
                std::cerr << "[IOCP] accept failed: " << e.what() << std::endl;
                continue;
            } catch (...) {
            std::cerr << "[IOCP] post_accept failed (unknown exception)" << std::endl;
            delete ctx;
            return;
                if (!event::Running) break;
                std::cerr << "[IOCP] accept failed (unknown)" << std::endl;
                continue;
            }
            
        // remember accept ctx by overlapped*
        if (ctx->csock && ctx->csock->_ReadBuffer) {
             WSAOVERLAPPED* ov = &ctx->csock->_ReadBuffer->overlapped;
             std::lock_guard<std::mutex> lk(st->accMutex);
             st->acceptByOv[(OVERLAPPED*)ov] = ctx;
        } else {
             delete ctx;
            if (!csock) continue;
            
            SOCKET accepted = csock->fd();
            if (accepted == INVALID_SOCKET) continue;
            
            // Create connection via user allocator
            std::shared_ptr<con> c;
            ev->CreateConnection(c);
            
            if (!c) {
                csock->close();
                continue;
            }
            
            // Attach accepted socket to connection
            c->csock = std::move(csock);
            
            // Bind accepted socket to IOCP
            HANDLE h = CreateIoCompletionPort((HANDLE)accepted,
                                              st->iocp,
                                              (ULONG_PTR)c->csock.get(),
                                              0);
            if (!h) {
                std::cerr << "[IOCP] CreateIoCompletionPort(accepted) failed: " << GetLastError() << std::endl;
                c->csock->close();
                continue;
            }
            
    static AcceptCtx* pop_accept(EventState* st, OVERLAPPED* pov) {
        std::lock_guard<std::mutex> lk(st->accMutex);
            // Register connection mapping
            register_con(st, accepted, c);
#if IOCP_DEBUG
        std::cerr << "[IOCP] pop_accept: looking for pov=" << pov << " in " << st->acceptByOv.size() << " entries" << std::endl;
        for (auto& kv : st->acceptByOv) {
            std::cerr << "[IOCP]   stored ov=" << kv.first << std::endl;
        }
            std::cerr << "[IOCP] Accepted connection: socket=" << accepted << std::endl;
#endif
        auto it = st->acceptByOv.find(pov);
        if (it == st->acceptByOv.end()) return nullptr;
        AcceptCtx* ctx = it->second;
        st->acceptByOv.erase(it);
        return ctx;
            
            // Connect callback
            ev->ConnectEvent(*c, 0, 0);
            
            // Post first recv
            try {
                post_recv(st, *c);
            } catch (...) {
                ev->DisconnectEvent(*c, 0, 0);
                remove_con(st, accepted);
                try { c->csock->close(); } catch (...) {}
            }
        }
    }

    // -------------------------------------------------------------------------
@@ -362,7 +342,7 @@ namespace netplus {
    // -------------------------------------------------------------------------
    class EventWorker {
    public:
        void operator()(event* ev, socket* serverSock, int tid) {
        void operator()(event* ev, int tid) {
        EventState* st = ST(ev);
        
        try {
@@ -380,76 +360,7 @@ namespace netplus {

            if (!pov && key == 0) continue; // wake packet

            // 1) Accept completion?
            // std::cerr << "[IOCP] Checking if AcceptEx completion, pov=" << pov << std::endl;
            if (AcceptCtx* actx = pop_accept(st, pov)) {
                // std::cerr << "[IOCP] AcceptEx completion detected!" << std::endl;

                // Take ownership of the accepted socket
                std::unique_ptr<socket> acceptedSock = std::move(actx->csock);
                SOCKET accepted = acceptedSock->fd();

                if (!ok) {
                    // socket closed by destructor
                    delete actx;
                    post_accept(st, serverSock);
                    continue;
                }

                // update accept context
                SOCKET ls = (SOCKET)serverSock->fd();
                setsockopt(accepted, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char*)&ls, sizeof(ls));

                // Create connection via user allocator
                std::shared_ptr<con> c; // create empty shared_ptr
                ev->CreateConnection(c); // populate it

                if (!c) {
                    delete actx;
                    post_accept(st, serverSock);
                    continue;
                }

                // attach accepted socket to con::csock
                c->csock = std::move(acceptedSock); // Transfers type (tcp/ssl) and state

                // bind accepted socket to IOCP (key = socket*)
                HANDLE h = CreateIoCompletionPort((HANDLE)accepted,
                                                 st->iocp,
                                                 (ULONG_PTR)c->csock.get(),
                                                 0);
                if (!h) {
                    delete actx;
                    post_accept(st, serverSock);
                    continue;
                }

                // register mapping
                register_con(st, accepted, c);
#if IOCP_DEBUG
                std::cerr << "[IOCP] Registered connection: socket=" << accepted << " csock->fd()=" << c->csock->fd() << std::endl;
#endif

                // connect callback
                ev->ConnectEvent(*c, tid, 0);

                // post first recv
                try {
                    post_recv(st, *c);
                } catch (...) {
                    ev->DisconnectEvent(*c, tid, 0);
                    remove_con(st, accepted);
                    try { c->csock->close(); } catch (...) {}
                }

                delete actx;

                // repost accept immediately
                post_accept(st, serverSock);
                continue;
            }

            // 2) Normal I/O completion (recv/send)
            // I/O completion (recv/send)
            socket* sockObj = reinterpret_cast<socket*>(key);
            if (!sockObj) {
#if IOCP_DEBUG
@@ -929,7 +840,7 @@ namespace netplus {
        EventState* st = ST(this);
        if (!st) return;

        // Close server socket first to stop AcceptEx from blocking
        // Close server socket first to stop accept from blocking
        if (_ServerSocket) {
            closesocket((SOCKET)_ServerSocket->fd());
        }
@@ -942,16 +853,6 @@ namespace netplus {
            }
        }

        // Cancel pending accepts
        {
            std::lock_guard<std::mutex> lk(st->accMutex);
            for (auto& kv : st->acceptByOv) {
                if (kv.second && kv.second->csock) {
                    CancelIoEx((HANDLE)kv.second->csock->fd(), nullptr);
                }
            }
        }

        // wake all workers multiple times to ensure they exit
        for (int round = 0; round < 3; ++round) {
            for (size_t i = 0; i < st->workers.size(); ++i) {
@@ -959,6 +860,11 @@ namespace netplus {
            }
        }

        // Join accept thread
        if (st->acceptThread.joinable()) {
            st->acceptThread.join();
        }

        for (auto& t : st->workers) {
            if (t.joinable()) t.join();
        }
@@ -984,16 +890,15 @@ namespace netplus {
        Running = true;
        std::cerr << "[IOCP] runEventloop: Starting " << st->threads << " threads." << std::endl;

        // Pre-post accepts (like "listen ready")
        // recommended: 2*threads AcceptEx in flight
        for (int i = 0; i < st->threads * 2; ++i) {
            post_accept(st, _ServerSocket);
        }
        // Start dedicated accept thread (works for TCP and UDP)
        st->acceptThread = std::thread([=]() {
            accept_loop(this, _ServerSocket);
        });

        // start workers
        for (int i = 0; i < st->threads; ++i) {
            st->workers.emplace_back([=]() {
                EventWorker()(this, _ServerSocket, i);
                EventWorker()(this, i);
            });
        }

+360 −34

File changed.

Preview size limit exceeded, changes collapsed.

+40 −1
Changes for src/socket.h: 40 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -37,6 +37,7 @@
#include <map>
#include <cstring>
#include <algorithm>
#include <functional>

#include "config.h"
#include "crypto/aes.h"
@@ -180,6 +181,11 @@ namespace netplus {
		virtual size_t sendData(buffer& data, int flags = 0) = 0;
		virtual size_t recvData(buffer& data, int flags = 0) = 0;

		// Read raw transport data and buffer it (for SSL/TLS pre-decryption)
		// Returns bytes read. For plain TCP, this is same as recvData.
		// For SSL, reads raw TCP into internal buffer for later decryption.
		virtual size_t prime_recv(buffer& data, int flags = 0) { return recvData(data, flags); }

		virtual bool getHandshakeDone() { return true; }
		virtual bool hasBufferedData() const { return false; }
		virtual int  getSocketType() const { return _Type; }
@@ -332,6 +338,15 @@ namespace netplus {
		size_t sendData(buffer& data, int flags = 0) override;
		size_t recvData(buffer& data, int flags = 0) override;

		// Read raw TCP data and buffer it for TLS processing
		size_t prime_recv(buffer& data, int flags = 0) override {
			size_t rcv = tcp::recvData(data, flags);
			if (rcv > 0) {
				pushReceivedData((const uint8_t*)data.data.buf, rcv);
			}
			return rcv;
		}

#ifdef Windows
		void accept(LPFN_ACCEPTEX lpfnAcceptEx, std::unique_ptr<socket>& csock) override;
		void prime_read();
@@ -795,6 +810,15 @@ namespace netplus {
		void pushReceivedData(const uint8_t* data, size_t len) override;
		bool hasBufferedData() const override { return !_recv_buffer.empty(); }

		// Read raw UDP data and buffer it for QUIC processing
		size_t prime_recv(buffer& data, int flags = 0) override {
			size_t rcv = udp::recvData(data, flags);
			if (rcv > 0) {
				pushReceivedData((const uint8_t*)data.data.buf, rcv);
			}
			return rcv;
		}

		// QUIC-specific methods
		void setVersion(uint32_t version) { _version = version; }
		uint32_t getVersion() const { return _version; }
@@ -813,11 +837,18 @@ namespace netplus {
		const std::vector<uint8_t>& getRemoteConnectionId() const { return _remote_cid; }

		// Handshake status
		bool isHandshakeComplete() const { return _handshake_complete; }
		bool getHandshakeDone() override { return _handshake_complete; }

		// Certificate configuration (server mode)
		void setCertificates(const std::map<std::string, ssl::CertificateBundle>& certs);
		
		// Stream data callback (for HTTP/3 handling in application layer)
		using StreamCallback = std::function<void(quic*, uint64_t stream_id, const std::vector<uint8_t>& data, bool fin)>;
		void setStreamCallback(StreamCallback cb) { _stream_callback = cb; }
		
		// Send data on a stream (vector overload for application use)
		void sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data, bool fin);

	private:
		// Packet processing
		void processIncomingPacket(const uint8_t* data, size_t len);
@@ -889,6 +920,7 @@ namespace netplus {
		void processTLSMessages();
		void processFinished(const std::vector<uint8_t>& msg);
		void sendClientFinished();
		void sendHandshakeDone();
		void completeHandshake();

		// Packet number handling
@@ -938,6 +970,10 @@ namespace netplus {
		uint8_t _app_iv_server[12] = {0};
		uint8_t _app_hp_server[16] = {0};

		// TLS handshake traffic secrets (for computing Finished)
		std::vector<uint8_t> _c_hs_traffic_secret;
		std::vector<uint8_t> _s_hs_traffic_secret;

		// TLS handshake state
		std::vector<uint8_t> _tls_transcript;
		std::vector<uint8_t> _client_random;
@@ -994,6 +1030,9 @@ namespace netplus {
		std::map<std::vector<uint8_t>, quic*> _child_connections;
		quic* _parent = nullptr;  // For child connections, pointer to parent listening socket

		// Stream data callback for application layer
		StreamCallback _stream_callback;

		// Mutex for thread safety
		mutable std::mutex _quic_mutex;

Loading