summaryrefslogtreecommitdiff
path: root/test/socket
diff options
context:
space:
mode:
Diffstat (limited to 'test/socket')
-rw-r--r--test/socket/test_addrinfo.rb710
-rw-r--r--test/socket/test_ancdata.rb68
-rw-r--r--test/socket/test_basicsocket.rb228
-rw-r--r--test/socket/test_nonblock.rb278
-rw-r--r--test/socket/test_socket.rb1132
-rw-r--r--test/socket/test_sockopt.rb80
-rw-r--r--test/socket/test_tcp.rb426
-rw-r--r--test/socket/test_udp.rb94
-rw-r--r--test/socket/test_unix.rb827
9 files changed, 3670 insertions, 173 deletions
diff --git a/test/socket/test_addrinfo.rb b/test/socket/test_addrinfo.rb
new file mode 100644
index 0000000000..0c9529090e
--- /dev/null
+++ b/test/socket/test_addrinfo.rb
@@ -0,0 +1,710 @@
+# frozen_string_literal: true
+
+begin
+ require "socket"
+rescue LoadError
+end
+
+require "test/unit"
+
+class TestSocketAddrinfo < Test::Unit::TestCase
+ HAS_UNIXSOCKET = defined?(UNIXSocket) && /cygwin/ !~ RUBY_PLATFORM
+
+ def tcp_unspecified_to_loopback(addrinfo)
+ if addrinfo.ipv4? && addrinfo.ip_address == "0.0.0.0"
+ Addrinfo.tcp("127.0.0.1", addrinfo.ip_port)
+ elsif addrinfo.ipv6? && addrinfo.ipv6_unspecified?
+ Addrinfo.tcp("::1", addrinfo.ip_port)
+ elsif addrinfo.ipv6? && (ai = addrinfo.ipv6_to_ipv4) && ai.ip_address == "0.0.0.0"
+ Addrinfo.tcp("127.0.0.1", addrinfo.ip_port)
+ else
+ addrinfo
+ end
+ end
+
+ def test_addrinfo_ip
+ ai = Addrinfo.ip("127.0.0.1")
+ assert_equal([0, "127.0.0.1"], Socket.unpack_sockaddr_in(ai))
+ assert_equal(Socket::AF_INET, ai.afamily)
+ assert_equal(Socket::PF_INET, ai.pfamily)
+ assert_equal(0, ai.socktype)
+ assert_equal(0, ai.protocol)
+
+ ai = Addrinfo.ip("<any>")
+ assert_equal([0, "0.0.0.0"], Socket.unpack_sockaddr_in(ai))
+
+ ai = Addrinfo.ip("<broadcast>")
+ assert_equal([0, "255.255.255.255"], Socket.unpack_sockaddr_in(ai))
+
+ ai = assert_nothing_raised(SocketError) do
+ base_str = "127.0.0.1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ addr = base_str[0, 9]
+ Addrinfo.ip(addr)
+ end
+ assert_equal([0, "127.0.0.1"], Socket.unpack_sockaddr_in(ai))
+ assert_raise(ArgumentError) do
+ Addrinfo.ip("127.0.0.1\000x")
+ end
+ end
+
+ def test_addrinfo_tcp
+ ai = Addrinfo.tcp("127.0.0.1", 80)
+ assert_equal([80, "127.0.0.1"], Socket.unpack_sockaddr_in(ai))
+ assert_equal(Socket::AF_INET, ai.afamily)
+ assert_equal(Socket::PF_INET, ai.pfamily)
+ assert_equal(Socket::SOCK_STREAM, ai.socktype)
+ assert_include([0, Socket::IPPROTO_TCP], ai.protocol)
+
+ ai = assert_nothing_raised(SocketError) do
+ Addrinfo.tcp("127.0.0.1", "0000000000000000000000080x".chop)
+ end
+ assert_equal([80, "127.0.0.1"], Socket.unpack_sockaddr_in(ai))
+ assert_raise(ArgumentError) do
+ Addrinfo.ip("127.0.0.1", "80\000x")
+ end
+ end
+
+ def test_addrinfo_udp
+ ai = Addrinfo.udp("127.0.0.1", 80)
+ assert_equal([80, "127.0.0.1"], Socket.unpack_sockaddr_in(ai))
+ assert_equal(Socket::AF_INET, ai.afamily)
+ assert_equal(Socket::PF_INET, ai.pfamily)
+ assert_equal(Socket::SOCK_DGRAM, ai.socktype)
+ assert_include([0, Socket::IPPROTO_UDP], ai.protocol)
+ end
+
+ def test_addrinfo_ip_unpack
+ ai = Addrinfo.tcp("127.0.0.1", 80)
+ assert_equal(["127.0.0.1", 80], ai.ip_unpack)
+ assert_equal("127.0.0.1", ai.ip_address)
+ assert_equal(80, ai.ip_port)
+ end
+
+ def test_addrinfo_inspect_sockaddr
+ ai = Addrinfo.tcp("127.0.0.1", 80)
+ assert_equal("127.0.0.1:80", ai.inspect_sockaddr)
+ end
+
+ def test_addrinfo_new_inet
+ ai = Addrinfo.new(["AF_INET", 46102, "localhost.localdomain", "127.0.0.2"])
+ assert_equal([46102, "127.0.0.2"], Socket.unpack_sockaddr_in(ai))
+ assert_equal(Socket::AF_INET, ai.afamily)
+ assert_equal(Socket::PF_INET, ai.pfamily)
+ assert_equal(0, ai.socktype)
+ assert_equal(0, ai.protocol)
+ end
+
+ def test_addrinfo_predicates
+ ipv4_ai = Addrinfo.new(Socket.sockaddr_in(80, "192.168.0.1"))
+ assert(ipv4_ai.ip?)
+ assert(ipv4_ai.ipv4?)
+ assert(!ipv4_ai.ipv6?)
+ assert(!ipv4_ai.unix?)
+ end
+
+ def test_error_message
+ e = assert_raise_with_message(Socket::ResolutionError, /getaddrinfo/) do
+ Addrinfo.ip("...")
+ end
+ m = e.message
+ assert_not_equal([false, Encoding::ASCII_8BIT], [m.ascii_only?, m.encoding], proc {m.inspect})
+ end
+
+ def test_ipv4_address_predicates
+ list = [
+ [:ipv4_private?, "10.0.0.0", "10.255.255.255",
+ "172.16.0.0", "172.31.255.255",
+ "192.168.0.0", "192.168.255.255"],
+ [:ipv4_loopback?, "127.0.0.1", "127.0.0.0", "127.255.255.255"],
+ [:ipv4_multicast?, "224.0.0.0", "224.255.255.255"]
+ ]
+ list.each {|meth, *addrs|
+ addrs.each {|addr|
+ assert(Addrinfo.ip(addr).send(meth), "Addrinfo.ip(#{addr.inspect}).#{meth}")
+ list.each {|meth2,|
+ next if meth == meth2
+ assert(!Addrinfo.ip(addr).send(meth2), "!Addrinfo.ip(#{addr.inspect}).#{meth2}")
+ }
+ }
+ }
+ end
+
+ def test_basicsocket_send
+ s1 = Socket.new(:INET, :DGRAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ sa = s1.getsockname
+ ai = Addrinfo.new(sa)
+ s2 = Socket.new(:INET, :DGRAM, 0)
+ s2.send("test-basicsocket-send", 0, ai)
+ assert_equal("test-basicsocket-send", s1.recv(100))
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ end
+
+ def test_udpsocket_send
+ s1 = UDPSocket.new
+ s1.bind("127.0.0.1", 0)
+ ai = Addrinfo.new(s1.getsockname)
+ s2 = UDPSocket.new
+ s2.send("test-udp-send", 0, ai)
+ assert_equal("test-udp-send", s1.recv(100))
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ end
+
+ def test_socket_bind
+ s1 = Socket.new(:INET, :DGRAM, 0)
+ sa = Socket.sockaddr_in(0, "127.0.0.1")
+ ai = Addrinfo.new(sa)
+ s1.bind(ai)
+ s2 = UDPSocket.new
+ s2.send("test-socket-bind", 0, s1.getsockname)
+ assert_equal("test-socket-bind", s1.recv(100))
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ end
+
+ def test_socket_connect
+ s1 = Socket.new(:INET, :STREAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s1.listen(5)
+ ai = Addrinfo.new(s1.getsockname)
+ s2 = Socket.new(:INET, :STREAM, 0)
+ s2.connect(ai)
+ s3, _ = s1.accept
+ s2.send("test-socket-connect", 0)
+ assert_equal("test-socket-connect", s3.recv(100))
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ s3.close if s3 && !s3.closed?
+ end
+
+ def test_socket_connect_nonblock
+ s1 = Socket.new(:INET, :STREAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s1.listen(5)
+ ai = Addrinfo.new(s1.getsockname)
+ s2 = Socket.new(:INET, :STREAM, 0)
+ begin
+ s2.connect_nonblock(ai)
+ rescue IO::WaitWritable
+ IO.select(nil, [s2])
+ r = s2.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR)
+ assert_equal(0, r.int, "NOERROR is expected but #{r.inspect}")
+ begin
+ s2.connect_nonblock(ai)
+ rescue Errno::EISCONN
+ end
+ end
+ s3, _ = s1.accept
+ s2.send("test-socket-connect-nonblock", 0)
+ assert_equal("test-socket-connect-nonblock", s3.recv(100))
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ s3.close if s3 && !s3.closed?
+ end
+
+ def test_socket_getnameinfo
+ ai = Addrinfo.udp("127.0.0.1", 8888)
+ assert_equal(["127.0.0.1", "8888"], Socket.getnameinfo(ai, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV))
+ end
+
+ def test_basicsocket_local_address
+ s1 = Socket.new(:INET, :DGRAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ e = Socket.unpack_sockaddr_in(s1.getsockname)
+ a = Socket.unpack_sockaddr_in(s1.local_address.to_sockaddr)
+ assert_equal(e, a)
+ assert_equal(Socket::AF_INET, s1.local_address.afamily)
+ assert_equal(Socket::PF_INET, s1.local_address.pfamily)
+ assert_equal(Socket::SOCK_DGRAM, s1.local_address.socktype)
+ ensure
+ s1.close if s1 && !s1.closed?
+ end
+
+ def test_basicsocket_remote_address
+ s1 = TCPServer.new("127.0.0.1", 0)
+ s2 = Socket.new(:INET, :STREAM, 0)
+ s2.connect(s1.getsockname)
+ s3, _ = s1.accept
+ e = Socket.unpack_sockaddr_in(s2.getsockname)
+ a = Socket.unpack_sockaddr_in(s3.remote_address.to_sockaddr)
+ assert_equal(e, a)
+ assert_equal(Socket::AF_INET, s3.remote_address.afamily)
+ assert_equal(Socket::PF_INET, s3.remote_address.pfamily)
+ assert_equal(Socket::SOCK_STREAM, s3.remote_address.socktype)
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ s3.close if s3 && !s3.closed?
+ end
+
+ def test_socket_accept
+ serv = Socket.new(:INET, :STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ c = Socket.new(:INET, :STREAM, 0)
+ c.connect(serv.local_address)
+ ret = serv.accept
+ s, ai = ret
+ assert_kind_of(Array, ret)
+ assert_equal(2, ret.length)
+ assert_kind_of(Addrinfo, ai)
+ e = Socket.unpack_sockaddr_in(c.getsockname)
+ a = Socket.unpack_sockaddr_in(ai.to_sockaddr)
+ assert_equal(e, a)
+ ensure
+ serv.close if serv && !serv.closed?
+ s.close if s && !s.closed?
+ c.close if c && !c.closed?
+ end
+
+ def test_socket_accept_nonblock
+ serv = Socket.new(:INET, :STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ c = Socket.new(:INET, :STREAM, 0)
+ c.connect(serv.local_address)
+ begin
+ ret = serv.accept_nonblock
+ rescue IO::WaitReadable, Errno::EINTR
+ IO.select([serv])
+ retry
+ end
+ s, ai = ret
+ assert_kind_of(Array, ret)
+ assert_equal(2, ret.length)
+ assert_kind_of(Addrinfo, ai)
+ e = Socket.unpack_sockaddr_in(c.getsockname)
+ a = Socket.unpack_sockaddr_in(ai.to_sockaddr)
+ assert_equal(e, a)
+ ensure
+ serv.close if serv && !serv.closed?
+ s.close if s && !s.closed?
+ c.close if c && !c.closed?
+ end
+
+ def test_socket_sysaccept
+ serv = Socket.new(:INET, :STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ c = Socket.new(:INET, :STREAM, 0)
+ c.connect(serv.local_address)
+ ret = serv.sysaccept
+ fd, ai = ret
+ s = IO.new(fd)
+ assert_kind_of(Array, ret)
+ assert_equal(2, ret.length)
+ assert_kind_of(Addrinfo, ai)
+ e = Socket.unpack_sockaddr_in(c.getsockname)
+ a = Socket.unpack_sockaddr_in(ai.to_sockaddr)
+ assert_equal(e, a)
+ ensure
+ serv.close if serv && !serv.closed?
+ s.close if s && !s.closed?
+ c.close if c && !c.closed?
+ end
+
+ def test_socket_recvfrom
+ s1 = Socket.new(:INET, :DGRAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s2 = Socket.new(:INET, :DGRAM, 0)
+ s2.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s2.send("test-socket-recvfrom", 0, s1.getsockname)
+ data, ai = s1.recvfrom(100)
+ assert_equal("test-socket-recvfrom", data)
+ assert_kind_of(Addrinfo, ai)
+ e = Socket.unpack_sockaddr_in(s2.getsockname)
+ a = Socket.unpack_sockaddr_in(ai.to_sockaddr)
+ assert_equal(e, a)
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ end
+
+ def test_socket_recvfrom_nonblock
+ s1 = Socket.new(:INET, :DGRAM, 0)
+ s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s2 = Socket.new(:INET, :DGRAM, 0)
+ s2.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ s2.send("test-socket-recvfrom", 0, s1.getsockname)
+ begin
+ data, ai = s1.recvfrom_nonblock(100)
+ rescue IO::WaitReadable
+ IO.select([s1])
+ retry
+ end
+ assert_equal("test-socket-recvfrom", data)
+ assert_kind_of(Addrinfo, ai)
+ e = Socket.unpack_sockaddr_in(s2.getsockname)
+ a = Socket.unpack_sockaddr_in(ai.to_sockaddr)
+ assert_equal(e, a)
+ ensure
+ s1.close if s1 && !s1.closed?
+ s2.close if s2 && !s2.closed?
+ end
+
+ def test_family_addrinfo
+ ai = Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("127.0.0.1", 80)
+ assert_equal(["127.0.0.1", 80], ai.ip_unpack)
+ assert_equal(Socket::SOCK_STREAM, ai.socktype)
+ return unless Addrinfo.respond_to?(:unix)
+ ai = Addrinfo.unix("/testdir/sock").family_addrinfo("/testdir/sock2")
+ assert_equal("/testdir/sock2", ai.unix_path)
+ assert_equal(Socket::SOCK_STREAM, ai.socktype)
+ assert_raise(Socket::ResolutionError) { Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("::1", 80) }
+ end
+
+ def test_ractor_shareable
+ assert_ractor(<<~'RUBY', require: 'socket', timeout: 60)
+ Ractor.make_shareable Addrinfo.new "\x10\x02\x14\xE9\xE0\x00\x00\xFB\x00\x00\x00\x00\x00\x00\x00\x00".b
+ RUBY
+ end
+
+ def random_port
+ # IANA suggests dynamic port for 49152 to 65535
+ # http://www.iana.org/assignments/port-numbers
+ case RUBY_PLATFORM
+ when /mingw|mswin/
+ rand(50000..65535)
+ else
+ rand(49152..65535)
+ end
+ end
+
+ def errors_addrinuse
+ errs = [Errno::EADDRINUSE]
+ # Windows fails with "Errno::EACCES: Permission denied - bind(2) for 0.0.0.0:49721"
+ errs << Errno::EACCES if /mingw|mswin/ =~ RUBY_PLATFORM
+ errs
+ end
+
+ def test_connect_from
+ TCPServer.open("0.0.0.0", 0) {|serv|
+ serv_ai = Addrinfo.new(serv.getsockname, :INET, :STREAM)
+ serv_ai = tcp_unspecified_to_loopback(serv_ai)
+ port = random_port
+ begin
+ serv_ai.connect_from("0.0.0.0", port) {|s1|
+ s2 = serv.accept
+ begin
+ assert_equal(port, s2.remote_address.ip_port)
+ ensure
+ s2.close
+ end
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ }
+
+ TCPServer.open("0.0.0.0", 0) {|serv|
+ serv_ai = Addrinfo.new(serv.getsockname, :INET, :STREAM)
+ serv_ai = tcp_unspecified_to_loopback(serv_ai)
+ port = random_port
+ begin
+ serv_ai.connect_from(Addrinfo.tcp("0.0.0.0", port)) {|s1|
+ s2 = serv.accept
+ begin
+ assert_equal(port, s2.remote_address.ip_port)
+ ensure
+ s2.close
+ end
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ }
+ end
+
+ def test_connect_to
+ TCPServer.open("0.0.0.0", 0) {|serv|
+ serv_ai = Addrinfo.new(serv.getsockname, :INET, :STREAM)
+ serv_ai = tcp_unspecified_to_loopback(serv_ai)
+ port = random_port
+ client_ai = Addrinfo.tcp("0.0.0.0", port)
+ begin
+ client_ai.connect_to(*serv_ai.ip_unpack) {|s1|
+ s2 = serv.accept
+ begin
+ assert_equal(port, s2.remote_address.ip_port)
+ ensure
+ s2.close
+ end
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ }
+ end
+
+ def test_connect
+ TCPServer.open("0.0.0.0", 0) {|serv|
+ serv_ai = Addrinfo.new(serv.getsockname, :INET, :STREAM)
+ serv_ai = tcp_unspecified_to_loopback(serv_ai)
+ begin
+ serv_ai.connect {|s1|
+ s2 = serv.accept
+ begin
+ assert_equal(s1.local_address.ip_unpack, s2.remote_address.ip_unpack)
+ assert_equal(s2.local_address.ip_unpack, s1.remote_address.ip_unpack)
+ ensure
+ s2.close
+ end
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ }
+ end
+
+ def test_bind
+ port = random_port
+ client_ai = Addrinfo.tcp("0.0.0.0", port)
+ begin
+ client_ai.bind {|s|
+ assert_equal(port, s.local_address.ip_port)
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ end
+
+ def test_listen
+ port = random_port
+ client_ai = Addrinfo.tcp("0.0.0.0", port)
+ begin
+ client_ai.listen {|serv|
+ assert_equal(port, serv.local_address.ip_port)
+ serv_addr, serv_port = serv.local_address.ip_unpack
+ case serv_addr
+ when "0.0.0.0" then serv_addr = "127.0.0.1"
+ end
+ TCPSocket.open(serv_addr, serv_port) {|s1|
+ s2, addr = serv.accept
+ begin
+ assert_equal(s1.local_address.ip_unpack, addr.ip_unpack)
+ ensure
+ s2.close
+ end
+ }
+ }
+ rescue *errors_addrinuse
+ # not test failure
+ end
+ end
+
+ def test_s_foreach
+ Addrinfo.foreach(nil, 80, nil, :STREAM) {|ai|
+ assert_kind_of(Addrinfo, ai)
+ }
+ end
+
+ def test_marshal
+ ai1 = Addrinfo.tcp("127.0.0.1", 80)
+ ai2 = Marshal.load(Marshal.dump(ai1))
+ assert_equal(ai1.afamily, ai2.afamily)
+ assert_equal(ai1.ip_unpack, ai2.ip_unpack)
+ assert_equal(ai1.pfamily, ai2.pfamily)
+ assert_equal(ai1.socktype, ai2.socktype)
+ assert_equal(ai1.protocol, ai2.protocol)
+ assert_equal(ai1.canonname, ai2.canonname)
+ end
+
+ def test_marshal_memory_leak
+ bug11051 = '[ruby-dev:48923] [Bug #11051]'
+ assert_no_memory_leak(%w[-rsocket], <<-PREP, <<-CODE, bug11051, rss: true)
+ d = Marshal.dump(Addrinfo.tcp("127.0.0.1", 80))
+ 1000.times {Marshal.load(d)}
+ PREP
+ GC.start
+ 20_000.times {Marshal.load(d)}
+ CODE
+ end
+
+ if Socket.const_defined?("AF_INET6") && Socket::AF_INET6.is_a?(Integer)
+
+ def test_addrinfo_new_inet6
+ ai = Addrinfo.new(["AF_INET6", 42304, "ip6-localhost", "::1"])
+ assert_equal([42304, "::1"], Socket.unpack_sockaddr_in(ai))
+ assert_equal(Socket::AF_INET6, ai.afamily)
+ assert_equal(Socket::PF_INET6, ai.pfamily)
+ assert_equal(0, ai.socktype)
+ assert_equal(0, ai.protocol)
+ end
+
+ def test_addrinfo_ip_unpack_inet6
+ ai = Addrinfo.tcp("::1", 80)
+ assert_equal(["::1", 80], ai.ip_unpack)
+ assert_equal("::1", ai.ip_address)
+ assert_equal(80, ai.ip_port)
+ end
+
+ def test_addrinfo_inspect_sockaddr_inet6
+ ai = Addrinfo.tcp("::1", 80)
+ assert_equal("[::1]:80", ai.inspect_sockaddr)
+ end
+
+ def test_marshal_inet6
+ ai1 = Addrinfo.tcp("::1", 80)
+ ai2 = Marshal.load(Marshal.dump(ai1))
+ assert_equal(ai1.afamily, ai2.afamily)
+ assert_equal(ai1.ip_unpack, ai2.ip_unpack)
+ assert_equal(ai1.pfamily, ai2.pfamily)
+ assert_equal(ai1.socktype, ai2.socktype)
+ assert_equal(ai1.protocol, ai2.protocol)
+ assert_equal(ai1.canonname, ai2.canonname)
+ end
+
+ def ipv6(str)
+ Addrinfo.getaddrinfo(str, nil, :INET6, :DGRAM).fetch(0)
+ end
+
+ def test_ipv6_address_predicates
+ list = [
+ [:ipv6_unspecified?, "::"],
+ [:ipv6_loopback?, "::1"],
+ [:ipv6_v4compat?, "::0.0.0.2", "::255.255.255.255"],
+ [:ipv6_v4mapped?, "::ffff:0.0.0.0", "::ffff:255.255.255.255"],
+ [:ipv6_linklocal?, "fe80::", "febf::"],
+ [:ipv6_sitelocal?, "fec0::", "feef::"],
+ [:ipv6_multicast?, "ff00::", "ffff::"],
+ [:ipv6_unique_local?, "fc00::", "fd00::"],
+ ]
+ mlist = [
+ [:ipv6_mc_nodelocal?, "ff01::", "ff11::"],
+ [:ipv6_mc_linklocal?, "ff02::", "ff12::"],
+ [:ipv6_mc_sitelocal?, "ff05::", "ff15::"],
+ [:ipv6_mc_orglocal?, "ff08::", "ff18::"],
+ [:ipv6_mc_global?, "ff0e::", "ff1e::"]
+ ]
+ list.each {|meth, *addrs|
+ addrs.each {|addr|
+ addr_exp = "Addrinfo.getaddrinfo(#{addr.inspect}, nil, :INET6, :DGRAM).fetch(0)"
+ if meth == :ipv6_v4compat? || meth == :ipv6_v4mapped?
+ # MacOS X returns IPv4 address for ::ffff:1.2.3.4 and ::1.2.3.4.
+ # Solaris returns IPv4 address for ::ffff:1.2.3.4.
+ ai = ipv6(addr)
+ begin
+ assert(ai.ipv4? || ai.send(meth), "ai=#{addr_exp}; ai.ipv4? || .#{meth}")
+ rescue Test::Unit::AssertionFailedError
+ if /aix/ =~ RUBY_PLATFORM
+ omit "Known bug in IN6_IS_ADDR_V4COMPAT and IN6_IS_ADDR_V4MAPPED on AIX"
+ end
+ raise $!
+ end
+ else
+ assert(ipv6(addr).send(meth), "#{addr_exp}.#{meth}")
+ assert_equal(addr, ipv6(addr).ip_address)
+ end
+ list.each {|meth2,|
+ next if meth == meth2
+ assert(!ipv6(addr).send(meth2), "!#{addr_exp}.#{meth2}")
+ }
+ }
+ }
+ mlist.each {|meth, *addrs|
+ addrs.each {|addr|
+ addr_exp = "Addrinfo.getaddrinfo(#{addr.inspect}, nil, :INET6, :DGRAM).fetch(0)"
+ assert(ipv6(addr).send(meth), "#{addr_exp}.#{meth}")
+ assert(ipv6(addr).ipv6_multicast?, "#{addr_exp}.ipv6_multicast?")
+ mlist.each {|meth2,|
+ next if meth == meth2
+ assert(!ipv6(addr).send(meth2), "!#{addr_exp}.#{meth2}")
+ }
+ list.each {|meth2,|
+ next if :ipv6_multicast? == meth2
+ assert(!ipv6(addr).send(meth2), "!#{addr_exp}.#{meth2}")
+ }
+ }
+ }
+ end
+
+ def test_ipv6_to_ipv4
+ ai = Addrinfo.ip("::192.0.2.3")
+ ai = ai.ipv6_to_ipv4 if !ai.ipv4?
+ assert(ai.ipv4?)
+ assert_equal("192.0.2.3", ai.ip_address)
+
+ ai = Addrinfo.ip("::ffff:192.0.2.3")
+ ai = ai.ipv6_to_ipv4 if !ai.ipv4?
+ assert(ai.ipv4?)
+ assert_equal("192.0.2.3", ai.ip_address)
+
+ assert_nil(Addrinfo.ip("::1").ipv6_to_ipv4)
+ assert_nil(Addrinfo.ip("192.0.2.3").ipv6_to_ipv4)
+ if HAS_UNIXSOCKET
+ assert_nil(Addrinfo.unix("/testdir/sock").ipv6_to_ipv4)
+ end
+ end
+ end
+
+ if HAS_UNIXSOCKET
+
+ def test_addrinfo_unix
+ ai = Addrinfo.unix("/testdir/sock")
+ assert_equal("/testdir/sock", Socket.unpack_sockaddr_un(ai))
+ assert_equal(Socket::AF_UNIX, ai.afamily)
+ assert_equal(Socket::PF_UNIX, ai.pfamily)
+ assert_equal(Socket::SOCK_STREAM, ai.socktype)
+ assert_equal(0, ai.protocol)
+ end
+
+ def test_addrinfo_unix_dgram
+ ai = Addrinfo.unix("/testdir/sock", :DGRAM)
+ assert_equal("/testdir/sock", Socket.unpack_sockaddr_un(ai))
+ assert_equal(Socket::AF_UNIX, ai.afamily)
+ assert_equal(Socket::PF_UNIX, ai.pfamily)
+ assert_equal(Socket::SOCK_DGRAM, ai.socktype)
+ assert_equal(0, ai.protocol)
+ end
+
+ def test_addrinfo_unix_path
+ ai = Addrinfo.unix("/testdir/sock1")
+ assert_equal("/testdir/sock1", ai.unix_path)
+ end
+
+ def test_addrinfo_inspect_sockaddr_unix
+ ai = Addrinfo.unix("/testdir/test_addrinfo_inspect_sockaddr_unix")
+ assert_equal("/testdir/test_addrinfo_inspect_sockaddr_unix", ai.inspect_sockaddr)
+ end
+
+ def test_addrinfo_new_unix
+ ai = Addrinfo.new(["AF_UNIX", "/testdir/sock"])
+ assert_equal("/testdir/sock", Socket.unpack_sockaddr_un(ai))
+ assert_equal(Socket::AF_UNIX, ai.afamily)
+ assert_equal(Socket::PF_UNIX, ai.pfamily)
+ assert_equal(Socket::SOCK_STREAM, ai.socktype) # UNIXSocket/UNIXServer is SOCK_STREAM only.
+ assert_equal(0, ai.protocol)
+ end
+
+ def test_addrinfo_predicates_unix
+ unix_ai = Addrinfo.new(Socket.sockaddr_un("/testdir/sososo"))
+ assert(!unix_ai.ip?)
+ assert(!unix_ai.ipv4?)
+ assert(!unix_ai.ipv6?)
+ assert(unix_ai.unix?)
+ end
+
+ def test_marshal_unix
+ ai1 = Addrinfo.unix("/testdir/sock")
+ ai2 = Marshal.load(Marshal.dump(ai1))
+ assert_equal(ai1.afamily, ai2.afamily)
+ assert_equal(ai1.unix_path, ai2.unix_path)
+ assert_equal(ai1.pfamily, ai2.pfamily)
+ assert_equal(ai1.socktype, ai2.socktype)
+ assert_equal(ai1.protocol, ai2.protocol)
+ assert_equal(ai1.canonname, ai2.canonname)
+ end
+
+ def test_addrinfo_timeout
+ ai = Addrinfo.getaddrinfo("localhost", "ssh", Socket::PF_INET, Socket::SOCK_STREAM, timeout: 1).fetch(0)
+ assert_equal(22, ai.ip_port)
+ end
+ end
+end
diff --git a/test/socket/test_ancdata.rb b/test/socket/test_ancdata.rb
new file mode 100644
index 0000000000..b2f86a0bb1
--- /dev/null
+++ b/test/socket/test_ancdata.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+require 'test/unit'
+require 'socket'
+
+class TestSocketAncData < Test::Unit::TestCase
+ def test_int
+ ancdata = Socket::AncillaryData.int(0, 0, 0, 123)
+ assert_equal(123, ancdata.int)
+ assert_equal([123].pack("i"), ancdata.data)
+ end
+
+ def test_ip_pktinfo
+ addr = Addrinfo.ip("127.0.0.1")
+ ifindex = 0
+ spec_dst = Addrinfo.ip("127.0.0.2")
+ begin
+ ancdata = Socket::AncillaryData.ip_pktinfo(addr, ifindex, spec_dst)
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(Socket::AF_INET, ancdata.family)
+ assert_equal(Socket::IPPROTO_IP, ancdata.level)
+ assert_equal(Socket::IP_PKTINFO, ancdata.type)
+ assert_equal(addr.ip_address, ancdata.ip_pktinfo[0].ip_address)
+ assert_equal(ifindex, ancdata.ip_pktinfo[1])
+ assert_equal(spec_dst.ip_address, ancdata.ip_pktinfo[2].ip_address)
+ assert(ancdata.cmsg_is?(:IP, :PKTINFO))
+ assert(ancdata.cmsg_is?("IP", "PKTINFO"))
+ assert(ancdata.cmsg_is?(Socket::IPPROTO_IP, Socket::IP_PKTINFO))
+ if defined? Socket::IPV6_PKTINFO
+ assert(!ancdata.cmsg_is?(:IPV6, :PKTINFO))
+ end
+ ancdata2 = Socket::AncillaryData.ip_pktinfo(addr, ifindex)
+ assert_equal(addr.ip_address, ancdata2.ip_pktinfo[2].ip_address)
+ end
+
+ def test_ipv6_pktinfo
+ addr = Addrinfo.ip("::1")
+ ifindex = 0
+ begin
+ ancdata = Socket::AncillaryData.ipv6_pktinfo(addr, ifindex)
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(Socket::AF_INET6, ancdata.family)
+ assert_equal(Socket::IPPROTO_IPV6, ancdata.level)
+ assert_equal(Socket::IPV6_PKTINFO, ancdata.type)
+ assert_equal(addr.ip_address, ancdata.ipv6_pktinfo[0].ip_address)
+ assert_equal(ifindex, ancdata.ipv6_pktinfo[1])
+ assert_equal(addr.ip_address, ancdata.ipv6_pktinfo_addr.ip_address)
+ assert_equal(ifindex, ancdata.ipv6_pktinfo_ifindex)
+ assert(ancdata.cmsg_is?(:IPV6, :PKTINFO))
+ assert(ancdata.cmsg_is?("IPV6", "PKTINFO"))
+ assert(ancdata.cmsg_is?(Socket::IPPROTO_IPV6, Socket::IPV6_PKTINFO))
+ if defined? Socket::IP_PKTINFO
+ assert(!ancdata.cmsg_is?(:IP, :PKTINFO))
+ end
+ end
+
+ if defined?(Socket::SCM_RIGHTS) && defined?(Socket::SCM_TIMESTAMP)
+ def test_unix_rights
+ assert_raise(TypeError) {
+ Socket::AncillaryData.int(:UNIX, :SOL_SOCKET, :TIMESTAMP, 1).unix_rights
+ }
+ end
+ end
+end if defined? Socket::AncillaryData
diff --git a/test/socket/test_basicsocket.rb b/test/socket/test_basicsocket.rb
new file mode 100644
index 0000000000..8c1b434a83
--- /dev/null
+++ b/test/socket/test_basicsocket.rb
@@ -0,0 +1,228 @@
+# frozen_string_literal: true
+
+begin
+ require "socket"
+ require "test/unit"
+ require "io/nonblock"
+rescue LoadError
+end
+
+class TestSocket_BasicSocket < Test::Unit::TestCase
+ def inet_stream
+ sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ yield sock
+ ensure
+ assert(sock.closed?)
+ end
+
+ def test_getsockopt
+ inet_stream do |s|
+ begin
+ n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_TYPE)
+ assert_equal([Socket::SOCK_STREAM].pack("i"), n.data)
+
+ n = s.getsockopt("SOL_SOCKET", "SO_TYPE")
+ assert_equal([Socket::SOCK_STREAM].pack("i"), n.data)
+
+ n = s.getsockopt(:SOL_SOCKET, :SO_TYPE)
+ assert_equal([Socket::SOCK_STREAM].pack("i"), n.data)
+
+ n = s.getsockopt(:SOCKET, :TYPE)
+ assert_equal([Socket::SOCK_STREAM].pack("i"), n.data)
+
+ n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR)
+ assert_equal([0].pack("i"), n.data)
+ rescue Test::Unit::AssertionFailedError
+ s.close
+ if /aix/ =~ RUBY_PLATFORM
+ omit "Known bug in getsockopt(2) on AIX"
+ end
+ raise $!
+ end
+
+ val = Object.new
+ class << val; self end.send(:define_method, :to_int) {
+ s.close
+ Socket::SO_TYPE
+ }
+ assert_raise(IOError) {
+ n = s.getsockopt(Socket::SOL_SOCKET, val)
+ }
+ end
+ end
+
+ def test_setsockopt
+ s = nil
+ linger = [0, 0].pack("ii")
+
+ val = Object.new
+ class << val; self end.send(:define_method, :to_str) {
+ s.close
+ linger
+ }
+ inet_stream do |sock|
+ s = sock
+ assert_equal(0, s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger))
+
+ assert_raise(IOError, "[ruby-dev:25039]") {
+ s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, val)
+ }
+ end
+
+ val = Object.new
+ class << val; self end.send(:define_method, :to_int) {
+ s.close
+ Socket::SO_LINGER
+ }
+ inet_stream do |sock|
+ s = sock
+ assert_raise(IOError) {
+ s.setsockopt(Socket::SOL_SOCKET, val, linger)
+ }
+ end
+ end
+
+ def test_listen
+ s = nil
+ log = Object.new
+ class << log; self end.send(:define_method, :to_int) {
+ s.close
+ 2
+ }
+ inet_stream do |sock|
+ s = sock
+ assert_raise(IOError) {
+ s.listen(log)
+ }
+ end
+ end
+
+ def socks
+ sserv = TCPServer.new('localhost', 0)
+ ssock = nil
+ t = Thread.new { ssock = sserv.accept }
+ csock = TCPSocket.new('localhost', sserv.addr[1])
+ t.join
+ yield sserv, ssock, csock
+ ensure
+ ssock.close rescue nil
+ csock.close rescue nil
+ sserv.close rescue nil
+ end
+
+ def test_close_read
+ socks do |sserv, ssock, csock|
+
+ # close_read makes subsequent reads raise IOError
+ csock.close_read
+ assert_raise(IOError) { csock.read(5) }
+
+ # close_read ignores any error from shutting down half of still-open socket
+ assert_nothing_raised { csock.close_read }
+
+ # close_read raises if socket is not open
+ assert_nothing_raised { csock.close }
+ assert_raise(IOError) { csock.close_read }
+ end
+ end
+
+ def test_close_write
+ socks do |sserv, ssock, csock|
+
+ # close_write makes subsequent writes raise IOError
+ csock.close_write
+ assert_raise(IOError) { csock.write(5) }
+
+ # close_write ignores any error from shutting down half of still-open socket
+ assert_nothing_raised { csock.close_write }
+
+ # close_write raises if socket is not open
+ assert_nothing_raised { csock.close }
+ assert_raise(IOError) { csock.close_write }
+ end
+ end
+
+ def test_for_fd
+ assert_raise(Errno::EBADF, '[ruby-core:72418] [Bug #11854]') do
+ BasicSocket.for_fd(-1)
+ end
+ inet_stream do |sock|
+ s = BasicSocket.for_fd(sock.fileno)
+ assert_instance_of BasicSocket, s
+ s.autoclose = false
+ sock.close
+ end
+ end
+
+ def test_read_write_nonblock
+ socks do |sserv, ssock, csock|
+ set_nb = true
+ buf = String.new
+ if ssock.respond_to?(:nonblock?)
+ csock.nonblock = ssock.nonblock = false
+
+ # Linux may use MSG_DONTWAIT to avoid setting O_NONBLOCK
+ if RUBY_PLATFORM.match?(/linux/) && Socket.const_defined?(:MSG_DONTWAIT)
+ set_nb = false
+ end
+ end
+ assert_equal :wait_readable, ssock.read_nonblock(1, buf, exception: false)
+ assert_equal 5, csock.write_nonblock('hello')
+ IO.select([ssock])
+ assert_same buf, ssock.read_nonblock(5, buf, exception: false)
+ assert_equal 'hello', buf
+ buf = '*' * 16384
+ n = 0
+
+ case w = csock.write_nonblock(buf, exception: false)
+ when Integer
+ n += w
+ when :wait_writable
+ break
+ end while true
+
+ assert_equal :wait_writable, w
+ assert_raise(IO::WaitWritable) { loop { csock.write_nonblock(buf) } }
+ assert_operator n, :>, 0
+ assert_not_predicate(csock, :nonblock?, '[Feature #13362]') unless set_nb
+ csock.close
+
+ case r = ssock.read_nonblock(16384, buf, exception: false)
+ when String
+ next
+ when nil
+ break
+ when :wait_readable
+ IO.select([ssock], nil, nil, 10) or
+ flunk 'socket did not become readable'
+ else
+ flunk "unexpected read_nonblock return: #{r.inspect}"
+ end while true
+
+ assert_raise(EOFError) { ssock.read_nonblock(1) }
+
+ assert_not_predicate(ssock, :nonblock?) unless set_nb
+ end
+ end
+
+ def test_read_nonblock_mix_buffered
+ socks do |sserv, ssock, csock|
+ ssock.write("hello\nworld\n")
+ assert_equal "hello\n", csock.gets
+ IO.select([csock], nil, nil, 10) or
+ flunk 'socket did not become readable'
+ assert_equal "world\n", csock.read_nonblock(8)
+ end
+ end
+
+ def test_write_nonblock_buffered
+ socks do |sserv, ssock, csock|
+ ssock.sync = false
+ ssock.write("h")
+ assert_equal :wait_readable, csock.read_nonblock(1, exception: false)
+ assert_equal 4, ssock.write_nonblock("ello")
+ ssock.close
+ assert_equal "hello", csock.read(5)
+ end
+ end
+end if defined?(BasicSocket)
diff --git a/test/socket/test_nonblock.rb b/test/socket/test_nonblock.rb
index ed6487b49f..5a4688bac3 100644
--- a/test/socket/test_nonblock.rb
+++ b/test/socket/test_nonblock.rb
@@ -1,5 +1,9 @@
+# frozen_string_literal: true
+
begin
require "socket"
+ require "io/nonblock"
+ require "io/wait"
rescue LoadError
end
@@ -7,16 +11,26 @@ require "test/unit"
require "tempfile"
require "timeout"
-class TestNonblockSocket < Test::Unit::TestCase
+class TestSocketNonblock < Test::Unit::TestCase
def test_accept_nonblock
serv = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
serv.listen(5)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { serv.accept_nonblock }
+ assert_raise(IO::WaitReadable) { serv.accept_nonblock }
+ assert_equal :wait_readable, serv.accept_nonblock(exception: false)
+ assert_raise(IO::WaitReadable) { serv.accept_nonblock(exception: true) }
c = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
c.connect(serv.getsockname)
- s, sockaddr = serv.accept_nonblock
+ begin
+ s, sockaddr = serv.accept_nonblock
+ rescue IO::WaitReadable
+ IO.select [serv]
+ s, sockaddr = serv.accept_nonblock
+ end
assert_equal(Socket.unpack_sockaddr_in(c.getsockname), Socket.unpack_sockaddr_in(sockaddr))
+ if s.respond_to?(:nonblock?)
+ assert_predicate(s, :nonblock?, 'accepted socket is non-blocking')
+ end
ensure
serv.close if serv
c.close if c
@@ -31,7 +45,7 @@ class TestNonblockSocket < Test::Unit::TestCase
servaddr = serv.getsockname
begin
c.connect_nonblock(servaddr)
- rescue Errno::EINPROGRESS
+ rescue IO::WaitWritable
IO.select nil, [c]
assert_nothing_raised {
begin
@@ -48,24 +62,49 @@ class TestNonblockSocket < Test::Unit::TestCase
s.close if s
end
+ def test_connect_nonblock_no_exception
+ serv = Socket.new(:INET, :STREAM)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ c = Socket.new(:INET, :STREAM)
+ servaddr = serv.getsockname
+ rv = c.connect_nonblock(servaddr, exception: false)
+ case rv
+ when 0
+ # some OSes return immediately on non-blocking local connect()
+ else
+ assert_equal :wait_writable, rv
+ end
+ assert_equal([ [], [c], [] ], IO.select(nil, [c], nil, 60))
+ assert_equal(0, c.connect_nonblock(servaddr, exception: false),
+ 'there should be no EISCONN error')
+ s, sockaddr = serv.accept
+ assert_equal(Socket.unpack_sockaddr_in(c.getsockname),
+ Socket.unpack_sockaddr_in(sockaddr))
+ ensure
+ serv.close if serv
+ c.close if c
+ s.close if s
+ end
+
def test_udp_recvfrom_nonblock
u1 = UDPSocket.new
u2 = UDPSocket.new
u1.bind("127.0.0.1", 0)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recvfrom_nonblock(100) }
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { u2.recvfrom_nonblock(100) }
+ assert_raise(IO::WaitReadable) { u1.recvfrom_nonblock(100) }
+ assert_raise(IO::WaitReadable, Errno::EINVAL) { u2.recvfrom_nonblock(100) }
u2.send("aaa", 0, u1.getsockname)
IO.select [u1]
mesg, inet_addr = u1.recvfrom_nonblock(100)
assert_equal(4, inet_addr.length)
assert_equal("aaa", mesg)
- af, port, host, addr = inet_addr
- u2_port, u2_addr = Socket.unpack_sockaddr_in(u2.getsockname)
+ _, port, _, _ = inet_addr
+ u2_port, _ = Socket.unpack_sockaddr_in(u2.getsockname)
assert_equal(u2_port, port)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recvfrom_nonblock(100) }
+ assert_raise(IO::WaitReadable) { u1.recvfrom_nonblock(100) }
u2.send("", 0, u1.getsockname)
assert_nothing_raised("cygwin 1.5.19 has a problem to send an empty UDP packet. [ruby-dev:28915]") {
- timeout(1) { IO.select [u1] }
+ Timeout.timeout(1) { IO.select [u1] }
}
mesg, inet_addr = u1.recvfrom_nonblock(100)
assert_equal("", mesg)
@@ -78,19 +117,29 @@ class TestNonblockSocket < Test::Unit::TestCase
u1 = UDPSocket.new
u2 = UDPSocket.new
u1.bind("127.0.0.1", 0)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recv_nonblock(100) }
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { u2.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable) { u1.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable, Errno::EINVAL) { u2.recv_nonblock(100) }
u2.send("aaa", 0, u1.getsockname)
IO.select [u1]
mesg = u1.recv_nonblock(100)
assert_equal("aaa", mesg)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { u1.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable) { u1.recv_nonblock(100) }
u2.send("", 0, u1.getsockname)
assert_nothing_raised("cygwin 1.5.19 has a problem to send an empty UDP packet. [ruby-dev:28915]") {
- timeout(1) { IO.select [u1] }
+ Timeout.timeout(1) { IO.select [u1] }
}
mesg = u1.recv_nonblock(100)
assert_equal("", mesg)
+
+ buf = "short".dup
+ out = "hello world" * 4
+ out.freeze
+ u2.send(out, 0, u1.getsockname)
+ IO.select [u1]
+ rv = u1.recv_nonblock(100, 0, buf)
+ assert_equal rv.object_id, buf.object_id
+ assert_equal out, rv
+ assert_equal out, buf
ensure
u1.close if u1
u2.close if u2
@@ -100,14 +149,14 @@ class TestNonblockSocket < Test::Unit::TestCase
s1 = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM, 0)
s1.bind(Socket.sockaddr_in(0, "127.0.0.1"))
s2 = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM, 0)
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s1.recvfrom_nonblock(100) }
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL) { s2.recvfrom_nonblock(100) }
+ assert_raise(IO::WaitReadable) { s1.recvfrom_nonblock(100) }
+ assert_raise(IO::WaitReadable, Errno::EINVAL) { s2.recvfrom_nonblock(100) }
s2.send("aaa", 0, s1.getsockname)
IO.select [s1]
- mesg, sockaddr = s1.recvfrom_nonblock(100)
+ mesg, sockaddr = s1.recvfrom_nonblock(100)
assert_equal("aaa", mesg)
- port, addr = Socket.unpack_sockaddr_in(sockaddr)
- s2_port, s2_addr = Socket.unpack_sockaddr_in(s2.getsockname)
+ port, _ = Socket.unpack_sockaddr_in(sockaddr)
+ s2_port, _ = Socket.unpack_sockaddr_in(s2.getsockname)
assert_equal(s2_port, port)
ensure
s1.close if s1
@@ -116,23 +165,56 @@ class TestNonblockSocket < Test::Unit::TestCase
def tcp_pair
serv = TCPServer.new("127.0.0.1", 0)
- af, port, host, addr = serv.addr
+ _, port, _, addr = serv.addr
c = TCPSocket.new(addr, port)
s = serv.accept
- return c, s
+ if block_given?
+ begin
+ yield c, s
+ ensure
+ c.close if !c.closed?
+ s.close if !s.closed?
+ end
+ else
+ return c, s
+ end
ensure
- serv.close if serv
+ serv.close if serv && !serv.closed?
+ end
+
+ def udp_pair
+ s1 = UDPSocket.new
+ s1.bind('127.0.0.1', 0)
+ _, port1, _, addr1 = s1.addr
+
+ s2 = UDPSocket.new
+ s2.bind('127.0.0.1', 0)
+ _, port2, _, addr2 = s2.addr
+
+ s1.connect(addr2, port2)
+ s2.connect(addr1, port1)
+
+ if block_given?
+ begin
+ yield s1, s2
+ ensure
+ s1.close if !s1.closed?
+ s2.close if !s2.closed?
+ end
+ else
+ return s1, s2
+ end
end
def test_tcp_recv_nonblock
c, s = tcp_pair
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { c.recv_nonblock(100) }
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable) { c.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable) { s.recv_nonblock(100) }
c.write("abc")
IO.select [s]
assert_equal("a", s.recv_nonblock(1))
assert_equal("bc", s.recv_nonblock(100))
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.recv_nonblock(100) }
+ assert_raise(IO::WaitReadable) { s.recv_nonblock(100) }
ensure
c.close if c
s.close if s
@@ -140,13 +222,27 @@ class TestNonblockSocket < Test::Unit::TestCase
def test_read_nonblock
c, s = tcp_pair
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { c.read_nonblock(100) }
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.read_nonblock(100) }
+ assert_raise(IO::WaitReadable) { c.read_nonblock(100) }
+ assert_raise(IO::WaitReadable) { s.read_nonblock(100) }
c.write("abc")
IO.select [s]
assert_equal("a", s.read_nonblock(1))
assert_equal("bc", s.read_nonblock(100))
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) { s.read_nonblock(100) }
+ assert_raise(IO::WaitReadable) { s.read_nonblock(100) }
+ ensure
+ c.close if c
+ s.close if s
+ end
+
+ def test_read_nonblock_no_exception
+ c, s = tcp_pair
+ assert_equal :wait_readable, c.read_nonblock(100, exception: false)
+ assert_equal :wait_readable, s.read_nonblock(100, exception: false)
+ c.write("abc")
+ IO.select [s]
+ assert_equal("a", s.read_nonblock(1, exception: false))
+ assert_equal("bc", s.read_nonblock(100, exception: false))
+ assert_equal :wait_readable, s.read_nonblock(100, exception: false)
ensure
c.close if c
s.close if s
@@ -161,7 +257,7 @@ class TestNonblockSocket < Test::Unit::TestCase
ret = c.write_nonblock(str)
assert_operator(ret, :>, 0)
loop {
- assert_raise(Errno::EAGAIN, Errno::EWOULDBLOCK) {
+ assert_raise(IO::WaitWritable) {
loop {
ret = c.write_nonblock(str)
assert_operator(ret, :>, 0)
@@ -176,4 +272,128 @@ class TestNonblockSocket < Test::Unit::TestCase
end
=end
+ def test_sendmsg_nonblock_error
+ udp_pair {|s1, s2|
+ begin
+ loop {
+ s1.sendmsg_nonblock("a" * 100000)
+ }
+ rescue NotImplementedError, Errno::ENOSYS
+ omit "sendmsg not implemented on this platform: #{$!}"
+ rescue Errno::EMSGSIZE
+ # UDP has 64K limit (if no Jumbograms). No problem.
+ rescue Errno::EWOULDBLOCK
+ assert_kind_of(IO::WaitWritable, $!)
+ end
+ }
+ end
+
+ def test_recvfrom_nonblock_no_exception
+ udp_pair do |s1, s2|
+ assert_equal :wait_readable, s1.recvfrom_nonblock(100, exception: false)
+ s2.send("aaa", 0)
+ assert_predicate s1, :wait_readable
+ mesg, inet_addr = s1.recvfrom_nonblock(100, exception: false)
+ assert_equal(4, inet_addr.length)
+ assert_equal("aaa", mesg)
+ end
+ end
+
+ if defined?(UNIXSocket) && defined?(Socket::SOCK_SEQPACKET)
+ def test_sendmsg_nonblock_seqpacket
+ buf = '*' * 4096
+ UNIXSocket.pair(:SEQPACKET) do |s1, s2|
+ assert_raise(IO::WaitWritable) do
+ loop { s1.sendmsg_nonblock(buf) }
+ end
+ end
+ rescue NotImplementedError, Errno::ENOSYS, Errno::EPROTONOSUPPORT, Errno::EPROTOTYPE
+ omit "UNIXSocket.pair(:SEQPACKET) not implemented on this platform: #{$!}"
+ end
+
+ def test_sendmsg_nonblock_no_exception
+ omit "AF_UNIX + SEQPACKET is not supported on windows" if /mswin|mingw/ =~ RUBY_PLATFORM
+
+ buf = '*' * 4096
+ UNIXSocket.pair(:SEQPACKET) do |s1, s2|
+ n = 0
+ Timeout.timeout(60) do
+ case rv = s1.sendmsg_nonblock(buf, exception: false)
+ when Integer
+ n += rv
+ when :wait_writable
+ break
+ else
+ flunk "unexpected return value: #{rv.inspect}"
+ end while true
+ assert_equal :wait_writable, rv
+ assert_operator n, :>, 0
+ end
+ end
+ rescue NotImplementedError, Errno::ENOSYS, Errno::EPROTONOSUPPORT
+ omit "UNIXSocket.pair(:SEQPACKET) not implemented on this platform: #{$!}"
+ end
+ end
+
+ def test_recvmsg_nonblock_error
+ udp_pair {|s1, s2|
+ begin
+ s1.recvmsg_nonblock(4096)
+ rescue NotImplementedError
+ omit "recvmsg not implemented on this platform."
+ rescue Errno::EWOULDBLOCK
+ assert_kind_of(IO::WaitReadable, $!)
+ end
+ assert_equal :wait_readable, s1.recvmsg_nonblock(11, exception: false)
+ }
+ end
+
+ def test_recv_nonblock_error
+ tcp_pair {|c, s|
+ begin
+ c.recv_nonblock(4096)
+ rescue Errno::EWOULDBLOCK
+ assert_kind_of(IO::WaitReadable, $!)
+ end
+ }
+ end
+
+ def test_recv_nonblock_no_exception
+ tcp_pair {|c, s|
+ assert_equal :wait_readable, c.recv_nonblock(11, exception: false)
+ s.write('HI')
+ assert_predicate c, :wait_readable
+ assert_equal 'HI', c.recv_nonblock(11, exception: false)
+ assert_equal :wait_readable, c.recv_nonblock(11, exception: false)
+ }
+ end
+
+ def test_connect_nonblock_error
+ serv = TCPServer.new("127.0.0.1", 0)
+ _, port, _, _ = serv.addr
+ c = Socket.new(:INET, :STREAM)
+ begin
+ c.connect_nonblock(Socket.sockaddr_in(port, "127.0.0.1"))
+ rescue Errno::EINPROGRESS
+ assert_kind_of(IO::WaitWritable, $!)
+ end
+ ensure
+ serv.close if serv && !serv.closed?
+ c.close if c && !c.closed?
+ end
+
+ def test_accept_nonblock_error
+ serv = Socket.new(:INET, :STREAM)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen(5)
+ begin
+ s, _ = serv.accept_nonblock
+ rescue Errno::EWOULDBLOCK
+ assert_kind_of(IO::WaitReadable, $!)
+ end
+ ensure
+ serv.close if serv && !serv.closed?
+ s.close if s && !s.closed?
+ end
+
end if defined?(Socket)
diff --git a/test/socket/test_socket.rb b/test/socket/test_socket.rb
index 78e678c96f..c42527f370 100644
--- a/test/socket/test_socket.rb
+++ b/test/socket/test_socket.rb
@@ -1,100 +1,1102 @@
+# frozen_string_literal: true
+
begin
require "socket"
+ require "tmpdir"
+ require "fcntl"
+ require "etc"
require "test/unit"
rescue LoadError
end
-class TestBasicSocket < Test::Unit::TestCase
- def inet_stream
- sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
- yield sock
+class TestSocket < Test::Unit::TestCase
+ def test_socket_new
+ begin
+ s = Socket.new(:INET, :STREAM)
+ assert_kind_of(Socket, s)
+ ensure
+ s.close
+ end
+ end
+
+ def test_socket_new_cloexec
+ return unless defined? Fcntl::FD_CLOEXEC
+ begin
+ s = Socket.new(:INET, :STREAM)
+ assert(s.close_on_exec?)
+ ensure
+ s.close
+ end
+ end
+
+ def test_unpack_sockaddr
+ sockaddr_in = Socket.sockaddr_in(80, "")
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_un(sockaddr_in) }
+ sockaddr_un = Socket.sockaddr_un("/testdir/s")
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_in(sockaddr_un) }
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_in("") }
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_un("") }
+ end if Socket.respond_to?(:sockaddr_un)
+
+ def test_sysaccept
+ serv = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ serv.listen 5
+ c = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
+ c.connect(serv.getsockname)
+ fd, peeraddr = serv.sysaccept
+ assert_equal(c.getsockname, peeraddr.to_sockaddr)
ensure
- assert_raise(IOError) {sock.close}
+ serv.close if serv
+ c.close if c
+ IO.for_fd(fd).close if fd
+ end
+
+ def test_initialize
+ Socket.open(Socket::AF_INET, Socket::SOCK_STREAM, 0) {|s|
+ s.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ addr = s.getsockname
+ assert_nothing_raised { Socket.unpack_sockaddr_in(addr) }
+ assert_raise(ArgumentError, NoMethodError) { Socket.unpack_sockaddr_un(addr) }
+ }
+ Socket.open("AF_INET", "SOCK_STREAM", 0) {|s|
+ s.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ addr = s.getsockname
+ assert_nothing_raised { Socket.unpack_sockaddr_in(addr) }
+ assert_raise(ArgumentError, NoMethodError) { Socket.unpack_sockaddr_un(addr) }
+ }
+ Socket.open(:AF_INET, :SOCK_STREAM, 0) {|s|
+ s.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ addr = s.getsockname
+ assert_nothing_raised { Socket.unpack_sockaddr_in(addr) }
+ assert_raise(ArgumentError, NoMethodError) { Socket.unpack_sockaddr_un(addr) }
+ }
+ end
+
+ def test_bind
+ Socket.open(Socket::AF_INET, Socket::SOCK_STREAM, 0) {|bound|
+ bound.bind(Socket.sockaddr_in(0, "127.0.0.1"))
+ addr = bound.getsockname
+ port, = Socket.unpack_sockaddr_in(addr)
+
+ Socket.open(Socket::AF_INET, Socket::SOCK_STREAM, 0) {|s|
+ e = assert_raise(Errno::EADDRINUSE) do
+ s.bind(Socket.sockaddr_in(port, "127.0.0.1"))
+ end
+
+ assert_match "bind(2) for 127.0.0.1:#{port}", e.message
+ }
+ }
+ end
+
+ def test_getaddrinfo
+ # This should not send a DNS query because AF_UNIX.
+ assert_raise(Socket::ResolutionError) { Socket.getaddrinfo("www.kame.net", 80, "AF_UNIX") }
+ end
+
+ def test_getaddrinfo_raises_no_errors_on_port_argument_of_0 # [ruby-core:29427]
+ assert_nothing_raised('[ruby-core:29427]'){ Socket.getaddrinfo('localhost', 0, Socket::AF_INET, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) }
+ assert_nothing_raised('[ruby-core:29427]'){ Socket.getaddrinfo('localhost', '0', Socket::AF_INET, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) }
+ assert_nothing_raised('[ruby-core:29427]'){ Socket.getaddrinfo('localhost', '00', Socket::AF_INET, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) }
+ assert_raise(Socket::ResolutionError, '[ruby-core:29427]'){ Socket.getaddrinfo(nil, nil, Socket::AF_INET, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) }
+ assert_nothing_raised('[ruby-core:29427]'){ TCPServer.open('localhost', 0) {} }
+ end
+
+
+ def test_getnameinfo
+ assert_raise(Socket::ResolutionError) { Socket.getnameinfo(["AF_UNIX", 80, "0.0.0.0"]) }
+ assert_raise(ArgumentError) {Socket.getnameinfo(["AF_INET", "http\0", "example.net"])}
+ assert_raise(ArgumentError) {Socket.getnameinfo(["AF_INET", "http", "example.net\0"])}
+ end
+
+ def test_ip_address_list
+ begin
+ list = Socket.ip_address_list
+ rescue NotImplementedError
+ return
+ end
+ list.each {|ai|
+ assert_instance_of(Addrinfo, ai)
+ assert(ai.ip?)
+ }
+ end
+
+ def test_ip_address_list_include_localhost
+ begin
+ list = Socket.ip_address_list
+ rescue NotImplementedError
+ return
+ end
+ assert_includes list.map(&:ip_address), Addrinfo.tcp("localhost", 0).ip_address
+ end
+
+ def test_tcp
+ TCPServer.open(0) {|serv|
+ addr = serv.connect_address
+ addr.connect {|s1|
+ s2 = serv.accept
+ begin
+ assert_equal(s2.remote_address.ip_unpack, s1.local_address.ip_unpack)
+ ensure
+ s2.close
+ end
+ }
+ }
+ end
+
+ def test_tcp_cloexec
+ return unless defined? Fcntl::FD_CLOEXEC
+ TCPServer.open(0) {|serv|
+ addr = serv.connect_address
+ addr.connect {|s1|
+ s2 = serv.accept
+ begin
+ assert(s2.close_on_exec?)
+ ensure
+ s2.close
+ end
+ }
+
+ }
+ end
+
+ def random_port
+ # IANA suggests dynamic port for 49152 to 65535
+ # http://www.iana.org/assignments/port-numbers
+ case RUBY_PLATFORM
+ when /mingw|mswin/
+ rand(50000..65535)
+ else
+ rand(49152..65535)
+ end
end
- def test_getsockopt
- inet_stream do |s|
- n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_TYPE)
- assert_equal([Socket::SOCK_STREAM].pack("i"), n)
- n = s.getsockopt(Socket::SOL_SOCKET, Socket::SO_ERROR)
- assert_equal([0].pack("i"), n)
- val = Object.new
- class << val; self end.send(:define_method, :to_int) {
+ def errors_addrinuse
+ errs = [Errno::EADDRINUSE]
+ # Windows can fail with "Errno::EACCES: Permission denied - bind(2) for 0.0.0.0:49721"
+ # or "Test::Unit::ProxyError: Permission denied - bind(2) for 0.0.0.0:55333"
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ errs += [Errno::EACCES, Test::Unit::ProxyError]
+ end
+ errs
+ end
+
+ def test_tcp_server_sockets
+ port = random_port
+ begin
+ sockets = Socket.tcp_server_sockets(port)
+ rescue *errors_addrinuse
+ return # not test failure
+ end
+ begin
+ sockets.each {|s|
+ assert_equal(port, s.local_address.ip_port)
+ }
+ ensure
+ sockets.each {|s|
s.close
- Socket::SO_TYPE
}
- assert_raise(IOError) {
- n = s.getsockopt(Socket::SOL_SOCKET, val)
+ end
+ end
+
+ def test_tcp_server_sockets_port0
+ sockets = Socket.tcp_server_sockets(0)
+ ports = sockets.map {|s| s.local_address.ip_port }
+ the_port = ports.first
+ ports.each {|port|
+ assert_equal(the_port, port)
+ }
+ ensure
+ if sockets
+ sockets.each {|s|
+ s.close
}
end
end
- def test_setsockopt # [ruby-dev:25039]
- s = nil
- linger = [0, 0].pack("ii")
+ if defined? UNIXSocket
+ def test_unix
+ Dir.mktmpdir {|tmpdir|
+ path = "#{tmpdir}/sock"
+ UNIXServer.open(path) {|serv|
+ Socket.unix(path) {|s1|
+ s2 = serv.accept
+ begin
+ s2raddr = s2.remote_address
+ s1laddr = s1.local_address
+ assert(s2raddr.to_sockaddr.empty? ||
+ s1laddr.to_sockaddr.empty? ||
+ s2raddr.unix_path == s1laddr.unix_path)
+ assert(s2.close_on_exec?)
+ ensure
+ s2.close
+ end
+ }
+ }
+ }
+ end
- val = Object.new
- class << val; self end.send(:define_method, :to_str) {
- s.close
- linger
+ def test_unix_server_socket
+ Dir.mktmpdir {|tmpdir|
+ path = "#{tmpdir}/sock"
+ 2.times {
+ serv = Socket.unix_server_socket(path)
+ begin
+ assert_kind_of(Socket, serv)
+ assert(File.socket?(path))
+ assert_equal(path, serv.local_address.unix_path)
+ ensure
+ serv.close
+ end
+ }
+ }
+ end
+
+ def test_accept_loop_with_unix
+ Dir.mktmpdir {|tmpdir|
+ tcp_servers = []
+ clients = []
+ accepted = []
+ begin
+ tcp_servers = Socket.tcp_server_sockets(0)
+ unix_server = Socket.unix_server_socket("#{tmpdir}/sock")
+ tcp_servers.each {|s|
+ addr = s.connect_address
+ begin
+ clients << addr.connect
+ rescue
+ # allow failure if the address is IPv6
+ raise unless addr.ipv6?
+ end
+ }
+ addr = unix_server.connect_address
+ assert_nothing_raised("connect to #{addr.inspect}") {
+ clients << addr.connect
+ }
+ Socket.accept_loop(tcp_servers, unix_server) {|s|
+ accepted << s
+ break if clients.length == accepted.length
+ }
+ assert_equal(clients.length, accepted.length)
+ ensure
+ tcp_servers.each {|s| s.close if !s.closed? }
+ unix_server.close if unix_server && !unix_server.closed?
+ clients.each {|s| s.close if !s.closed? }
+ accepted.each {|s| s.close if !s.closed? }
+ end
+ }
+ end
+ end
+
+ def test_accept_loop
+ servers = []
+ begin
+ servers = Socket.tcp_server_sockets(0)
+ port = servers[0].local_address.ip_port
+ Socket.tcp("localhost", port) {|s1|
+ Socket.accept_loop(servers) {|s2, client_ai|
+ begin
+ assert_equal(s1.local_address.ip_unpack, client_ai.ip_unpack)
+ ensure
+ s2.close
+ end
+ break
+ }
+ }
+ ensure
+ servers.each {|s| s.close if !s.closed? }
+ end
+ end
+
+ def test_accept_loop_multi_port
+ servers = []
+ begin
+ servers = Socket.tcp_server_sockets(0)
+ port = servers[0].local_address.ip_port
+ servers2 = Socket.tcp_server_sockets(0)
+ servers.concat servers2
+ port2 = servers2[0].local_address.ip_port
+
+ Socket.tcp("localhost", port) {|s1|
+ Socket.accept_loop(servers) {|s2, client_ai|
+ begin
+ assert_equal(s1.local_address.ip_unpack, client_ai.ip_unpack)
+ ensure
+ s2.close
+ end
+ break
+ }
+ }
+ Socket.tcp("localhost", port2) {|s1|
+ Socket.accept_loop(servers) {|s2, client_ai|
+ begin
+ assert_equal(s1.local_address.ip_unpack, client_ai.ip_unpack)
+ ensure
+ s2.close
+ end
+ break
+ }
+ }
+ ensure
+ servers.each {|s| s.close if !s.closed? }
+ end
+ end
+
+ def test_udp_server
+ # http://rubyci.s3.amazonaws.com/rhel_zlinux/ruby-master/log/20230312T023302Z.fail.html.gz
+ # Errno::EHOSTUNREACH: No route to host - recvmsg(2)
+ omit if 'rhel_zlinux' == ENV['RUBYCI_NICKNAME']
+
+ begin
+ ifaddrs = Socket.getifaddrs
+ rescue NotImplementedError
+ omit "Socket.getifaddrs not implemented"
+ end
+
+ ifconfig = nil
+ Socket.udp_server_sockets(0) {|sockets|
+ famlies = {}
+ sockets.each {|s| famlies[s.local_address.afamily] = s }
+ nd6 = {}
+ ifaddrs.reject! {|ifa|
+ ai = ifa.addr
+ next true unless ai
+ s = famlies[ai.afamily]
+ next true unless s
+ next true if ai.ipv6_linklocal? # IPv6 link-local address is too troublesome in this test.
+ case RUBY_PLATFORM
+ when /linux/
+ if ai.ip_address.include?('%') and
+ (Etc.uname[:release][/[0-9.]+/].split('.').map(&:to_i) <=> [2,6,18]) <= 0
+ # Cent OS 5.6 (2.6.18-238.19.1.el5xen) doesn't correctly work
+ # sendmsg with pktinfo for link-local ipv6 addresses
+ next true
+ end
+ when /freebsd/
+ if ifa.addr.ipv6_linklocal?
+ # FreeBSD 9.0 with default setting (ipv6_activate_all_interfaces
+ # is not YES) sets IFDISABLED to interfaces which don't have
+ # global IPv6 address.
+ # Link-local IPv6 addresses on those interfaces don't work.
+ ulSIOCGIFINFO_IN6 = 3225971052
+ ulND6_IFF_IFDISABLED = 8
+ in6_ondireq = ifa.name
+ s.ioctl(ulSIOCGIFINFO_IN6, in6_ondireq)
+ flag = in6_ondireq.unpack('A16L6').last
+ next true if flag & ulND6_IFF_IFDISABLED != 0
+ nd6[ai] = flag
+ end
+ when /darwin/
+ if !ai.ipv6?
+ elsif ai.ipv6_unique_local? && /darwin1[01]\./ =~ RUBY_PLATFORM
+ next true # iCloud addresses do not work, see Bug #6692
+ elsif ifr_name = ai.ip_address[/%(.*)/, 1]
+ # Mac OS X may sets IFDISABLED as FreeBSD does
+ ulSIOCGIFFLAGS = 3223349521
+ ulSIOCGIFINFO_IN6 = 3224398156
+ ulIFF_POINTOPOINT = 0x10
+ ulND6_IFF_IFDISABLED = 8
+ in6_ondireq = ifr_name
+ s.ioctl(ulSIOCGIFINFO_IN6, in6_ondireq)
+ flag = in6_ondireq.unpack('A16L6').last
+ next true if (flag & ulND6_IFF_IFDISABLED) != 0
+ nd6[ai] = flag
+ in6_ifreq = [ifr_name,ai.to_sockaddr].pack('a16A*')
+ s.ioctl(ulSIOCGIFFLAGS, in6_ifreq)
+ next true if in6_ifreq.unpack('A16L1').last & ulIFF_POINTOPOINT != 0
+ end
+ ifconfig ||= `/sbin/ifconfig`
+ next true if ifconfig.scan(/^(\w+):(.*(?:\n\t.*)*)/).find do |_ifname, value|
+ value.include?(ai.ip_address) && value.include?('POINTOPOINT')
+ end
+ end
+ false
+ }
+ skipped = false
+ begin
+ port = sockets.first.local_address.ip_port
+
+ ping_p = false
+ th = Thread.new {
+ Socket.udp_server_loop_on(sockets) {|msg, msg_src|
+ break if msg == "exit"
+ rmsg = Marshal.dump([msg, msg_src.remote_address, msg_src.local_address])
+ ping_p = true
+ msg_src.reply rmsg
+ }
+ }
+
+ ifaddrs.each {|ifa|
+ ai = ifa.addr
+ Addrinfo.udp(ai.ip_address, port).connect {|s|
+ ping_p = false
+ msg1 = "<<<#{ai.inspect}>>>"
+ s.sendmsg msg1
+ unless IO.select([s], nil, nil, 10)
+ nd6options = nd6.key?(ai) ? "nd6=%x " % nd6[ai] : ''
+ raise "no response from #{ifa.inspect} #{nd6options}ping=#{ping_p}"
+ end
+ msg2, addr = s.recvmsg
+ msg2, _, _ = Marshal.load(msg2)
+ assert_equal(msg1, msg2)
+ assert_equal(ai.ip_address, addr.ip_address)
+ }
+ }
+ rescue NotImplementedError, Errno::ENOSYS
+ skipped = true
+ omit "need sendmsg and recvmsg: #{$!}"
+ rescue RuntimeError
+ skipped = true
+ omit "UDP server is no response: #{$!}"
+ ensure
+ if th
+ unless skipped
+ Addrinfo.udp("127.0.0.1", port).connect {|s| s.sendmsg "exit" }
+ end
+ unless th.join(10)
+ th.kill.join(10)
+ unless skipped
+ raise "thread killed"
+ end
+ end
+ end
+ end
}
- inet_stream do |sock|
- s = sock
- assert_equal(0, s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger))
+ end
- assert_raise(IOError) {
- s.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, val)
+ def test_linger
+ opt = Socket::Option.linger(true, 0)
+ assert_equal([true, 0], opt.linger)
+ Addrinfo.tcp("127.0.0.1", 0).listen {|serv|
+ serv.local_address.connect {|s1|
+ s2, _ = serv.accept
+ begin
+ s1.setsockopt(opt)
+ s1.close
+ assert_raise(Errno::ECONNRESET) { s2.read }
+ ensure
+ s2.close
+ end
}
+ }
+ end
+
+ def timestamp_retry_rw(s1, s2, t1, type)
+ IO.pipe do |r,w|
+ # UDP may not be reliable, keep sending until recvmsg returns:
+ th = Thread.new do
+ n = 0
+ begin
+ s2.send("a", 0, s1.local_address)
+ n += 1
+ end while IO.select([r], nil, nil, 0.1).nil?
+ n
+ end
+ timeout = 30
+ assert_equal([[s1],[],[]], IO.select([s1], nil, nil, timeout))
+ msg, _, _, stamp = s1.recvmsg
+ assert_equal("a", msg)
+ assert(stamp.cmsg_is?(:SOCKET, type))
+ w.close # stop th
+ n = th.value
+ th = nil
+ n > 1 and
+ warn "UDP packet loss for #{type} over loopback, #{n} tries needed"
+ t2 = Time.now.strftime("%Y-%m-%d")
+ pat = Regexp.union([t1, t2].uniq)
+ assert_match(pat, stamp.inspect)
+ t = stamp.timestamp
+ assert_match(pat, t.strftime("%Y-%m-%d"))
+ stamp
+ ensure
+ if th and !th.join(10)
+ th.kill.join(10)
+ end
end
+ end
- val = Object.new
- class << val; self end.send(:define_method, :to_int) {
- s.close
- Socket::SO_LINGER
+ def test_timestamp
+ return if /linux|freebsd|netbsd|openbsd|darwin/ !~ RUBY_PLATFORM
+ return if !defined?(Socket::AncillaryData) || !defined?(Socket::SO_TIMESTAMP)
+ t1 = Time.now.strftime("%Y-%m-%d")
+ stamp = nil
+ Addrinfo.udp("127.0.0.1", 0).bind {|s1|
+ Addrinfo.udp("127.0.0.1", 0).bind {|s2|
+ s1.setsockopt(:SOCKET, :TIMESTAMP, true)
+ stamp = timestamp_retry_rw(s1, s2, t1, :TIMESTAMP)
+ }
}
- inet_stream do |sock|
- s = sock
- assert_raise(IOError) {
- s.setsockopt(Socket::SOL_SOCKET, val, linger)
+ t = stamp.timestamp
+ pat = /\.#{"%06d" % t.usec}/
+ assert_match(pat, stamp.inspect)
+ end
+
+ def test_timestampns
+ return if /linux/ !~ RUBY_PLATFORM || !defined?(Socket::SO_TIMESTAMPNS)
+ t1 = Time.now.strftime("%Y-%m-%d")
+ stamp = nil
+ Addrinfo.udp("127.0.0.1", 0).bind {|s1|
+ Addrinfo.udp("127.0.0.1", 0).bind {|s2|
+ begin
+ s1.setsockopt(:SOCKET, :TIMESTAMPNS, true)
+ rescue Errno::ENOPROTOOPT
+ # SO_TIMESTAMPNS is available since Linux 2.6.22
+ return
+ end
+ stamp = timestamp_retry_rw(s1, s2, t1, :TIMESTAMPNS)
+ }
+ }
+ t = stamp.timestamp
+ pat = /\.#{"%09d" % t.nsec}/
+ assert_match(pat, stamp.inspect)
+ end
+
+ def test_bintime
+ return if /freebsd/ !~ RUBY_PLATFORM
+ t1 = Time.now.strftime("%Y-%m-%d")
+ stamp = nil
+ Addrinfo.udp("127.0.0.1", 0).bind {|s1|
+ Addrinfo.udp("127.0.0.1", 0).bind {|s2|
+ s1.setsockopt(:SOCKET, :BINTIME, true)
+ s2.send "a", 0, s1.local_address
+ msg, _, _, stamp = s1.recvmsg
+ assert_equal("a", msg)
+ assert(stamp.cmsg_is?(:SOCKET, :BINTIME))
+ }
+ }
+ t2 = Time.now.strftime("%Y-%m-%d")
+ pat = Regexp.union([t1, t2].uniq)
+ assert_match(pat, stamp.inspect)
+ t = stamp.timestamp
+ assert_match(pat, t.strftime("%Y-%m-%d"))
+ assert_equal(stamp.data[-8,8].unpack("Q")[0], t.subsec * 2**64)
+ end
+
+ def test_closed_read
+ require 'timeout'
+ require 'socket'
+ bug4390 = '[ruby-core:35203]'
+ server = TCPServer.new("localhost", 0)
+ serv_thread = Thread.new {server.accept}
+ begin sleep(0.1) end until serv_thread.stop?
+ sock = TCPSocket.new("localhost", server.addr[1])
+ client_thread = Thread.new do
+ assert_raise(IOError, bug4390) {
+ sock.readline
}
end
+ begin sleep(0.1) end until client_thread.stop?
+ Timeout.timeout(1) do
+ sock.close
+ sock = nil
+ client_thread.join
+ end
+ ensure
+ serv_thread.value.close
+ server.close
+ end unless RUBY_PLATFORM.include?("freebsd")
+
+ def test_connect_timeout
+ host = "127.0.0.1"
+ server = TCPServer.new(host, 0)
+ port = server.addr[1]
+ serv_thread = Thread.new {server.accept}
+ sock = Socket.tcp(host, port, :connect_timeout => 30)
+ accepted = serv_thread.value
+ assert_kind_of TCPSocket, accepted
+ assert_equal sock, IO.select(nil, [ sock ])[1][0], "not writable"
+ sock.close
+
+ # some platforms may not timeout when the listener queue overflows,
+ # but we know Linux does with the default listen backlog of SOMAXCONN for
+ # TCPServer.
+ assert_raise(Errno::ETIMEDOUT) do
+ (Socket::SOMAXCONN*2).times do |i|
+ sock = Socket.tcp(host, port, :connect_timeout => 0)
+ assert_equal sock, IO.select(nil, [ sock ])[1][0],
+ "not writable (#{i})"
+ sock.close
+ end
+ end if RUBY_PLATFORM =~ /linux/
+ ensure
+ server.close
+ accepted.close if accepted
+ sock.close if sock && ! sock.closed?
end
- def test_listen
- s = nil
- log = Object.new
- class << log; self end.send(:define_method, :to_int) {
- s.close
- 2
+ def test_getifaddrs
+ begin
+ list = Socket.getifaddrs
+ rescue NotImplementedError
+ return
+ end
+ list.each {|ifaddr|
+ assert_instance_of(Socket::Ifaddr, ifaddr)
}
- inet_stream do |sock|
- s = sock
- assert_raise(IOError) {
- s.listen(log)
+ end
+
+ def test_connect_in_rescue
+ serv = Addrinfo.tcp(nil, 0).listen
+ addr = serv.connect_address
+ begin
+ raise "dummy error"
+ rescue
+ s = addr.connect
+ assert(!s.closed?)
+ end
+ ensure
+ serv.close if serv && !serv.closed?
+ s.close if s && !s.closed?
+ end
+
+ def test_bind_in_rescue
+ begin
+ raise "dummy error"
+ rescue
+ s = Addrinfo.tcp(nil, 0).bind
+ assert(!s.closed?)
+ end
+ ensure
+ s.close if s && !s.closed?
+ end
+
+ def test_listen_in_rescue
+ begin
+ raise "dummy error"
+ rescue
+ s = Addrinfo.tcp(nil, 0).listen
+ assert(!s.closed?)
+ end
+ ensure
+ s.close if s && !s.closed?
+ end
+
+ def test_udp_server_sockets_in_rescue
+ begin
+ raise "dummy error"
+ rescue
+ ss = Socket.udp_server_sockets(0)
+ ss.each {|s|
+ assert(!s.closed?)
+ }
+ end
+ ensure
+ if ss
+ ss.each {|s|
+ s.close if !s.closed?
}
end
end
-end if defined?(Socket)
-class TestSocket < Test::Unit::TestCase
- def test_unpack_sockaddr
- sockaddr_in = Socket.sockaddr_in(80, "")
- assert_raise(ArgumentError) { Socket.unpack_sockaddr_un(sockaddr_in) }
- sockaddr_un = Socket.sockaddr_un("/tmp/s")
- assert_raise(ArgumentError) { Socket.unpack_sockaddr_in(sockaddr_un) }
- end if Socket.respond_to?(:sockaddr_un)
+ def test_tcp_server_sockets_in_rescue
+ begin
+ raise "dummy error"
+ rescue
+ ss = Socket.tcp_server_sockets(0)
+ ss.each {|s|
+ assert(!s.closed?)
+ }
+ end
+ ensure
+ if ss
+ ss.each {|s|
+ s.close if !s.closed?
+ }
+ end
+ end
- def test_sysaccept
- serv = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
- serv.bind(Socket.sockaddr_in(0, "127.0.0.1"))
- serv.listen 5
- c = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
- c.connect(serv.getsockname)
- fd, peeraddr = serv.sysaccept
- assert_equal(c.getsockname, peeraddr)
+ def test_recvmsg_udp_no_arg
+ n = 4097
+ s1 = Addrinfo.udp("127.0.0.1", 0).bind
+ s2 = s1.connect_address.connect
+ s2.send("a" * n, 0)
+ ret = s1.recvmsg
+ assert_equal n, ret[0].bytesize, '[ruby-core:71517] [Bug #11701]'
+
+ s2.send("a" * n, 0)
+ IO.select([s1])
+ ret = s1.recvmsg_nonblock
+ assert_equal n, ret[0].bytesize, 'non-blocking should also grow'
ensure
- serv.close if serv
- c.close if c
- IO.for_fd(fd).close if fd
+ s1.close
+ s2.close
+ end
+
+ def test_udp_read_truncation
+ s1 = Addrinfo.udp("127.0.0.1", 0).bind
+ s2 = s1.connect_address.connect
+ s2.send("a" * 100, 0)
+ ret = s1.read(10)
+ assert_equal "a" * 10, ret
+ s2.send("b" * 100, 0)
+ ret = s1.read(10)
+ assert_equal "b" * 10, ret
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_udp_recv_truncation
+ s1 = Addrinfo.udp("127.0.0.1", 0).bind
+ s2 = s1.connect_address.connect
+ s2.send("a" * 100, 0)
+ ret = s1.recv(10, Socket::MSG_PEEK)
+ assert_equal "a" * 10, ret
+ ret = s1.recv(10, 0)
+ assert_equal "a" * 10, ret
+ s2.send("b" * 100, 0)
+ ret = s1.recv(10, 0)
+ assert_equal "b" * 10, ret
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_udp_recvmsg_truncation
+ s1 = Addrinfo.udp("127.0.0.1", 0).bind
+ s2 = s1.connect_address.connect
+ s2.send("a" * 100, 0)
+ ret, addr, rflags = s1.recvmsg(10, Socket::MSG_PEEK)
+ assert_equal "a" * 10, ret
+ # AIX does not set MSG_TRUNC for a message partially read with MSG_PEEK.
+ assert_equal Socket::MSG_TRUNC, rflags & Socket::MSG_TRUNC if !rflags.nil? && /aix/ !~ RUBY_PLATFORM
+ ret, addr, rflags = s1.recvmsg(10, 0)
+ assert_equal "a" * 10, ret
+ assert_equal Socket::MSG_TRUNC, rflags & Socket::MSG_TRUNC if !rflags.nil?
+ s2.send("b" * 100, 0)
+ ret, addr, rflags = s1.recvmsg(10, 0)
+ assert_equal "b" * 10, ret
+ assert_equal Socket::MSG_TRUNC, rflags & Socket::MSG_TRUNC if !rflags.nil?
+ addr
+ ensure
+ s1.close
+ s2.close
+ end
+
+ def test_resolurion_error_error_code
+ begin
+ Socket.getaddrinfo("example.com", 80, "AF_UNIX")
+ rescue => e
+ assert_include([Socket::EAI_FAMILY, Socket::EAI_FAIL], e.error_code)
+ end
+ end
+
+ def test_tcp_socket_v6_hostname_resolved_earlier
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then [Addrinfo.tcp("::1", port)]
+ when Socket::AF_INET then sleep(10); [Addrinfo.tcp("127.0.0.1", port)]
+ end
+ end
+
+ socket = Socket.tcp("localhost", port)
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_v4_hostname_resolved_earlier
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ server = TCPServer.new("127.0.0.1", 0)
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then sleep(10); [Addrinfo.tcp("::1", port)]
+ when Socket::AF_INET then [Addrinfo.tcp("127.0.0.1", port)]
+ end
+ end
+
+ socket = Socket.tcp("localhost", port)
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_v6_hostname_resolved_in_resolution_delay
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ delay_time = 0.025 # Socket::RESOLUTION_DELAY (private) is 0.05
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then sleep(delay_time); [Addrinfo.tcp("::1", port)]
+ when Socket::AF_INET then [Addrinfo.tcp("127.0.0.1", port)]
+ end
+ end
+
+ socket = Socket.tcp("localhost", port)
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_v6_hostname_resolved_earlier_and_v6_server_is_not_listening
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ ipv4_address = "127.0.0.1"
+ server = Socket.new(Socket::AF_INET, :STREAM)
+ server.bind(Socket.pack_sockaddr_in(0, ipv4_address))
+ port = server.connect_address.ip_port
+ server_thread = Thread.new { server.listen(1); server.accept }
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then [Addrinfo.tcp("::1", port)]
+ when Socket::AF_INET then sleep(0.001); [Addrinfo.tcp(ipv4_address, port)]
+ end
+ end
+
+ socket = Socket.tcp("localhost", port)
+ assert_equal(ipv4_address, socket.remote_address.ip_address)
+ ensure
+ accepted, _ = server_thread&.value
+ accepted&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_resolv_timeout
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ server = TCPServer.new("localhost", 0)
+ _, port, = server.addr
+
+ Addrinfo.define_singleton_method(:getaddrinfo) { |*_| sleep }
+
+ assert_raise(IO::TimeoutError) do
+ Socket.tcp("localhost", port, resolv_timeout: 0.01)
+ end
+ ensure
+ server&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_resolv_timeout_with_connection_failure
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ server = TCPServer.new("127.0.0.1", 12345)
+ _, port, = server.addr
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ if family == Socket::AF_INET6
+ sleep
+ else
+ [Addrinfo.tcp("127.0.0.1", port)]
+ end
+ end
+
+ server.close
+
+ assert_raise(IO::TimeoutError) do
+ Socket.tcp("localhost", port, resolv_timeout: 0.01)
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_open_timeout
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ if family == Socket::AF_INET6
+ sleep
+ else
+ [Addrinfo.tcp("127.0.0.1", 12345)]
+ end
+ end
+
+ assert_raise(IO::TimeoutError) do
+ Socket.tcp("localhost", 12345, open_timeout: 0.01)
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_open_timeout_with_other_timeouts
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ assert_raise(ArgumentError) do
+ Socket.tcp("localhost", 12345, open_timeout: 0.01, resolv_timout: 0.01)
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_one_hostname_resolution_succeeded_at_least
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then [Addrinfo.tcp("::1", port)]
+ when Socket::AF_INET then sleep(0.001); raise SocketError
+ end
+ end
+
+ socket = nil
+
+ assert_nothing_raised do
+ socket = Socket.tcp("localhost", port)
+ end
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_all_hostname_resolution_failed
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ server = TCPServer.new("localhost", 0)
+ _, port, = server.addr
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then raise SocketError
+ when Socket::AF_INET then sleep(0.01); raise SocketError, "Last hostname resolution error"
+ end
+ end
+
+ assert_raise_with_message(SocketError, "Last hostname resolution error") do
+ Socket.tcp("localhost", port)
+ end
+ ensure
+ server&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_hostname_resolution_failed_after_connection_failure
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ server = TCPServer.new("127.0.0.1", 0)
+ port = server.connect_address.ip_port
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |_, _, family, *_|
+ case family
+ when Socket::AF_INET6 then sleep(0.1); raise Socket::ResolutionError
+ when Socket::AF_INET then [Addrinfo.tcp("127.0.0.1", port)]
+ end
+ end
+
+ server.close
+
+ # SystemCallError is a workaround for Windows environment
+ assert_raise(Errno::ECONNREFUSED, SystemCallError) do
+ Socket.tcp("localhost", port)
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_v6_address_passed
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ begin
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ Addrinfo.define_singleton_method(:getaddrinfo) do |*_|
+ [Addrinfo.tcp("::1", port)]
+ end
+
+ socket = Socket.tcp("::1", port)
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+ RUBY
+ end
+
+ def test_tcp_socket_fast_fallback_is_false
+ server = TCPServer.new("127.0.0.1", 0)
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+ socket = Socket.tcp("127.0.0.1", port, fast_fallback: false)
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_tcp_fast_fallback
+ opts = %w[-rsocket -W1]
+ assert_separately opts, <<~RUBY
+ assert_true(Socket.tcp_fast_fallback)
+
+ Socket.tcp_fast_fallback = false
+ assert_false(Socket.tcp_fast_fallback)
+
+ Socket.tcp_fast_fallback = true
+ assert_true(Socket.tcp_fast_fallback)
+ RUBY
end
end if defined?(Socket)
diff --git a/test/socket/test_sockopt.rb b/test/socket/test_sockopt.rb
new file mode 100644
index 0000000000..7e343e8c36
--- /dev/null
+++ b/test/socket/test_sockopt.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+require 'test/unit'
+require 'socket'
+
+class TestSocketOption < Test::Unit::TestCase
+ def test_new
+ data = [1].pack("i")
+ sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, data)
+ assert_equal(Socket::AF_INET, sockopt.family)
+ assert_equal(Socket::SOL_SOCKET, sockopt.level)
+ assert_equal(Socket::SO_KEEPALIVE, sockopt.optname)
+ assert_equal(Socket::SO_KEEPALIVE, sockopt.optname)
+ assert_equal(data, sockopt.data)
+ end
+
+ def test_bool
+ opt = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true)
+ assert_equal(1, opt.int)
+ opt = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false)
+ assert_equal(0, opt.int)
+ opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 0)
+ assert_equal(false, opt.bool)
+ opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 1)
+ assert_equal(true, opt.bool)
+ opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 2)
+ assert_equal(true, opt.bool)
+ begin
+ Socket.open(:INET, :STREAM) {|s|
+ s.setsockopt(Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true))
+ assert_equal(true, s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).bool)
+ s.setsockopt(Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false))
+ assert_equal(false, s.getsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE).bool)
+ }
+ rescue TypeError
+ if /aix/ =~ RUBY_PLATFORM
+ omit "Known bug in getsockopt(2) on AIX"
+ end
+ raise $!
+ end
+ end
+
+ def test_ipv4_multicast_loop
+ sockopt = Socket::Option.ipv4_multicast_loop(128)
+ assert_equal('#<Socket::Option: INET IP MULTICAST_LOOP 128>', sockopt.inspect)
+ assert_equal(Socket::AF_INET, sockopt.family)
+ assert_equal(Socket::IPPROTO_IP, sockopt.level)
+ assert_equal(Socket::IP_MULTICAST_LOOP, sockopt.optname)
+ assert_equal(128, sockopt.ipv4_multicast_loop)
+ end
+
+ def test_ipv4_multicast_loop_size
+ expected_size = Socket.open(:INET, :DGRAM) {|s|
+ s.getsockopt(:IP, :MULTICAST_LOOP).to_s.bytesize
+ }
+ assert_equal(expected_size, Socket::Option.ipv4_multicast_loop(0).to_s.bytesize)
+ end
+
+ def test_ipv4_multicast_ttl
+ sockopt = Socket::Option.ipv4_multicast_ttl(128)
+ assert_equal('#<Socket::Option: INET IP MULTICAST_TTL 128>', sockopt.inspect)
+ assert_equal(Socket::AF_INET, sockopt.family)
+ assert_equal(Socket::IPPROTO_IP, sockopt.level)
+ assert_equal(Socket::IP_MULTICAST_TTL, sockopt.optname)
+ assert_equal(128, sockopt.ipv4_multicast_ttl)
+ end
+
+ def test_ipv4_multicast_ttl_size
+ expected_size = Socket.open(:INET, :DGRAM) {|s|
+ s.getsockopt(:IP, :MULTICAST_TTL).to_s.bytesize
+ }
+ assert_equal(expected_size, Socket::Option.ipv4_multicast_ttl(0).to_s.bytesize)
+ end
+
+ def test_unpack
+ sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, [1].pack("i"))
+ assert_equal([1], sockopt.unpack("i"))
+ assert_equal([1], sockopt.data.unpack("i"))
+ end
+end
diff --git a/test/socket/test_tcp.rb b/test/socket/test_tcp.rb
index ed6391f86e..d689ab2376 100644
--- a/test/socket/test_tcp.rb
+++ b/test/socket/test_tcp.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
begin
require "socket"
require "test/unit"
@@ -5,25 +7,417 @@ rescue LoadError
end
-class TestTCPSocket < Test::Unit::TestCase
- def test_recvfrom # [ruby-dev:24705]
-assert false, "TODO: doesn't work on mswin32/64" if /mswin/ =~ RUBY_PLATFORM
- c = s = nil
- svr = TCPServer.new("localhost", 0)
- th = Thread.new {
- c = svr.accept
- Thread.pass
- ObjectSpace.each_object(String) {|s|
- s.replace "a" if s.length == 0x10000 and !s.frozen?
+class TestSocket_TCPSocket < Test::Unit::TestCase
+ def test_inspect
+ TCPServer.open("localhost", 0) {|server|
+ assert_match(/AF_INET/, server.inspect)
+ TCPSocket.open("localhost", server.addr[1]) {|client|
+ assert_match(/AF_INET/, client.inspect)
}
- c.print("x"*0x1000)
}
- addr = svr.addr
- sock = TCPSocket.open(addr[2], addr[1])
- assert_raise(RuntimeError, SocketError) {
- sock.recvfrom(0x10000)
+ end
+
+ def test_initialize_failure
+ assert_raise(Socket::ResolutionError) do
+ t = TCPSocket.open(nil, nil)
+ ensure
+ t&.close
+ end
+
+ # These addresses are chosen from TEST-NET-1, TEST-NET-2, and TEST-NET-3.
+ # [RFC 5737]
+ # They are chosen because probably they are not used as a host address.
+ # Anyway the addresses are used for bind() and should be failed.
+ # So no packets should be generated.
+ test_ip_addresses = [
+ '192.0.2.1', '192.0.2.42', # TEST-NET-1
+ '198.51.100.1', '198.51.100.42', # TEST-NET-2
+ '203.0.113.1', '203.0.113.42', # TEST-NET-3
+ ]
+ begin
+ list = Socket.ip_address_list
+ rescue NotImplementedError
+ return
+ end
+ test_ip_addresses -= list.reject {|ai| !ai.ipv4? }.map {|ai| ai.ip_address }
+ if test_ip_addresses.empty?
+ return
+ end
+ client_addr = test_ip_addresses.first
+ client_port = 8000
+
+ server_addr = '127.0.0.1'
+ server_port = 80
+
+ e = assert_raise_kind_of(SystemCallError) do
+ # Since client_addr is not an IP address of this host,
+ # bind() in TCPSocket.new should fail as EADDRNOTAVAIL.
+ t = TCPSocket.new(server_addr, server_port, client_addr, client_port)
+ ensure
+ t&.close
+ end
+ assert_include e.message, "for \"#{client_addr}\" port #{client_port}"
+ end
+
+ def test_initialize_resolv_timeout
+ TCPServer.open("localhost", 0) do |svr|
+ th = Thread.new {
+ c = svr.accept
+ c.close
+ }
+ addr = svr.addr
+ s = TCPSocket.new(addr[3], addr[1], resolv_timeout: 10)
+ th.join
+ ensure
+ s.close()
+ end
+ end
+
+ def test_tcp_initialize_open_timeout
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ port = server.connect_address.ip_port
+ server.close
+
+ assert_raise(IO::TimeoutError) do
+ TCPSocket.new(
+ "localhost",
+ port,
+ open_timeout: 0.01,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 1000 } }
+ )
+ end
+ end
+
+ def test_initialize_open_timeout_with_other_timeouts
+ assert_raise(ArgumentError) do
+ TCPSocket.new("localhost", 12345, open_timeout: 0.01, resolv_timeout: 0.01)
+ end
+ end
+
+ def test_initialize_connect_timeout
+ assert_raise(IO::TimeoutError, Errno::ENETUNREACH, Errno::EACCES) do
+ TCPSocket.new("192.0.2.1", 80, connect_timeout: 0)
+ end
+ end
+
+ def test_recvfrom
+ TCPServer.open("localhost", 0) {|svr|
+ th = Thread.new {
+ c = svr.accept
+ c.write "foo"
+ c.close
+ }
+ addr = svr.addr
+ TCPSocket.open(addr[3], addr[1]) {|sock|
+ assert_equal(["foo", nil], sock.recvfrom(0x10000))
+ }
+ th.join
}
+ end
+
+ def test_encoding
+ TCPServer.open("localhost", 0) {|svr|
+ th = Thread.new {
+ c = svr.accept
+ c.write "foo\r\n"
+ c.close
+ }
+ addr = svr.addr
+ TCPSocket.open(addr[3], addr[1]) {|sock|
+ assert_equal(true, sock.binmode?)
+ s = sock.gets
+ assert_equal("foo\r\n", s)
+ assert_equal(Encoding.find("ASCII-8BIT"), s.encoding)
+ }
+ th.join
+ }
+ end
+
+ def test_accept_nonblock
+ TCPServer.open("localhost", 0) {|svr|
+ assert_raise(IO::WaitReadable) { svr.accept_nonblock }
+ assert_equal :wait_readable, svr.accept_nonblock(exception: false)
+ assert_raise(IO::WaitReadable) { svr.accept_nonblock(exception: true) }
+ }
+ end
+
+ def test_accept_multithread
+ attempts_count = 5
+ server_threads_count = 3
+ client_threads_count = 3
+
+ attempts_count.times do
+ server_threads = Array.new(server_threads_count) do
+ Thread.new do
+ TCPServer.open("localhost", 0) do |server|
+ accept_threads = Array.new(client_threads_count) do
+ Thread.new { server.accept.close }
+ end
+ client_threads = Array.new(client_threads_count) do
+ Thread.new { TCPSocket.open(server.addr[3], server.addr[1]) {} }
+ end
+ client_threads.each(&:join)
+ accept_threads.each(&:join)
+ end
+ end
+ end
+
+ server_threads.each(&:join)
+ end
+ end
+
+ def test_initialize_v6_hostname_resolved_earlier
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ server_thread = Thread.new { server.accept }
+ port = server.addr[1]
+
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 1000 } }
+ )
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v4_hostname_resolved_earlier
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ port = server.addr[1]
+
+ server_thread = Thread.new { server.accept }
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv6: 1000 } }
+ )
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v6_hostname_resolved_in_resolution_delay
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ begin
+ # Verify that "localhost" can be resolved to an IPv6 address
+ Socket.getaddrinfo("localhost", 0, Socket::AF_INET6)
+ server = TCPServer.new("::1", 0)
+ rescue Socket::ResolutionError, Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ port = server.addr[1]
+ delay_time = 25 # Socket::RESOLUTION_DELAY (private) is 50ms
+
+ server_thread = Thread.new { server.accept }
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv6: delay_time } }
+ )
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v6_hostname_resolved_earlier_and_v6_server_is_not_listening
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ ipv4_address = "127.0.0.1"
+ server = Socket.new(Socket::AF_INET, :STREAM)
+ server.bind(Socket.pack_sockaddr_in(0, ipv4_address))
+ port = server.connect_address.ip_port
+
+ server_thread = Thread.new { server.listen(1); server.accept }
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 10 } }
+ )
+ assert_equal(ipv4_address, socket.remote_address.ip_address)
+ ensure
+ accepted, _ = server_thread&.value
+ accepted&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v6_hostname_resolved_later_and_v6_server_is_not_listening
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = Socket.new(Socket::AF_INET, :STREAM)
+ server.bind(Socket.pack_sockaddr_in(0, "127.0.0.1"))
+ port = server.connect_address.ip_port
+
+ server_thread = Thread.new { server.listen(1); server.accept }
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv6: 25 } }
+ )
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ accepted, _ = server_thread&.value
+ accepted&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v6_hostname_resolution_failed_and_v4_hostname_resolution_is_success
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ port = server.addr[1]
+
+ server_thread = Thread.new { server.accept }
+ socket = TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 10 }, error: { ipv6: Socket::EAI_FAIL } }
+ )
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_resolv_timeout_with_connection_failure
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ begin
+ server = TCPServer.new("::1", 0)
+ rescue Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ port = server.connect_address.ip_port
+ server.close
+
+ assert_raise(IO::TimeoutError) do
+ TCPSocket.new(
+ "localhost",
+ port,
+ resolv_timeout: 0.01,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 1000 } }
+ )
+ end
+ end
+
+ def test_initialize_with_hostname_resolution_failure_after_connection_failure
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ begin
+ server = TCPServer.new("::1", 0)
+ rescue Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ port = server.connect_address.ip_port
+ server.close
+
+ assert_raise(Errno::ECONNREFUSED) do
+ TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 100 }, error: { ipv4: Socket::EAI_FAIL } }
+ )
+ end
+ end
+
+ def test_initialize_with_connection_failure_after_hostname_resolution_failure
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ port = server.connect_address.ip_port
+ server.close
+
+ assert_raise(Errno::ECONNREFUSED) do
+ TCPSocket.new(
+ "localhost",
+ port,
+ fast_fallback: true,
+ test_mode_settings: { delay: { ipv4: 100 }, error: { ipv6: Socket::EAI_FAIL } }
+ )
+ end
+ end
+
+ def test_initialize_v6_connected_socket_with_v6_address
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ begin
+ server = TCPServer.new("::1", 0)
+ rescue Errno::EADDRNOTAVAIL # IPv6 is not supported
+ return
+ end
+
+ server_thread = Thread.new { server.accept }
+ port = server.addr[1]
+
+ socket = TCPSocket.new("::1", port)
+ assert_true(socket.remote_address.ipv6?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_v4_connected_socket_with_v4_address
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ server_thread = Thread.new { server.accept }
+ port = server.addr[1]
+
+ socket = TCPSocket.new("127.0.0.1", port)
+ assert_true(socket.remote_address.ipv4?)
+ ensure
+ server_thread&.value&.close
+ server&.close
+ socket&.close
+ end
+
+ def test_initialize_fast_fallback_is_false
+ return if RUBY_PLATFORM =~ /mswin|mingw|cygwin/
+
+ server = TCPServer.new("127.0.0.1", 0)
+ _, port, = server.addr
+ server_thread = Thread.new { server.accept }
+
+ socket = TCPSocket.new("127.0.0.1", port, fast_fallback: false)
+ assert_true(socket.remote_address.ipv4?)
ensure
- th.join
+ server_thread&.value&.close
+ server&.close
+ socket&.close
end
end if defined?(TCPSocket)
diff --git a/test/socket/test_udp.rb b/test/socket/test_udp.rb
index 07fd17a2cb..4b2b7ab976 100644
--- a/test/socket/test_udp.rb
+++ b/test/socket/test_udp.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
begin
require "socket"
require "test/unit"
@@ -5,28 +7,110 @@ rescue LoadError
end
-class TestUDPSocket < Test::Unit::TestCase
- def test_connect # [ruby-dev:25045]
+class TestSocket_UDPSocket < Test::Unit::TestCase
+ def test_open
+ assert_nothing_raised { UDPSocket.open {} }
+ assert_nothing_raised { UDPSocket.open(Socket::AF_INET) {} }
+ assert_nothing_raised { UDPSocket.open("AF_INET") {} }
+ assert_nothing_raised { UDPSocket.open(:AF_INET) {} }
+ end
+
+ def test_inspect
+ UDPSocket.open() {|sock|
+ assert_match(/AF_INET\b/, sock.inspect)
+ }
+ if Socket.const_defined?(:AF_INET6)
+ begin
+ UDPSocket.open(Socket::AF_INET6) {|sock|
+ assert_match(/AF_INET6\b/, sock.inspect)
+ }
+ rescue Errno::EAFNOSUPPORT
+ omit 'AF_INET6 not supported by kernel'
+ end
+ end
+ end
+
+ def test_connect
s = UDPSocket.new
host = Object.new
class << host; self end.send(:define_method, :to_str) {
s.close
"127.0.0.1"
}
- assert_raise(IOError) {
+ assert_raise(IOError, "[ruby-dev:25045]") {
s.connect(host, 1)
}
end
- def test_bind # [ruby-dev:25057]
+ def test_bind
s = UDPSocket.new
host = Object.new
class << host; self end.send(:define_method, :to_str) {
s.close
"127.0.0.1"
}
- assert_raise(IOError) {
+ assert_raise(IOError, "[ruby-dev:25057]") {
s.bind(host, 2000)
}
+ ensure
+ s.close if s && !s.closed?
+ end
+
+ def test_bind_addrinuse
+ host = "127.0.0.1"
+
+ in_use = UDPSocket.new
+ in_use.bind(host, 0)
+ port = in_use.addr[1]
+
+ s = UDPSocket.new
+
+ e = assert_raise(Errno::EADDRINUSE) do
+ s.bind(host, port)
+ end
+
+ assert_match "bind(2) for \"#{host}\" port #{port}", e.message
+ ensure
+ in_use.close if in_use
+ s.close if s
+ end
+
+ def test_send_too_long
+ u = UDPSocket.new
+
+ e = assert_raise(Errno::EMSGSIZE) do
+ u.send "\0" * 100_000, 0, "127.0.0.1", 7 # echo
+ end
+
+ assert_match 'for "127.0.0.1" port 7', e.message
+ ensure
+ u.close if u
+ end
+
+ def test_bind_no_memory_leak
+ assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
+ s = UDPSocket.new
+ s.close
+ end;
+ 100_000.times {begin s.bind("127.0.0.1", 1) rescue IOError; end}
+ end;
+ end
+
+ def test_connect_no_memory_leak
+ assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
+ s = UDPSocket.new
+ s.close
+ end;
+ 100_000.times {begin s.connect("127.0.0.1", 1) rescue IOError; end}
+ end;
+ end
+
+ def test_send_no_memory_leak
+ assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
+ s = UDPSocket.new
+ s.close
+ end;
+ 100_000.times {begin s.send("\0"*100, 0, "127.0.0.1", 1) rescue IOError; end}
+ end;
end
end if defined?(UDPSocket)
diff --git a/test/socket/test_unix.rb b/test/socket/test_unix.rb
index 3bd3d94c9d..e239e3935b 100644
--- a/test/socket/test_unix.rb
+++ b/test/socket/test_unix.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
begin
require "socket"
rescue LoadError
@@ -5,8 +7,11 @@ end
require "test/unit"
require "tempfile"
+require "timeout"
+require "tmpdir"
+require "io/nonblock"
-class TestUNIXSocket < Test::Unit::TestCase
+class TestSocket_UNIXSocket < Test::Unit::TestCase
def test_fd_passing
r1, w = IO.pipe
s1, s2 = UNIXSocket.pair
@@ -19,6 +24,7 @@ class TestUNIXSocket < Test::Unit::TestCase
r2 = s2.recv_io
assert_equal(r1.stat.ino, r2.stat.ino)
assert_not_equal(r1.fileno, r2.fileno)
+ assert(r2.close_on_exec?)
w.syswrite "a"
assert_equal("a", r2.sysread(10))
ensure
@@ -30,99 +36,399 @@ class TestUNIXSocket < Test::Unit::TestCase
end
end
+ def test_fd_passing_class_mode
+ UNIXSocket.pair do |s1, s2|
+ s1.send_io(s1.fileno)
+ r = s2.recv_io(nil)
+ assert_kind_of Integer, r, 'recv_io with klass=nil returns integer FD'
+ assert_not_equal s1.fileno, r
+ r = IO.for_fd(r)
+ assert_equal s1.stat.ino, r.stat.ino
+ r.close
+
+ s1.send_io(s1)
+ klass = UNIXSocket
+ r = s2.recv_io(klass)
+ assert_instance_of klass, r, 'recv_io with proper klass'
+ assert_not_equal s1.fileno, r.fileno
+ r.close
+
+ s1.send_io(s1)
+ klass = IO
+ r = s2.recv_io(klass, 'r+')
+ assert_instance_of klass, r, 'recv_io with proper klass and mode'
+ assert_not_equal s1.fileno, r.fileno
+ r.close
+ end
+ rescue NotImplementedError => error
+ omit error.message
+ end
+
+ def test_fd_passing_n
+ io_ary = []
+ return if !defined?(Socket::SCM_RIGHTS)
+ io_ary.concat IO.pipe
+ io_ary.concat IO.pipe
+ io_ary.concat IO.pipe
+ send_io_ary = []
+ io_ary.each {|io|
+ send_io_ary << io
+ UNIXSocket.pair {|s1, s2|
+ begin
+ ret = s1.sendmsg("\0", 0, nil, [Socket::SOL_SOCKET, Socket::SCM_RIGHTS,
+ send_io_ary.map {|io2| io2.fileno }.pack("i!*")])
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(1, ret)
+ ret = s2.recvmsg(:scm_rights=>true)
+ _, _, _, *ctls = ret
+ recv_io_ary = []
+ begin
+ ctls.each {|ctl|
+ next if ctl.level != Socket::SOL_SOCKET || ctl.type != Socket::SCM_RIGHTS
+ recv_io_ary.concat ctl.unix_rights
+ }
+ assert_equal(send_io_ary.length, recv_io_ary.length)
+ send_io_ary.length.times {|i|
+ assert_not_equal(send_io_ary[i].fileno, recv_io_ary[i].fileno)
+ assert(File.identical?(send_io_ary[i], recv_io_ary[i]))
+ assert(recv_io_ary[i].close_on_exec?)
+ }
+ ensure
+ recv_io_ary.each {|io2| io2.close if !io2.closed? }
+ end
+ }
+ }
+ ensure
+ io_ary.each {|io| io.close if !io.closed? }
+ end
+
+ def test_fd_passing_n2
+ io_ary = []
+ return if !defined?(Socket::SCM_RIGHTS)
+ return if !defined?(Socket::AncillaryData)
+ io_ary.concat IO.pipe
+ io_ary.concat IO.pipe
+ io_ary.concat IO.pipe
+ send_io_ary = []
+ io_ary.each {|io|
+ send_io_ary << io
+ UNIXSocket.pair {|s1, s2|
+ begin
+ ancdata = Socket::AncillaryData.unix_rights(*send_io_ary)
+ ret = s1.sendmsg("\0", 0, nil, ancdata)
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(1, ret)
+ ret = s2.recvmsg(:scm_rights=>true)
+ _, _, _, *ctls = ret
+ recv_io_ary = []
+ begin
+ ctls.each {|ctl|
+ next if ctl.level != Socket::SOL_SOCKET || ctl.type != Socket::SCM_RIGHTS
+ recv_io_ary.concat ctl.unix_rights
+ }
+ assert_equal(send_io_ary.length, recv_io_ary.length)
+ send_io_ary.length.times {|i|
+ assert_not_equal(send_io_ary[i].fileno, recv_io_ary[i].fileno)
+ assert(File.identical?(send_io_ary[i], recv_io_ary[i]))
+ assert(recv_io_ary[i].close_on_exec?)
+ }
+ ensure
+ recv_io_ary.each {|io2| io2.close if !io2.closed? }
+ end
+ }
+ }
+ ensure
+ io_ary.each {|io| io.close if !io.closed? }
+ end
+
+ def test_fd_passing_race_condition
+ omit 'randomly crashes on macOS' if RUBY_PLATFORM =~ /darwin/
+ r1, w = IO.pipe
+ s1, s2 = UNIXSocket.pair
+ s1.nonblock = s2.nonblock = true
+ lock = Thread::Mutex.new
+ nr = 0
+ x = 2
+ y = 400
+ begin
+ s1.send_io(nil)
+ rescue NotImplementedError
+ assert_raise(NotImplementedError) { s2.recv_io }
+ rescue TypeError
+ thrs = x.times.map do
+ Thread.new do
+ y.times do
+ s2.recv_io.close
+ lock.synchronize { nr += 1 }
+ end
+ true
+ end
+ end
+ (x * y).times { s1.send_io r1 }
+ assert_equal([true]*x, thrs.map { |t| t.value })
+ assert_equal x * y, nr
+ ensure
+ s1.close
+ s2.close
+ w.close
+ r1.close
+ end
+ end
+
+ def test_sendmsg
+ return if !defined?(Socket::SCM_RIGHTS)
+ IO.pipe {|r1, w|
+ UNIXSocket.pair {|s1, s2|
+ begin
+ ret = s1.sendmsg("\0", 0, nil, [Socket::SOL_SOCKET, Socket::SCM_RIGHTS, [r1.fileno].pack("i!")])
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(1, ret)
+ r2 = s2.recv_io
+ begin
+ assert(File.identical?(r1, r2))
+ assert(r2.close_on_exec?)
+ ensure
+ r2.close
+ end
+ }
+ }
+ end
+
+ def test_sendmsg_ancillarydata_int
+ return if !defined?(Socket::SCM_RIGHTS)
+ return if !defined?(Socket::AncillaryData)
+ IO.pipe {|r1, w|
+ UNIXSocket.pair {|s1, s2|
+ begin
+ ad = Socket::AncillaryData.int(:UNIX, :SOCKET, :RIGHTS, r1.fileno)
+ ret = s1.sendmsg("\0", 0, nil, ad)
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(1, ret)
+ r2 = s2.recv_io
+ begin
+ assert(File.identical?(r1, r2))
+ ensure
+ r2.close
+ end
+ }
+ }
+ end
+
+ def test_sendmsg_ancillarydata_unix_rights
+ return if !defined?(Socket::SCM_RIGHTS)
+ return if !defined?(Socket::AncillaryData)
+ IO.pipe {|r1, w|
+ UNIXSocket.pair {|s1, s2|
+ begin
+ ad = Socket::AncillaryData.unix_rights(r1)
+ ret = s1.sendmsg("\0", 0, nil, ad)
+ rescue NotImplementedError
+ return
+ end
+ assert_equal(1, ret)
+ r2 = s2.recv_io
+ begin
+ assert(File.identical?(r1, r2))
+ ensure
+ r2.close
+ end
+ }
+ }
+ end
+
+ def test_recvmsg
+ return if !defined?(Socket::SCM_RIGHTS)
+ return if !defined?(Socket::AncillaryData)
+ IO.pipe {|r1, w|
+ UNIXSocket.pair {|s1, s2|
+ s1.send_io(r1)
+ ret = s2.recvmsg(:scm_rights=>true)
+ data, srcaddr, flags, *ctls = ret
+ assert_equal("\0", data)
+ if flags == nil
+ # struct msghdr is 4.3BSD style (msg_accrights field).
+ assert_instance_of(Array, ctls)
+ assert_equal(0, ctls.length)
+ else
+ # struct msghdr is POSIX/4.4BSD style (msg_control field).
+ assert_equal(0, flags & (Socket::MSG_TRUNC|Socket::MSG_CTRUNC))
+ assert_instance_of(Addrinfo, srcaddr)
+ assert_instance_of(Array, ctls)
+ assert_equal(1, ctls.length)
+ ctl = ctls[0]
+ assert_instance_of(Socket::AncillaryData, ctl)
+ assert_equal(Socket::SOL_SOCKET, ctl.level)
+ assert_equal(Socket::SCM_RIGHTS, ctl.type)
+ assert_instance_of(String, ctl.data)
+ ios = ctl.unix_rights
+ assert_equal(1, ios.length)
+ r2 = ios[0]
+ begin
+ assert(File.identical?(r1, r2))
+ assert(r2.close_on_exec?)
+ ensure
+ r2.close
+ end
+ end
+ }
+ }
+ end
+
def bound_unix_socket(klass)
- tmpfile = Tempfile.new("testrubysock")
+ tmpfile = Tempfile.new("s")
path = tmpfile.path
tmpfile.close(true)
- yield klass.new(path), path
+ io = klass.new(path)
+ yield io, path
ensure
+ io.close
File.unlink path if path && File.socket?(path)
end
+ def test_open_argument
+ assert_raise(TypeError) {UNIXServer.new(nil)}
+ assert_raise(TypeError) {UNIXServer.new(1)}
+ Tempfile.create("s") do |s|
+ path = s.path
+ s.close
+ File.unlink(path)
+ assert_raise(ArgumentError) {UNIXServer.open(path+"\0")}
+ assert_raise(ArgumentError) {UNIXSocket.open(path+"\0")}
+ arg = Struct.new(:to_path).new(path)
+ assert_equal(path, UNIXServer.open(arg) { |server| server.path })
+ end
+ end
+
def test_addr
bound_unix_socket(UNIXServer) {|serv, path|
- c = UNIXSocket.new(path)
- s = serv.accept
- assert_equal(["AF_UNIX", path], c.peeraddr)
- assert_equal(["AF_UNIX", ""], c.addr)
- assert_equal(["AF_UNIX", ""], s.peeraddr)
- assert_equal(["AF_UNIX", path], s.addr)
- assert_equal(path, s.path)
- assert_equal("", c.path)
+ UNIXSocket.open(path) {|c|
+ s = serv.accept
+ begin
+ assert_equal(["AF_UNIX", path], c.peeraddr)
+ assert_equal(["AF_UNIX", ""], c.addr)
+ assert_equal(["AF_UNIX", ""], s.peeraddr)
+ assert_equal(["AF_UNIX", path], s.addr)
+ assert_equal(path, s.path)
+ assert_equal("", c.path)
+ ensure
+ s.close
+ end
+ }
+ }
+ end
+
+ def test_cloexec
+ bound_unix_socket(UNIXServer) {|serv, path|
+ UNIXSocket.open(path) {|c|
+ s = serv.accept
+ begin
+ assert(serv.close_on_exec?)
+ assert(c.close_on_exec?)
+ assert(s.close_on_exec?)
+ ensure
+ s.close
+ end
+ }
}
end
def test_noname_path
- s1, s2 = UNIXSocket.pair
- assert_equal("", s1.path)
- assert_equal("", s2.path)
- ensure
- s1.close
- s2.close
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit "unnamed pipe is emulated on windows"
+ end
+
+ UNIXSocket.pair do |s1, s2|
+ assert_equal("", s1.path)
+ assert_equal("", s2.path)
+ end
end
def test_noname_addr
- s1, s2 = UNIXSocket.pair
- assert_equal(["AF_UNIX", ""], s1.addr)
- assert_equal(["AF_UNIX", ""], s2.addr)
- ensure
- s1.close
- s2.close
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit "unnamed pipe is emulated on windows"
+ end
+
+ UNIXSocket.pair do |s1, s2|
+ assert_equal(["AF_UNIX", ""], s1.addr)
+ assert_equal(["AF_UNIX", ""], s2.addr)
+ end
end
def test_noname_peeraddr
- s1, s2 = UNIXSocket.pair
- assert_equal(["AF_UNIX", ""], s1.peeraddr)
- assert_equal(["AF_UNIX", ""], s2.peeraddr)
- ensure
- s1.close
- s2.close
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit "unnamed pipe is emulated on windows"
+ end
+
+ UNIXSocket.pair do |s1, s2|
+ assert_equal(["AF_UNIX", ""], s1.peeraddr)
+ assert_equal(["AF_UNIX", ""], s2.peeraddr)
+ end
end
def test_noname_unpack_sockaddr_un
- s1, s2 = UNIXSocket.pair
- n = nil
- assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
- assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
- assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getsockname) != ""
- assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getpeername) != ""
- assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getpeername) != ""
- ensure
- s1.close
- s2.close
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit "unnamed pipe is emulated on windows"
+ end
+
+ UNIXSocket.pair do |s1, s2|
+ n = nil
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getsockname) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s1.getpeername) != ""
+ assert_equal("", Socket.unpack_sockaddr_un(n)) if (n = s2.getpeername) != ""
+ end
end
def test_noname_recvfrom
- s1, s2 = UNIXSocket.pair
- s2.write("a")
- assert_equal(["a", ["AF_UNIX", ""]], s1.recvfrom(10))
- ensure
- s1.close
- s2.close
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit "unnamed pipe is emulated on windows"
+ end
+
+ UNIXSocket.pair do |s1, s2|
+ s2.write("a")
+ assert_equal(["a", ["AF_UNIX", ""]], s1.recvfrom(10))
+ end
end
def test_noname_recv_nonblock
- s1, s2 = UNIXSocket.pair
- s2.write("a")
- IO.select [s1]
- assert_equal("a", s1.recv_nonblock(10))
- ensure
- s1.close
- s2.close
+ UNIXSocket.pair do |s1, s2|
+ s2.write("a")
+ IO.select [s1]
+ assert_equal("a", s1.recv_nonblock(10))
+ end
end
def test_too_long_path
- assert_raise(ArgumentError) { Socket.sockaddr_un("a" * 300) }
- assert_raise(ArgumentError) { UNIXServer.new("a" * 300) }
+ assert_raise(ArgumentError) { Socket.sockaddr_un("a" * 3000) }
+ assert_raise(ArgumentError) { UNIXServer.new("a" * 3000) }
end
- def test_nul
- assert_raise(ArgumentError) { Socket.sockaddr_un("a\0b") }
+ def test_abstract_namespace
+ return if /linux/ !~ RUBY_PLATFORM
+ addr = Socket.pack_sockaddr_un("\0foo")
+ assert_match(/\0foo\z/, addr)
+ assert_equal("\0foo", Socket.unpack_sockaddr_un(addr))
end
def test_dgram_pair
s1, s2 = UNIXSocket.pair(Socket::SOCK_DGRAM)
- assert_raise(Errno::EAGAIN) { s1.recv_nonblock(10) }
+ begin
+ s1.recv_nonblock(10)
+ fail
+ rescue => e
+ assert_kind_of(IO::EWOULDBLOCKWaitReadable, e)
+ assert_kind_of(IO::WaitReadable, e)
+ end
+
s2.send("", 0)
s2.send("haha", 0)
s2.send("", 0)
@@ -131,10 +437,415 @@ class TestUNIXSocket < Test::Unit::TestCase
assert_equal("haha", s1.recv(10))
assert_equal("", s1.recv(10))
assert_equal("", s1.recv(10))
- assert_raise(Errno::EAGAIN) { s1.recv_nonblock(10) }
+ assert_raise(IO::EAGAINWaitReadable) { s1.recv_nonblock(10) }
+
+ buf = "".dup
+ s2.send("BBBBBB", 0)
+ IO.select([s1])
+ rv = s1.recv(100, 0, buf)
+ assert_equal buf.object_id, rv.object_id
+ assert_equal "BBBBBB", rv
+ rescue Errno::EPROTOTYPE => error
+ omit error.message
+ ensure
+ s1.close if s1
+ s2.close if s2
+ end
+
+ def test_stream_pair
+ s1, s2 = UNIXSocket.pair(Socket::SOCK_STREAM)
+ begin
+ s1.recv_nonblock(10)
+ fail
+ rescue => e
+ assert_kind_of(IO::EWOULDBLOCKWaitReadable, e)
+ assert_kind_of(IO::WaitReadable, e)
+ end
+
+ s2.send("", 0)
+ s2.send("haha", 0)
+ assert_equal("haha", s1.recv(10))
+ assert_raise(IO::EWOULDBLOCKWaitReadable) { s1.recv_nonblock(10) }
+
+ buf = "".dup
+ s2.send("BBBBBB", 0)
+ IO.select([s1])
+ rv = s1.recv(100, 0, buf)
+ assert_equal buf.object_id, rv.object_id
+ assert_equal "BBBBBB", rv
+
+ s2.close
+ assert_nil(s1.recv(10))
+ rescue Errno::EPROTOTYPE => error
+ omit error.message
ensure
s1.close if s1
s2.close if s2
end
+ def test_seqpacket_pair
+ s1, s2 = UNIXSocket.pair(Socket::SOCK_SEQPACKET)
+ begin
+ s1.recv_nonblock(10)
+ fail
+ rescue => e
+ assert_kind_of(IO::EWOULDBLOCKWaitReadable, e)
+ assert_kind_of(IO::WaitReadable, e)
+ end
+
+ s2.send("haha", 0)
+ assert_equal("haha", s1.recv(10))
+ assert_raise(IO::EWOULDBLOCKWaitReadable) { s1.recv_nonblock(10) }
+
+ buf = "".dup
+ s2.send("BBBBBB", 0)
+ IO.select([s1])
+ rv = s1.recv(100, 0, buf)
+ assert_equal buf.object_id, rv.object_id
+ assert_equal "BBBBBB", rv
+
+ s2.close
+ assert_nil(s1.recv(10))
+ rescue Errno::EPROTOTYPE, Errno::EPROTONOSUPPORT => error
+ omit error.message
+ ensure
+ s1.close if s1
+ s2.close if s2
+ end
+
+ def test_dgram_pair_sendrecvmsg_errno_set
+ if /mswin|mingw/ =~ RUBY_PLATFORM
+ omit("AF_UNIX + SOCK_DGRAM is not supported on windows")
+ end
+
+ s1, s2 = to_close = UNIXSocket.pair(Socket::SOCK_DGRAM)
+ pipe = IO.pipe
+ to_close.concat(pipe)
+ set_errno = lambda do
+ begin
+ pipe[0].read_nonblock(1)
+ fail
+ rescue => e
+ assert(IO::EAGAINWaitReadable === e)
+ end
+ end
+ Timeout.timeout(10) do
+ set_errno.call
+ assert_equal(2, s1.sendmsg("HI"))
+ set_errno.call
+ assert_equal("HI", s2.recvmsg[0])
+ end
+ ensure
+ to_close.each(&:close) if to_close
+ end
+
+ def test_epipe # [ruby-dev:34619]
+ # This is a good example of why reporting the exact `errno` is a terrible
+ # idea for platform abstractions.
+ if RUBY_PLATFORM =~ /mswin|mingw/
+ error = Errno::ESHUTDOWN
+ else
+ error = Errno::EPIPE
+ end
+
+ UNIXSocket.pair {|s1, s2|
+ s1.shutdown(Socket::SHUT_WR)
+ assert_raise(error) { s1.write "a" }
+ assert_equal(nil, s2.read(1))
+ s2.write "a"
+ assert_equal("a", s1.read(1))
+ }
+ end
+
+ def test_socket_pair_with_block
+ pair = nil
+ ret = Socket.pair(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) {|s1, s2|
+ pair = [s1, s2]
+ :return_value
+ }
+ assert_equal(:return_value, ret)
+ assert_kind_of(Socket, pair[0])
+ assert_kind_of(Socket, pair[1])
+ end
+
+ def test_unix_socket_pair_with_block
+ pair = nil
+ UNIXSocket.pair {|s1, s2|
+ pair = [s1, s2]
+ }
+ assert_kind_of(UNIXSocket, pair[0])
+ assert_kind_of(UNIXSocket, pair[1])
+ end
+
+ def test_unix_socket_pair_close_on_exec
+ UNIXSocket.pair {|s1, s2|
+ assert(s1.close_on_exec?)
+ assert(s2.close_on_exec?)
+ }
+ end
+
+ if /mingw|mswin/ =~ RUBY_PLATFORM
+
+ def test_unix_socket_with_encoding
+ Dir.mktmpdir do |tmpdir|
+ path = "#{tmpdir}/sockäöü".encode("cp850")
+ UNIXServer.open(path) do |serv|
+ assert File.socket?(path)
+ assert File.stat(path).socket?
+ assert File.lstat(path).socket?
+ assert_equal path.encode("utf-8"), serv.path
+ UNIXSocket.open(path) do |s1|
+ s2 = serv.accept
+ s2.close
+ end
+ end
+ end
+ end
+
+ def test_windows_unix_socket_pair_with_umlaut
+ otmp = ENV['TMP']
+ ENV['TMP'] = File.join(Dir.tmpdir, "äöü€")
+ FileUtils.mkdir_p ENV['TMP']
+
+ s1, = UNIXSocket.pair
+ assert !s1.path.empty?
+ assert !File.exist?(s1.path)
+ ensure
+ FileUtils.rm_rf ENV['TMP']
+ ENV['TMP'] = otmp
+ end
+
+ def test_windows_unix_socket_pair_paths
+ s1, s2 = UNIXSocket.pair
+ assert !s1.path.empty?
+ assert s2.path.empty?
+ assert !File.exist?(s1.path)
+ end
+ end
+
+ def test_initialize
+ Dir.mktmpdir {|d|
+ Socket.open(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) {|s|
+ s.bind(Socket.pack_sockaddr_un("#{d}/s1"))
+ addr = s.getsockname
+ assert_nothing_raised { Socket.unpack_sockaddr_un(addr) }
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_in(addr) }
+ }
+ Socket.open("AF_UNIX", "SOCK_STREAM", 0) {|s|
+ s.bind(Socket.pack_sockaddr_un("#{d}/s2"))
+ addr = s.getsockname
+ assert_nothing_raised { Socket.unpack_sockaddr_un(addr) }
+ assert_raise(ArgumentError) { Socket.unpack_sockaddr_in(addr) }
+ }
+ }
+ end
+
+ def test_unix_server_socket
+ Dir.mktmpdir {|d|
+ path = "#{d}/sock"
+ s0 = nil
+ Socket.unix_server_socket(path) {|s|
+ assert_equal(path, s.local_address.unix_path)
+ assert(File.socket?(path))
+ s0 = s
+ }
+ assert(s0.closed?)
+ assert_raise(Errno::ENOENT) { File.stat path }
+ }
+ end
+
+ def test_getcred_ucred
+ return if /linux/ !~ RUBY_PLATFORM
+ Dir.mktmpdir {|d|
+ sockpath = "#{d}/sock"
+ Socket.unix_server_socket(sockpath) {|serv|
+ Socket.unix(sockpath) {|c|
+ s, = serv.accept
+ begin
+ cred = s.getsockopt(:SOCKET, :PEERCRED)
+ inspect = cred.inspect
+ assert_match(/ pid=#{$$} /, inspect)
+ assert_match(/ euid=#{Process.euid} /, inspect)
+ assert_match(/ egid=#{Process.egid} /, inspect)
+ assert_match(/ \(ucred\)/, inspect)
+ ensure
+ s.close
+ end
+ }
+ }
+ }
+ end
+
+ def test_getcred_xucred
+ return if /freebsd|darwin/ !~ RUBY_PLATFORM
+ Dir.mktmpdir do |d|
+ sockpath = "#{d}/sock"
+ serv = Socket.unix_server_socket(sockpath)
+ u = Socket.unix(sockpath)
+ s, = serv.accept
+ cred = s.getsockopt(0, Socket::LOCAL_PEERCRED)
+ inspect = cred.inspect
+ assert_match(/ euid=#{Process.euid} /, inspect)
+ assert_match(/ \(xucred\)/, inspect)
+ ensure
+ s&.close
+ u&.close
+ serv&.close
+ end
+ end
+
+ def test_sendcred_ucred
+ return if /linux/ !~ RUBY_PLATFORM
+ Dir.mktmpdir {|d|
+ sockpath = "#{d}/sock"
+ Socket.unix_server_socket(sockpath) {|serv|
+ Socket.unix(sockpath) {|c|
+ s, = serv.accept
+ begin
+ s.setsockopt(:SOCKET, :PASSCRED, 1)
+ c.print "a"
+ msg, _, _, cred = s.recvmsg
+ inspect = cred.inspect
+ assert_equal("a", msg)
+ assert_match(/ pid=#{$$} /, inspect)
+ assert_match(/ uid=#{Process.uid} /, inspect)
+ assert_match(/ gid=#{Process.gid} /, inspect)
+ assert_match(/ \(ucred\)/, inspect)
+ ensure
+ s.close
+ end
+ }
+ }
+ }
+ end
+
+ def test_sendcred_sockcred
+ return if /netbsd|freebsd/ !~ RUBY_PLATFORM
+ Dir.mktmpdir {|d|
+ sockpath = "#{d}/sock"
+ serv = Socket.unix_server_socket(sockpath)
+ c = Socket.unix(sockpath)
+ s, = serv.accept
+ s.setsockopt(0, Socket::LOCAL_CREDS, 1)
+ c.print "a"
+ msg, _, _, cred = s.recvmsg
+ assert_equal("a", msg)
+ inspect = cred.inspect
+ assert_match(/ uid=#{Process.uid} /, inspect)
+ assert_match(/ euid=#{Process.euid} /, inspect)
+ assert_match(/ gid=#{Process.gid} /, inspect)
+ assert_match(/ egid=#{Process.egid} /, inspect)
+ assert_match(/ \(sockcred\)/, inspect)
+ }
+ end
+
+ def test_sendcred_cmsgcred
+ return if /freebsd/ !~ RUBY_PLATFORM
+ Dir.mktmpdir {|d|
+ sockpath = "#{d}/sock"
+ serv = Socket.unix_server_socket(sockpath)
+ c = Socket.unix(sockpath)
+ s, = serv.accept
+ c.sendmsg("a", 0, nil, [:SOCKET, Socket::SCM_CREDS, ""])
+ msg, _, _, cred = s.recvmsg
+ assert_equal("a", msg)
+ inspect = cred.inspect
+ assert_match(/ pid=#{$$} /, inspect)
+ assert_match(/ uid=#{Process.uid} /, inspect)
+ assert_match(/ euid=#{Process.euid} /, inspect)
+ assert_match(/ gid=#{Process.gid} /, inspect)
+ assert_match(/ \(cmsgcred\)/, inspect)
+ }
+ end
+
+ def test_getpeereid
+ Dir.mktmpdir {|d|
+ path = "#{d}/sock"
+ Socket.unix_server_socket(path) {|serv|
+ Socket.unix(path) {|c|
+ s, = serv.accept
+ begin
+ assert_equal([Process.euid, Process.egid], c.getpeereid)
+ assert_equal([Process.euid, Process.egid], s.getpeereid)
+ rescue NotImplementedError
+ ensure
+ s.close
+ end
+ }
+ }
+ }
+ end
+
+ def test_abstract_unix_server
+ return if /linux/ !~ RUBY_PLATFORM
+ name = "\0ruby-test_unix"
+ s0 = nil
+ UNIXServer.open(name) {|s|
+ assert_equal(name, s.local_address.unix_path)
+ s0 = s
+ UNIXSocket.open(name) {|c|
+ sock = s.accept
+ begin
+ assert_equal(name, c.remote_address.unix_path)
+ ensure
+ sock.close
+ end
+ }
+ }
+ assert(s0.closed?)
+ end
+
+ def test_abstract_unix_socket_econnrefused
+ return if /linux/ !~ RUBY_PLATFORM
+ name = "\0ruby-test_unix"
+ assert_raise(Errno::ECONNREFUSED) do
+ UNIXSocket.open(name) {}
+ end
+ end
+
+ def test_abstract_unix_server_socket
+ return if /linux/ !~ RUBY_PLATFORM
+ name = "\0ruby-test_unix"
+ s0 = nil
+ Socket.unix_server_socket(name) {|s|
+ assert_equal(name, s.local_address.unix_path)
+ s0 = s
+ Socket.unix(name) {|c|
+ sock, = s.accept
+ begin
+ assert_equal(name, c.remote_address.unix_path)
+ ensure
+ sock.close
+ end
+ }
+ }
+ assert(s0.closed?)
+ end
+
+ def test_autobind
+ return if /linux/ !~ RUBY_PLATFORM
+ s0 = nil
+ Socket.unix_server_socket("") {|s|
+ name = s.local_address.unix_path
+ assert_match(/\A\0[0-9a-f]{5}\z/, name)
+ s0 = s
+ Socket.unix(name) {|c|
+ sock, = s.accept
+ begin
+ assert_equal(name, c.remote_address.unix_path)
+ ensure
+ sock.close
+ end
+ }
+ }
+ assert(s0.closed?)
+ end
+
+ def test_accept_nonblock
+ bound_unix_socket(UNIXServer) {|serv, path|
+ assert_raise(IO::WaitReadable) { serv.accept_nonblock }
+ assert_raise(IO::WaitReadable) { serv.accept_nonblock(exception: true) }
+ assert_equal :wait_readable, serv.accept_nonblock(exception: false)
+ }
+ end
end if defined?(UNIXSocket) && /cygwin/ !~ RUBY_PLATFORM