1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Low-level socket functionalities
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
35 #include <netinet/tcp.h>
38 # Wrapper for the data structure PollFD used for polling on a socket
43 private var poll_struct
: NativeSocketPollFD
45 # A collection of the events to be watched
46 var events
: Array[NativeSocketPollValues]
48 init(pid
: Int, events
: Array[NativeSocketPollValues])
50 assert events
.length
>= 1
53 var events_in_one
= events
[0]
55 for i
in [1 .. events
.length-1
] do
56 events_in_one
+= events
[i
]
59 self.poll_struct
= new NativeSocketPollFD(pid
, events_in_one
)
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]
65 var resp_array
= new Array[NativeSocketPollValues]
67 if c_check_resp
(response
, i
) != 0 then
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
77 return response & mask;
80 redef fun finalize_once
86 # Data structure used by the poll function
87 private extern class NativeSocketPollFD `{ struct pollfd * `}
90 fun fd: Int `{ return recv->fd; `}
92 # List of events to be watched
93 fun events
: Int `{ return recv->events; `}
95 # List of events received by the last poll function
96 fun revents: Int `{ return recv->revents; `}
98 new (pid
: Int, events
: NativeSocketPollValues) `{
99 struct pollfd *poll = malloc(sizeof(struct pollfd));
101 poll->events = events;
106 extern class NativeSocket `{ int* `}
108 new socket(domain: NativeSocketAddressFamilies, socketType: NativeSocketTypes, protocol: NativeSocketProtocolFamilies) `{
109 int ds
= socket
(domain
, socketType
, protocol
);
113 int
*d
= malloc
(sizeof
(int
));
114 memcpy
(d
, &ds
, sizeof
(ds
));
118 fun destroy `{ free(recv); `}
120 fun close
: Int `{ return close(*recv); `}
122 fun descriptor: Int `{ return *recv; `}
124 fun gethostbyname
(n
: String): NativeSocketHostent import String.to_cstring
`{ return gethostbyname(String_to_cstring(n)); `}
126 fun connect(addrIn: NativeSocketAddrIn): Int `{
127 return connect
(*recv
, (struct sockaddr
*)addrIn
, sizeof
(*addrIn
));
130 fun write(buffer: String): Int
131 import String.to_cstring, String.length `{
132 return write
(*recv
, (char
*)String_to_cstring(buffer
), String_length(buffer
));
135 fun read: String import NativeString.to_s_with_length `{
137 int n
= read
(*recv
, c
, 1024);
139 return NativeString_to_s_with_length("",0);
141 char
* ret
= malloc
(n
+ 1);
144 return NativeString_to_s_with_length(ret
, n
);
147 # Sets an option for the socket
148 fun setsockopt(level: NativeSocketOptLevels, option_name: NativeSocketOptNames, option_value: Int) `{
149 int err
= setsockopt
(*recv
, level
, option_name
, &option_value
, sizeof
(int
));
151 perror
("Error on setsockopts: ");
156 fun bind(addrIn: NativeSocketAddrIn): Int `{ return bind(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn)); `}
158 fun listen
(size
: Int): Int `{ return listen(*recv, size); `}
160 # Checks if the buffer is ready for any event specified when creating the pollfd structure
161 fun socket_poll(filedesc: PollFD, timeout: Int): Array[NativeSocketPollValues]
163 var result = native_poll(filedesc.poll_struct, timeout)
165 return filedesc.check_response(result)
168 # Call to the poll function of the C socket
171 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
173 # Official documentation of the poll function:
175 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
176 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
177 # The number of pollfd structures in the fds array is specified by nfds.
178 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
179 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
180 # It is a pointer to an array with one member for each open file descriptor of interest.
181 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
182 # OR'ing a combination of the pollfd flags.
183 private fun native_poll(filedesc: NativeSocketPollFD, timeout: Int): Int `{
184 int poll_return
= poll
(filedesc
, 1, timeout
);
188 private fun native_accept(addr_in: NativeSocketAddrIn): NativeSocket `{
189 socklen_t s
= sizeof
(struct sockaddr
);
190 int socket
= accept
(*recv
, (struct sockaddr
*)addr_in
, &s
);
191 if (socket
== -1) return NULL;
193 int
*ptr
= malloc
(sizeof
(int
));
198 fun accept: nullable SocketAcceptResult
200 var addrIn = new NativeSocketAddrIn
201 var s = native_accept(addrIn)
202 if s.address_is_null then return null
203 return new SocketAcceptResult(s, addrIn)
206 # Set wether this socket is non blocking
207 fun non_blocking=(value: Bool) `{
208 int flags
= fcntl
(*recv
, F_GETFL, 0);
209 if (flags
== -1) flags
= 0;
212 flags
= flags
| O_NONBLOCK;
213 } else if (flags
& O_NONBLOCK) {
214 flags
= flags
- O_NONBLOCK;
218 fcntl
(*recv
, F_SETFL, flags
);
222 # Result of a call to `NativeSocket::accept
`
223 class SocketAcceptResult
226 var socket: NativeSocket
228 # Address of the remote client
229 var addr_in: NativeSocketAddrIn
232 extern class NativeSocketAddrIn `{ struct sockaddr_in* `}
234 struct sockaddr_in *sai = NULL;
235 sai = malloc(sizeof(struct sockaddr_in));
239 new with
(port
: Int, family
: NativeSocketAddressFamilies) `{
240 struct sockaddr_in *sai = NULL;
241 sai = malloc(sizeof(struct sockaddr_in));
242 sai->sin_family = family;
243 sai->sin_port = htons(port);
244 sai->sin_addr.s_addr = INADDR_ANY;
248 new with_hostent
(hostent
: NativeSocketHostent, port
: Int) `{
249 struct sockaddr_in *sai = NULL;
250 sai = malloc(sizeof(struct sockaddr_in));
251 sai->sin_family = hostent->h_addrtype;
252 sai->sin_port = htons(port);
253 memcpy((char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length);
257 fun address
: String import NativeString.to_s
`{ return NativeString_to_s((char*)inet_ntoa(recv->sin_addr)); `}
259 fun family: NativeSocketAddressFamilies `{ return recv->sin_family; `}
261 fun port
: Int `{ return ntohs(recv->sin_port); `}
263 fun destroy `{ free(recv); `}
266 extern class NativeSocketHostent `{ struct hostent* `}
267 private fun native_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(recv->h_aliases[i]); `}
269 private fun native_h_aliases_reachable
(i
: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
271 fun h_aliases: Array[String]
274 var d=new Array[String]
276 d.add(native_h_aliases(i))
277 if native_h_aliases_reachable(i+1) == false then break
283 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(*(struct in_addr*)recv->h_addr)); `}
285 fun h_addrtype
: Int `{ return recv->h_addrtype; `}
287 fun h_length: Int `{ return recv->h_length; `}
289 fun h_name
: String import NativeString.to_s
`{ return NativeString_to_s(recv->h_name); `}
292 extern class NativeTimeval `{ struct timeval* `}
293 new (seconds
: Int, microseconds
: Int) `{
294 struct timeval* tv = NULL;
295 tv = malloc(sizeof(struct timeval));
296 tv->tv_sec = seconds;
297 tv->tv_usec = microseconds;
301 fun seconds
: Int `{ return recv->tv_sec; `}
303 fun microseconds: Int `{ return recv->tv_usec; `}
305 fun destroy
`{ free(recv); `}
308 extern class NativeSocketSet `{ fd_set* `}
311 f = malloc(sizeof(fd_set));
315 fun set
(s
: NativeSocket) `{ FD_SET(*s, recv); `}
317 fun is_set(s: NativeSocket): Bool `{ return FD_ISSET(*s, recv); `}
319 fun zero
`{ FD_ZERO(recv); `}
321 fun clear(s: NativeSocket) `{ FD_CLR(*s, recv); `}
323 fun destroy
`{ free(recv); `}
326 class NativeSocketObserver
327 # FIXME this implementation is broken. `reads
`, `write
` and `except
`
328 # are boxed objects, passing them to a C function is illegal.
329 fun select(max: NativeSocket, reads: nullable NativeSocketSet, write: nullable NativeSocketSet,
330 except: nullable NativeSocketSet, timeout: NativeTimeval): Int `{
331 fd_set
*rds
, *wts
, *exs
= NULL;
332 struct timeval
*tm
= NULL;
333 if (reads
!= NULL) rds
= (fd_set
*)reads
;
334 if (write
!= NULL) wts
= (fd_set
*)write
;
335 if (except
!= NULL) exs
= (fd_set
*)except
;
336 if (timeout
!= NULL) tm
= (struct timeval
*)timeout
;
337 return select
(*max
, rds
, wts
, exs
, tm
);
341 extern class NativeSocketTypes `{ int `}
342 new sock_stream
`{ return SOCK_STREAM; `}
343 new sock_dgram `{ return SOCK_DGRAM; `}
344 new sock_raw
`{ return SOCK_RAW; `}
345 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
348 extern class NativeSocketAddressFamilies `{ int `}
349 new af_null `{ return 0; `}
352 new af_unspec
`{ return AF_UNSPEC; `}
354 # Local to host (pipes)
355 new af_unix `{ return AF_UNIX; `}
357 # For backward compatibility
358 new af_local
`{ return AF_LOCAL; `}
360 # Internetwork: UDP, TCP, etc.
361 new af_inet `{ return AF_INET; `}
364 new af_sna
`{ return AF_SNA; `}
367 new af_decnet `{ return AF_DECnet; `}
369 # Internal Routing Protocol
370 new af_route
`{ return AF_ROUTE; `}
372 # Novell Internet Protocol
373 new af_ipx `{ return AF_IPX; `}
376 new af_inet6
`{ return AF_INET6; `}
378 new af_max `{ return AF_MAX; `}
381 extern class NativeSocketProtocolFamilies `{ int `}
382 new pf_null `{ return 0; `}
383 new pf_unspec
`{ return PF_UNSPEC; `}
384 new pf_local `{ return PF_LOCAL; `}
385 new pf_unix
`{ return PF_UNIX; `}
386 new pf_inet `{ return PF_INET; `}
387 new pf_sna
`{ return PF_SNA; `}
388 new pf_decnet `{ return PF_DECnet; `}
389 new pf_route
`{ return PF_ROUTE; `}
390 new pf_ipx `{ return PF_IPX; `}
391 new pf_key
`{ return PF_KEY; `}
392 new pf_inet6 `{ return PF_INET6; `}
393 new pf_max
`{ return PF_MAX; `}
396 # Level on which to set options
397 extern class NativeSocketOptLevels `{ int `}
399 # Dummy for IP (As defined in C)
400 new ip
`{ return IPPROTO_IP;`}
402 # Control message protocol
403 new icmp `{ return IPPROTO_ICMP;`}
406 new tcp
`{ return IPPROTO_TCP; `}
408 # Socket level options
409 new socket `{ return SOL_SOCKET; `}
412 # Options for socket, use with setsockopt
413 extern class NativeSocketOptNames `{ int `}
415 # Enables debugging information
416 new debug `{ return SO_DEBUG; `}
418 # Authorizes the broadcasting of messages
419 new broadcast
`{ return SO_BROADCAST; `}
421 # Authorizes the reuse of the local address
422 new reuseaddr `{ return SO_REUSEADDR; `}
424 # Authorizes the use of keep-alive packets in a connection
425 new keepalive
`{ return SO_KEEPALIVE; `}
427 # Disable the Nagle algorithm and send data as soon as possible, in smaller packets
428 new tcp_nodelay `{ return TCP_NODELAY; `}
431 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
432 extern class NativeSocketPollValues `{ int `}
434 # Data other than high-priority data may be read without blocking.
435 new pollin `{ return POLLIN; `}
437 # Normal data may be read without blocking.
438 new pollrdnorm
`{ return POLLRDNORM; `}
440 # Priority data may be read without blocking.
441 new pollrdband `{ return POLLRDBAND; `}
443 # High-priority data may be read without blocking.
444 new pollpri
`{ return POLLPRI; `}
446 # Normal data may be written without blocking.
447 new pollout `{ return POLLOUT; `}
449 # Equivalent to POLLOUT
450 new pollwrnorm
`{ return POLLWRNORM; `}
452 # Priority data may be written.
453 new pollwrband `{ return POLLWRBAND; `}
455 # An error has occurred on the device or stream.
457 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
458 new pollerr
`{ return POLLERR; `}
460 # The device has been disconnected.
462 # This event and POLLOUT are mutually-exclusive; a stream can never be
463 # writable if a hangup has occurred. However, this event and POLLIN,
464 # POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive.
466 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
467 new pollhup `{ return POLLHUP; `}
469 # The specified fd value is invalid.
471 # This flag is only valid in the revents member; it shall ignored in the events member.
472 new pollnval
`{ return POLLNVAL; `}
474 # Combines two NativeSocketPollValues
475 private fun +(other: NativeSocketPollValues): NativeSocketPollValues `{