1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/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(InspIRCd* Instance) : SocketEngine(Instance)
23 MAX_DESCRIPTORS = FD_SETSIZE;
27 writeable = new bool [GetMaxFds()];
28 memset(writeable, 0, sizeof(writeable));
29 ref = new EventHandler* [GetMaxFds()];
30 memset(ref, 0, GetMaxFds() * sizeof(EventHandler*));
31 ev = new EventHandler* [GetMaxFds()];
34 SelectEngine::~SelectEngine()
40 bool SelectEngine::AddFd(EventHandler* eh)
43 if ((fd < 0) || (fd > GetMaxFds() - 1))
46 if (GetRemainingFds() <= 1)
56 ServerInstance->Logs->Log("SOCKET",DEBUG,"New file descriptor: %d", fd);
60 void SelectEngine::WantWrite(EventHandler* eh)
62 writeable[eh->GetFd()] = true;
65 bool SelectEngine::DelFd(EventHandler* eh, bool force)
69 if ((fd < 0) || (fd > GetMaxFds() - 1))
72 std::map<int,int>::iterator t = fds.find(fd);
79 ServerInstance->Logs->Log("SOCKET",DEBUG,"Remove file descriptor: %d", fd);
83 int SelectEngine::GetMaxFds()
88 int SelectEngine::GetRemainingFds()
90 return GetMaxFds() - CurrentSetSize;
93 int SelectEngine::DispatchEvents()
105 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
107 if (ref[a->second]->Readable())
108 FD_SET (a->second, &rfdset);
110 FD_SET (a->second, &wfdset);
111 if (writeable[a->second])
112 FD_SET (a->second, &wfdset);
114 FD_SET (a->second, &errfdset);
120 sresult = select(FD_SETSIZE, &rfdset, &wfdset, &errfdset, &tval);
124 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
126 if ((FD_ISSET (a->second, &rfdset)) || (FD_ISSET (a->second, &wfdset)) || FD_ISSET (a->second, &errfdset))
128 ev[result++] = ref[a->second];
133 /** An event handler may remove its own descriptor from the list, therefore it is not
134 * safe to directly iterate over the list and dispatch events there with STL iterators.
135 * Thats a shame because it makes this code slower and more resource intensive, but maybe
136 * the user should stop using select(), as select() smells anyway.
138 for (int i = 0; i < result; i++)
142 if (FD_ISSET (ev[i]->GetFd(), &errfdset))
146 if (getsockopt(ev[i]->GetFd(), SOL_SOCKET, SO_ERROR, (char*)&errcode, &codesize) < 0)
149 ev[i]->HandleEvent(EVENT_ERROR, errcode);
155 if (writeable[ev[i]->GetFd()])
158 writeable[ev[i]->GetFd()] = false;
159 ev[i]->HandleEvent(EVENT_WRITE);
163 if (ev[i]->Readable())
166 ev[i]->HandleEvent(EVENT_READ);
171 ev[i]->HandleEvent(EVENT_WRITE);
181 std::string SelectEngine::GetName()