winsock_event.h revision 269257
1/*
2 * util/winsock_event.h - unbound event handling for winsock on windows
3 *
4 * Copyright (c) 2008, NLnet Labs. All rights reserved.
5 *
6 * This software is open source.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
14 *
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
18 *
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
36/**
37 * \file
38 *
39 * This file contains interface functions with the WinSock2 API on Windows.
40 * It uses the winsock WSAWaitForMultipleEvents interface on a number of
41 * sockets.
42 *
43 * Note that windows can only wait for max 64 events at one time.
44 *
45 * Also, file descriptors cannot be waited for.
46 *
47 * Named pipes are not easily available (and are not usable in select() ).
48 * For interprocess communication, it is possible to wait for a hEvent to
49 * be signaled by another thread.
50 *
51 * When a socket becomes readable, then it will not be flagged as
52 * readable again until you have gotten WOULDBLOCK from a recv routine.
53 * That means the event handler must store the readability (edge notify)
54 * and process the incoming data until it blocks.
55 * The function performing recv then has to inform the event handler that
56 * the socket has blocked, and the event handler can mark it as such.
57 * Thus, this file transforms the edge notify from windows to a level notify
58 * that is compatible with UNIX.
59 * The WSAEventSelect page says that it does do level notify, as long
60 * as you call a recv/write/accept at least once when it is signalled.
61 * This last bit is not true, even though documented in server2008 api docs
62 * from microsoft, it does not happen at all. Instead you have to test for
63 * WSAEWOULDBLOCK on a tcp stream, and only then retest the socket.
64 * And before that remember the previous result as still valid.
65 *
66 * To stay 'fair', instead of emptying a socket completely, the event handler
67 * can test the other (marked as blocking) sockets for new events.
68 *
69 * Additionally, TCP accept sockets get special event support.
70 *
71 * Socket numbers are not starting small, they can be any number (say 33060).
72 * Therefore, bitmaps are not used, but arrays.
73 *
74 * on winsock, you must use recv() and send() for TCP reads and writes,
75 * not read() and write(), those work only on files.
76 *
77 * Also fseek and fseeko do not work if a FILE is not fopen-ed in binary mode.
78 *
79 * When under a high load windows gives out lots of errors, from recvfrom
80 * on udp sockets for example (WSAECONNRESET). Even though the udp socket
81 * has no connection per se.
82 */
83
84#ifndef UTIL_WINSOCK_EVENT_H
85#define UTIL_WINSOCK_EVENT_H
86
87#ifdef USE_WINSOCK
88
89#ifndef HAVE_EVENT_BASE_FREE
90#define HAVE_EVENT_BASE_FREE
91#endif
92
93/** event timeout */
94#define EV_TIMEOUT      0x01
95/** event fd readable */
96#define EV_READ         0x02
97/** event fd writable */
98#define EV_WRITE        0x04
99/** event signal */
100#define EV_SIGNAL       0x08
101/** event must persist */
102#define EV_PERSIST      0x10
103
104/* needs our redblack tree */
105#include "rbtree.h"
106
107/** max number of signals to support */
108#define MAX_SIG 32
109
110/** The number of items that the winsock event handler can service.
111 * Windows cannot handle more anyway */
112#define WSK_MAX_ITEMS 64
113
114/**
115 * event base for winsock event handler
116 */
117struct event_base
118{
119	/** sorted by timeout (absolute), ptr */
120	rbtree_t* times;
121	/** array (first part in use) of handles to work on */
122	struct event** items;
123	/** number of items in use in array */
124	int max;
125	/** capacity of array, size of array in items */
126	int cap;
127	/** array of 0 - maxsig of ptr to event for it */
128        struct event** signals;
129	/** if we need to exit */
130	int need_to_exit;
131	/** where to store time in seconds */
132	time_t* time_secs;
133	/** where to store time in microseconds */
134	struct timeval* time_tv;
135	/**
136	 * TCP streams have sticky events to them, these are not
137	 * reported by the windows event system anymore, we have to
138	 * keep reporting those events as present until wouldblock() is
139	 * signalled by the handler back to use.
140	 */
141	int tcp_stickies;
142	/**
143	 * should next cycle process reinvigorated stickies,
144	 * these are stickies that have been stored, but due to a new
145	 * event_add a sudden interest in the event has incepted.
146	 */
147	int tcp_reinvigorated;
148	/** The list of events that is currently being processed. */
149	WSAEVENT waitfor[WSK_MAX_ITEMS];
150};
151
152/**
153 * Event structure. Has some of the event elements.
154 */
155struct event {
156        /** node in timeout rbtree */
157        rbnode_t node;
158        /** is event already added */
159        int added;
160
161        /** event base it belongs to */
162        struct event_base *ev_base;
163        /** fd to poll or -1 for timeouts. signal number for sigs. */
164        int ev_fd;
165        /** what events this event is interested in, see EV_.. above. */
166        short ev_events;
167        /** timeout value */
168        struct timeval ev_timeout;
169
170        /** callback to call: fd, eventbits, userarg */
171        void (*ev_callback)(int, short, void *);
172        /** callback user arg */
173        void *ev_arg;
174
175	/* ----- nonpublic part, for winsock_event only ----- */
176	/** index of this event in the items array (if added) */
177	int idx;
178	/** the event handle to wait for new events to become ready */
179	WSAEVENT hEvent;
180	/** true if this filedes is a TCP socket and needs special attention */
181	int is_tcp;
182	/** remembered EV_ values */
183	short old_events;
184	/** should remembered EV_ values be used for TCP streams.
185	 * Reset after WOULDBLOCK is signaled using the function. */
186	int stick_events;
187
188	/** true if this event is a signaling WSAEvent by the user.
189	 * User created and user closed WSAEvent. Only signaled/unsigneled,
190	 * no read/write/distinctions needed. */
191	int is_signal;
192	/** used during callbacks to see which events were just checked */
193	int just_checked;
194};
195
196/** create event base */
197void *event_init(time_t* time_secs, struct timeval* time_tv);
198/** get version */
199const char *event_get_version(void);
200/** get polling method (select,epoll) */
201const char *event_get_method(void);
202/** run select in a loop */
203int event_base_dispatch(struct event_base *);
204/** exit that loop */
205int event_base_loopexit(struct event_base *, struct timeval *);
206/** free event base. Free events yourself */
207void event_base_free(struct event_base *);
208/** set content of event */
209void event_set(struct event *, int, short, void (*)(int, short, void *), void *);
210
211/** add event to a base. You *must* call this for every event. */
212int event_base_set(struct event_base *, struct event *);
213/** add event to make it active. You may not change it with event_set anymore */
214int event_add(struct event *, struct timeval *);
215/** remove event. You may change it again */
216int event_del(struct event *);
217
218#define evtimer_add(ev, tv)             event_add(ev, tv)
219#define evtimer_del(ev)                 event_del(ev)
220
221/* uses different implementation. Cannot mix fd/timeouts and signals inside
222 * the same struct event. create several event structs for that.  */
223/** install signal handler */
224int signal_add(struct event *, struct timeval *);
225/** set signal event contents */
226#define signal_set(ev, x, cb, arg)      \
227        event_set(ev, x, EV_SIGNAL|EV_PERSIST, cb, arg)
228/** remove signal handler */
229int signal_del(struct event *);
230
231/** compare events in tree, based on timevalue, ptr for uniqueness */
232int mini_ev_cmp(const void* a, const void* b);
233
234/**
235 * Routine for windows only, where the handling layer can signal that
236 * a TCP stream encountered WSAEWOULDBLOCK for a stream and thus needs
237 * retesting the event.
238 * Pass if EV_READ or EV_WRITE gave wouldblock.
239 */
240void winsock_tcp_wouldblock(struct event* ev, int eventbit);
241
242/**
243 * Routine for windows only. where you pass a signal WSAEvent that
244 * you wait for. When the event is signaled, the callback gets called.
245 * The callback has to WSAResetEvent to disable the signal.
246 * @param base: the event base.
247 * @param ev: the event structure for data storage
248 * 	can be passed uninitialised.
249 * @param wsaevent: the WSAEvent that gets signaled.
250 * @param cb: callback routine.
251 * @param arg: user argument to callback routine.
252 * @return false on error.
253 */
254int winsock_register_wsaevent(struct event_base* base, struct event* ev,
255	WSAEVENT wsaevent, void (*cb)(int, short, void*), void* arg);
256
257/**
258 * Unregister a wsaevent. User has to close the WSAEVENT itself.
259 * @param ev: event data storage.
260 */
261void winsock_unregister_wsaevent(struct event* ev);
262
263#endif /* USE_WINSOCK */
264#endif /* UTIL_WINSOCK_EVENT_H */
265