1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
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
10 # http://www.apache.org/licenses/LICENSE-2.0
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.
18 # Low-level wrapper around the libevent library to manage events on file descriptors
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")
26 #include <sys/types.h>
29 #include <sys/socket.h>
31 #include <event2/listener.h>
32 #include <event2/bufferevent.h>
33 #include <event2/buffer.h>
37 // Callback forwarded to 'Connection.write_callback'
38 static void c_write_cb(struct bufferevent *bev, Connection ctx) {
39 Connection_write_callback(ctx);
42 // Callback forwarded to 'Connection.read_callback_native'
43 static void c_read_cb(struct bufferevent *bev, Connection ctx)
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);
53 // Callback forwarded to 'Connection.event_callback'
54 static void c_event_cb(struct bufferevent *bev, short events, Connection ctx)
56 Connection_event_callback(ctx, events);
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);
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)
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);
75 Connection nit_con = ConnectionFactory_spawn_connection(ctx, bev);
76 Connection_incr_ref(nit_con);
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);
86 # Structure to hold information and state for a Libevent dispatch loop.
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 * `}
93 # Create a new event_base to use with the rest of Libevent
94 new `{ return event_base_new(); `}
96 # Has `self` been correctly initialized?
97 fun is_valid
: Bool do return not address_is_null
99 # Event dispatching loop
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); `}
105 # Exit the event loop
108 fun exit_loop `{ event_base_loopexit(self, NULL); `}
110 # Destroy this instance
111 fun destroy
`{ event_base_free(self); `}
114 # Spawned to manage a specific connection
120 # Closing this connection has been requested, but may not yet be `closed
`
121 var close_requested = false
123 # This connection is closed
126 # The native libevent linked to `self`
127 var native_buffer_event: NativeBufferEvent
129 # Close this connection if possible, otherwise mark it to be closed later
132 var success = native_buffer_event.destroy
133 close_requested = true
137 # Callback method on a write event
140 if close_requested and not closed then close
143 private fun read_callback_native(cstr: NativeString, len: Int)
145 read_callback(cstr.to_s_with_length(len))
148 # Callback method when data is available to read
149 fun read_callback(content: String)
151 if close_requested and not closed then close
154 # Callback method on events
155 fun event_callback(events: Int) do end
157 # Write a string to the connection
160 native_buffer_event.write(str.to_cstring, str.length)
163 redef fun write_byte(byte) do native_buffer_event.write_byte(byte)
165 # Write a file to the connection
167 # require: `path
.file_exists
`
168 fun write_file(path: String)
170 assert path.file_exists
172 var file = new FileReader.open(path)
173 var output = native_buffer_event.output_buffer
175 var length = file.file_stat.size
177 output.add_file(fd, 0, length)
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);
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);
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.
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) {
202 bufferevent_free(self);
207 # The output buffer associated to `self`
208 fun output_buffer
: OutputNativeEvBuffer `{ return bufferevent_get_output(self); `}
210 # The input buffer associated to `self`
211 fun input_buffer: InputNativeEvBuffer `{ return bufferevent_get_input(self); `}
215 extern class NativeEvBuffer `{ struct evbuffer * `}
216 # Length of data in this buffer
217 fun length: Int `{ return evbuffer_get_length(self); `}
221 extern class InputNativeEvBuffer
224 # Empty/clear `length` data from buffer
225 fun drain
(length
: Int) `{ evbuffer_drain(self, length); `}
229 extern class OutputNativeEvBuffer
233 fun add_file(fd, offset, length: Int): Bool `{
234 return evbuffer_add_file
(self, fd
, offset
, length
);
238 # A listener acting on an interface and port, spawns `Connection` on new connections
239 extern class ConnectionListener `{ struct evconnlistener * `}
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
`{
245 struct sockaddr_in sin;
246 struct evconnlistener *listener;
247 ConnectionFactory_incr_ref(factory);
249 struct hostent *hostent = gethostbyname(address);
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 );
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));
261 if (listener != NULL) {
262 evconnlistener_set_error_cb(listener, (evconnlistener_errorcb)ConnectionListener_error_callback);
268 # Get the `NativeEventBase` associated to `self`
269 fun base
: NativeEventBase `{ return evconnlistener_get_base(self); `}
271 # Callback method on listening error
272 fun error_callback do
273 var cstr = socket_error
274 sys.stderr.write "libevent error: '{cstr}'"
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
);
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
290 # On new connection, create the handler `Connection` object
291 fun spawn_connection(nat_buf_ev: NativeBufferEvent): Connection
293 return new Connection(nat_buf_ev)
296 # Listen on `address
`:`port
` for new connection, which will callback `spawn_connection
`
297 fun bind_to(address: String, port: Int): nullable ConnectionListener
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"