793b1c53b6315bf58147ad83a58aefb31f23d8cc
[nit.git] / lib / socket / socket_c.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Low-level socket functionalities
18 module socket_c
19
20 in "C Header" `{
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #include <sys/poll.h>
31 `}
32
33 in "C" `{
34 #include <fcntl.h>
35 #include <netinet/tcp.h>
36 `}
37
38 # Wrapper for the data structure PollFD used for polling on a socket
39 class PollFD
40
41 # The PollFD object
42 private var poll_struct: NativeSocketPollFD
43
44 # A collection of the events to be watched
45 var events: Array[NativeSocketPollValues]
46
47 init(pid: Int, events: Array[NativeSocketPollValues])
48 do
49 assert events.length >= 1
50 self.events = events
51
52 var events_in_one = events[0]
53
54 for i in [1 .. events.length-1] do
55 events_in_one += events[i]
56 end
57
58 self.poll_struct = new NativeSocketPollFD(pid, events_in_one)
59 end
60
61 # Reads the response and returns an array with the type of events that have been found
62 private fun check_response(response: Int): Array[NativeSocketPollValues]
63 do
64 var resp_array = new Array[NativeSocketPollValues]
65 for i in events do
66 if c_check_resp(response, i) != 0 then
67 resp_array.push(i)
68 end
69 end
70 return resp_array
71 end
72
73 # Checks if the poll call has returned true for a particular type of event
74 private fun c_check_resp(response: Int, mask: NativeSocketPollValues): Int
75 `{
76 return response & mask;
77 `}
78
79 end
80
81 # Data structure used by the poll function
82 private extern class NativeSocketPollFD `{ struct pollfd * `}
83
84 # File descriptor
85 fun fd: Int `{ return recv->fd; `}
86
87 # List of events to be watched
88 fun events: Int `{ return recv->events; `}
89
90 # List of events received by the last poll function
91 fun revents: Int `{ return recv->revents; `}
92
93 new (pid: Int, events: NativeSocketPollValues) `{
94 struct pollfd *poll = malloc(sizeof(struct pollfd));
95 poll->fd = pid;
96 poll->events = events;
97 return poll;
98 `}
99 end
100
101 extern class NativeSocket `{ int* `}
102
103 new socket(domain: NativeSocketAddressFamilies, socketType: NativeSocketTypes, protocol: NativeSocketProtocolFamilies) `{
104 int ds = socket(domain, socketType, protocol);
105 if(ds == -1){
106 return NULL;
107 }
108 int *d = malloc(sizeof(int));
109 memcpy(d, &ds, sizeof(ds));
110 return d;
111 `}
112
113 fun destroy `{ free(recv); `}
114
115 fun close: Int `{ return close(*recv); `}
116
117 fun descriptor: Int `{ return *recv; `}
118
119 fun gethostbyname(n: String): NativeSocketHostent import String.to_cstring `{ return gethostbyname(String_to_cstring(n)); `}
120
121 fun connect(addrIn: NativeSocketAddrIn): Int `{
122 return connect(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn));
123 `}
124
125 fun write(buffer: String): Int
126 import String.to_cstring, String.length `{
127 return write(*recv, (char*)String_to_cstring(buffer), String_length(buffer));
128 `}
129
130 fun read: String import NativeString.to_s_with_length `{
131 static char c[1024];
132 int n = read(*recv, c, 1024);
133 if(n < 0) {
134 return NativeString_to_s_with_length("",0);
135 }
136 char* ret = malloc(n + 1);
137 memcpy(ret, c, n);
138 ret[n] = '\0';
139 return NativeString_to_s_with_length(ret, n);
140 `}
141
142 # Sets an option for the socket
143 fun setsockopt(level: NativeSocketOptLevels, option_name: NativeSocketOptNames, option_value: Int) `{
144 int err = setsockopt(*recv, level, option_name, &option_value, sizeof(int));
145 if(err != 0){
146 perror("Error on setsockopts: ");
147 exit(1);
148 }
149 `}
150
151 fun bind(addrIn: NativeSocketAddrIn): Int `{ return bind(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn)); `}
152
153 fun listen(size: Int): Int `{ return listen(*recv, size); `}
154
155 # Checks if the buffer is ready for any event specified when creating the pollfd structure
156 fun socket_poll(filedesc: PollFD, timeout: Int): Array[NativeSocketPollValues]
157 do
158 var result = native_poll(filedesc.poll_struct, timeout)
159 assert result != -1
160 return filedesc.check_response(result)
161 end
162
163 # Call to the poll function of the C socket
164 #
165 # Signature:
166 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
167 #
168 # Official documentation of the poll function:
169 #
170 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
171 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
172 # The number of pollfd structures in the fds array is specified by nfds.
173 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
174 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
175 # It is a pointer to an array with one member for each open file descriptor of interest.
176 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
177 # OR'ing a combination of the pollfd flags.
178 private fun native_poll(filedesc: NativeSocketPollFD, timeout: Int): Int `{
179 int poll_return = poll(filedesc, 1, timeout);
180 return poll_return;
181 `}
182
183 private fun native_accept(addr_in: NativeSocketAddrIn): NativeSocket `{
184 socklen_t s = sizeof(struct sockaddr);
185 int socket = accept(*recv, (struct sockaddr*)addr_in, &s);
186 if (socket == -1) return NULL;
187
188 int *ptr = malloc(sizeof(int));
189 *ptr = socket;
190 return ptr;
191 `}
192
193 fun accept: nullable SocketAcceptResult
194 do
195 var addrIn = new NativeSocketAddrIn
196 var s = native_accept(addrIn)
197 if s.address_is_null then return null
198 return new SocketAcceptResult(s, addrIn)
199 end
200
201 # Set wether this socket is non blocking
202 fun non_blocking=(value: Bool) `{
203 int flags = fcntl(*recv, F_GETFL, 0);
204 if (flags == -1) flags = 0;
205
206 if (value) {
207 flags = flags | O_NONBLOCK;
208 } else if (flags & O_NONBLOCK) {
209 flags = flags - O_NONBLOCK;
210 } else {
211 return;
212 }
213 fcntl(*recv, F_SETFL, flags);
214 `}
215 end
216
217 # Result of a call to `NativeSocket::accept`
218 class SocketAcceptResult
219
220 # Opened socket
221 var socket: NativeSocket
222
223 # Address of the remote client
224 var addr_in: NativeSocketAddrIn
225 end
226
227 extern class NativeSocketAddrIn `{ struct sockaddr_in* `}
228 new `{
229 struct sockaddr_in *sai = NULL;
230 sai = malloc(sizeof(struct sockaddr_in));
231 return sai;
232 `}
233
234 new with(port: Int, family: NativeSocketAddressFamilies) `{
235 struct sockaddr_in *sai = NULL;
236 sai = malloc(sizeof(struct sockaddr_in));
237 sai->sin_family = family;
238 sai->sin_port = htons(port);
239 sai->sin_addr.s_addr = INADDR_ANY;
240 return sai;
241 `}
242
243 new with_hostent(hostent: NativeSocketHostent, port: Int) `{
244 struct sockaddr_in *sai = NULL;
245 sai = malloc(sizeof(struct sockaddr_in));
246 sai->sin_family = hostent->h_addrtype;
247 sai->sin_port = htons(port);
248 memcpy((char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length);
249 return sai;
250 `}
251
252 fun address: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(recv->sin_addr)); `}
253
254 fun family: NativeSocketAddressFamilies `{ return recv->sin_family; `}
255
256 fun port: Int `{ return ntohs(recv->sin_port); `}
257
258 fun destroy `{ free(recv); `}
259 end
260
261 extern class NativeSocketHostent `{ struct hostent* `}
262 private fun native_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(recv->h_aliases[i]); `}
263
264 private fun native_h_aliases_reachable(i: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
265
266 fun h_aliases: Array[String]
267 do
268 var i=0
269 var d=new Array[String]
270 loop
271 d.add(native_h_aliases(i))
272 if native_h_aliases_reachable(i+1) == false then break
273 i += 1
274 end
275 return d
276 end
277
278 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(*(struct in_addr*)recv->h_addr)); `}
279
280 fun h_addrtype: Int `{ return recv->h_addrtype; `}
281
282 fun h_length: Int `{ return recv->h_length; `}
283
284 fun h_name: String import NativeString.to_s `{ return NativeString_to_s(recv->h_name); `}
285 end
286
287 extern class NativeTimeval `{ struct timeval* `}
288 new (seconds: Int, microseconds: Int) `{
289 struct timeval* tv = NULL;
290 tv = malloc(sizeof(struct timeval));
291 tv->tv_sec = seconds;
292 tv->tv_usec = microseconds;
293 return tv;
294 `}
295
296 fun seconds: Int `{ return recv->tv_sec; `}
297
298 fun microseconds: Int `{ return recv->tv_usec; `}
299
300 fun destroy `{ free(recv); `}
301 end
302
303 extern class NativeSocketSet `{ fd_set* `}
304 new `{
305 fd_set *f = NULL;
306 f = malloc(sizeof(fd_set));
307 return f;
308 `}
309
310 fun set(s: NativeSocket) `{ FD_SET(*s, recv); `}
311
312 fun is_set(s: NativeSocket): Bool `{ return FD_ISSET(*s, recv); `}
313
314 fun zero `{ FD_ZERO(recv); `}
315
316 fun clear(s: NativeSocket) `{ FD_CLR(*s, recv); `}
317
318 fun destroy `{ free(recv); `}
319 end
320
321 class NativeSocketObserver
322 # FIXME this implementation is broken. `reads`, `write` and `except`
323 # are boxed objects, passing them to a C function is illegal.
324 fun select(max: NativeSocket, reads: nullable NativeSocketSet, write: nullable NativeSocketSet,
325 except: nullable NativeSocketSet, timeout: NativeTimeval): Int `{
326 fd_set *rds, *wts, *exs = NULL;
327 struct timeval *tm = NULL;
328 if (reads != NULL) rds = (fd_set*)reads;
329 if (write != NULL) wts = (fd_set*)write;
330 if (except != NULL) exs = (fd_set*)except;
331 if (timeout != NULL) tm = (struct timeval*)timeout;
332 return select(*max, rds, wts, exs, tm);
333 `}
334 end
335
336 extern class NativeSocketTypes `{ int `}
337 new sock_stream `{ return SOCK_STREAM; `}
338 new sock_dgram `{ return SOCK_DGRAM; `}
339 new sock_raw `{ return SOCK_RAW; `}
340 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
341 end
342
343 extern class NativeSocketAddressFamilies `{ int `}
344 new af_null `{ return 0; `}
345
346 # Unspecified
347 new af_unspec `{ return AF_UNSPEC; `}
348
349 # Local to host (pipes)
350 new af_unix `{ return AF_UNIX; `}
351
352 # For backward compatibility
353 new af_local `{ return AF_LOCAL; `}
354
355 # Internetwork: UDP, TCP, etc.
356 new af_inet `{ return AF_INET; `}
357
358 # IBM SNA
359 new af_sna `{ return AF_SNA; `}
360
361 # DECnet
362 new af_decnet `{ return AF_DECnet; `}
363
364 # Internal Routing Protocol
365 new af_route `{ return AF_ROUTE; `}
366
367 # Novell Internet Protocol
368 new af_ipx `{ return AF_IPX; `}
369
370 # IPv6
371 new af_inet6 `{ return AF_INET6; `}
372
373 new af_max `{ return AF_MAX; `}
374 end
375
376 extern class NativeSocketProtocolFamilies `{ int `}
377 new pf_null `{ return 0; `}
378 new pf_unspec `{ return PF_UNSPEC; `}
379 new pf_local `{ return PF_LOCAL; `}
380 new pf_unix `{ return PF_UNIX; `}
381 new pf_inet `{ return PF_INET; `}
382 new pf_sna `{ return PF_SNA; `}
383 new pf_decnet `{ return PF_DECnet; `}
384 new pf_route `{ return PF_ROUTE; `}
385 new pf_ipx `{ return PF_IPX; `}
386 new pf_key `{ return PF_KEY; `}
387 new pf_inet6 `{ return PF_INET6; `}
388 new pf_max `{ return PF_MAX; `}
389 end
390
391 # Level on which to set options
392 extern class NativeSocketOptLevels `{ int `}
393
394 # Dummy for IP (As defined in C)
395 new ip `{ return IPPROTO_IP;`}
396
397 # Control message protocol
398 new icmp `{ return IPPROTO_ICMP;`}
399
400 # Use TCP
401 new tcp `{ return IPPROTO_TCP; `}
402
403 # Socket level options
404 new socket `{ return SOL_SOCKET; `}
405 end
406
407 # Options for socket, use with setsockopt
408 extern class NativeSocketOptNames `{ int `}
409
410 # Enables debugging information
411 new debug `{ return SO_DEBUG; `}
412
413 # Authorizes the broadcasting of messages
414 new broadcast `{ return SO_BROADCAST; `}
415
416 # Authorizes the reuse of the local address
417 new reuseaddr `{ return SO_REUSEADDR; `}
418
419 # Authorizes the use of keep-alive packets in a connection
420 new keepalive `{ return SO_KEEPALIVE; `}
421
422 # Disable the Nagle algorithm and send data as soon as possible, in smaller packets
423 new tcp_nodelay `{ return TCP_NODELAY; `}
424 end
425
426 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
427 extern class NativeSocketPollValues `{ int `}
428
429 # Data other than high-priority data may be read without blocking.
430 new pollin `{ return POLLIN; `}
431
432 # Normal data may be read without blocking.
433 new pollrdnorm `{ return POLLRDNORM; `}
434
435 # Priority data may be read without blocking.
436 new pollrdband `{ return POLLRDBAND; `}
437
438 # High-priority data may be read without blocking.
439 new pollpri `{ return POLLPRI; `}
440
441 # Normal data may be written without blocking.
442 new pollout `{ return POLLOUT; `}
443
444 # Equivalent to POLLOUT
445 new pollwrnorm `{ return POLLWRNORM; `}
446
447 # Priority data may be written.
448 new pollwrband `{ return POLLWRBAND; `}
449
450 # An error has occurred on the device or stream.
451 #
452 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
453 new pollerr `{ return POLLERR; `}
454
455 # The device has been disconnected.
456 #
457 # This event and POLLOUT are mutually-exclusive; a stream can never be
458 # writable if a hangup has occurred. However, this event and POLLIN,
459 # POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive.
460 #
461 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
462 new pollhup `{ return POLLHUP; `}
463
464 # The specified fd value is invalid.
465 #
466 # This flag is only valid in the revents member; it shall ignored in the events member.
467 new pollnval `{ return POLLNVAL; `}
468
469 # Combines two NativeSocketPollValues
470 private fun +(other: NativeSocketPollValues): NativeSocketPollValues `{
471 return recv | other;
472 `}
473 end