Commit 285aa854 authored by jan.koester's avatar jan.koester
Browse files

test

parent c12ae6bb
Loading
Loading
Loading
Loading
+696 −0
Changes for src/event/poll.cpp: 696 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
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
      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.
*******************************************************************************/

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

#include <unistd.h>
#include <signal.h>
#include <sys/select.h> // Standard POSIX select
#include <fcntl.h>
#include <stdlib.h>
#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

// Define the epoll constants needed for event flags handling compatibility
// Since we removed <sys/epoll.h>
#define EPOLLIN     0x001
#define EPOLLOUT    0x004
#define EPOLLERR    0x008
#define EPOLLHUP    0x010
// #define EPOLLONESHOT is not needed as it's handled by manually clearing FD_SETs

namespace netplus {

    std::atomic<bool> event::Running = true;
    std::atomic<bool> event::Restart = false;

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

    std::mutex POLL_HANDLER_MUTEX;

    class pollapi {
    public:
        pollapi(eventapi *evcon,int timeout) : evconnection(evcon){
        };

        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;
    };

    // Reimplementing 'poll' class using the select API
    class poll : public pollapi{
    public:
        // pollfd argument is ignored as select does not use a common descriptor
        poll(socket *serversocket,eventapi *evcon,int pollfd,int timeout) :
            pollapi(evcon,timeout),
            _ServerSocket (serversocket),
            _Timeout(timeout),
            _maxFD(0)
        {
            FD_ZERO(&_masterReadSet);
            FD_ZERO(&_masterWriteSet);
            FD_ZERO(&_masterExceptSet);
            SSOCKETS.emplace_back(_ServerSocket);
        };

        virtual ~poll() {
        };

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

        /*event handler function*/
        void initEventHandler() {
            // Add server socket to the master read set
            FD_SET(_ServerSocket->fd(), &_masterReadSet);
            _maxFD = std::max(_maxFD, _ServerSocket->fd());
        };

        int getEventFlags(int pos) {
            // Returns the event flags from the list of ready FDs populated by waitEventHandler
            return _ReadyEvents[pos].second;
        }

        void setpollEvents(int pos,int events){
            // In select, this simulates EPOLL_CTL_MOD by manually updating the master FD sets

            // Find the connection object from the ready list using the file descriptor
            int fd = _ReadyEvents[pos].first;
            con *curcon = nullptr;

            // Lock to safely access the global CONNECTIONS map
            {
                std::lock_guard<std::mutex> lock(POLL_HANDLER_MUTEX);
                auto it = CONNECTIONS.find(fd);
                if (it != CONNECTIONS.end()) {
                    curcon = it->second;
                }
            }
            if (!curcon || !curcon->csock) {
                return;
            }

            // Update the master sets based on the requested event flags
            // EPOLLONESHOT is simulated by clearing the other set

            // Clear any existing interests
            FD_CLR(fd, &_masterReadSet);
            FD_CLR(fd, &_masterWriteSet);

            if (events & EPOLLIN) {
                FD_SET(fd, &_masterReadSet);
            }
            if (events & EPOLLOUT) {
                FD_SET(fd, &_masterWriteSet);
            }
        }

        int pollState(int pos){
            // Check if the ready FD is the server socket (signals new connection)
            if (_ReadyEvents[pos].first == _ServerSocket->fd()) {
                return EventHandlerStatus::EVCON;
            }
            // Return the simulated event flags
            return _ReadyEvents[pos].second;
        }

        int waitEventHandler(int timeout) {
            NetException exception;
            _ReadyEvents.clear();

            // 1. Copy master sets to temporary sets for select()
            _currentReadSet = _masterReadSet;
            _currentWriteSet = _masterWriteSet;
            _currentExceptSet = _masterExceptSet;

            struct timeval tv;
            tv.tv_sec = timeout / 1000;
            tv.tv_usec = (timeout % 1000) * 1000;

            // 2. Call select()
            int nready = select(_maxFD + 1, &_currentReadSet, &_currentWriteSet, &_currentExceptSet, &tv);

            if (nready < 0) {
                if (errno == EINTR) {
                    return 0; // Interrupted by signal
                }
                char str[255];
                strerror_r_netplus(errno,str,255);
                exception[NetException::Error] << "waitEventHandler: select failure: " << str;
                throw exception;
            }
            if (nready == 0) {
                return 0; // Timeout
            }

            // 3. Populate _ReadyEvents list based on which FDs are set in the current sets
            for (int fd = 0; fd <= _maxFD; ++fd) {
                int event_flags = 0;

                if (FD_ISSET(fd, &_currentReadSet)) {
                    // Check if it's the server socket (new connection)
                    if (fd == _ServerSocket->fd()) {
                        // Special handling for connect event, which is EVCON for the EventWorker
                        _ReadyEvents.push_back({fd, EventHandlerStatus::EVCON});
                        continue;
                    }
                    event_flags |= EPOLLIN;
                }

                if (FD_ISSET(fd, &_currentWriteSet)) {
                    event_flags |= EPOLLOUT;
                }

                if (FD_ISSET(fd, &_currentExceptSet)) {
                    // Treat exception/error as close event
                    event_flags |= (EPOLLERR | EPOLLHUP);
                }

                if (event_flags != 0) {
                     _ReadyEvents.push_back({fd, event_flags});
                }
            }
            return _ReadyEvents.size();
        };

        void ConnectEventHandler(int pos,const int tid,ULONG_PTR args)  {
            NetException exception;
            std::unique_ptr<con> ccon;
            int new_fd = -1;

            evconnection->CreateConnection(ccon);

             if(!ccon){
                char errstr[255];
                strerror_r_netplus(errno,errstr,255);
                std::cerr << "ConnectEventHandler: Failed to accept connection or invalid connection object: " << errstr << std::endl;
                return;
            }

            if(_ServerSocket->_Type==sockettype::TCP){
                ccon->csock=std::make_unique<tcp>(-1);
            }else if(_ServerSocket->_Type==sockettype::UDP){
                ccon->csock=std::make_unique<udp>(-1);
            }else if(_ServerSocket->_Type==sockettype::SSL){
                // clt->connection->csock=std::make_unique<ssl>( -1);
            }

            if (!ccon->csock) {
                 char errstr[255];
                 strerror_r_netplus(errno,errstr,255);
                 std::cerr << "ConnectEventHandler: Failed to create socket object: " << errstr << std::endl;
                 return;
            }

            _ServerSocket->accept(ccon->csock);
            new_fd = ccon->csock->fd();
            ccon->csock->setFlag(O_NONBLOCK,1);

            std::string ip;
            ccon->csock->getAddress(ip);
            std::cout << "Connected: " << ip  << std::endl;

            ccon->lasteventime = time(nullptr);

            // Add new client socket to the master read set (EPOLLIN simulation)
            {
                std::lock_guard<std::mutex> global_lock(POLL_HANDLER_MUTEX);
                FD_SET(new_fd, &_masterReadSet);
                _maxFD = std::max(_maxFD, new_fd);
                CONNECTIONS.emplace(new_fd, ccon.get());
            }

            evconnection ->ConnectEvent(*ccon,tid,args);
            ccon.release(); // Ownership transferred to CONNECTIONS map
        };

        void ReadEventHandler(int pos,const int tid,ULONG_PTR args) {
            int fd = _ReadyEvents[pos].first;
            con *rcon = nullptr;

            // Get connection object from global map
            {
                std::lock_guard<std::mutex> lock(POLL_HANDLER_MUTEX);
                auto it = CONNECTIONS.find(fd);
                if (it != CONNECTIONS.end()) {
                    rcon = it->second;
                }
            }

            if (!rcon || !rcon->csock) {
                return;
            }

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

            buffer buf(BLOCKSIZE);

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

                rcon->lasteventime = time(nullptr);

                if(rcvsize!=0){
                    rcon->RecvData.append(buf.data.buf,rcvsize);
                }

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

                if(!rcon->SendData.empty()){
                    // Switch to Write mode for this FD in the master sets
                    FD_CLR(fd, &_masterReadSet);
                    FD_SET(fd, &_masterWriteSet);
                    return;
                }

                // If nothing to send, stay in Read mode. No action needed if EPOLLONESHOT is simulated by the change logic.
            }catch(NetException &e){
                if(e.getErrorType()== NetException::Note){
                     // Note suggests temporary issue, stay in read mode
                     return;
                }
                throw e;
            }
        };

        void WriteEventHandler(int pos,const int tid,ULONG_PTR args) {
            int fd = _ReadyEvents[pos].first;
            con *wcon = nullptr;

            // Get connection object from global map
            {
                std::lock_guard<std::mutex> lock(POLL_HANDLER_MUTEX);
                auto it = CONNECTIONS.find(fd);
                if (it != CONNECTIONS.end()) {
                    wcon = it->second;
                }
            }

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

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

            try{
                evconnection->ResponseEvent(*wcon,tid,args);

                if(wcon->SendData.empty()){
                    // Switch back to Read mode for this FD in the master sets
                    FD_CLR(fd, &_masterWriteSet);
                    FD_SET(fd, &_masterReadSet);
                    return;
                }

                size_t ssize = BLOCKSIZE < wcon->SendData.size() ? BLOCKSIZE : wcon->SendData.size();

                buffer buf(wcon->SendData.data(),ssize);
                size_t sended = wcon->csock->sendData(buf);

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

                wcon->SendData.resize(sended);

                wcon->lasteventime = time(nullptr);

                // Stay in Write mode. No action needed if EPOLLONESHOT is simulated by the change logic.
            }catch(NetException &e){
                if(e.getErrorType()== NetException::Note){
                    return;
                }else{
                    throw e;
                }
            }
        };

        void CloseEventHandler(int pos,const int tid,ULONG_PTR args) {
            int fd = _ReadyEvents[pos].first;
            con *ccon = nullptr;

            std::lock_guard<std::mutex> global_lock(POLL_HANDLER_MUTEX);

            auto it = CONNECTIONS.find(fd);
            if (it != CONNECTIONS.end()) {
                ccon = it->second;
            } else {
                return;
            }

            {
                std::lock_guard<std::mutex> lock(ccon->event_mutex);

                if (ccon->csock) {
                    try {
                        // 1. Remove from master sets
                        FD_CLR(ccon->csock->fd(), &_masterReadSet);
                        FD_CLR(ccon->csock->fd(), &_masterWriteSet);
                        FD_CLR(ccon->csock->fd(), &_masterExceptSet);

                        // 2. Perform disconnect event
                        evconnection->DisconnectEvent(*ccon, tid, args);

                    } catch (NetException &e) {
                        throw e;
                    }
                }
                // 3. Remove from global map
                CONNECTIONS.erase(it);
            }

            // 4. Delete the memory
            delete ccon;

            // 5. Recalculate _maxFD
            _maxFD = 0;
            for (auto const& [conn_fd, conn_ptr] : CONNECTIONS) {
                _maxFD = std::max(_maxFD, conn_fd);
            }
            for (auto const& ssock : SSOCKETS) {
                _maxFD = std::max(_maxFD, ssock->fd());
            }
        }

    private:
        // fd_set for master list of FDs to monitor
        fd_set _masterReadSet;
        fd_set _masterWriteSet;
        fd_set _masterExceptSet;

        // fd_set used as temporary storage for select()
        fd_set _currentReadSet;
        fd_set _currentWriteSet;
        fd_set _currentExceptSet;

        // List of ready events to be compatible with the existing EventWorker loop
        std::vector<std::pair<int, int>> _ReadyEvents;

        int _maxFD; // Highest file descriptor number
        socket* _ServerSocket;
        int _Timeout;
        friend  void signalHandler(int signum);
    };

    class EventWorkerArgs{
    public:
        EventWorkerArgs(){
        }

        EventWorkerArgs(const EventWorkerArgs &eargs){
            pollfd=eargs.pollfd;
            ssocket=eargs.ssocket;
            timeout=eargs.timeout;
            args=eargs.args;
            event=eargs.event;
        }

        int      pollfd; // Ignored in select implementation
        int      timeout;

        eventapi    *event;
        socket      *ssocket;
        void        *args;
    };

    class EventWorker {
    public:
        EventWorker(int tid,ULONG_PTR args,EventWorkerArgs* eargs) {

            // 'poll' is now the select-based implementation
            poll pollptr(eargs->ssocket,eargs->event,eargs->pollfd, eargs->timeout);
            pollptr.initEventHandler(); // Sets up the initial FD sets for the server socket

            int wait=0;

            // In EventWorker::EventWorker:
            while(event::Running){
                try {
                    wait=pollptr.waitEventHandler(eargs->timeout);
                    for(int i =0; i<wait; ++i){
                        try{
                            int events = pollptr.pollState(i);

                            // Check for listener socket (EVCON for the select implementation)
                            if (events == pollapi::EventHandlerStatus::EVCON) {
                                pollptr.ConnectEventHandler(i,tid,args);
                                continue;
                            }

                            // Get the simulated event flags
                            events = pollptr.getEventFlags(i);

                            // Check for error/hangs (EPOLLHUP/EPOLLERR)
                            if (events & (EPOLLHUP | EPOLLERR)) {
                                // Treat as close event if any of these flags are set
                                pollptr.CloseEventHandler(i,tid,args);
                                continue;
                            }

                            // Prioritize read events (new data from client)
                            if (events & EPOLLIN) {
                                pollptr.ReadEventHandler(i,tid,args);
                                continue;
                            }

                            // Handle write events (ready to send data)
                            if (events & EPOLLOUT) {
                                pollptr.WriteEventHandler(i,tid,args);
                                continue;
                            }

                            // FALLBACK/DEFAULT HANDLER
                            NetException e;
                            e[NetException::Error] << "EventWorker: Unhandled select event type!";
                            throw e;

                        }catch(NetException& e){
                             std::cerr << e.what() << std::endl;
                             pollptr.CloseEventHandler(i,tid,args);
                             if(e.getErrorType()==NetException::Critical)
                                 throw e;
                        }
                    }
                }catch (NetException& e) {
                    std::cerr << e.what() << std::endl;
                }
            }
        }
    };

    struct ThreadHelperArgs {
        EventWorkerArgs* eargs;
        ULONG_PTR args;
        int tid;
    };

    void* worker_wrapper(void* data) {
        ThreadHelperArgs* helper_args = reinterpret_cast<ThreadHelperArgs*>(data);

        try {
            // Call the original worker function
            EventWorker(helper_args->tid, helper_args->args, helper_args->eargs);
        } catch (NetException& e) {
            std::cerr << "Thread " << helper_args->tid << " exited with exception: " << e.what() << std::endl;
        } catch (...) {
            std::cerr << "Thread " << helper_args->tid << " exited with unknown exception." << std::endl;
        }

        // Clean up allocated memory
        delete helper_args;
        return nullptr;
    }

    void eventapi::RequestEvent(con &curcon,const int tid,ULONG_PTR args){
        //dummy
    };

    void eventapi::ResponseEvent(con &curcon,const int tid,ULONG_PTR args){
        //dummy
    };

    void eventapi::ConnectEvent(con &curcon,const int tid,ULONG_PTR args){
        //dummy
    };

    void eventapi::DisconnectEvent(con &curcon,const int tid,ULONG_PTR args){
        //dummy
    };

    event::event(socket *serversocket,int timeout) : _ServerSocket(serversocket) {
        if (!serversocket) {
            NetException exp;
            exp[NetException::Critical] << "server socket empty!";
            throw exp;
        }
        _Timeout=timeout;
        _ServerSocket->bind();
        _ServerSocket->setNonBlock();
        _ServerSocket->listen();
        threads=sysconf(_SC_NPROCESSORS_ONLN);
    }

    event::event(const event &src) : _ServerSocket(src._ServerSocket) {
    }

    event::~event() {
    }

    void signalHandler(int signum) {
        std::lock_guard<std::mutex> lock(POLL_HANDLER_MUTEX);
        switch(signum){
            case SIGINT:
                for(auto ssock : SSOCKETS){
                    ssock->close();
                }
                for(auto ccon : CONNECTIONS){
                    {
                        std::lock_guard<std::mutex> clock(ccon.second->event_mutex);
                        ccon.second->csock->close();
                    }
                }
                event::Running=false;
                break;
            default:
                break;
        }
    }

    void event::runEventloop(ULONG_PTR args) {
        NetException exception;

        signal(SIGINT, signalHandler);
        signal(SIGPIPE, SIG_IGN);

        MAINWORKERLOOP:
        // _pollFD is vestigial from the epoll implementation and is ignored in select.
        _pollFD = -1;

        EventWorkerArgs eargs;
        eargs.ssocket=_ServerSocket;
        eargs.pollfd=_pollFD;
        eargs.timeout=_Timeout;
        eargs.event=this;

        pthread_attr_t attr;
        if (pthread_attr_init(&attr) != 0) {
            exception[NetException::Critical] << "runEventloop: Failed to initialize pthread attributes: " << strerror(errno);
            throw exception;
        }

        // NOTE: THREAD_STACK_SIZE is an external constant.
        // Uncomment the following block if THREAD_STACK_SIZE is defined in your environment.
        /*
        if (pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE) != 0) {
            exception[NetException::Critical] << "runEventloop: Failed to set pthread stack size: " << strerror(errno);
            pthread_attr_destroy(&attr);
            throw exception;
        }
        */

        // Use std::vector<pthread_t> to store thread handles
        std::vector <pthread_t> threadpool_handles;
        threadpool_handles.reserve(threads);

        for (int i = 0; i < threads; i++) {
            // Allocate memory for thread arguments on the heap
            ThreadHelperArgs *helper_args = new ThreadHelperArgs{&eargs, args, i};

            pthread_t thread_id;
            // Use pthread_create with the custom attributes and C-style wrapper
            int ret = pthread_create(&thread_id, &attr, worker_wrapper, helper_args);

            if (ret != 0) {
                delete helper_args; // Cleanup allocated arguments
                char errstr[255];
                strerror_r(ret, errstr, 255);
                exception[NetException::Critical] << "runEventloop: Failed to create thread: " << errstr;
                pthread_attr_destroy(&attr);
                throw exception;
            }
            threadpool_handles.push_back(thread_id);
        }

        // Wait for all threads to finish using pthread_join
        for(auto i = threadpool_handles.begin(); i!=threadpool_handles.end(); ++i){
            pthread_join(*i, nullptr);
        }

        // Cleanup thread attributes
        pthread_attr_destroy(&attr);

        // close(_pollFD); is removed as it was epoll-specific

        if (event::Restart) {
            event::Restart = false;
            goto MAINWORKERLOOP;
        }
    }
};