5ad186fceeb33cba517e89060514f9ad855308a3
[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 <sys/stat.h>
26 #include <sys/types.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <sys/socket.h>
30
31 #include <event2/listener.h>
32 #include <event2/bufferevent.h>
33 #include <event2/buffer.h>
34 `}
35
36 in "C" `{
37 // Callback forwarded to 'Connection.write_callback'
38 static void c_write_cb(struct bufferevent *bev, Connection ctx) {
39 Connection_write_callback(ctx);
40 }
41
42 // Callback forwarded to 'Connection.read_callback_native'
43 static void c_read_cb(struct bufferevent *bev, Connection ctx)
44 {
45 Connection_read_callback_native(ctx, bev);
46 }
47
48 // Callback forwarded to 'Connection.event_callback'
49 static void c_event_cb(struct bufferevent *bev, short events, Connection ctx)
50 {
51 Connection_event_callback(ctx, events);
52
53 // TODO move to Nit code
54 if (events & BEV_EVENT_ERROR)
55 perror("Error from bufferevent");
56 if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
57 bufferevent_free(bev);
58 Connection_decr_ref(ctx);
59 }
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 *address, int socklen, ConnectionFactory ctx)
65 {
66 ConnectionFactory_accept_connection(ctx, listener, fd, address, socklen);
67 }
68 `}
69
70 # Structure to hold information and state for a Libevent dispatch loop.
71 #
72 # The event_base lies at the center of Libevent; every application will
73 # have one. It keeps track of all pending and active events, and
74 # notifies your application of the active ones.
75 extern class NativeEventBase `{ struct event_base * `}
76
77 # Create a new event_base to use with the rest of Libevent
78 new `{ return event_base_new(); `}
79
80 # Has `self` been correctly initialized?
81 fun is_valid: Bool do return not address_is_null
82
83 # Event dispatching loop
84 #
85 # This loop will run the event base until either there are no more added
86 # events, or until something calls `exit_loop`.
87 fun dispatch `{ event_base_dispatch(self); `}
88
89 # Exit the event loop
90 #
91 # TODO support timer
92 fun exit_loop `{ event_base_loopexit(self, NULL); `}
93
94 # Destroy this instance
95 fun destroy `{ event_base_free(self); `}
96 end
97
98 # Spawned to manage a specific connection
99 #
100 # TODO, use polls
101 class Connection
102 super Writer
103
104 # Closing this connection has been requested, but may not yet be `closed`
105 var close_requested = false
106
107 # This connection is closed
108 var closed = false
109
110 # The native libevent linked to `self`
111 var native_buffer_event: NativeBufferEvent
112
113 # Close this connection if possible, otherwise mark it to be closed later
114 redef fun close
115 do
116 if closed then return
117 var success = native_buffer_event.destroy
118 close_requested = true
119 closed = success
120 end
121
122 # Callback method on a write event
123 fun write_callback
124 do
125 if close_requested then close
126 end
127
128 private fun read_callback_native(bev: NativeBufferEvent)
129 do
130 var evbuffer = bev.input_buffer
131 var len = evbuffer.length
132 var buf = new NativeString(len)
133 evbuffer.remove(buf, len)
134 var str = buf.to_s_with_length(len)
135 read_callback str
136 end
137
138 # Callback method when data is available to read
139 fun read_callback(content: String)
140 do
141 if close_requested then close
142 end
143
144 # Callback method on events
145 fun event_callback(events: Int) do end
146
147 # Write a string to the connection
148 redef fun write(str)
149 do
150 if close_requested then return
151 native_buffer_event.write(str.to_cstring, str.bytelen)
152 end
153
154 redef fun write_byte(byte)
155 do
156 if close_requested then return
157 native_buffer_event.write_byte(byte)
158 end
159
160 redef fun write_bytes(bytes)
161 do
162 if close_requested then return
163 native_buffer_event.write(bytes.items, bytes.length)
164 end
165
166 # Write a file to the connection
167 #
168 # If `not path.file_exists`, the method returns.
169 fun write_file(path: String)
170 do
171 if close_requested then return
172
173 var file = new FileReader.open(path)
174 if file.last_error != null then
175 var error = new IOError("Failed to open file at '{path}'")
176 error.cause = file.last_error
177 self.last_error = error
178 file.close
179 return
180 end
181
182 var stat = file.file_stat
183 if stat == null then
184 last_error = new IOError("Failed to stat file at '{path}'")
185 file.close
186 return
187 end
188
189 var err = native_buffer_event.output_buffer.add_file(file.fd, 0, stat.size)
190 if err then
191 last_error = new IOError("Failed to add file at '{path}'")
192 file.close
193 end
194 end
195 end
196
197 # ---
198 # Error code for event callbacks
199
200 # error encountered while reading
201 fun bev_event_reading: Int `{ return BEV_EVENT_READING; `}
202
203 # error encountered while writing
204 fun bev_event_writing: Int `{ return BEV_EVENT_WRITING; `}
205
206 # eof file reached
207 fun bev_event_eof: Int `{ return BEV_EVENT_EOF; `}
208
209 # unrecoverable error encountered
210 fun bev_event_error: Int `{ return BEV_EVENT_ERROR; `}
211
212 # user-specified timeout reached
213 fun bev_event_timeout: Int `{ return BEV_EVENT_TIMEOUT; `}
214
215 # connect operation finished.
216 fun bev_event_connected: Int `{ return BEV_EVENT_CONNECTED; `}
217
218 # ---
219 # Options that can be specified when creating a `NativeBufferEvent`
220
221 # Close the underlying file descriptor/bufferevent/whatever when this bufferevent is freed.
222 fun bev_opt_close_on_free: Int `{ return BEV_OPT_CLOSE_ON_FREE; `}
223
224 # If threading is enabled, protect the operations on this bufferevent with a lock.
225 fun bev_opt_threadsafe: Int `{ return BEV_OPT_THREADSAFE; `}
226
227 # Run callbacks deferred in the event loop.
228 fun bev_opt_defer_callbacks: Int `{ return BEV_OPT_DEFER_CALLBACKS; `}
229
230 # If set, callbacks are executed without locks being held on the bufferevent.
231 fun bev_opt_unlock_callbacks: Int `{ return BEV_OPT_UNLOCK_CALLBACKS; `}
232
233 # ---
234 # Options for `NativeBufferEvent::enable`
235
236 # Read operation
237 fun ev_read: Int `{ return EV_READ; `}
238
239 # Write operation
240 fun ev_write: Int `{ return EV_WRITE; `}
241
242 # ---
243
244 # A buffer event structure, strongly associated to a connection, an input buffer and an output_buffer
245 extern class NativeBufferEvent `{ struct bufferevent * `}
246
247 # Socket-based `NativeBufferEvent` that reads and writes data onto a network
248 new socket(base: NativeEventBase, fd, options: Int) `{
249 return bufferevent_socket_new(base, fd, options);
250 `}
251
252 # Enable a bufferevent.
253 fun enable(operation: Int) `{
254 bufferevent_enable(self, operation);
255 `}
256
257 # Set callbacks to `read_callback_native`, `write_callback` and `event_callback` of `conn`
258 fun setcb(conn: Connection) import Connection.read_callback_native,
259 Connection.write_callback, Connection.event_callback, NativeString `{
260 Connection_incr_ref(conn);
261 bufferevent_setcb(self,
262 (bufferevent_data_cb)c_read_cb,
263 (bufferevent_data_cb)c_write_cb,
264 (bufferevent_event_cb)c_event_cb, conn);
265 `}
266
267 # Write `length` bytes of `line`
268 fun write(line: NativeString, length: Int): Int `{
269 return bufferevent_write(self, line, length);
270 `}
271
272 # Write the byte `value`
273 fun write_byte(value: Byte): Int `{
274 unsigned char byt = (unsigned char)value;
275 return bufferevent_write(self, &byt, 1);
276 `}
277
278 # Check if we have anything left in our buffers. If so, we set our connection to be closed
279 # on a callback. Otherwise we close it and free it right away.
280 fun destroy: Bool `{
281 struct evbuffer* out = bufferevent_get_output(self);
282 struct evbuffer* in = bufferevent_get_input(self);
283 if(evbuffer_get_length(in) > 0 || evbuffer_get_length(out) > 0) {
284 return 0;
285 } else {
286 bufferevent_free(self);
287 return 1;
288 }
289 `}
290
291 # The output buffer associated to `self`
292 fun output_buffer: OutputNativeEvBuffer `{ return bufferevent_get_output(self); `}
293
294 # The input buffer associated to `self`
295 fun input_buffer: InputNativeEvBuffer `{ return bufferevent_get_input(self); `}
296
297 # Read data from this buffer
298 fun read_buffer(buf: NativeEvBuffer): Int `{ return bufferevent_read_buffer(self, buf); `}
299
300 # Write data to this buffer
301 fun write_buffer(buf: NativeEvBuffer): Int `{ return bufferevent_write_buffer(self, buf); `}
302 end
303
304 # A single buffer
305 extern class NativeEvBuffer `{ struct evbuffer * `}
306 # Length of data in this buffer
307 fun length: Int `{ return evbuffer_get_length(self); `}
308
309 # Read data from an evbuffer and drain the bytes read
310 fun remove(buffer: NativeString, len: Int) `{
311 evbuffer_remove(self, buffer, len);
312 `}
313 end
314
315 # An input buffer
316 extern class InputNativeEvBuffer
317 super NativeEvBuffer
318
319 # Empty/clear `length` data from buffer
320 fun drain(length: Int) `{ evbuffer_drain(self, length); `}
321 end
322
323 # An output buffer
324 extern class OutputNativeEvBuffer
325 super NativeEvBuffer
326
327 # Add file to buffer
328 fun add_file(fd, offset, length: Int): Bool `{
329 return evbuffer_add_file(self, fd, offset, length);
330 `}
331 end
332
333 # A listener acting on an interface and port, spawns `Connection` on new connections
334 extern class ConnectionListener `{ struct evconnlistener * `}
335
336 private new bind_to(base: NativeEventBase, address: NativeString, port: Int, factory: ConnectionFactory)
337 import ConnectionFactory.accept_connection, error_callback `{
338
339 struct sockaddr_in sin;
340 struct evconnlistener *listener;
341 ConnectionFactory_incr_ref(factory);
342
343 struct hostent *hostent = gethostbyname(address);
344
345 memset(&sin, 0, sizeof(sin));
346 sin.sin_family = hostent->h_addrtype;
347 sin.sin_port = htons(port);
348 memcpy( &(sin.sin_addr.s_addr), (const void*)hostent->h_addr, hostent->h_length );
349
350 listener = evconnlistener_new_bind(base,
351 (evconnlistener_cb)accept_connection_cb, factory,
352 LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
353 (struct sockaddr*)&sin, sizeof(sin));
354
355 if (listener != NULL) {
356 evconnlistener_set_error_cb(listener, (evconnlistener_errorcb)ConnectionListener_error_callback);
357 }
358
359 return listener;
360 `}
361
362 # Get the `NativeEventBase` associated to `self`
363 fun base: NativeEventBase `{ return evconnlistener_get_base(self); `}
364
365 # Callback method on listening error
366 fun error_callback do
367 var cstr = socket_error
368 sys.stderr.write "libevent error: '{cstr}'"
369 end
370
371 # Error with sockets
372 fun socket_error: NativeString `{
373 // TODO move to Nit and maybe NativeEventBase
374 int err = EVUTIL_SOCKET_ERROR();
375 return evutil_socket_error_to_string(err);
376 `}
377 end
378
379 # Factory to listen on sockets and create new `Connection`
380 class ConnectionFactory
381 # The `NativeEventBase` for the dispatch loop of this factory
382 var event_base: NativeEventBase
383
384 # Accept a connection on `listener`
385 #
386 # By default, it creates a new NativeBufferEvent and calls `spawn_connection`.
387 fun accept_connection(listener: ConnectionListener, fd: Int, address: Pointer, socklen: Int)
388 do
389 var base = listener.base
390 var bev = new NativeBufferEvent.socket(base, fd, bev_opt_close_on_free)
391 var conn = spawn_connection(bev)
392 bev.enable ev_read|ev_write
393 bev.setcb conn
394 end
395
396 # Create a new `Connection` object for `buffer_event`
397 fun spawn_connection(buffer_event: NativeBufferEvent): Connection
398 do
399 return new Connection(buffer_event)
400 end
401
402 # Listen on `address`:`port` for new connection, which will callback `spawn_connection`
403 fun bind_to(address: String, port: Int): nullable ConnectionListener
404 do
405 var listener = new ConnectionListener.bind_to(event_base, address.to_cstring, port, self)
406 if listener.address_is_null then
407 sys.stderr.write "libevent warning: Opening {address}:{port} failed\n"
408 end
409 return listener
410 end
411 end