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