1/*
2 * Copyright 2007-2012 Niels Provos and Nick Mathewson
3 * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
4 * Copyright 2003 Michael A. Davis <mike@datanerds.net>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <winsock2.h>
30#include <windows.h>
31#include <sys/types.h>
32#include <sys/queue.h>
33#include <limits.h>
34#include <signal.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <errno.h>
39
40#include "event2/util.h"
41#include "event2/event-config.h"
42#include "util-internal.h"
43#include "log-internal.h"
44#include "event2/event.h"
45#include "event-internal.h"
46#include "evmap-internal.h"
47#include "event2/thread.h"
48#include "evthread-internal.h"
49
50#define XFREE(ptr) do { if (ptr) mm_free(ptr); } while (0)
51
52extern struct event_list timequeue;
53extern struct event_list addqueue;
54
55struct win_fd_set {
56	u_int fd_count;
57	SOCKET fd_array[1];
58};
59
60/* MSDN says this is required to handle SIGFPE */
61volatile double SIGFPE_REQ = 0.0f;
62
63struct idx_info {
64	int read_pos_plus1;
65	int write_pos_plus1;
66};
67
68struct win32op {
69	unsigned num_fds_in_fd_sets;
70	int resize_out_sets;
71	struct win_fd_set *readset_in;
72	struct win_fd_set *writeset_in;
73	struct win_fd_set *readset_out;
74	struct win_fd_set *writeset_out;
75	struct win_fd_set *exset_out;
76	unsigned signals_are_broken : 1;
77};
78
79static void *win32_init(struct event_base *);
80static int win32_add(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
81static int win32_del(struct event_base *, evutil_socket_t, short old, short events, void *_idx);
82static int win32_dispatch(struct event_base *base, struct timeval *);
83static void win32_dealloc(struct event_base *);
84
85struct eventop win32ops = {
86	"win32",
87	win32_init,
88	win32_add,
89	win32_del,
90	win32_dispatch,
91	win32_dealloc,
92	0, /* doesn't need reinit */
93	0, /* No features supported. */
94	sizeof(struct idx_info),
95};
96
97#define FD_SET_ALLOC_SIZE(n) ((sizeof(struct win_fd_set) + ((n)-1)*sizeof(SOCKET)))
98
99static int
100grow_fd_sets(struct win32op *op, unsigned new_num_fds)
101{
102	size_t size;
103
104	EVUTIL_ASSERT(new_num_fds >= op->readset_in->fd_count &&
105	       new_num_fds >= op->writeset_in->fd_count);
106	EVUTIL_ASSERT(new_num_fds >= 1);
107
108	size = FD_SET_ALLOC_SIZE(new_num_fds);
109	if (!(op->readset_in = mm_realloc(op->readset_in, size)))
110		return (-1);
111	if (!(op->writeset_in = mm_realloc(op->writeset_in, size)))
112		return (-1);
113	op->resize_out_sets = 1;
114	op->num_fds_in_fd_sets = new_num_fds;
115	return (0);
116}
117
118static int
119do_fd_set(struct win32op *op, struct idx_info *ent, evutil_socket_t s, int read)
120{
121	struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
122	if (read) {
123		if (ent->read_pos_plus1 > 0)
124			return (0);
125	} else {
126		if (ent->write_pos_plus1 > 0)
127			return (0);
128	}
129	if (set->fd_count == op->num_fds_in_fd_sets) {
130		if (grow_fd_sets(op, op->num_fds_in_fd_sets*2))
131			return (-1);
132		/* set pointer will have changed and needs reiniting! */
133		set = read ? op->readset_in : op->writeset_in;
134	}
135	set->fd_array[set->fd_count] = s;
136	if (read)
137		ent->read_pos_plus1 = set->fd_count+1;
138	else
139		ent->write_pos_plus1 = set->fd_count+1;
140	return (set->fd_count++);
141}
142
143static int
144do_fd_clear(struct event_base *base,
145			struct win32op *op, struct idx_info *ent, int read)
146{
147	int i;
148	struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
149	if (read) {
150		i = ent->read_pos_plus1 - 1;
151		ent->read_pos_plus1 = 0;
152	} else {
153		i = ent->write_pos_plus1 - 1;
154		ent->write_pos_plus1 = 0;
155	}
156	if (i < 0)
157		return (0);
158	if (--set->fd_count != (unsigned)i) {
159		struct idx_info *ent2;
160		SOCKET s2;
161		s2 = set->fd_array[i] = set->fd_array[set->fd_count];
162
163		ent2 = evmap_io_get_fdinfo(&base->io, s2);
164
165		if (!ent2) /* This indicates a bug. */
166			return (0);
167		if (read)
168			ent2->read_pos_plus1 = i+1;
169		else
170			ent2->write_pos_plus1 = i+1;
171	}
172	return (0);
173}
174
175#define NEVENT 32
176void *
177win32_init(struct event_base *_base)
178{
179	struct win32op *winop;
180	size_t size;
181	if (!(winop = mm_calloc(1, sizeof(struct win32op))))
182		return NULL;
183	winop->num_fds_in_fd_sets = NEVENT;
184	size = FD_SET_ALLOC_SIZE(NEVENT);
185	if (!(winop->readset_in = mm_malloc(size)))
186		goto err;
187	if (!(winop->writeset_in = mm_malloc(size)))
188		goto err;
189	if (!(winop->readset_out = mm_malloc(size)))
190		goto err;
191	if (!(winop->writeset_out = mm_malloc(size)))
192		goto err;
193	if (!(winop->exset_out = mm_malloc(size)))
194		goto err;
195	winop->readset_in->fd_count = winop->writeset_in->fd_count = 0;
196	winop->readset_out->fd_count = winop->writeset_out->fd_count
197		= winop->exset_out->fd_count = 0;
198
199	if (evsig_init(_base) < 0)
200		winop->signals_are_broken = 1;
201
202	return (winop);
203 err:
204	XFREE(winop->readset_in);
205	XFREE(winop->writeset_in);
206	XFREE(winop->readset_out);
207	XFREE(winop->writeset_out);
208	XFREE(winop->exset_out);
209	XFREE(winop);
210	return (NULL);
211}
212
213int
214win32_add(struct event_base *base, evutil_socket_t fd,
215			 short old, short events, void *_idx)
216{
217	struct win32op *win32op = base->evbase;
218	struct idx_info *idx = _idx;
219
220	if ((events & EV_SIGNAL) && win32op->signals_are_broken)
221		return (-1);
222
223	if (!(events & (EV_READ|EV_WRITE)))
224		return (0);
225
226	event_debug(("%s: adding event for %d", __func__, (int)fd));
227	if (events & EV_READ) {
228		if (do_fd_set(win32op, idx, fd, 1)<0)
229			return (-1);
230	}
231	if (events & EV_WRITE) {
232		if (do_fd_set(win32op, idx, fd, 0)<0)
233			return (-1);
234	}
235	return (0);
236}
237
238int
239win32_del(struct event_base *base, evutil_socket_t fd, short old, short events,
240		  void *_idx)
241{
242	struct win32op *win32op = base->evbase;
243	struct idx_info *idx = _idx;
244
245	event_debug(("%s: Removing event for %d", __func__, fd));
246	if (events & EV_READ)
247		do_fd_clear(base, win32op, idx, 1);
248	if (events & EV_WRITE)
249		do_fd_clear(base, win32op, idx, 0);
250
251	return 0;
252}
253
254static void
255fd_set_copy(struct win_fd_set *out, const struct win_fd_set *in)
256{
257	out->fd_count = in->fd_count;
258	memcpy(out->fd_array, in->fd_array, in->fd_count * (sizeof(SOCKET)));
259}
260
261/*
262  static void dump_fd_set(struct win_fd_set *s)
263  {
264  unsigned int i;
265  printf("[ ");
266  for(i=0;i<s->fd_count;++i)
267  printf("%d ",(int)s->fd_array[i]);
268  printf("]\n");
269  }
270*/
271
272int
273win32_dispatch(struct event_base *base, struct timeval *tv)
274{
275	struct win32op *win32op = base->evbase;
276	int res = 0;
277	unsigned j, i;
278	int fd_count;
279	SOCKET s;
280
281	if (win32op->resize_out_sets) {
282		size_t size = FD_SET_ALLOC_SIZE(win32op->num_fds_in_fd_sets);
283		if (!(win32op->readset_out = mm_realloc(win32op->readset_out, size)))
284			return (-1);
285		if (!(win32op->exset_out = mm_realloc(win32op->exset_out, size)))
286			return (-1);
287		if (!(win32op->writeset_out = mm_realloc(win32op->writeset_out, size)))
288			return (-1);
289		win32op->resize_out_sets = 0;
290	}
291
292	fd_set_copy(win32op->readset_out, win32op->readset_in);
293	fd_set_copy(win32op->exset_out, win32op->writeset_in);
294	fd_set_copy(win32op->writeset_out, win32op->writeset_in);
295
296	fd_count =
297	    (win32op->readset_out->fd_count > win32op->writeset_out->fd_count) ?
298	    win32op->readset_out->fd_count : win32op->writeset_out->fd_count;
299
300	if (!fd_count) {
301		long msec = evutil_tv_to_msec(tv);
302		/* Sleep's DWORD argument is unsigned long */
303		if (msec < 0)
304			msec = LONG_MAX;
305		/* Windows doesn't like you to call select() with no sockets */
306		Sleep(msec);
307		return (0);
308	}
309
310	EVBASE_RELEASE_LOCK(base, th_base_lock);
311
312	res = select(fd_count,
313		     (struct fd_set*)win32op->readset_out,
314		     (struct fd_set*)win32op->writeset_out,
315		     (struct fd_set*)win32op->exset_out, tv);
316
317	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
318
319	event_debug(("%s: select returned %d", __func__, res));
320
321	if (res <= 0) {
322		return res;
323	}
324
325	if (win32op->readset_out->fd_count) {
326		i = rand() % win32op->readset_out->fd_count;
327		for (j=0; j<win32op->readset_out->fd_count; ++j) {
328			if (++i >= win32op->readset_out->fd_count)
329				i = 0;
330			s = win32op->readset_out->fd_array[i];
331			evmap_io_active(base, s, EV_READ);
332		}
333	}
334	if (win32op->exset_out->fd_count) {
335		i = rand() % win32op->exset_out->fd_count;
336		for (j=0; j<win32op->exset_out->fd_count; ++j) {
337			if (++i >= win32op->exset_out->fd_count)
338				i = 0;
339			s = win32op->exset_out->fd_array[i];
340			evmap_io_active(base, s, EV_WRITE);
341		}
342	}
343	if (win32op->writeset_out->fd_count) {
344		SOCKET s;
345		i = rand() % win32op->writeset_out->fd_count;
346		for (j=0; j<win32op->writeset_out->fd_count; ++j) {
347			if (++i >= win32op->writeset_out->fd_count)
348				i = 0;
349			s = win32op->writeset_out->fd_array[i];
350			evmap_io_active(base, s, EV_WRITE);
351		}
352	}
353	return (0);
354}
355
356void
357win32_dealloc(struct event_base *_base)
358{
359	struct win32op *win32op = _base->evbase;
360
361	evsig_dealloc(_base);
362	if (win32op->readset_in)
363		mm_free(win32op->readset_in);
364	if (win32op->writeset_in)
365		mm_free(win32op->writeset_in);
366	if (win32op->readset_out)
367		mm_free(win32op->readset_out);
368	if (win32op->writeset_out)
369		mm_free(win32op->writeset_out);
370	if (win32op->exset_out)
371		mm_free(win32op->exset_out);
372	/* XXXXX free the tree. */
373
374	memset(win32op, 0, sizeof(win32op));
375	mm_free(win32op);
376}
377