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.
20 private import socket_c
21 intrude import core
::stream
23 # A general Socket, either TCP or UDP
27 private var native
: NativeSocket is noinit
29 # Is this socket closed?
32 # Set whether calls to `accept` are blocking
33 fun blocking
=(value
: Bool)
35 # We use the opposite from the native version as the native API
36 # is closer to the C API. In the Nity API, we use a positive version
38 native
.non_blocking
= not value
42 # A general TCP socket, either a `TCPStream` or a `TCPServer`
43 abstract class TCPSocket
46 # Port used by the socket
49 # IPv4 address to which `self` is connected
51 # Formatted as xxx.xxx.xxx.xxx.
52 var address
: String is noinit
55 # Simple communication stream with a remote socket
61 # Real canonical name of the host to which `self` is connected
64 private var addrin
: NativeSocketAddrIn is noinit
66 redef var closed
= false
68 # TODO make init private
70 # Creates a socket connection to host `host` on port `port`
71 init connect
(host
: String, port
: Int)
73 native
= new NativeSocket.socket
(new NativeSocketAddressFamilies.af_inet
,
74 new NativeSocketTypes.sock_stream
, new NativeSocketProtocolFamilies.pf_unspec
)
75 if native
.address_is_null
then
79 if not native
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.reuseaddr
, 1) then
84 var hostent
= sys
.gethostbyname
(host
.to_cstring
)
85 if hostent
.address_is_null
then
86 # Error in name lookup
87 last_error
= new IOError.from_h_errno
94 addrin
= new NativeSocketAddrIn
95 addrin
.fill_from_hostent hostent
98 address
= addrin
.address
.to_s
99 init(addrin
.port
, hostent
.h_name
.to_s
)
101 closed
= not internal_connect
104 last_error
= new IOError.from_errno
108 # Creates a client socket, this is meant to be used by accept only
109 private init server_side
(h
: SocketAcceptResult)
113 address
= addrin
.address
.to_s
115 init(addrin
.port
, address
)
118 redef fun poll_in
do return ready_to_read
(0)
120 # Returns an array containing an enum of the events ready to be read
122 # event_types : Combination of several event types to watch
124 # timeout : Time in milliseconds before stopping listening for events on this socket
125 private fun pollin
(event_types
: Array[NativeSocketPollValues], timeout
: Int): Array[NativeSocketPollValues] do
126 if closed
then return new Array[NativeSocketPollValues]
127 return native
.socket_poll
(new PollFD.from_poll_values
(native
.descriptor
, event_types
), timeout
)
130 # Easier use of pollin to check for something to read on all channels of any priority
132 # timeout : Time in milliseconds before stopping to wait for events
133 fun ready_to_read
(timeout
: Int): Bool
135 var events
= [new NativeSocketPollValues.pollin
]
136 return pollin
(events
, timeout
).length
!= 0
139 # Is this socket still connected?
142 if closed
then return false
143 if native
.poll_hup_err
== 0 then
151 redef fun is_writable
do return not closed
153 # Establishes a connection to socket addrin
155 # REQUIRES : not self.end_reached
156 private fun internal_connect
: Bool
159 return native
.connect
(addrin
) >= 0
162 redef fun raw_read_byte
do
163 var rd
= native
.read
(write_buffer
, 1)
164 if rd
< 1 then return -1
165 return write_buffer
[0].to_i
168 redef fun raw_read_bytes
(ns
, max
) do
169 var rd
= native
.read
(ns
, max
)
170 print
"Read {rd} bytes"
171 if rd
< 0 then return -1
175 # If socket.end_reached, nothing will happen
178 if closed
then return
179 native
.write
(msg
.to_cstring
, msg
.length
)
182 redef fun write_byte
(value
)
184 if closed
then return
185 native
.write_byte value
188 redef fun write_bytes_from_cstring
(ns
, len
) do
189 if closed
then return
190 native
.write
(ns
, len
)
193 # Write `msg`, with a trailing `\n`
194 fun write_ln
(msg
: Text)
196 if closed
then return
203 if closed
then return
204 if native
.close
>= 0 then
209 # Send the data present in the socket buffer
212 if not native
.setsockopt
(new NativeSocketOptLevels.tcp
, new NativeSocketOptNames.tcp_nodelay
, 1) or
213 not native
.setsockopt
(new NativeSocketOptLevels.tcp
, new NativeSocketOptNames.tcp_nodelay
, 0) then
219 # A socket listening on a given `port` for incomming connections
221 # Create streams to communicate with clients using `accept`.
225 private var addrin
: NativeSocketAddrIn is noinit
227 # Create and bind a listening server socket on port `port`
230 native
= new NativeSocket.socket
(new NativeSocketAddressFamilies.af_inet
,
231 new NativeSocketTypes.sock_stream
, new NativeSocketProtocolFamilies.pf_unspec
)
232 assert not native
.address_is_null
233 if not native
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.reuseaddr
, 1) then
238 addrin
= new NativeSocketAddrIn
239 addrin
.family
= new NativeSocketAddressFamilies.af_inet
243 address
= addrin
.address
.to_s
249 # Associates the socket to a local address and port
251 # Returns whether the socket has been be bound.
252 private fun bind
: Bool do
253 return native
.bind
(addrin
) >= 0
256 # Sets the socket as ready to accept incoming connections, `size` is the maximum number of queued clients
258 # Returns `true` if the socket could be set, `false` otherwise
259 fun listen
(size
: Int): Bool do
260 return native
.listen
(size
) >= 0
263 # Accepts an incoming connection from a client
265 # Create and return a new socket to the client. May return null if not
266 # `blocking` and there's no waiting clients, or upon an interruption
267 # (whether `blocking` or not).
269 # Require: not closed
270 fun accept
: nullable TCPStream
273 var native
= native
.accept
274 if native
== null then return null
275 return new TCPStream.server_side
(native
)
281 # FIXME unify with `SocketStream::close` when we can use qualified names
283 if closed
then return
284 if native
.close
>= 0 then
290 # A simple set of sockets used by `SocketObserver`
292 private var native
= new NativeSocketSet
296 # Add `socket` to this set
297 fun add
(socket
: Socket) do native
.set
(socket
.native
)
299 # Remove `socket` from this set
300 fun remove
(socket
: Socket) do native
.clear
(socket
.native
)
302 # Does this set has `socket`?
303 fun has
(socket
: Socket): Bool do return native
.is_set
(socket
.native
)
305 # Clear all sockets from this set
306 fun clear
do native
.zero
309 # Service class to manage calls to `select`
311 private var native
= new NativeSocketObserver
313 # Set of file descriptors on which to watch read events
314 var read_set
: nullable SocketSet = null
316 # Set of file descriptors on which to watch write events
317 var write_set
: nullable SocketSet = null
319 # Set of file descriptors on which to watch exception events
320 var except_set
: nullable SocketSet = null
322 # Initialize a socket observer
323 init with_sets
(read
: Bool, write
: Bool, except
: Bool) do
324 if read
then read_set
= new SocketSet
325 if write
then write_set
= new SocketSet
326 if except
then except_set
= new SocketSet
329 # Watch for changes in the states of several sockets.
330 fun select
(max
: Socket, seconds
: Int, microseconds
: Int): Bool
332 # FIXME this implementation (see the call to nullable attributes below) and
333 # `NativeSockectObserver::select` is not stable.
335 var timeval
= new NativeTimeval(seconds
, microseconds
)
336 var rd
= if read_set
!= null then read_set
.as(not null).native
else null
337 var wrt
= if write_set
!= null then write_set
.as(not null).native
else null
338 var expt
= if except_set
!= null then except_set
.as(not null).native
else null
339 return native
.select
(max
.native
, rd
, wrt
, expt
, timeval
) > 0
343 # Socket over UDP, sends and receive data without the need for a connection
347 # Last error raised by this socket
348 var error
: nullable Error = null
350 init do native
= new NativeSocket.socket
(
351 new NativeSocketAddressFamilies.af_inet
,
352 new NativeSocketTypes.sock_dgram
,
353 new NativeSocketProtocolFamilies.pf_unspec
)
355 # Bind this socket to an `address`, on `port` (to all addresses if `null`)
357 # On error, sets `error` appropriately.
358 fun bind
(address
: nullable Text, port
: Int)
360 var addr_in
= new NativeSocketAddrIn
362 if address
!= null then
363 # FIXME replace all use of gethostbyname with something not obsolete
364 var hostent
= sys
.gethostbyname
(address
.to_cstring
)
365 if hostent
.address_is_null
then
366 error
= new IOError.from_h_errno
371 addr_in
.fill_from_hostent hostent
373 addr_in
.family
= new NativeSocketAddressFamilies.af_inet
377 if native
.bind
(addr_in
) != 0 then error
= new IOError.from_errno
382 # Receive `length` bytes of data from any sender
384 # On error, returns an empty string and sets `error` appropriately.
385 fun recv
(length
: Int): String
387 var buf
= new CString(length
)
388 var len
= native
.recvfrom
(buf
, length
, 0, new NativeSocketAddrIn.nul
)
390 error
= new IOError.from_errno
393 return buf
.to_s_unsafe
(len
, copy
=false)
396 # Receive `length` bytes of data from any sender and store the sender info in `sender.item`
398 # On error, returns an empty string and sets `error` appropriately.
399 fun recv_from
(length
: Int, sender
: Ref[nullable SocketAddress]): String
401 var src
= new NativeSocketAddrIn
402 var buf
= new CString(length
)
404 var len
= native
.recvfrom
(buf
, length
, 0, src
)
406 error
= new IOError.from_errno
411 sender
.item
= new SocketAddress(src
)
412 return buf
.to_s_unsafe
(len
, copy
=false)
415 # Send `data` to `dest_address` on `port`
417 # On error, sets `error` appropriately.
418 fun send_to
(dest_address
: Text, port
: Int, data
: Text)
420 var hostent
= sys
.gethostbyname
(dest_address
.to_cstring
)
421 if hostent
.address_is_null
then
422 error
= new IOError.from_h_errno
426 var dest
= new NativeSocketAddrIn
427 dest
.fill_from_hostent hostent
429 native
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.broadcast
, 1)
431 var buf
= data
.to_cstring
432 if native
.sendto
(buf
, data
.length
, 0, dest
) == -1 then
433 error
= new IOError.from_errno
438 # Enable broadcasting for this socket
440 # On error, sets `error` appropriately.
441 fun enable_broadcast
=(value
: Bool) do
442 var res
= native
.setsockopt
(new NativeSocketOptLevels.socket
, new NativeSocketOptNames.broadcast
, value
.to_i
)
443 if res
== -1 then error
= new IOError.from_errno
446 # Broadcast `data` on the network on `port`
448 # On error, sets `error` appropriately.
450 # Require: setting `enable_broadcast = true`
451 fun broadcast
(port
: Int, data
: Text)
453 var addr_in
= new NativeSocketAddrIn
455 addr_in
.family
= new NativeSocketAddressFamilies.af_inet
456 addr_in
.address_broadcast
458 var buf
= data
.to_cstring
459 if native
.sendto
(buf
, data
.length
, 0, addr_in
) == -1 then
460 error
= new IOError.from_errno
467 # Address of a socket in the Internet namespace
469 # Used in one of the out parameters of `UDPSocket::recv_from`.
471 super FinalizableOnce
473 # FIXME make init private
475 private var native
: NativeSocketAddrIn
479 address
= native
.address
.to_s
484 var address
: String is noinit
487 var port
: Int is noinit
489 redef fun ==(o
) do return o
isa SocketAddress and o
.address
== address
and o
.port
== port
491 redef fun finalize_once
do native
.free
495 # Fill a new `IOError` from the message of `errno`
496 init from_errno
do init errno
.strerror
498 # Fill a new `IOError` from the message of `h_errno`
500 # Used with `gethostbyname`.
501 init from_h_errno
do init h_errno
.to_s