summaryrefslogtreecommitdiff
path: root/src/socketengine_iocp.cpp
blob: 58ce36177e94ed653074ec1ea6cd30c0d8c077ad (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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*       +------------------------------------+
 *       | Inspire Internet Relay Chat Daemon |
 *       +------------------------------------+
 *
 *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
 * See: http://www.inspircd.org/wiki/index.php/Credits
 *
 * This program is free but copyrighted software; see
 *            the file COPYING for details.
 *
 * ---------------------------------------------------
 */

#include "socketengine_iocp.h"
#include <mswsock.h>

IOCPEngine::IOCPEngine(InspIRCd * Instance) : SocketEngine(Instance)
{
	/* Create completion port */
	m_completionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (ULONG_PTR)0, 0);

	/* Null variables out. */
	CurrentSetSize = 0;
	EngineHandle = 0;
	memset(ref, 0, sizeof(EventHandler*) * MAX_DESCRIPTORS);
}

IOCPEngine::~IOCPEngine()
{
	CloseHandle(m_completionPort);
}

bool IOCPEngine::AddFd(EventHandler* eh)
{
	int fake_fd = GenerateFd(eh->GetFd());
	int is_accept = 0;
	int opt_len = sizeof(int);
	if(fake_fd < 0)
		return false;

	/* are we a listen socket? */
	getsockopt(eh->GetFd(), SOL_SOCKET, SO_ACCEPTCONN, (char*)&is_accept, &opt_len);

	/* set up the read event so the socket can actually receive data :P */
	eh->m_internalFd = fake_fd;
	eh->m_writeEvent = 0;
	eh->m_acceptEvent = 0;

	/* assign the socket to the completion port */
	if(!CreateIoCompletionPort((HANDLE)eh->GetFd(), m_completionPort, (ULONG_PTR)eh->m_internalFd, 0))
		return false;

	/* set up binding, increase set size */
	ref[fake_fd] = eh;
	++CurrentSetSize;

	/* setup initial events */
	if(is_accept)
		PostAcceptEvent(eh);
	else
		PostReadEvent(eh);

	/* log message */
	ServerInstance->Log(DEBUG, "New fake fd: %u, real fd: %u, address 0x%p", fake_fd, eh->GetFd(), eh);

	/* post a write event if there is data to be written */
	if(eh->Writeable())
		WantWrite(eh);

	/* we're all good =) */
	try
	{
		m_binding.insert( map<int, EventHandler*>::value_type( eh->GetFd(), eh ) );
	}
	catch (...)
	{
		/* Ohshi-, map::insert failed :/ */
		return false;
	}

	return true;
}

bool IOCPEngine::DelFd(EventHandler* eh, bool force /* = false */)
{
	int fake_fd = eh->m_internalFd;
	int fd = eh->GetFd();
	
	if(ref[fake_fd] == 0)
		return false;

	ServerInstance->Log(DEBUG, "Removing fake fd %u, real fd %u, address 0x%p", fake_fd, eh->GetFd(), eh);

	/* Cancel pending i/o operations. */
	if (CancelIo((HANDLE)fd) == FALSE)
		return false;

	/* Free the buffer, and delete the event. */
	if(eh->m_readEvent != 0)
		delete ((Overlapped*)eh->m_readEvent);

	if(eh->m_writeEvent != 0)
		delete ((Overlapped*)eh->m_writeEvent);

	if(eh->m_acceptEvent != 0)
	{
		delete ((accept_overlap*)((Overlapped*)eh->m_acceptEvent)->m_params);
		delete ((Overlapped*)eh->m_acceptEvent);
	}

	/* Clear binding */
	ref[fake_fd] = 0;
	m_binding.erase(eh->GetFd());

	/* decrement set size */
	--CurrentSetSize;
	
	/* success */
	return true;
}

void IOCPEngine::WantWrite(EventHandler* eh)
{
	/* Post event - write begin */
	if(!eh->m_writeEvent)
	{
		Overlapped * ov = new Overlapped(SOCKET_IO_EVENT_WRITE_READY, 0);
		eh->m_writeEvent = (void*)ov;
		PostQueuedCompletionStatus(m_completionPort, 0, (ULONG_PTR)eh->m_internalFd, &ov->m_overlap);
	}
}

bool IOCPEngine::PostCompletionEvent(EventHandler * eh, SocketIOEvent type, int param)
{
	Overlapped * ov = new Overlapped(type, param);
	return PostQueuedCompletionStatus(m_completionPort, 0, (ULONG_PTR)eh->m_internalFd, &ov->m_overlap);
}

void IOCPEngine::PostReadEvent(EventHandler * eh)
{
	Overlapped * ov = new Overlapped(SOCKET_IO_EVENT_READ_READY, 0);
	DWORD flags = 0;
	DWORD r_length = 0;
	WSABUF buf;

	/* by passing a null buffer pointer, we can have this working in the same way as epoll..
	 * its slower, but it saves modifying all network code.
	 */
	buf.buf = 0;
	buf.len = 0;

	/* determine socket type. */
	DWORD sock_type;
	int sock_len = sizeof(DWORD);
	if(getsockopt(eh->GetFd(), SOL_SOCKET, SO_TYPE, (char*)&sock_type, &sock_len) == -1)
	{
		/* wtfhax? */
		PostCompletionEvent(eh, SOCKET_IO_EVENT_ERROR, 0);
		delete ov;
		return;
	}
	switch(sock_type)
	{
		case SOCK_DGRAM:			/* UDP Socket */
		{
			if(WSARecvFrom(eh->GetFd(), &buf, 1, &r_length, &flags, 0, 0, &ov->m_overlap, 0))
			{
				int err = WSAGetLastError();
				if(WSAGetLastError() != WSA_IO_PENDING)
				{
					delete ov;
					PostCompletionEvent(eh, SOCKET_IO_EVENT_ERROR, 0);
					return;
				}
			}
		}
		break;

		case SOCK_STREAM:			/* TCP Socket */
		{
			if(WSARecv(eh->GetFd(), &buf, 1, &r_length, &flags, &ov->m_overlap, 0) == SOCKET_ERROR)
			{
				if(WSAGetLastError() != WSA_IO_PENDING)
				{
					delete ov;
					PostCompletionEvent(eh, SOCKET_IO_EVENT_ERROR, 0);
					return;
				}
			}
		}
		break;

		default:
		{
			printf("unknwon socket type: %u\n", sock_type);
			return;
		}
		break;
	}
	eh->m_readEvent = (void*)ov;
}

int IOCPEngine::DispatchEvents()
{
	DWORD len;
	LPOVERLAPPED overlap;
	Overlapped * ov;
	EventHandler * eh;
	int intfd;
	int ret;
	unsigned long bytes_recv;

	while(GetQueuedCompletionStatus(m_completionPort, &len, (PULONG_PTR)&intfd, &overlap, 1000))
	{
		// woot, we got an event on a socket :P
		eh = ref[intfd];
		ov = CONTAINING_RECORD(overlap, Overlapped, m_overlap);
		if(eh == 0) continue;
		switch(ov->m_event)
		{
			case SOCKET_IO_EVENT_WRITE_READY:
			{
				eh->m_writeEvent = 0;
				eh->HandleEvent(EVENT_WRITE, 0);
			}
			break;

			case SOCKET_IO_EVENT_READ_READY:
			{
				ret = ioctlsocket(eh->GetFd(), FIONREAD, &bytes_recv);
				eh->m_readEvent = 0;
				if(ret != 0 || bytes_recv == 0)
				{
					/* end of file */
					PostCompletionEvent(eh, SOCKET_IO_EVENT_ERROR, EIO); /* Old macdonald had an error, EIEIO. */
				}
				else
				{
					eh->HandleEvent(EVENT_READ, 0);
					PostReadEvent(eh);
				}
			}
			break;
		
			case SOCKET_IO_EVENT_ACCEPT:
			{
				/* this is kinda messy.. :/ */
				eh->HandleEvent(EVENT_READ, ov->m_params);
				delete ((accept_overlap*)ov->m_params);
				eh->m_acceptEvent = 0;
				PostAcceptEvent(eh);
			}
			break;

			case SOCKET_IO_EVENT_ERROR:
			{
				eh->HandleEvent(EVENT_ERROR, ov->m_params);
			}
			break;
		}
		
		delete ov;
	}

	return 0;
}

void IOCPEngine::PostAcceptEvent(EventHandler * eh)
{
	int fd = WSASocket(AF_INET, SOCK_STREAM, 0, 0, 0, WSA_FLAG_OVERLAPPED);
	int len = sizeof(sockaddr_in) + 16;
	DWORD dwBytes;
	accept_overlap* ao = new accept_overlap;
	memset(ao->buf, 0, 1024);
	ao->socket = fd;

	Overlapped* ov = new Overlapped(SOCKET_IO_EVENT_ACCEPT, (int)ao);
	eh->m_acceptEvent = (void*)ov;

	if(AcceptEx(eh->GetFd(), fd, ao->buf, 0, len, len, &dwBytes, &ov->m_overlap) == FALSE)
	{
		int err = WSAGetLastError();
		if(err != WSA_IO_PENDING)
		{
			printf("PostAcceptEvent err: %d\n", err);
		}
	}
}


std::string IOCPEngine::GetName()
{
	return "iocp";
}

int __accept_socket(SOCKET s, sockaddr * addr, int * addrlen, void * acceptevent)
{
	Overlapped* ovl = (Overlapped*)acceptevent;
	accept_overlap* ov = (accept_overlap*)ovl->m_params;

	sockaddr_in* server_address = (sockaddr_in*)&ov->buf[10];
	sockaddr_in* client_address = (sockaddr_in*)&ov->buf[38];

	memcpy(addr, client_address, sizeof(sockaddr_in));
	*addrlen = sizeof(sockaddr_in);

	return ov->socket;
}

int __getsockname(SOCKET s, sockaddr * name, int * namelen, void * acceptevent)
{
	Overlapped* ovl = (Overlapped*)acceptevent;
	accept_overlap* ov = (accept_overlap*)ovl->m_params;

	sockaddr_in* server_address = (sockaddr_in*)&ov->buf[10];
	sockaddr_in* client_address = (sockaddr_in*)&ov->buf[38];

	memcpy(name, server_address, sizeof(sockaddr_in));
	*namelen = sizeof(sockaddr_in);

	return 0;
}

EventHandler * IOCPEngine::GetRef(int fd)
{
	map<int, EventHandler*>::iterator itr = m_binding.find(fd);
	return (itr == m_binding.end()) ? 0 : itr->second;
}

bool IOCPEngine::HasFd(int fd)
{
	return (GetRef(fd) != 0);
}

EventHandler * IOCPEngine::GetIntRef(int fd)
{
	if(fd < 0 || fd > MAX_DESCRIPTORS)
		return 0;
	return ref[fd];
}