README: document nit_env.sh
[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
96 # Has `self` been correctly initialized?
97 fun is_valid: Bool do return not address_is_null
98
99 # Event dispatching loop
100 #
101 # This loop will run the event base until either there are no more added
102 # events, or until something calls `exit_loop`.
103 fun dispatch `{ event_base_dispatch(self); `}
104
105 # Exit the event loop
106 #
107 # TODO support timer
108 fun exit_loop `{ event_base_loopexit(self, NULL); `}
109
110 # Destroy this instance
111 fun destroy `{ event_base_free(self); `}
112 end
113
114 # Spawned to manage a specific connection
115 #
116 # TODO, use polls
117 class Connection
118 super Writer
119
120 # Closing this connection has been requested, but may not yet be `closed`
121 var close_requested = false
122
123 # This connection is closed
124 var closed = false
125
126 # The native libevent linked to `self`
127 var native_buffer_event: NativeBufferEvent
128
129 # Close this connection if possible, otherwise mark it to be closed later
130 redef fun close
131 do
132 var success = native_buffer_event.destroy
133 close_requested = true
134 closed = success
135 end
136
137 # Callback method on a write event
138 fun write_callback
139 do
140 if close_requested and not closed then close
141 end
142
143 private fun read_callback_native(cstr: NativeString, len: Int)
144 do
145 read_callback(cstr.to_s_with_length(len))
146 end
147
148 # Callback method when data is available to read
149 fun read_callback(content: String)
150 do
151 if close_requested and not closed then close
152 end
153
154 # Callback method on events
155 fun event_callback(events: Int) do end
156
157 # Write a string to the connection
158 redef fun write(str)
159 do
160 native_buffer_event.write(str.to_cstring, str.bytelen)
161 end
162
163 redef fun write_byte(byte) do native_buffer_event.write_byte(byte)
164
165 # Write a file to the connection
166 #
167 # require: `path.file_exists`
168 fun write_file(path: String)
169 do
170 assert path.file_exists
171
172 var file = new FileReader.open(path)
173 var output = native_buffer_event.output_buffer
174 var fd = file.fd
175 var length = file.file_stat.size
176
177 output.add_file(fd, 0, length)
178 end
179 end
180
181 # A buffer event structure, strongly associated to a connection, an input buffer and an output_buffer
182 extern class NativeBufferEvent `{ struct bufferevent * `}
183 # Write `length` bytes of `line`
184 fun write(line: NativeString, length: Int): Int `{
185 return bufferevent_write(self, line, length);
186 `}
187
188 # Write the byte `value`
189 fun write_byte(value: Byte): Int `{
190 unsigned char byt = (unsigned char)value;
191 return bufferevent_write(self, &byt, 1);
192 `}
193
194 # Check if we have anything left in our buffers. If so, we set our connection to be closed
195 # on a callback. Otherwise we close it and free it right away.
196 fun destroy: Bool `{
197 struct evbuffer* out = bufferevent_get_output(self);
198 struct evbuffer* in = bufferevent_get_input(self);
199 if(evbuffer_get_length(in) > 0 || evbuffer_get_length(out) > 0) {
200 return 0;
201 } else {
202 bufferevent_free(self);
203 return 1;
204 }
205 `}
206
207 # The output buffer associated to `self`
208 fun output_buffer: OutputNativeEvBuffer `{ return bufferevent_get_output(self); `}
209
210 # The input buffer associated to `self`
211 fun input_buffer: InputNativeEvBuffer `{ return bufferevent_get_input(self); `}
212 end
213
214 # A single buffer
215 extern class NativeEvBuffer `{ struct evbuffer * `}
216 # Length of data in this buffer
217 fun length: Int `{ return evbuffer_get_length(self); `}
218 end
219
220 # An input buffer
221 extern class InputNativeEvBuffer
222 super NativeEvBuffer
223
224 # Empty/clear `length` data from buffer
225 fun drain(length: Int) `{ evbuffer_drain(self, length); `}
226 end
227
228 # An output buffer
229 extern class OutputNativeEvBuffer
230 super NativeEvBuffer
231
232 # Add file to buffer
233 fun add_file(fd, offset, length: Int): Bool `{
234 return evbuffer_add_file(self, fd, offset, length);
235 `}
236 end
237
238 # A listener acting on an interface and port, spawns `Connection` on new connections
239 extern class ConnectionListener `{ struct evconnlistener * `}
240
241 private new bind_to(base: NativeEventBase, address: NativeString, port: Int, factory: ConnectionFactory)
242 import ConnectionFactory.spawn_connection, error_callback, Connection.read_callback_native,
243 Connection.write_callback, Connection.event_callback `{
244
245 struct sockaddr_in sin;
246 struct evconnlistener *listener;
247 ConnectionFactory_incr_ref(factory);
248
249 struct hostent *hostent = gethostbyname(address);
250
251 memset(&sin, 0, sizeof(sin));
252 sin.sin_family = hostent->h_addrtype;
253 sin.sin_port = htons(port);
254 memcpy( &(sin.sin_addr.s_addr), (const void*)hostent->h_addr, hostent->h_length );
255
256 listener = evconnlistener_new_bind(base,
257 (evconnlistener_cb)accept_conn_cb, factory,
258 LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,
259 (struct sockaddr*)&sin, sizeof(sin));
260
261 if (listener != NULL) {
262 evconnlistener_set_error_cb(listener, (evconnlistener_errorcb)ConnectionListener_error_callback);
263 }
264
265 return listener;
266 `}
267
268 # Get the `NativeEventBase` associated to `self`
269 fun base: NativeEventBase `{ return evconnlistener_get_base(self); `}
270
271 # Callback method on listening error
272 fun error_callback do
273 var cstr = socket_error
274 sys.stderr.write "libevent error: '{cstr}'"
275 end
276
277 # Error with sockets
278 fun socket_error: NativeString `{
279 // TODO move to Nit and maybe NativeEventBase
280 int err = EVUTIL_SOCKET_ERROR();
281 return evutil_socket_error_to_string(err);
282 `}
283 end
284
285 # Factory to listen on sockets and create new `Connection`
286 class ConnectionFactory
287 # The `NativeEventBase` for the dispatch loop of this factory
288 var event_base: NativeEventBase
289
290 # On new connection, create the handler `Connection` object
291 fun spawn_connection(nat_buf_ev: NativeBufferEvent): Connection
292 do
293 return new Connection(nat_buf_ev)
294 end
295
296 # Listen on `address`:`port` for new connection, which will callback `spawn_connection`
297 fun bind_to(address: String, port: Int): nullable ConnectionListener
298 do
299 var listener = new ConnectionListener.bind_to(event_base, address.to_cstring, port, self)
300 if listener.address_is_null then
301 sys.stderr.write "libevent warning: Opening {address}:{port} failed\n"
302 end
303 return listener
304 end
305 end