525915cf29ffb013e5aaeb34a8a867be44bf8d5d
[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 // TODO move to Nit code
46 struct evbuffer *input = bufferevent_get_input(bev);
47 size_t len = evbuffer_get_length(input);
48 char* cstr = malloc(len);
49 evbuffer_remove(input, cstr, len);
50 Connection_read_callback_native(ctx, cstr, len);
51 }
52
53 // Callback forwarded to 'Connection.event_callback'
54 static void c_event_cb(struct bufferevent *bev, short events, Connection ctx)
55 {
56 Connection_event_callback(ctx, events);
57
58 // TODO move to Nit code
59 if (events & BEV_EVENT_ERROR)
60 perror("Error from bufferevent");
61 if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
62 bufferevent_free(bev);
63 Connection_decr_ref(ctx);
64 }
65 }
66
67 // Callback fowarded to 'ConnectionFactory.spawn_connection'
68 static void accept_conn_cb(struct evconnlistener *listener, evutil_socket_t fd,
69 struct sockaddr *address, int socklen, ConnectionFactory ctx)
70 {
71 // TODO move to Nit code
72 struct event_base *base = evconnlistener_get_base(listener);
73 struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
74
75 Connection nit_con = ConnectionFactory_spawn_connection(ctx, bev);
76 Connection_incr_ref(nit_con);
77
78 bufferevent_setcb(bev,
79 (bufferevent_data_cb)c_read_cb,
80 (bufferevent_data_cb)c_write_cb,
81 (bufferevent_event_cb)c_event_cb, nit_con);
82 bufferevent_enable(bev, EV_READ|EV_WRITE);
83 }
84 `}
85
86 # Structure to hold information and state for a Libevent dispatch loop.
87 #
88 # The event_base lies at the center of Libevent; every application will
89 # have one. It keeps track of all pending and active events, and
90 # notifies your application of the active ones.
91 extern class NativeEventBase `{ struct event_base * `}
92
93 # Create a new event_base to use with the rest of Libevent
94 new `{ return event_base_new(); `}
95 fun is_valid: Bool do return not address_is_null
96 #fun creation_ok
97
98 # Event dispatching loop
99 #
100 # This loop will run the event base until either there are no more added
101 # events, or until something calls `exit_loop`.
102 fun dispatch `{ event_base_dispatch(recv); `}
103
104 # Exit the event loop
105 #
106 # TODO support timer
107 fun exit_loop `{ event_base_loopexit(recv, NULL); `}
108
109 # Destroy this instance
110 fun destroy `{ event_base_free(recv); `}
111 end
112
113 # Spawned to manage a specific connection
114 #
115 # TODO, use polls
116 class Connection
117 # Closing this connection has been requested, but may not yet be `closed`
118 var close_requested = false
119
120 # This connection is closed
121 var closed = false
122
123 # The native libevent linked to `self`
124 var native_buffer_event: NativeBufferEvent
125
126 # Close this connection if possible, otherwise mark it to be closed later
127 fun close
128 do
129 var success = native_buffer_event.destroy
130 close_requested = true
131 closed = success
132 end
133
134 # Callback method on a write event
135 fun write_callback
136 do
137 if close_requested and not closed then close
138 end
139
140 private fun read_callback_native(cstr: NativeString, len: Int)
141 do
142 read_callback(cstr.to_s_with_length(len))
143 end
144
145 # Callback method when data is available to read
146 fun read_callback(content: String)
147 do
148 if close_requested and not closed then close
149 end
150
151 # Callback method on events
152 fun event_callback(events: Int) do end
153
154 # Write a string to the connection
155 fun write(str: String)
156 do
157 var res = native_buffer_event.write(str.to_cstring, str.length)
158 end
159
160 # Write a file to the connection
161 #
162 # require: `path.file_exists`
163 fun write_file(path: String)
164 do
165 assert path.file_exists
166
167 var file = new IFStream.open(path)
168 var output = native_buffer_event.output_buffer
169 var fd = file.fd
170 var length = file.file_stat.size
171
172 output.add_file(fd, 0, length)
173 end
174 end
175
176 # A buffer event structure, strongly associated to a connection, an input buffer and an output_buffer
177 extern class NativeBufferEvent `{ struct bufferevent * `}
178 fun write(line: NativeString, length: Int): Int `{
179 return bufferevent_write(recv, line, length);
180 `}
181
182 # Check if we have anything left in our buffers. If so, we set our connection to be closed
183 # on a callback. Otherwise we close it and free it right away.
184 fun destroy: Bool `{
185 struct evbuffer* out = bufferevent_get_output(recv);
186 struct evbuffer* in = bufferevent_get_input(recv);
187 if(evbuffer_get_length(in) > 0 || evbuffer_get_length(out) > 0) {
188 return 0;
189 } else {
190 bufferevent_free(recv);
191 return 1;
192 }
193 `}
194
195 # The output buffer associated to `self`
196 fun output_buffer: OutputNativeEvBuffer `{ return bufferevent_get_output(recv); `}
197
198 # The input buffer associated to `self`
199 fun input_buffer: InputNativeEvBuffer `{ return bufferevent_get_input(recv); `}
200 end
201
202 # A single buffer
203 extern class NativeEvBuffer `{ struct evbuffer * `}
204 # Length of data in this buffer
205 fun length: Int `{ return evbuffer_get_length(recv); `}
206 end
207
208 extern class InputNativeEvBuffer
209 super NativeEvBuffer
210
211 # Empty/clear `length` data from buffer
212 fun drain(length: Int) `{ evbuffer_drain(recv, length); `}
213 end
214
215 extern class OutputNativeEvBuffer
216 super NativeEvBuffer
217
218 # Add file to buffer
219 fun add_file(fd, offset, length: Int): Bool `{
220 return evbuffer_add_file(recv, fd, offset, length);
221 `}
222 end
223
224 # A listener acting on an interface and port, spawns `Connection` on new connections
225 extern class ConnectionListener `{ struct evconnlistener * `}
226
227 private new bind_to(base: NativeEventBase, address: NativeString, port: Int, factory: ConnectionFactory)
228 import ConnectionFactory.spawn_connection, error_callback, Connection.read_callback_native,
229 Connection.write_callback, Connection.event_callback `{
230
231 struct sockaddr_in sin;
232 struct evconnlistener *listener;
233 ConnectionFactory_incr_ref(factory);
234
235 struct hostent *hostent = gethostbyname(address);
236
237 memset(&sin, 0, sizeof(sin));
238 sin.sin_family = hostent->h_addrtype;
239 sin.sin_port = htons(port);
240 memcpy( &(sin.sin_addr.s_addr), (const void*)hostent->h_addr, hostent->h_length );
241
242 listener = evconnlistener_new_bind(base,
243 (evconnlistener_cb)accept_conn_cb, factory,
244 LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
245 (struct sockaddr*)&sin, sizeof(sin));
246
247 if (listener != NULL) {
248 evconnlistener_set_error_cb(listener, (evconnlistener_errorcb)ConnectionListener_error_callback);
249 }
250
251 return listener;
252 `}
253
254 # Get the `NativeEventBase` associated to `self`
255 fun base: NativeEventBase `{ return evconnlistener_get_base(recv); `}
256
257 # Callback method on listening error
258 fun error_callback do
259 var cstr = socket_error
260 sys.stderr.write "libevent error: '{cstr}'"
261 end
262
263 # Error with sockets
264 fun socket_error: NativeString `{
265 // TODO move to Nit and maybe NativeEventBase
266 int err = EVUTIL_SOCKET_ERROR();
267 return evutil_socket_error_to_string(err);
268 `}
269 end
270
271 # Factory to listen on sockets and create new `Connection`
272 class ConnectionFactory
273 var event_base: NativeEventBase
274
275 # On new connection, create the handler `Connection` object
276 fun spawn_connection(nat_buf_ev: NativeBufferEvent): Connection
277 do
278 return new Connection(nat_buf_ev)
279 end
280
281 # Listen on `address`:`port` for new connection, which will callback `spawn_connection`
282 fun bind_to(address: String, port: Int): nullable ConnectionListener
283 do
284 var listener = new ConnectionListener.bind_to(event_base, address.to_cstring, port, self)
285 if listener.address_is_null then
286 sys.stderr.write "libevent warning: Opening {address}:{port} failed\n"
287 end
288 return listener
289 end
290 end