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

test

parent fe8091df
Loading
Loading
Loading
Loading
+92 −98
Changes for src/event/kqueue.cpp: 92 added lines, 98 removed lines.
Original line number Diff line number Diff line

Primärnavigation
Startseite
3
Projekt

    L
    libnetplus

    Tickets
    0

Merge Requests
0

    Merge Requests
    0

Repository
Branch
Commits
Tags
Repository-Diagramm
Revisionen vergleichen
Code-Schnipsel

    jan.koester
    libnetplus
    Repository

    libnetplus
    src
    event
    kqueue.cpp

kqueue.cpp
Avatar von Jan Koester
test
Von jan.koester verfasst am vor 2 Tagen
be1e9f5f
kqueue.cpp
23,35 KiB

/*******************************************************************************
Copyright (c) 2014, 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
@@ -12,7 +54,6 @@ modification, are permitted provided that the following conditions are met:
    * 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
@@ -24,12 +65,10 @@ 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.
*******************************************************************************/

#include <iostream>
#include <algorithm>
#include <chrono>
#include <memory>

#include <unistd.h>
#include <signal.h>
#include <sys/event.h>
@@ -38,31 +77,23 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdint.h>
#include <mutex>
#include <map>

#include <cstring>
#include <errno.h>

#include "socket.h"
#include "exception.h"
#include "eventapi.h"
#include "connection.h"
#include "../posix/error.h"
#include <assert.h>

#define READEVENT 0
#define SENDEVENT 1

#define BLOCKSIZE 16384

namespace netplus {
    std::atomic<bool> event::Running(true);
    std::atomic<bool> event::Restart(false);

    std::mutex POLL_HANDLER_MUTEX;

    std::vector<socket*> SSOCKETS;
    std::map<int,con*>    CONNECTIONS;

    class pollapi {
    public:
        pollapi(eventapi *eapi,int timeout){
@@ -70,27 +101,21 @@ namespace netplus {
        };

        virtual ~pollapi(){

        };

        enum EventHandlerStatus{EVWAIT=0,EVIN=1,EVOUT=2,EVUP=3,EVERR=4,EVCON=5};

        virtual void initEventHandler()=0;
        virtual const char *getpolltype()=0;
        /*pollstate*/
        virtual int pollState(int pos)=0;

        /*EventHandler*/
        virtual  int waitEventHandler(int timeout)=0;
        virtual void ConnectEventHandler(int pos,const int tid,ULONG_PTR args)=0;
        virtual void ReadEventHandler(int pos,const int tid,ULONG_PTR args)=0;
        virtual void WriteEventHandler(int pos,const int tid,ULONG_PTR args)=0;
        virtual void CloseEventHandler(int pos,const int tid,ULONG_PTR args)=0;

    protected:
        eventapi *evconnection;
    };

    class poll : public pollapi{
    public:
        poll(socket* serversocket,eventapi *eapi,int pollfd,int timeout) : pollapi(eapi,timeout){
@@ -109,33 +134,25 @@ namespace netplus {
                _Events[i].udata=nullptr;
            }
        };

        ~poll() {
            delete[] _Events;
        };

        /*basic functions*/
        const char* getpolltype() {
            return "KQUEUE";
        }

        /*event handler function*/
        void initEventHandler() {

        };

        int getEventFlags(int pos) {
            return _Events[pos].filter;
        }

        void setpollEvents(con* curcon,int filter,int events){
            NetException except;
            struct kevent setevent = { 0 };
            if(!curcon)
                return;

            if(!curcon->csock) return;

            EV_SET(&setevent,curcon->csock->fd(),filter,events,0,0,curcon);

            if (kevent(_pollFD, &setevent, 1, nullptr, 0, nullptr) < 0) {
@@ -208,6 +225,7 @@ void ConnectEventHandler(int pos, const int tid, ULONG_PTR args) {
                    // 3. Attempt to accept the new connection
                    _ServerSocket->accept(ccon->csock);
                }catch(NetException &e){

                    // Check for the non-fatal error (EAGAIN/EWOULDBLOCK) wrapped in NetException::Note.
                    if (e.getErrorType()==NetException::Note) {
                        // This means the listen queue is empty. Break the accept loop.
@@ -264,132 +282,105 @@ void ConnectEventHandler(int pos, const int tid, ULONG_PTR args) {
        }

        void ReadEventHandler(int pos,const int tid,ULONG_PTR args) {
            // Get pointer directly from udata.
            con *rcon = reinterpret_cast<con*>(_Events[pos].udata);
            if (!rcon) return;

            std::lock_guard<std::mutex> lk(rcon->event_mutex);
            if (!rcon->csock) return;
            if (!rcon) { return; }

            // Acquire connection-specific lock immediately
            std::lock_guard<std::mutex> lock_guard(rcon->event_mutex);

            // Double check pointer validity under lock
            if (!rcon->csock) { return; }

            try {
                for (;;) {
            buffer buf(BLOCKSIZE);

                    size_t rcvsize = 0;
            try{
                        rcvsize = rcon->csock->recvData(buf, 0);   // FLAGS MUST BE 0 (or real flags), NOT BLOCKSIZE
                    } catch (NetException& e) {
                        if (e.getErrorType() == NetException::Note) {
                            // would-block -> re-arm based on whether we need to write
                            if (!rcon->SendData.empty() || rcon->csock->hasPendingWrite()) {
                                setpollEvents(rcon, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
                            } else {
                                setpollEvents(rcon, EVFILT_READ, EV_ADD | EV_ONESHOT);
                            }
                            return;
                        }
                        throw;
                    }

                    if (rcvsize == 0) {
                        // Real EOF (tcp close) or TLS close_notify mapped to 0

                size_t rcvsize = rcon->csock->recvData(buf, BLOCKSIZE);

                rcon->lasteventime = time(nullptr);

                if (rcvsize <= 0) {
                    NetException e;
                        e[NetException::Close] << "ReadEventHandler: peer closed connection (EOF)";
                    if (rcvsize == 0) {
                        e[NetException::Note] << "ReadEventHandler: EOF detected. Closing connection.";
                    } else {
                        e[NetException::Note] << "ReadEventHandler: Fatal socket error or eof detected. Closing connection.";
                    }
                    throw e;
                }

                    rcon->lasteventime = time(nullptr);
                rcon->RecvData.append(buf.data.buf,rcvsize);

                evconnection->RequestEvent(*rcon,tid,args);

                    // If parser produced output OR ssl has pending ciphertext, go write
                    if (!rcon->SendData.empty() || rcon->csock->hasPendingWrite()) {
                if(!rcon->SendData.empty()){
                    setpollEvents(rcon,EVFILT_WRITE,EV_ADD | EV_ONESHOT);
                    return;
                }

                    // else: keep draining reads until would-block
                }
                setpollEvents(rcon,EVFILT_READ,EV_ADD | EV_ONESHOT);

            }catch(NetException &e){
                if(e.getErrorType()== NetException::Note){
                    // already handled, but keep safe
                    // Re-register for read or write if it was a non-fatal temporary error
                    if(!rcon->SendData.empty()){
                        setpollEvents(rcon,EVFILT_WRITE,EV_ADD | EV_ONESHOT);
                    }else{
                        setpollEvents(rcon,EVFILT_READ,EV_ADD | EV_ONESHOT);
                    return;
                    }
                throw;
                     return;
                }
                throw e;
            }
        };

        void WriteEventHandler(int pos,const int tid,ULONG_PTR args) {
            con *wcon = reinterpret_cast<con*>(_Events[pos].udata);
            if (!wcon) return;

            std::lock_guard<std::mutex> lk(wcon->event_mutex);
            if (!wcon->csock) return;
            if (!wcon) { return; }

            std::lock_guard<std::mutex> lock_guard(wcon->event_mutex);

            if (!wcon->csock) { return; }

            try{
                // allow protocol to queue bytes
                evconnection->ResponseEvent(*wcon,tid,args);

                for (;;) {
                    // If no app bytes left, we might still need to flush TLS internal ciphertext
                if(wcon->SendData.empty()){
                        if (wcon->csock->hasPendingWrite()) {
                            setpollEvents(wcon, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
                            return;
                        }

                        // truly nothing left to send
                    setpollEvents(wcon,EVFILT_READ,EV_ADD | EV_ONESHOT);
                    return;
                }

                    const size_t ssize = std::min<size_t>(BLOCKSIZE, wcon->SendData.size());
                    buffer buf(wcon->SendData.data(), ssize);

                    size_t consumed = 0;
                    try {
                        consumed = wcon->csock->sendData(buf, 0);
                    } catch (NetException& e) {
                        if (e.getErrorType() == NetException::Note) {
                            setpollEvents(wcon, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
                            return;
                        }
                        throw;
                    }
                size_t ssize = BLOCKSIZE < wcon->SendData.size() ? BLOCKSIZE : wcon->SendData.size();

                    if (consumed == 0) {
                        // would-block or ssl flushing internal record
                        setpollEvents(wcon, EVFILT_WRITE, EV_ADD | EV_ONESHOT);
                        return;
                    }
                buffer buf(wcon->SendData.data(),ssize);
                size_t sended = wcon->csock->sendData(buf);

                    if (consumed > ssize) {
                if (sended > ssize) {
                    NetException e;
                        e[NetException::Error] << "WriteEventHandler: sendData consumed > provided bytes";
                    e[NetException::Note] << "WriteEventHandler: Fatal socket error detected. Closing connection.";
                    throw e;
                }

                wcon->SendData.erase(wcon->SendData.begin(),
                                        wcon->SendData.begin() + consumed);
                                        wcon->SendData.begin() + sended);

                    wcon->lasteventime = time(nullptr);

                    // If we emptied app queue, let protocol enqueue more (chunking, pipelining, etc.)
                    if (wcon->SendData.empty()) {
                        evconnection->ResponseEvent(*wcon, tid, args);
                    }
                wcon->lasteventime = time(nullptr);

                    // loop continues until would-block
                }
                setpollEvents(wcon,EVFILT_WRITE,EV_ADD | EV_ONESHOT);
            }catch(NetException &e){
                if(e.getErrorType()== NetException::Note){
                    setpollEvents(wcon,EVFILT_WRITE,EV_ADD | EV_ONESHOT);
                    return;
                }
                throw;
                }else{
                    throw e;
                }
            }
        };

        void CloseEventHandler(int pos, const int tid, ULONG_PTR args) {
            std::lock_guard<std::mutex> global_lock(POLL_HANDLER_MUTEX);
@@ -447,6 +438,7 @@ void ConnectEventHandler(int pos, const int tid, ULONG_PTR args) {

    class EventWorkerArgs{
    public:

        EventWorkerArgs(){
        }

@@ -517,6 +509,7 @@ void ConnectEventHandler(int pos, const int tid, ULONG_PTR args) {
                            }
                        }
                    }

                } catch (NetException& e) {
                    // Catches critical exceptions re-thrown from inner block or waitEventHandler failure.
                    std::cerr << "CRITICAL WORKER ERROR: " << e.what() << std::endl;
@@ -587,6 +580,7 @@ void ConnectEventHandler(int pos, const int tid, ULONG_PTR args) {
    void signalHandler(int signum) {
        std::lock_guard<std::mutex> lock(POLL_HANDLER_MUTEX);
        switch(signum){

            case SIGINT:
                for(auto ssock : SSOCKETS){
                    ssock->close();