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)
26 writeable = new bool [GetMaxFds()];
27 memset(writeable, 0, sizeof(writeable));
28 ref = new EventHandler* [GetMaxFds()];
29 memset(ref, 0, GetMaxFds() * sizeof(EventHandler*));
30 ev = new EventHandler* [GetMaxFds()];
33 SelectEngine::~SelectEngine()
39 bool SelectEngine::AddFd(EventHandler* eh)
42 if ((fd < 0) || (fd > GetMaxFds() - 1))
45 if (GetRemainingFds() <= 1)
55 ServerInstance->Logs->Log("SOCKET",DEBUG,"New file descriptor: %d", fd);
59 void SelectEngine::WantWrite(EventHandler* eh)
61 writeable[eh->GetFd()] = true;
64 bool SelectEngine::DelFd(EventHandler* eh, bool force)
68 if ((fd < 0) || (fd > GetMaxFds() - 1))
71 std::map<int,int>::iterator t = fds.find(fd);
78 ServerInstance->Logs->Log("SOCKET",DEBUG,"Remove file descriptor: %d", fd);
82 int SelectEngine::GetMaxFds()
87 int SelectEngine::GetRemainingFds()
89 return GetMaxFds() - CurrentSetSize;
92 int SelectEngine::DispatchEvents()
104 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
106 if (ref[a->second]->Readable())
107 FD_SET (a->second, &rfdset);
109 FD_SET (a->second, &wfdset);
110 if (writeable[a->second])
111 FD_SET (a->second, &wfdset);
113 FD_SET (a->second, &errfdset);
119 sresult = select(FD_SETSIZE, &rfdset, &wfdset, &errfdset, &tval);
123 for (std::map<int,int>::iterator a = fds.begin(); a != fds.end(); a++)
125 if ((FD_ISSET (a->second, &rfdset)) || (FD_ISSET (a->second, &wfdset)) || FD_ISSET (a->second, &errfdset))
127 ev[result++] = ref[a->second];
132 /** An event handler may remove its own descriptor from the list, therefore it is not
133 * safe to directly iterate over the list and dispatch events there with STL iterators.
134 * Thats a shame because it makes this code slower and more resource intensive, but maybe
135 * the user should stop using select(), as select() smells anyway.
137 for (int i = 0; i < result; i++)
141 if (FD_ISSET (ev[i]->GetFd(), &errfdset))
145 if (getsockopt(ev[i]->GetFd(), SOL_SOCKET, SO_ERROR, (char*)&errcode, &codesize) < 0)
148 ev[i]->HandleEvent(EVENT_ERROR, errcode);
154 if (writeable[ev[i]->GetFd()])
157 writeable[ev[i]->GetFd()] = false;
158 ev[i]->HandleEvent(EVENT_WRITE);
162 if (ev[i]->Readable())
165 ev[i]->HandleEvent(EVENT_READ);
170 ev[i]->HandleEvent(EVENT_WRITE);
180 std::string SelectEngine::GetName()