summaryrefslogtreecommitdiff
path: root/src/socketengines/socketengine_poll.cpp
blob: 46a517c5105d8c1099cda8a5d4e8370225ffb6de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
 * InspIRCd -- Internet Relay Chat Daemon
 *
 *   Copyright (C) 2014 Adam <Adam@anope.org>
 *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
 *   Copyright (C) 2009 Uli Schlachter <psychon@znc.in>
 *   Copyright (C) 2009 Craig Edwards <craigedwards@brainbox.cc>
 *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
 *
 * This file is part of InspIRCd.  InspIRCd is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, version 2.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include "exitcodes.h"
#include "inspircd.h"
#include "socketengine.h"

#ifndef _WIN32
# ifndef __USE_XOPEN
#  define __USE_XOPEN /* fuck every fucking OS ever made. needed by poll.h to work.*/
# endif
# include <poll.h>
# include <sys/poll.h>
# include <sys/resource.h>
#else
# define struct pollfd WSAPOLLFD
# define poll WSAPoll
#endif

/** A specialisation of the SocketEngine class, designed to use poll().
 */
class PollEngine : public SocketEngine
{
private:
	/** These are used by poll() to hold socket events
	 */
	std::vector<struct pollfd> events;
	/** This vector maps fds to an index in the events array.
	 */
	std::vector<int> fd_mappings;
public:
	/** Create a new PollEngine
	 */
	PollEngine();
	virtual bool AddFd(EventHandler* eh, int event_mask);
	virtual void OnSetEvent(EventHandler* eh, int old_mask, int new_mask);
	virtual void DelFd(EventHandler* eh);
	virtual int DispatchEvents();
};

PollEngine::PollEngine() : events(1), fd_mappings(1)
{
	struct rlimit limits;
	if (!getrlimit(RLIMIT_NOFILE, &limits))
	{
		MAX_DESCRIPTORS = limits.rlim_cur;
	}
	else
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ERROR: Can't determine maximum number of open sockets: %s", strerror(errno));
		std::cout << "ERROR: Can't determine maximum number of open sockets: " << strerror(errno) << std::endl;
		ServerInstance->QuickExit(EXIT_STATUS_SOCKETENGINE);
	}
}

static int mask_to_poll(int event_mask)
{
	int rv = 0;
	if (event_mask & (FD_WANT_POLL_READ | FD_WANT_FAST_READ))
		rv |= POLLIN;
	if (event_mask & (FD_WANT_POLL_WRITE | FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE))
		rv |= POLLOUT;
	return rv;
}

bool PollEngine::AddFd(EventHandler* eh, int event_mask)
{
	int fd = eh->GetFd();
	if ((fd < 0) || (fd > GetMaxFds() - 1))
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "AddFd out of range: (fd: %d, max: %d)", fd, GetMaxFds());
		return false;
	}

	if (static_cast<unsigned int>(fd) < fd_mappings.size() && fd_mappings[fd] != -1)
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to add duplicate fd: %d", fd);
		return false;
	}

	unsigned int index = CurrentSetSize;

	if (!SocketEngine::AddFdRef(eh))
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Attempt to add duplicate fd: %d", fd);
		return false;
	}

	while (static_cast<unsigned int>(fd) >= fd_mappings.size())
		fd_mappings.resize(fd_mappings.size() * 2, -1);
	fd_mappings[fd] = index;

	ResizeDouble(events);
	events[index].fd = fd;
	events[index].events = mask_to_poll(event_mask);

	ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "New file descriptor: %d (%d; index %d)", fd, events[index].events, index);
	SocketEngine::SetEventMask(eh, event_mask);
	return true;
}

void PollEngine::OnSetEvent(EventHandler* eh, int old_mask, int new_mask)
{
	int fd = eh->GetFd();
	if (fd < 0 || static_cast<unsigned int>(fd) >= fd_mappings.size() || fd_mappings[fd] == -1)
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "SetEvents() on unknown fd: %d", eh->GetFd());
		return;
	}

	events[fd_mappings[fd]].events = mask_to_poll(new_mask);
}

void PollEngine::DelFd(EventHandler* eh)
{
	int fd = eh->GetFd();
	if ((fd < 0) || (fd > MAX_DESCRIPTORS))
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DelFd out of range: (fd: %d, max: %d)", fd, GetMaxFds());
		return;
	}

	if (static_cast<unsigned int>(fd) >= fd_mappings.size() || fd_mappings[fd] == -1)
	{
		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "DelFd() on unknown fd: %d", fd);
		return;
	}

	unsigned int index = fd_mappings[fd];
	unsigned int last_index = CurrentSetSize - 1;
	int last_fd = events[last_index].fd;

	if (index != last_index)
	{
		// We need to move the last fd we got into this gap (gaps are evil!)

		// So update the mapping for the last fd to its new position
		fd_mappings[last_fd] = index;

		// move last_fd from last_index into index
		events[index].fd = last_fd;
		events[index].events = events[last_index].events;
	}

	// Now remove all data for the last fd we got into out list.
	// Above code made sure this always is right
	fd_mappings[fd] = -1;
	events[last_index].fd = 0;
	events[last_index].events = 0;

	SocketEngine::DelFdRef(eh);

	ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Remove file descriptor: %d (index: %d) "
			"(Filled gap with: %d (index: %d))", fd, index, last_fd, last_index);
}

int PollEngine::DispatchEvents()
{
	int i = poll(&events[0], CurrentSetSize, 1000);
	int processed = 0;
	ServerInstance->UpdateTime();

	for (int index = 0; index < CurrentSetSize && processed < i; index++)
	{
		struct pollfd& pfd = events[index];

		// Copy these in case the vector gets resized and pfd invalidated
		const int fd = pfd.fd;
		const short revents = pfd.revents;

		if (revents)
			processed++;

		EventHandler* eh = GetRef(fd);
		if (!eh)
			continue;

		if (revents & POLLHUP)
		{
			eh->HandleEvent(EVENT_ERROR, 0);
			continue;
		}

		if (revents & POLLERR)
		{
			// Get error number
			socklen_t codesize = sizeof(int);
			int errcode;
			if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &codesize) < 0)
				errcode = errno;
			eh->HandleEvent(EVENT_ERROR, errcode);
			continue;
		}

		if (revents & POLLIN)
		{
			SetEventMask(eh, eh->GetEventMask() & ~FD_READ_WILL_BLOCK);
			eh->HandleEvent(EVENT_READ);
			if (eh != GetRef(fd))
				// whoops, deleted out from under us
				continue;
		}

		if (revents & POLLOUT)
		{
			int mask = eh->GetEventMask();
			mask &= ~(FD_WRITE_WILL_BLOCK | FD_WANT_SINGLE_WRITE);
			SetEventMask(eh, mask);

			// The vector could've been resized, reference can be invalid by now; don't use it
			events[index].events = mask_to_poll(mask);
			eh->HandleEvent(EVENT_WRITE);
		}
	}

	return i;
}

SocketEngine* CreateSocketEngine()
{
	return new PollEngine;
}