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
42 private var poll_struct
: NativeSocketPollFD
44 # A collection of the events to be watched
45 var events
: Array[NativeSocketPollValues]
47 init(pid
: Int, events
: Array[NativeSocketPollValues])
49 assert events
.length
>= 1
52 var events_in_one
= events
[0]
54 for i
in [1 .. events
.length-1
] do
55 events_in_one
+= events
[i
]
58 self.poll_struct
= new NativeSocketPollFD(pid
, events_in_one
)
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]
64 var resp_array
= new Array[NativeSocketPollValues]
66 if c_check_resp
(response
, i
) != 0 then
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
76 return response & mask;
81 # Data structure used by the poll function
82 private extern class NativeSocketPollFD `{ struct pollfd `}
85 private fun fd: Int `{ return recv.fd; `}
87 # List of events to be watched
88 private fun events
: Int `{ return recv.events; `}
90 # List of events received by the last poll function
91 private fun revents: Int `{ return recv.revents; `}
93 new (pid
: Int, events
: NativeSocketPollValues) `{
102 extern class NativeSocket `{ int* `}
104 new socket(domain: NativeSocketAddressFamilies, socketType: NativeSocketTypes, protocol: NativeSocketProtocolFamilies) `{
105 int ds
= socket
(domain
, socketType
, protocol
);
109 int
*d
= malloc
(sizeof
(int
));
110 memcpy
(d
, &ds
, sizeof
(ds
));
114 fun destroy `{ free(recv); `}
116 fun close
: Int `{ return close(*recv); `}
118 fun descriptor: Int `{ return *recv; `}
120 fun gethostbyname
(n
: String): NativeSocketHostent import String.to_cstring
`{ return gethostbyname(String_to_cstring(n)); `}
122 fun connect(addrIn: NativeSocketAddrIn): Int `{
123 return connect
(*recv
, (struct sockaddr
*)addrIn
, sizeof
(*addrIn
));
126 fun write(buffer: String): Int
127 import String.to_cstring, String.length `{
128 return write
(*recv
, (char
*)String_to_cstring(buffer
), String_length(buffer
));
131 fun read: String import NativeString.to_s_with_length `{
133 int n
= read
(*recv
, c
, 1024);
135 return NativeString_to_s_with_length("",0);
137 char
* ret
= malloc
(n
+ 1);
140 return NativeString_to_s_with_length(ret
, n
);
143 # Sets an option for the socket
144 fun setsockopt(level: NativeSocketOptLevels, option_name: NativeSocketOptNames, option_value: Int) `{
145 int err
= setsockopt
(*recv
, level
, option_name
, &option_value
, sizeof
(int
));
147 perror
("Error on setsockopts: ");
152 fun bind(addrIn: NativeSocketAddrIn): Int `{ return bind(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn)); `}
154 fun listen
(size
: Int): Int `{ return listen(*recv, size); `}
156 # Checks if the buffer is ready for any event specified when creating the pollfd structure
157 fun socket_poll(filedesc: PollFD, timeout: Int): Array[NativeSocketPollValues]
159 var result = native_poll(filedesc.poll_struct, timeout)
161 return filedesc.check_response(result)
164 # Call to the poll function of the C socket
167 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
169 # Official documentation of the poll function:
171 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
172 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
173 # The number of pollfd structures in the fds array is specified by nfds.
174 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
175 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
176 # It is a pointer to an array with one member for each open file descriptor of interest.
177 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
178 # OR'ing a combination of the pollfd flags.
179 private fun native_poll(filedesc: NativeSocketPollFD, timeout: Int): Int `{
180 int poll_return
= poll
(&filedesc
, 1, timeout
);
184 private fun native_accept(addr_in: NativeSocketAddrIn): NativeSocket `{
185 socklen_t s
= sizeof
(struct sockaddr
);
186 int socket
= accept
(*recv
, (struct sockaddr
*)addr_in
, &s
);
187 if (socket
== -1) return NULL;
189 int
*ptr
= malloc
(sizeof
(int
));
194 fun accept: nullable SocketAcceptResult
196 var addrIn = new NativeSocketAddrIn
197 var s = native_accept(addrIn)
198 if s.address_is_null then return null
199 return new SocketAcceptResult(s, addrIn)
202 # Set wether this socket is non blocking
203 fun non_blocking=(value: Bool) `{
204 int flags
= fcntl
(*recv
, F_GETFL, 0);
205 if (flags
== -1) flags
= 0;
208 flags
= flags
| O_NONBLOCK;
209 } else if (flags
& O_NONBLOCK) {
210 flags
= flags
- O_NONBLOCK;
214 fcntl
(*recv
, F_SETFL, flags
);
218 # Result of a call to `NativeSocket::accept
`
219 class SocketAcceptResult
222 var socket: NativeSocket
224 # Address of the remote client
225 var addr_in: NativeSocketAddrIn
228 extern class NativeSocketAddrIn `{ struct sockaddr_in* `}
230 struct sockaddr_in *sai = NULL;
231 sai = malloc(sizeof(struct sockaddr_in));
235 new with
(port
: Int, family
: NativeSocketAddressFamilies) `{
236 struct sockaddr_in *sai = NULL;
237 sai = malloc(sizeof(struct sockaddr_in));
238 sai->sin_family = family;
239 sai->sin_port = htons(port);
240 sai->sin_addr.s_addr = INADDR_ANY;
244 new with_hostent
(hostent
: NativeSocketHostent, port
: Int) `{
245 struct sockaddr_in *sai = NULL;
246 sai = malloc(sizeof(struct sockaddr_in));
247 sai->sin_family = hostent->h_addrtype;
248 sai->sin_port = htons(port);
249 memcpy((char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length);
253 fun address
: String import NativeString.to_s
`{ return NativeString_to_s((char*)inet_ntoa(recv->sin_addr)); `}
255 fun family: NativeSocketAddressFamilies `{ return recv->sin_family; `}
257 fun port
: Int `{ return ntohs(recv->sin_port); `}
259 fun destroy `{ free(recv); `}
262 extern class NativeSocketHostent `{ struct hostent* `}
263 private fun native_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(recv->h_aliases[i]); `}
265 private fun native_h_aliases_reachable
(i
: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
267 fun h_aliases: Array[String]
270 var d=new Array[String]
272 d.add(native_h_aliases(i))
273 if native_h_aliases_reachable(i+1) == false then break
279 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(*(struct in_addr*)recv->h_addr)); `}
281 fun h_addrtype
: Int `{ return recv->h_addrtype; `}
283 fun h_length: Int `{ return recv->h_length; `}
285 fun h_name
: String import NativeString.to_s
`{ return NativeString_to_s(recv->h_name); `}
288 extern class NativeTimeval `{ struct timeval* `}
289 new (seconds
: Int, microseconds
: Int) `{
290 struct timeval* tv = NULL;
291 tv = malloc(sizeof(struct timeval));
292 tv->tv_sec = seconds;
293 tv->tv_usec = microseconds;
297 fun seconds
: Int `{ return recv->tv_sec; `}
299 fun microseconds: Int `{ return recv->tv_usec; `}
301 fun destroy
`{ free(recv); `}
304 extern class NativeSocketSet `{ fd_set* `}
307 f = malloc(sizeof(fd_set));
311 fun set
(s
: NativeSocket) `{ FD_SET(*s, recv); `}
313 fun is_set(s: NativeSocket): Bool `{ return FD_ISSET(*s, recv); `}
315 fun zero
`{ FD_ZERO(recv); `}
317 fun clear(s: NativeSocket) `{ FD_CLR(*s, recv); `}
319 fun destroy
`{ free(recv); `}
322 class NativeSocketObserver
323 fun select(max: NativeSocket, reads: nullable NativeSocketSet, write: nullable NativeSocketSet,
324 except: nullable NativeSocketSet, timeout: NativeTimeval): Int `{
325 fd_set
*rds
, *wts
, *exs
= NULL;
326 struct timeval
*tm
= NULL;
327 if (reads
!= NULL) rds
= (fd_set
*)reads
;
328 if (write
!= NULL) wts
= (fd_set
*)write
;
329 if (except
!= NULL) exs
= (fd_set
*)except
;
330 if (timeout
!= NULL) tm
= (struct timeval
*)timeout
;
331 return select
(*max
, rds
, wts
, exs
, tm
);
335 extern class NativeSocketTypes `{ int `}
336 new sock_stream
`{ return SOCK_STREAM; `}
337 new sock_dgram `{ return SOCK_DGRAM; `}
338 new sock_raw
`{ return SOCK_RAW; `}
339 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
342 extern class NativeSocketAddressFamilies `{ int `}
343 new af_null `{ return 0; `}
346 new af_unspec
`{ return AF_UNSPEC; `}
348 # Local to host (pipes)
349 new af_unix `{ return AF_UNIX; `}
351 # For backward compatibility
352 new af_local
`{ return AF_LOCAL; `}
354 # Internetwork: UDP, TCP, etc.
355 new af_inet `{ return AF_INET; `}
358 new af_sna
`{ return AF_SNA; `}
361 new af_decnet `{ return AF_DECnet; `}
363 # Internal Routing Protocol
364 new af_route
`{ return AF_ROUTE; `}
366 # Novell Internet Protocol
367 new af_ipx `{ return AF_IPX; `}
369 # Integrated Services Digital Network
370 new af_isdn
`{ return AF_ISDN; `}
373 new af_inet6 `{ return AF_INET6; `}
375 new af_max
`{ return AF_MAX; `}
378 extern class NativeSocketProtocolFamilies `{ int `}
379 new pf_null
`{ return 0; `}
380 new pf_unspec `{ return PF_UNSPEC; `}
381 new pf_local
`{ return PF_LOCAL; `}
382 new pf_unix `{ return PF_UNIX; `}
383 new pf_inet
`{ return PF_INET; `}
384 new pf_sna `{ return PF_SNA; `}
385 new pf_decnet
`{ return PF_DECnet; `}
386 new pf_route `{ return PF_ROUTE; `}
387 new pf_ipx
`{ return PF_IPX; `}
388 new pf_isdn `{ return PF_ISDN; `}
389 new pf_key
`{ return PF_KEY; `}
390 new pf_inet6 `{ return PF_INET6; `}
391 new pf_max
`{ return PF_MAX; `}
394 # Level on which to set options
395 extern class NativeSocketOptLevels `{ int `}
397 # Dummy for IP (As defined in C)
398 new ip
`{ return IPPROTO_IP;`}
400 # Control message protocol
401 new icmp `{ return IPPROTO_ICMP;`}
404 new tcp
`{ return IPPROTO_TCP; `}
406 # Socket level options
407 new socket `{ return SOL_SOCKET; `}
410 # Options for socket, use with setsockopt
411 extern class NativeSocketOptNames `{ int `}
413 # Enables debugging information
414 new debug `{ return SO_DEBUG; `}
416 # Authorizes the broadcasting of messages
417 new broadcast
`{ return SO_BROADCAST; `}
419 # Authorizes the reuse of the local address
420 new reuseaddr `{ return SO_REUSEADDR; `}
422 # Authorizes the use of keep-alive packets in a connection
423 new keepalive
`{ return SO_KEEPALIVE; `}
425 # Disable the Nagle algorithm and send data as soon as possible, in smaller packets
426 new tcp_nodelay `{ return TCP_NODELAY; `}
429 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
430 extern class NativeSocketPollValues `{ int `}
432 # Data other than high-priority data may be read without blocking.
433 new pollin `{ return POLLIN; `}
435 # Normal data may be read without blocking.
436 new pollrdnorm
`{ return POLLRDNORM; `}
438 # Priority data may be read without blocking.
439 new pollrdband `{ return POLLRDBAND; `}
441 # High-priority data may be read without blocking.
442 new pollpri
`{ return POLLPRI; `}
444 # Normal data may be written without blocking.
445 new pollout `{ return POLLOUT; `}
447 # Equivalent to POLLOUT
448 new pollwrnorm
`{ return POLLWRNORM; `}
450 # Priority data may be written.
451 new pollwrband `{ return POLLWRBAND; `}
453 # An error has occurred on the device or stream.
455 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
456 new pollerr
`{ return POLLERR; `}
458 # The device has been disconnected.
460 # This event and POLLOUT are mutually-exclusive; a stream can never be
461 # writable if a hangup has occurred. However, this event and POLLIN,
462 # POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive.
464 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
465 new pollhup `{ return POLLHUP; `}
467 # The specified fd value is invalid.
469 # This flag is only valid in the revents member; it shall ignored in the events member.
470 new pollnval
`{ return POLLNVAL; `}
472 # Combines two NativeSocketPollValues
473 private fun +(other: NativeSocketPollValues): NativeSocketPollValues `{