Merge: Floats in exponent notation
[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 super FinalizableOnce
41
42 # The PollFD object
43 private var poll_struct: NativeSocketPollFD
44
45 # A collection of the events to be watched
46 var events: Array[NativeSocketPollValues]
47
48 init(pid: Int, events: Array[NativeSocketPollValues])
49 do
50 assert events.length >= 1
51 self.events = events
52
53 var events_in_one = events[0]
54
55 for i in [1 .. events.length-1] do
56 events_in_one += events[i]
57 end
58
59 self.poll_struct = new NativeSocketPollFD(pid, events_in_one)
60 end
61
62 # Reads the response and returns an array with the type of events that have been found
63 private fun check_response(response: Int): Array[NativeSocketPollValues]
64 do
65 var resp_array = new Array[NativeSocketPollValues]
66 for i in events do
67 if c_check_resp(response, i) != 0 then
68 resp_array.push(i)
69 end
70 end
71 return resp_array
72 end
73
74 # Checks if the poll call has returned true for a particular type of event
75 private fun c_check_resp(response: Int, mask: NativeSocketPollValues): Int
76 `{
77 return response & mask;
78 `}
79
80 redef fun finalize_once
81 do
82 poll_struct.free
83 end
84 end
85
86 # Data structure used by the poll function
87 private extern class NativeSocketPollFD `{ struct pollfd * `}
88
89 # File descriptor
90 fun fd: Int `{ return self->fd; `}
91
92 # List of events to be watched
93 fun events: Int `{ return self->events; `}
94
95 # List of events received by the last poll function
96 fun revents: Int `{ return self->revents; `}
97
98 new (pid: Int, events: NativeSocketPollValues) `{
99 struct pollfd *poll = malloc(sizeof(struct pollfd));
100 poll->fd = pid;
101 poll->events = events;
102 return poll;
103 `}
104 end
105
106 extern class NativeSocket `{ int* `}
107
108 new socket(domain: NativeSocketAddressFamilies, socketType: NativeSocketTypes, protocol: NativeSocketProtocolFamilies) `{
109 int ds = socket(domain, socketType, protocol);
110 if(ds == -1){
111 return NULL;
112 }
113 int *d = malloc(sizeof(int));
114 memcpy(d, &ds, sizeof(ds));
115 return d;
116 `}
117
118 fun destroy `{ free(self); `}
119
120 fun close: Int `{ return close(*self); `}
121
122 fun descriptor: Int `{ return *self; `}
123
124 fun connect(addrIn: NativeSocketAddrIn): Int `{
125 return connect(*self, (struct sockaddr*)addrIn, sizeof(*addrIn));
126 `}
127
128 fun write(buffer: String): Int
129 import String.to_cstring, String.length `{
130 return write(*self, (char*)String_to_cstring(buffer), String_length(buffer));
131 `}
132
133 # Write `value` as a single byte
134 fun write_byte(value: Int): Int `{
135 unsigned char byt = (unsigned char)value;
136 return write(*self, &byt, 1);
137 `}
138
139 fun read: String import NativeString.to_s_with_length, NativeString `{
140 char *c = new_NativeString(1024);
141 int n = read(*self, c, 1023);
142 if(n < 0) {
143 return NativeString_to_s_with_length("",0);
144 }
145 c[n] = 0;
146 return NativeString_to_s_with_length(c, n);
147 `}
148
149 # Sets an option for the socket
150 #
151 # Returns `true` on success.
152 fun setsockopt(level: NativeSocketOptLevels, option_name: NativeSocketOptNames, option_value: Int): Bool `{
153 int err = setsockopt(*self, level, option_name, &option_value, sizeof(int));
154 if(err != 0){
155 return 0;
156 }
157 return 1;
158 `}
159
160 fun bind(addrIn: NativeSocketAddrIn): Int `{ return bind(*self, (struct sockaddr*)addrIn, sizeof(*addrIn)); `}
161
162 fun listen(size: Int): Int `{ return listen(*self, size); `}
163
164 # Checks if the buffer is ready for any event specified when creating the pollfd structure
165 fun socket_poll(filedesc: PollFD, timeout: Int): Array[NativeSocketPollValues]
166 do
167 var result = native_poll(filedesc.poll_struct, timeout)
168 assert result != -1
169 return filedesc.check_response(result)
170 end
171
172 # Call to the poll function of the C socket
173 #
174 # Signature:
175 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
176 #
177 # Official documentation of the poll function:
178 #
179 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
180 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
181 # The number of pollfd structures in the fds array is specified by nfds.
182 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
183 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
184 # It is a pointer to an array with one member for each open file descriptor of interest.
185 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
186 # OR'ing a combination of the pollfd flags.
187 private fun native_poll(filedesc: NativeSocketPollFD, timeout: Int): Int `{
188 int poll_return = poll(filedesc, 1, timeout);
189 return poll_return;
190 `}
191
192 private fun native_accept(addr_in: NativeSocketAddrIn): NativeSocket `{
193 socklen_t s = sizeof(struct sockaddr);
194 int socket = accept(*self, (struct sockaddr*)addr_in, &s);
195 if (socket == -1) return NULL;
196
197 int *ptr = malloc(sizeof(int));
198 *ptr = socket;
199 return ptr;
200 `}
201
202 fun accept: nullable SocketAcceptResult
203 do
204 var addrIn = new NativeSocketAddrIn
205 var s = native_accept(addrIn)
206 if s.address_is_null then return null
207 return new SocketAcceptResult(s, addrIn)
208 end
209
210 # Set wether this socket is non blocking
211 fun non_blocking=(value: Bool) `{
212 int flags = fcntl(*self, F_GETFL, 0);
213 if (flags == -1) flags = 0;
214
215 if (value) {
216 flags = flags | O_NONBLOCK;
217 } else if (flags & O_NONBLOCK) {
218 flags = flags - O_NONBLOCK;
219 } else {
220 return;
221 }
222 fcntl(*self, F_SETFL, flags);
223 `}
224 end
225
226 # Result of a call to `NativeSocket::accept`
227 class SocketAcceptResult
228
229 # Opened socket
230 var socket: NativeSocket
231
232 # Address of the remote client
233 var addr_in: NativeSocketAddrIn
234 end
235
236 extern class NativeSocketAddrIn `{ struct sockaddr_in* `}
237 new `{
238 struct sockaddr_in *sai = NULL;
239 sai = malloc(sizeof(struct sockaddr_in));
240 return sai;
241 `}
242
243 new with_port(port: Int, family: NativeSocketAddressFamilies) `{
244 struct sockaddr_in *sai = NULL;
245 sai = malloc(sizeof(struct sockaddr_in));
246 sai->sin_family = family;
247 sai->sin_port = htons(port);
248 sai->sin_addr.s_addr = INADDR_ANY;
249 return sai;
250 `}
251
252 new with_hostent(hostent: NativeSocketHostent, port: Int) `{
253 struct sockaddr_in *sai = NULL;
254 sai = malloc(sizeof(struct sockaddr_in));
255 sai->sin_family = hostent->h_addrtype;
256 sai->sin_port = htons(port);
257 memcpy((char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length);
258 return sai;
259 `}
260
261 fun address: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(self->sin_addr)); `}
262
263 fun family: NativeSocketAddressFamilies `{ return self->sin_family; `}
264
265 fun port: Int `{ return ntohs(self->sin_port); `}
266
267 fun destroy `{ free(self); `}
268 end
269
270 extern class NativeSocketHostent `{ struct hostent* `}
271 private fun native_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(self->h_aliases[i]); `}
272
273 private fun native_h_aliases_reachable(i: Int): Bool `{ return (self->h_aliases[i] != NULL); `}
274
275 fun h_aliases: Array[String]
276 do
277 var i=0
278 var d=new Array[String]
279 loop
280 d.add(native_h_aliases(i))
281 if native_h_aliases_reachable(i+1) == false then break
282 i += 1
283 end
284 return d
285 end
286
287 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(*(struct in_addr*)self->h_addr)); `}
288
289 fun h_addrtype: Int `{ return self->h_addrtype; `}
290
291 fun h_length: Int `{ return self->h_length; `}
292
293 fun h_name: String import NativeString.to_s `{ return NativeString_to_s(self->h_name); `}
294 end
295
296 extern class NativeTimeval `{ struct timeval* `}
297 new (seconds: Int, microseconds: Int) `{
298 struct timeval* tv = NULL;
299 tv = malloc(sizeof(struct timeval));
300 tv->tv_sec = seconds;
301 tv->tv_usec = microseconds;
302 return tv;
303 `}
304
305 fun seconds: Int `{ return self->tv_sec; `}
306
307 fun microseconds: Int `{ return self->tv_usec; `}
308
309 fun destroy `{ free(self); `}
310 end
311
312 extern class NativeSocketSet `{ fd_set* `}
313 new `{
314 fd_set *f = NULL;
315 f = malloc(sizeof(fd_set));
316 return f;
317 `}
318
319 fun set(s: NativeSocket) `{ FD_SET(*s, self); `}
320
321 fun is_set(s: NativeSocket): Bool `{ return FD_ISSET(*s, self); `}
322
323 fun zero `{ FD_ZERO(self); `}
324
325 fun clear(s: NativeSocket) `{ FD_CLR(*s, self); `}
326
327 fun destroy `{ free(self); `}
328 end
329
330 class NativeSocketObserver
331 # FIXME this implementation is broken. `reads`, `write` and `except`
332 # are boxed objects, passing them to a C function is illegal.
333 fun select(max: NativeSocket, reads: nullable NativeSocketSet, write: nullable NativeSocketSet,
334 except: nullable NativeSocketSet, timeout: NativeTimeval): Int `{
335 fd_set *rds, *wts, *exs = NULL;
336 struct timeval *tm = NULL;
337 if (reads != NULL) rds = (fd_set*)reads;
338 if (write != NULL) wts = (fd_set*)write;
339 if (except != NULL) exs = (fd_set*)except;
340 if (timeout != NULL) tm = (struct timeval*)timeout;
341 return select(*max, rds, wts, exs, tm);
342 `}
343 end
344
345 extern class NativeSocketTypes `{ int `}
346 new sock_stream `{ return SOCK_STREAM; `}
347 new sock_dgram `{ return SOCK_DGRAM; `}
348 new sock_raw `{ return SOCK_RAW; `}
349 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
350 end
351
352 extern class NativeSocketAddressFamilies `{ int `}
353 new af_null `{ return 0; `}
354
355 # Unspecified
356 new af_unspec `{ return AF_UNSPEC; `}
357
358 # Local to host (pipes)
359 new af_unix `{ return AF_UNIX; `}
360
361 # For backward compatibility
362 new af_local `{ return AF_LOCAL; `}
363
364 # Internetwork: UDP, TCP, etc.
365 new af_inet `{ return AF_INET; `}
366
367 # IBM SNA
368 new af_sna `{ return AF_SNA; `}
369
370 # DECnet
371 new af_decnet `{ return AF_DECnet; `}
372
373 # Internal Routing Protocol
374 new af_route `{ return AF_ROUTE; `}
375
376 # Novell Internet Protocol
377 new af_ipx `{ return AF_IPX; `}
378
379 # IPv6
380 new af_inet6 `{ return AF_INET6; `}
381
382 new af_max `{ return AF_MAX; `}
383 end
384
385 extern class NativeSocketProtocolFamilies `{ int `}
386 new pf_null `{ return 0; `}
387 new pf_unspec `{ return PF_UNSPEC; `}
388 new pf_local `{ return PF_LOCAL; `}
389 new pf_unix `{ return PF_UNIX; `}
390 new pf_inet `{ return PF_INET; `}
391 new pf_sna `{ return PF_SNA; `}
392 new pf_decnet `{ return PF_DECnet; `}
393 new pf_route `{ return PF_ROUTE; `}
394 new pf_ipx `{ return PF_IPX; `}
395 new pf_key `{ return PF_KEY; `}
396 new pf_inet6 `{ return PF_INET6; `}
397 new pf_max `{ return PF_MAX; `}
398 end
399
400 # Level on which to set options
401 extern class NativeSocketOptLevels `{ int `}
402
403 # Dummy for IP (As defined in C)
404 new ip `{ return IPPROTO_IP;`}
405
406 # Control message protocol
407 new icmp `{ return IPPROTO_ICMP;`}
408
409 # Use TCP
410 new tcp `{ return IPPROTO_TCP; `}
411
412 # Socket level options
413 new socket `{ return SOL_SOCKET; `}
414 end
415
416 # Options for socket, use with setsockopt
417 extern class NativeSocketOptNames `{ int `}
418
419 # Enables debugging information
420 new debug `{ return SO_DEBUG; `}
421
422 # Authorizes the broadcasting of messages
423 new broadcast `{ return SO_BROADCAST; `}
424
425 # Authorizes the reuse of the local address
426 new reuseaddr `{ return SO_REUSEADDR; `}
427
428 # Authorizes the use of keep-alive packets in a connection
429 new keepalive `{ return SO_KEEPALIVE; `}
430
431 # Disable the Nagle algorithm and send data as soon as possible, in smaller packets
432 new tcp_nodelay `{ return TCP_NODELAY; `}
433 end
434
435 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
436 extern class NativeSocketPollValues `{ int `}
437
438 # Data other than high-priority data may be read without blocking.
439 new pollin `{ return POLLIN; `}
440
441 # Normal data may be read without blocking.
442 new pollrdnorm `{ return POLLRDNORM; `}
443
444 # Priority data may be read without blocking.
445 new pollrdband `{ return POLLRDBAND; `}
446
447 # High-priority data may be read without blocking.
448 new pollpri `{ return POLLPRI; `}
449
450 # Normal data may be written without blocking.
451 new pollout `{ return POLLOUT; `}
452
453 # Equivalent to POLLOUT
454 new pollwrnorm `{ return POLLWRNORM; `}
455
456 # Priority data may be written.
457 new pollwrband `{ return POLLWRBAND; `}
458
459 # An error has occurred on the device or stream.
460 #
461 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
462 new pollerr `{ return POLLERR; `}
463
464 # The device has been disconnected.
465 #
466 # This event and POLLOUT are mutually-exclusive; a stream can never be
467 # writable if a hangup has occurred. However, this event and POLLIN,
468 # POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive.
469 #
470 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
471 new pollhup `{ return POLLHUP; `}
472
473 # The specified fd value is invalid.
474 #
475 # This flag is only valid in the revents member; it shall ignored in the events member.
476 new pollnval `{ return POLLNVAL; `}
477
478 # Combines two NativeSocketPollValues
479 private fun +(other: NativeSocketPollValues): NativeSocketPollValues `{
480 return self | other;
481 `}
482 end
483
484 redef class Sys
485 # Get network host entry
486 fun gethostbyname(name: NativeString): NativeSocketHostent `{
487 return gethostbyname(name);
488 `}
489
490 # Last error raised by `gethostbyname`
491 fun h_errno: HErrno `{ return h_errno; `}
492 end
493
494 # Error code of `Sys::h_errno`
495 extern class HErrno `{ int `}
496 # The specified host is unknown
497 fun host_not_found: Bool `{ return self == HOST_NOT_FOUND; `}
498
499 # The requested name is valid but does not have an IP address
500 #
501 # Same as `no_data`.
502 fun no_address: Bool `{ return self == NO_ADDRESS; `}
503
504 # The requested name is valid byt does not have an IP address
505 #
506 # Same as `no_address`.
507 fun no_data: Bool `{ return self == NO_DATA; `}
508
509 # A nonrecoverable name server error occurred
510 fun no_recovery: Bool `{ return self == NO_RECOVERY; `}
511
512 # A temporary error occurred on an authoritative name server, try again later
513 fun try_again: Bool `{ return self == TRY_AGAIN; `}
514
515 redef fun to_s
516 do
517 if host_not_found then
518 return "The specified host is unknown"
519 else if no_address then
520 return "The requested name is valid but does not have an IP address"
521 else if no_recovery then
522 return "A nonrecoverable name server error occurred"
523 else if try_again then
524 return "A temporary error occurred on an authoritative name server, try again later"
525 else
526 # This may happen if another call was made to `gethostbyname`
527 # before we fetch the error code.
528 return "Unknown error on `gethostbyname`"
529 end
530 end
531 end