summaryrefslogtreecommitdiff
path: root/src/libs/network/netmanager/netmanager_win.c
blob: f1467326f80304082aeeb516a7c6c572f6ecdebd (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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
 *  Copyright 2006  Serge van den Boom <svdb@stack.nl>
 *
 *  This program 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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#define PORT_WANT_ERRNO
#include "port.h"
#include "../netport.h"

#define NETMANAGER_INTERNAL
#define NETDESCRIPTOR_INTERNAL
#define SOCKET_INTERNAL
#include "netmanager_win.h"
#include "../socket/socket.h"

#include "ndesc.h"
#include "types.h"
#include "libs/misc.h"
#include "libs/log.h"

#include <assert.h>
#include <winsock2.h>

#include "netmanager_common.ci"

int closeWSAEvent(WSAEVENT event);


// The elements of the following arrays with the same index belong to
// eachother.
#define MAX_SOCKETS WSA_MAXIMUM_WAIT_EVENTS
		// We cannot have more sockets than we can have events, as
		// all may need an event at some point.
static NetDescriptor *netDescriptors[MAX_SOCKETS];
static WSAEVENT events[WSA_MAXIMUM_WAIT_EVENTS];
static size_t numSockets;
static size_t numActiveEvents;
// For each NetDescriptor registered with the NetManager, an event
// is created. Only the first numActiveEvents will be processed though.
// Inv: numActiveEvents <= numSockets
// Inv: for all i: 0 <= i < numActiveEvents: events[i] is active
//      (events[i] being active also means netDescriptor[i]->smd->eventMask
//      != 0)
// Inv: for all i: 0 <= i < numSockets: netDescriptor[i]->smd->index == i

void
NetManager_init(void) {
	numActiveEvents = 0;
}

void
NetManager_uninit(void) {
	assert(numActiveEvents == 0);
}

static inline SocketManagementDataWin *
SocketManagementData_alloc(void) {
	return malloc(sizeof (SocketManagementDataWin));
}

static inline void
SocketManagementData_free(SocketManagementDataWin *smd) {
	free(smd);
}

// XXX: This function should be moved to some file with generic network
// functions.
int
closeWSAEvent(WSAEVENT event) {
	for (;;) {
		int error;

		if (WSACloseEvent(event))
			break;

		error = WSAGetLastError();
		if (error != WSAEINPROGRESS) {
			log_add(log_Error,
					"WSACloseEvent() failed with error code %d.", error);
			errno = winsockErrorToErrno(error);
			return -1;
		}
	}
	return 0;
}

// Register the NetDescriptor with the NetManager.
int
NetManager_addDesc(NetDescriptor *nd) {
	long eventMask = 0;
	WSAEVENT event;

	if (numSockets >= WSA_MAXIMUM_WAIT_EVENTS) {
		errno = EMFILE;
		return -1;
	}

	if (nd->readCallback != NULL)
		eventMask |= FD_READ | FD_ACCEPT;

	if (nd->writeCallback != NULL)
		eventMask |= FD_WRITE /* | FD_CONNECT */;

	if (nd->exceptionCallback != NULL)
		eventMask |= FD_OOB;

	eventMask |= FD_CLOSE;

	event = WSACreateEvent();
	if (event == WSA_INVALID_EVENT) {
		errno = getWinsockErrno();
		return -1;
	}

	nd->smd = SocketManagementData_alloc();
	if (eventMask != 0) {
			// XXX: This guard is now always true, because of FD_CLOSE.
			//      This means that numActiveEvents will always be equal to
			//      numEvents.
			//      Once I'm convinced this is the right way to go,
			//      I can remove some unnecessary code.
		if (WSAEventSelect(nd->socket->sock, event, eventMask) ==
				SOCKET_ERROR) {
			int savedErrno = getWinsockErrno();
			int closeStatus = closeWSAEvent(event);
			if (closeStatus == -1) {
				log_add(log_Fatal, "closeWSAEvent() failed: %s.",
						strerror(errno));
				explode();
			}
			SocketManagementData_free(nd->smd);
			errno = savedErrno;
			return -1;
		}

		// Move existing socket for which there exists no event, so
		// so that all sockets for which there exists an event are at
		// the front of the array of netdescriptors.
		if (numActiveEvents < numSockets) {
			netDescriptors[numSockets] = netDescriptors[numActiveEvents];
			netDescriptors[numSockets]->smd->index = numSockets;
		}

		nd->smd->index = numActiveEvents;
		numActiveEvents++;
	} else {
		nd->smd->index = numSockets;
	}
	nd->smd->eventMask = eventMask;

	netDescriptors[nd->smd->index] = nd;
	events[nd->smd->index] = event;
	numSockets++;

	return 0;
}

void
NetManager_removeDesc(NetDescriptor *nd) {
	assert(nd->smd != NULL);
	assert(nd->smd->index < numSockets);
	assert(nd == netDescriptors[nd->smd->index]);

	{
		int closeStatus = closeWSAEvent(events[nd->smd->index]);
		if (closeStatus == -1)
			explode();
	}

	if (nd->smd->index < numActiveEvents) {
		size_t index = nd->smd->index;
		if (index + 1 != numActiveEvents) {
			// Keep the list of active events consecutive by filling
			// the new hole with the last active event.
			events[index] = events[numActiveEvents - 1];
			netDescriptors[index] = netDescriptors[numActiveEvents - 1];
			netDescriptors[index]->smd->index = index;
		}
		numActiveEvents--;
	}

	SocketManagementData_free(nd->smd);
	nd->smd = NULL;

	numSockets--;
}

static void
swapSockets(int index1, int index2) {
	NetDescriptor *tempNd;
	WSAEVENT tempEvent;

	tempNd = netDescriptors[index2];
	tempEvent = events[index2];

	netDescriptors[index2] = netDescriptors[index1];
	events[index2] = events[index1];
	netDescriptors[index2]->smd->index = index2;

	netDescriptors[index1] = tempNd;
	events[index1] = tempEvent;
	netDescriptors[index1]->smd->index = index1;
}

static int
NetManager_updateEvent(NetDescriptor *nd) {
	assert(nd == netDescriptors[nd->smd->index]);

	if (WSAEventSelect(nd->socket->sock,
			events[nd->smd->index], nd->smd->eventMask) == SOCKET_ERROR) {
		int savedErrno = getWinsockErrno();
		int closeStatus = closeWSAEvent(events[nd->smd->index]);
		if (closeStatus == -1) {
			log_add(log_Fatal, "closeWSAEvent() failed: %s.",
					strerror(errno));
			explode();
		}
		errno = savedErrno;
		return -1;
	}

	if (nd->smd->eventMask != 0) {
		// There are some events that we are interested in.
		if (nd->smd->index >= numActiveEvents) {
			// Event was not yet active.
			if (nd->smd->index != numActiveEvents) {
				// Need to keep the active nds and events in the front of
				// their arrays.
				swapSockets(nd->smd->index, numActiveEvents);
			}
			numActiveEvents++;
		}
	} else {
		// There are no events that we are interested in.
		if (nd->smd->index < numActiveEvents) {
			// Event was active.
			if (nd->smd->index != numActiveEvents - 1) {
				// Need to keep the active nds and events in the front of
				// their arrays.
				swapSockets(nd->smd->index, numActiveEvents - 1);
			}
		}
		numActiveEvents--;
	}

	return 0;	
}

static void
activateSomeCallback(NetDescriptor *nd, long eventMask) {
	nd->smd->eventMask |= eventMask;
	{
		int status = NetManager_updateEvent(nd);
		if (status == -1) {
			log_add(log_Fatal, "NetManager_updateEvent() failed: %s.",
					strerror(errno));
			explode();
			// TODO: better error handling.
		}
	}
}

static void
deactivateSomeCallback(NetDescriptor *nd, long eventMask) {
	nd->smd->eventMask &= ~eventMask;
	{
		int status = NetManager_updateEvent(nd);
		if (status == -1) {
			log_add(log_Fatal, "NetManager_updateEvent() failed: %s.",
					strerror(errno));
			explode();
			// TODO: better error handling
		}
	}
}

void
NetManager_activateReadCallback(NetDescriptor *nd) {
	activateSomeCallback(nd, FD_READ | FD_ACCEPT);
}

void
NetManager_deactivateReadCallback(NetDescriptor *nd) {
	deactivateSomeCallback(nd, FD_READ | FD_ACCEPT);
}

void
NetManager_activateWriteCallback(NetDescriptor *nd) {
	activateSomeCallback(nd, FD_WRITE /* | FD_CONNECT */);
}

void
NetManager_deactivateWriteCallback(NetDescriptor *nd) {
	deactivateSomeCallback(nd, FD_WRITE /* | FD_CONNECT */);
}

void
NetManager_activateExceptionCallback(NetDescriptor *nd) {
	activateSomeCallback(nd, FD_OOB);
}

void
NetManager_deactivateExceptionCallback(NetDescriptor *nd) {
	deactivateSomeCallback(nd, FD_OOB);
}

static inline int
NetManager_processEvent(size_t index) {
	WSANETWORKEVENTS networkEvents;
	int enumRes;

	enumRes = WSAEnumNetworkEvents(netDescriptors[index]->socket->sock,
			events[index], &networkEvents);
	if (enumRes == SOCKET_ERROR) {
		errno = getWinsockErrno();
		return -1;
	}

	if (networkEvents.lNetworkEvents & FD_READ) {
		bool closed;
		if (networkEvents.iErrorCode[FD_READ_BIT] != 0) {
			// No special handling is required; the callback function
			// will try to do a recv() and will get the error then.
		}

		closed = NetManager_doReadCallback(netDescriptors[index]);
		if (closed)
			goto closed;
	}
	if (networkEvents.lNetworkEvents & FD_WRITE) {
		bool closed;
		if (networkEvents.iErrorCode[FD_WRITE_BIT] != 0) {
			// No special handling is required; the callback function
			// will try to do a send() and will get the error then.
		}

		closed = NetManager_doWriteCallback(netDescriptors[index]);
		if (closed)
			goto closed;
	}
	if (networkEvents.lNetworkEvents & FD_OOB) {
		bool closed;
		if (networkEvents.iErrorCode[FD_OOB_BIT] != 0) {
			// No special handling is required; the callback function
			// will get the error then when it tries to do a recv().
		}

		closed = NetManager_doExceptionCallback(netDescriptors[index]);
		if (closed)
			goto closed;
	}
	if (networkEvents.lNetworkEvents & FD_ACCEPT) {
		// There is no specific accept callback (because the BSD sockets
		// don't work with specific notification for accept); we use
		// the read callback instead.
		bool closed;
		if (networkEvents.iErrorCode[FD_READ_BIT] != 0) {
			// No special handling is required; the callback function
			// will try to do an accept() and will get the error then.
		}

		closed = NetManager_doReadCallback(netDescriptors[index]);
		if (closed)
			goto closed;
	}
#if 0
	// No need for this. Windows also sets FD_WRITE in this case, and
	// writability is what we check for anyhow.
	if (networkEvents.lNetworkEvents & FD_CONNECT) {
		// There is no specific connect callback (because the BSD sockets
		// don't work with specific notification for connect); we use
		// the write callback instead.
		bool closed;
		if (networkEvents.iErrorCode[FD_WRITE_BIT] != 0) {
			// No special handling is required; the callback function
			// should do getsockopt() with SO_ERROR to get the error.
		}

		closed = NetManager_doWriteCallback(netDescriptors[index]);
		if (closed)
			goto closed;
	}
#endif
	if (networkEvents.lNetworkEvents & FD_CLOSE) {
		// The close event is handled last, in case there was still
		// data in the buffers which could be processed.
		NetDescriptor_close(netDescriptors[index]);
		goto closed;
	}

closed:  /* No special actions required for now. */

	return 0;
}

// This function may be called again from inside a callback function
// triggered by this function. BUG: This may result in callbacks being
// called multiple times.
// This function should however not be called from multiple threads at once.
int
NetManager_process(uint32 *timeoutMs) {
	DWORD timeoutTemp;
	DWORD waitResult;
	DWORD startEvent;

	timeoutTemp = (DWORD) *timeoutMs;

	// WSAWaitForMultipleEvents only reports events for one socket at a
	// time. In order to have each socket checked once, we call it
	// again after it has reported an event, but passing only the
	// events not yet processed. The second time, the timeout will be set
	// to 0, so it won't wait.
	startEvent = 0;
	while (startEvent < numActiveEvents) {
		waitResult = WSAWaitForMultipleEvents(numActiveEvents - startEvent,
				&events[startEvent], FALSE, timeoutTemp, FALSE);
		
		if (waitResult == WSA_WAIT_IO_COMPLETION)
			continue;

		if (waitResult == WSA_WAIT_TIMEOUT) {
			// No events waiting.
			*timeoutMs = 0;
			return 0;
		}

		if (waitResult == WSA_WAIT_FAILED) {
			errno = getWinsockErrno();
			*timeoutMs = timeoutTemp;
			return -1;
		}
		
		{
			DWORD eventIndex = waitResult - WSA_WAIT_EVENT_0;
			if (NetManager_processEvent((size_t) eventIndex) == -1) {
				// errno is set
				*timeoutMs = timeoutTemp;
				return -1;
			}
		
			// Check the rest of the sockets, but don't wait anymore.
			startEvent += eventIndex + 1;
			timeoutTemp = 0;
		}
	}

	*timeoutMs = timeoutTemp;
	return 0;
}