tests: update sav for nitunit
[nit.git] / lib / libevent.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Low-level wrapper around the libevent library to manage events on file descriptors
19 #
20 # For mor information, refer to the libevent documentation at
21 # http://monkey.org/~provos/libevent/doxygen-2.0.1/
22 module libevent is pkgconfig("libevent")
23
24 in "C header" `{
25 #include <event2/listener.h>
26 #include <event2/bufferevent.h>
27 #include <event2/buffer.h>
28 `}
29
30 in "C" `{
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <fcntl.h>
34 #include <errno.h>
35 #include <string.h>
36
37 #include <sys/socket.h>
38 #include <arpa/inet.h>
39 #include <netinet/in.h>
40 #include <netinet/ip.h>
41
42 // Protect callbacks for compatibility with light FFI
43 #ifdef Connection_decr_ref
44 // Callback forwarded to 'Connection.write_callback'
45 static void c_write_cb(struct bufferevent *bev, Connection ctx) {
46 Connection_write_callback(ctx);
47 }
48
49 // Callback forwarded to 'Connection.read_callback_native'
50 static void c_read_cb(struct bufferevent *bev, Connection ctx)
51 {
52 Connection_read_callback_native(ctx, bev);
53 }
54
55 // Callback forwarded to 'Connection.event_callback'
56 static void c_event_cb(struct bufferevent *bev, short events, Connection ctx)
57 {
58 int release = Connection_event_callback(ctx, events);
59 if (release) Connection_decr_ref(ctx);
60 }
61
62 // Callback forwarded to 'ConnectionFactory.accept_connection'
63 static void accept_connection_cb(struct evconnlistener *listener, evutil_socket_t fd,
64 struct sockaddr *addrin, int socklen, ConnectionFactory ctx)
65 {
66 ConnectionFactory_accept_connection(ctx, listener, fd, addrin, socklen);
67 }
68 #endif
69
70 `}
71
72 # Structure to hold information and state for a Libevent dispatch loop.
73 #
74 # The event_base lies at the center of Libevent; every application will
75 # have one. It keeps track of all pending and active events, and
76 # notifies your application of the active ones.
77 extern class NativeEventBase `{ struct event_base * `}
78
79 # Create a new event_base to use with the rest of Libevent
80 new `{ return event_base_new(); `}
81
82 # Has `self` been correctly initialized?
83 fun is_valid: Bool do return not address_is_null
84
85 # Event dispatching loop
86 #
87 # This loop will run the event base until either there are no more added
88 # events, or until something calls `exit_loop`.
89 fun dispatch `{ event_base_dispatch(self); `}
90
91 # Exit the event loop
92 #
93 # TODO support timer
94 fun exit_loop `{ event_base_loopexit(self, NULL); `}
95
96 # Destroy this instance
97 fun destroy `{ event_base_free(self); `}
98 end
99
100 # Spawned to manage a specific connection
101 #
102 # TODO, use polls
103 class Connection
104 super Writer
105
106 # Closing this connection has been requested, but may not yet be `closed`
107 var close_requested = false
108
109 # This connection is closed
110 var closed = false
111
112 # The native libevent linked to `self`
113 var native_buffer_event: NativeBufferEvent
114
115 # Close this connection if possible, otherwise mark it to be closed later
116 redef fun close
117 do
118 if closed then return
119 var success = native_buffer_event.destroy
120 close_requested = true
121 closed = success
122 end
123
124 # Callback method on a write event
125 fun write_callback
126 do
127 if close_requested then close
128 end
129
130 private fun read_callback_native(bev: NativeBufferEvent)
131 do
132 var evbuffer = bev.input_buffer
133 var len = evbuffer.length
134 var buf = new NativeString(len)
135 evbuffer.remove(buf, len)
136 var str = buf.to_s_with_length(len)
137 read_callback str
138 end
139
140 # Callback method when data is available to read
141 fun read_callback(content: String)
142 do
143 if close_requested then close
144 end
145
146 # Callback method on events: EOF, user-defined timeout and unrecoverable errors
147 #
148 # Returns `true` if the native handles to `self` can be released.
149 fun event_callback(events: Int): Bool
150 do
151 if events & bev_event_error != 0 or events & bev_event_eof != 0 then
152 if events & bev_event_error != 0 then print_error "Error from bufferevent"
153 close
154 return true
155 end
156
157 return false
158 end
159
160 # Write a string to the connection
161 redef fun write(str)
162 do
163 if close_requested then return
164 native_buffer_event.write(str.to_cstring, str.bytelen)
165 end
166
167 redef fun write_byte(byte)
168 do
169 if close_requested then return
170 native_buffer_event.write_byte(byte)
171 end
172
173 redef fun write_bytes(bytes)
174 do
175 if close_requested then return
176 native_buffer_event.write(bytes.items, bytes.length)
177 end
178
179 # Write a file to the connection
180 #
181 # If `not path.file_exists`, the method returns.
182 fun write_file(path: String)
183 do
184 if close_requested then return
185
186 var file = new FileReader.open(path)
187 if file.last_error != null then
188 var error = new IOError("Failed to open file at '{path}'")
189 error.cause = file.last_error
190 self.last_error = error
191 file.close
192 return
193 end
194
195 var stat = file.file_stat
196 if stat == null then
197 last_error = new IOError("Failed to stat file at '{path}'")
198 file.close
199 return
200 end
201
202 var err = native_buffer_event.output_buffer.add_file(file.fd, 0, stat.size)
203 if err then
204 last_error = new IOError("Failed to add file at '{path}'")
205 file.close
206 end
207 end
208 end
209
210 # ---
211 # Error code for event callbacks
212
213 # error encountered while reading
214 fun bev_event_reading: Int `{ return BEV_EVENT_READING; `}
215
216 # error encountered while writing
217 fun bev_event_writing: Int `{ return BEV_EVENT_WRITING; `}
218
219 # eof file reached
220 fun bev_event_eof: Int `{ return BEV_EVENT_EOF; `}
221
222 # unrecoverable error encountered
223 fun bev_event_error: Int `{ return BEV_EVENT_ERROR; `}
224
225 # user-specified timeout reached
226 fun bev_event_timeout: Int `{ return BEV_EVENT_TIMEOUT; `}
227
228 # connect operation finished.
229 fun bev_event_connected: Int `{ return BEV_EVENT_CONNECTED; `}
230
231 # ---
232 # Options that can be specified when creating a `NativeBufferEvent`
233
234 # Close the underlying file descriptor/bufferevent/whatever when this bufferevent is freed.
235 fun bev_opt_close_on_free: Int `{ return BEV_OPT_CLOSE_ON_FREE; `}
236
237 # If threading is enabled, protect the operations on this bufferevent with a lock.
238 fun bev_opt_threadsafe: Int `{ return BEV_OPT_THREADSAFE; `}
239
240 # Run callbacks deferred in the event loop.
241 fun bev_opt_defer_callbacks: Int `{ return BEV_OPT_DEFER_CALLBACKS; `}
242
243 # If set, callbacks are executed without locks being held on the bufferevent.
244 fun bev_opt_unlock_callbacks: Int `{ return BEV_OPT_UNLOCK_CALLBACKS; `}
245
246 # ---
247 # Options for `NativeBufferEvent::enable`
248
249 # Read operation
250 fun ev_read: Int `{ return EV_READ; `}
251
252 # Write operation
253 fun ev_write: Int `{ return EV_WRITE; `}
254
255 # ---
256
257 # A buffer event structure, strongly associated to a connection, an input buffer and an output_buffer
258 extern class NativeBufferEvent `{ struct bufferevent * `}
259
260 # Socket-based `NativeBufferEvent` that reads and writes data onto a network
261 new socket(base: NativeEventBase, fd, options: Int) `{
262 return bufferevent_socket_new(base, fd, options);
263 `}
264
265 # Enable a bufferevent.
266 fun enable(operation: Int) `{
267 bufferevent_enable(self, operation);
268 `}
269
270 # Set callbacks to `read_callback_native`, `write_callback` and `event_callback` of `conn`
271 fun setcb(conn: Connection) import Connection.read_callback_native,
272 Connection.write_callback, Connection.event_callback, NativeString `{
273 Connection_incr_ref(conn);
274 bufferevent_setcb(self,
275 (bufferevent_data_cb)c_read_cb,
276 (bufferevent_data_cb)c_write_cb,
277 (bufferevent_event_cb)c_event_cb, conn);
278 `}
279
280 # Write `length` bytes of `line`
281 fun write(line: NativeString, length: Int): Int `{
282 return bufferevent_write(self, line, length);
283 `}
284
285 # Write the byte `value`
286 fun write_byte(value: Byte): Int `{
287 unsigned char byt = (unsigned char)value;
288 return bufferevent_write(self, &byt, 1);
289 `}
290
291 # Check if we have anything left in our buffers. If so, we set our connection to be closed
292 # on a callback. Otherwise we close it and free it right away.
293 fun destroy: Bool `{
294 struct evbuffer* out = bufferevent_get_output(self);
295 struct evbuffer* in = bufferevent_get_input(self);
296 if(evbuffer_get_length(in) > 0 || evbuffer_get_length(out) > 0) {
297 return 0;
298 } else {
299 bufferevent_free(self);
300 return 1;
301 }
302 `}
303
304 # The output buffer associated to `self`
305 fun output_buffer: OutputNativeEvBuffer `{ return bufferevent_get_output(self); `}
306
307 # The input buffer associated to `self`
308 fun input_buffer: InputNativeEvBuffer `{ return bufferevent_get_input(self); `}
309
310 # Read data from this buffer
311 fun read_buffer(buf: NativeEvBuffer): Int `{ return bufferevent_read_buffer(self, buf); `}
312
313 # Write data to this buffer
314 fun write_buffer(buf: NativeEvBuffer): Int `{ return bufferevent_write_buffer(self, buf); `}
315 end
316
317 # A single buffer
318 extern class NativeEvBuffer `{ struct evbuffer * `}
319 # Length of data in this buffer
320 fun length: Int `{ return evbuffer_get_length(self); `}
321
322 # Read data from an evbuffer and drain the bytes read
323 fun remove(buffer: NativeString, len: Int) `{
324 evbuffer_remove(self, buffer, len);
325 `}
326 end
327
328 # An input buffer
329 extern class InputNativeEvBuffer
330 super NativeEvBuffer
331
332 # Empty/clear `length` data from buffer
333 fun drain(length: Int) `{ evbuffer_drain(self, length); `}
334 end
335
336 # An output buffer
337 extern class OutputNativeEvBuffer
338 super NativeEvBuffer
339
340 # Add file to buffer
341 fun add_file(fd, offset, length: Int): Bool `{
342 return evbuffer_add_file(self, fd, offset, length);
343 `}
344 end
345
346 # A listener acting on an interface and port, spawns `Connection` on new connections
347 extern class ConnectionListener `{ struct evconnlistener * `}
348
349 private new bind_to(base: NativeEventBase, address: NativeString, port: Int, factory: ConnectionFactory)
350 import ConnectionFactory.accept_connection, error_callback `{
351
352 struct sockaddr_in sin;
353 struct evconnlistener *listener;
354 ConnectionFactory_incr_ref(factory);
355
356 struct hostent *hostent = gethostbyname(address);
357
358 if (!hostent) {
359 return NULL;
360 }
361
362 memset(&sin, 0, sizeof(sin));
363 sin.sin_family = hostent->h_addrtype;
364 sin.sin_port = htons(port);
365 memcpy( &(sin.sin_addr.s_addr), (const void*)hostent->h_addr, hostent->h_length );
366
367 listener = evconnlistener_new_bind(base,
368 (evconnlistener_cb)accept_connection_cb, factory,
369 LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
370 (struct sockaddr*)&sin, sizeof(sin));
371
372 if (listener != NULL) {
373 evconnlistener_set_error_cb(listener, (evconnlistener_errorcb)ConnectionListener_error_callback);
374 }
375
376 return listener;
377 `}
378
379 # Get the `NativeEventBase` associated to `self`
380 fun base: NativeEventBase `{ return evconnlistener_get_base(self); `}
381
382 # Callback method on listening error
383 fun error_callback do
384 var cstr = socket_error
385 sys.stderr.write "libevent error: '{cstr}'"
386 end
387
388 # Error with sockets
389 fun socket_error: NativeString `{
390 // TODO move to Nit and maybe NativeEventBase
391 int err = EVUTIL_SOCKET_ERROR();
392 return evutil_socket_error_to_string(err);
393 `}
394 end
395
396 # Factory to listen on sockets and create new `Connection`
397 class ConnectionFactory
398 # The `NativeEventBase` for the dispatch loop of this factory
399 var event_base: NativeEventBase
400
401 # Accept a connection on `listener`
402 #
403 # By default, it creates a new NativeBufferEvent and calls `spawn_connection`.
404 fun accept_connection(listener: ConnectionListener, fd: Int, addrin: Pointer, socklen: Int)
405 do
406 var base = listener.base
407 var bev = new NativeBufferEvent.socket(base, fd, bev_opt_close_on_free)
408
409 # Human representation of remote client address
410 var addr_len = 46 # Longest possible IPv6 address + null byte
411 var addr_buf = new NativeString(addr_len)
412 addr_buf = addrin_to_address(addrin, addr_buf, addr_len)
413 var addr = if addr_buf.address_is_null then
414 "Unknown address"
415 else addr_buf.to_s
416
417 var conn = spawn_connection(bev, addr)
418 bev.enable ev_read|ev_write
419 bev.setcb conn
420 end
421
422 # Create a new `Connection` object for `buffer_event`
423 fun spawn_connection(buffer_event: NativeBufferEvent, address: String): Connection
424 do
425 return new Connection(buffer_event)
426 end
427
428 # Listen on `address`:`port` for new connection, which will callback `spawn_connection`
429 fun bind_to(address: String, port: Int): nullable ConnectionListener
430 do
431 var listener = new ConnectionListener.bind_to(event_base, address.to_cstring, port, self)
432 if listener.address_is_null then
433 sys.stderr.write "libevent warning: Opening {address}:{port} failed\n"
434 end
435 return listener
436 end
437
438 # Put string representation of source `address` into `buf`
439 private fun addrin_to_address(address: Pointer, buf: NativeString, buf_len: Int): NativeString `{
440 struct sockaddr *addrin = (struct sockaddr*)address;
441
442 if (addrin->sa_family == AF_INET) {
443 struct in_addr *src = &((struct sockaddr_in*)addrin)->sin_addr;
444 return (char *)inet_ntop(addrin->sa_family, src, buf, buf_len);
445 }
446 else if (addrin->sa_family == AF_INET6) {
447 struct in6_addr *src = &((struct sockaddr_in6*)addrin)->sin6_addr;
448 return (char *)inet_ntop(addrin->sa_family, src, buf, buf_len);
449 }
450 return NULL;
451 `}
452 end