1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 #include <sys/select.h>
18 #include "socketengines/socketengine_select.h"
21 SelectEngine::SelectEngine()
23 MAX_DESCRIPTORS = FD_SETSIZE;
26 ref = new EventHandler* [GetMaxFds()];
27 memset(ref, 0, GetMaxFds() * sizeof(EventHandler*));
30 SelectEngine::~SelectEngine()
35 bool SelectEngine::AddFd(EventHandler* eh, int)
38 if ((fd < 0) || (fd > GetMaxFds() - 1))
45 SocketEngine::SetEventMask(eh, event_mask);
48 ServerInstance->Logs->Log("SOCKET",DEBUG,"New file descriptor: %d", fd);
52 bool SelectEngine::DelFd(EventHandler* eh, bool force)
56 if ((fd < 0) || (fd > GetMaxFds() - 1))
62 ServerInstance->Logs->Log("SOCKET",DEBUG,"Remove file descriptor: %d", fd);
66 void SelectEngine::OnSetEvent(EventHandler* eh, int old_mask, int new_mask)
71 int SelectEngine::DispatchEvents()
75 socklen_t codesize = sizeof(int);
78 fd_set wfdset, rfdset, errfdset;
83 /* Populate the select FD sets (this is why select sucks compared to epoll, kqueue, IOCP) */
84 for (int i = 0; i < FD_SETSIZE; i++)
86 EventHandler* eh = ref[i];
89 int state = eh->GetEventMask();
90 if (state & (FD_WANT_POLL_READ | FD_WANT_FAST_READ))
92 if (state & (FD_WANT_POLL_WRITE | FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE))
94 FD_SET (i, &errfdset);
101 sresult = select(FD_SETSIZE, &rfdset, &wfdset, &errfdset, &tval);
103 /* Nothing to process this time around */
107 for (int i = 0; i < FD_SETSIZE; i++)
109 EventHandler* ev = ref[i];
112 if (FD_ISSET (i, &errfdset))
115 if (getsockopt(i, SOL_SOCKET, SO_ERROR, (char*)&errcode, &codesize) < 0)
118 ev->HandleEvent(EVENT_ERROR, errcode);
123 /* NOTE: This is a pair of seperate if statements as the socket
124 * may be in both read and writeable state at the same time.
125 * If an error event occurs above it is not worth processing the
126 * read and write states even if set.
128 if (FD_ISSET (i, &rfdset))
131 SetEventMask(eh, eh->GetEventMask() & ~FD_READ_WILL_BLOCK);
132 ev->HandleEvent(EVENT_READ);
134 if (FD_ISSET (i, &wfdset))
137 SetEventMask(eh, eh->GetEventMask() & ~(FD_WRITE_WILL_BLOCK | FD_WANT_SINGLE_WRITE));
138 ev->HandleEvent(EVENT_WRITE);
147 std::string SelectEngine::GetName()