diff options
Diffstat (limited to 'test/socket')
| -rw-r--r-- | test/socket/test_addrinfo.rb | 78 | ||||
| -rw-r--r-- | test/socket/test_ancdata.rb | 2 | ||||
| -rw-r--r-- | test/socket/test_basicsocket.rb | 162 | ||||
| -rw-r--r-- | test/socket/test_nonblock.rb | 114 | ||||
| -rw-r--r-- | test/socket/test_socket.rb | 534 | ||||
| -rw-r--r-- | test/socket/test_sockopt.rb | 15 | ||||
| -rw-r--r-- | test/socket/test_tcp.rb | 358 | ||||
| -rw-r--r-- | test/socket/test_udp.rb | 48 | ||||
| -rw-r--r-- | test/socket/test_unix.rb | 285 |
9 files changed, 1473 insertions, 123 deletions
diff --git a/test/socket/test_addrinfo.rb b/test/socket/test_addrinfo.rb index 61b889ed26..0c9529090e 100644 --- a/test/socket/test_addrinfo.rb +++ b/test/socket/test_addrinfo.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + begin require "socket" rescue LoadError @@ -27,6 +29,22 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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 @@ -36,6 +54,14 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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 @@ -76,6 +102,14 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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", @@ -323,17 +357,31 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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(SocketError) { Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("::1", 80) } + 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 - 49152 + rand(65535-49152+1) + case RUBY_PLATFORM + when /mingw|mswin/ + rand(50000..65535) + else + rand(49152..65535) + end end def errors_addrinuse - [Errno::EADDRINUSE] + 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 @@ -468,6 +516,17 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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 @@ -531,7 +590,14 @@ class TestSocketAddrinfo < Test::Unit::TestCase # 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) - assert(ai.ipv4? || ai.send(meth), "ai=#{addr_exp}; ai.ipv4? || .#{meth}") + 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) @@ -636,5 +702,9 @@ class TestSocketAddrinfo < Test::Unit::TestCase 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 index 112b0c9e58..b2f86a0bb1 100644 --- a/test/socket/test_ancdata.rb +++ b/test/socket/test_ancdata.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test/unit' require 'socket' diff --git a/test/socket/test_basicsocket.rb b/test/socket/test_basicsocket.rb index 59b739e813..8c1b434a83 100644 --- a/test/socket/test_basicsocket.rb +++ b/test/socket/test_basicsocket.rb @@ -1,6 +1,9 @@ +# frozen_string_literal: true + begin require "socket" require "test/unit" + require "io/nonblock" rescue LoadError end @@ -9,25 +12,33 @@ class TestSocket_BasicSocket < Test::Unit::TestCase sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) yield sock ensure - assert_raise(IOError) {sock.close} + assert(sock.closed?) 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.data) + 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(: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, :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) + 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) { @@ -85,4 +96,133 @@ class TestSocket_BasicSocket < Test::Unit::TestCase } 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 882e438deb..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 @@ -13,6 +17,8 @@ class TestSocketNonblock < Test::Unit::TestCase serv.bind(Socket.sockaddr_in(0, "127.0.0.1")) serv.listen(5) 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) begin @@ -22,6 +28,9 @@ class TestSocketNonblock < Test::Unit::TestCase 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 @@ -53,6 +62,31 @@ class TestSocketNonblock < 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 @@ -70,7 +104,7 @@ class TestSocketNonblock < Test::Unit::TestCase 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) @@ -92,10 +126,20 @@ class TestSocketNonblock < Test::Unit::TestCase 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 @@ -141,11 +185,11 @@ class TestSocketNonblock < Test::Unit::TestCase def udp_pair s1 = UDPSocket.new s1.bind('127.0.0.1', 0) - af, port1, host, addr1 = s1.addr + _, port1, _, addr1 = s1.addr s2 = UDPSocket.new s2.bind('127.0.0.1', 0) - af, port2, host, addr2 = s2.addr + _, port2, _, addr2 = s2.addr s1.connect(addr2, port2) s2.connect(addr1, port1) @@ -235,7 +279,7 @@ class TestSocketNonblock < Test::Unit::TestCase s1.sendmsg_nonblock("a" * 100000) } rescue NotImplementedError, Errno::ENOSYS - skip "sendmsg not implemented on this platform: #{$!}" + omit "sendmsg not implemented on this platform: #{$!}" rescue Errno::EMSGSIZE # UDP has 64K limit (if no Jumbograms). No problem. rescue Errno::EWOULDBLOCK @@ -244,15 +288,63 @@ class TestSocketNonblock < Test::Unit::TestCase } 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 - skip "recvmsg not implemented on this platform." + 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 @@ -266,6 +358,16 @@ class TestSocketNonblock < Test::Unit::TestCase } 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 diff --git a/test/socket/test_socket.rb b/test/socket/test_socket.rb index 1db0ea251d..c42527f370 100644 --- a/test/socket/test_socket.rb +++ b/test/socket/test_socket.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + begin require "socket" require "tmpdir" @@ -78,7 +80,7 @@ class TestSocket < Test::Unit::TestCase port, = Socket.unpack_sockaddr_in(addr) Socket.open(Socket::AF_INET, Socket::SOCK_STREAM, 0) {|s| - e = assert_raises(Errno::EADDRINUSE) do + e = assert_raise(Errno::EADDRINUSE) do s.bind(Socket.sockaddr_in(port, "127.0.0.1")) end @@ -89,20 +91,22 @@ class TestSocket < Test::Unit::TestCase def test_getaddrinfo # This should not send a DNS query because AF_UNIX. - assert_raise(SocketError) { Socket.getaddrinfo("www.kame.net", 80, "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(SocketError, '[ruby-core:29427]'){ Socket.getaddrinfo(nil, nil, 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(SocketError) { Socket.getnameinfo(["AF_UNIX", 80, "0.0.0.0"]) } + 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 @@ -117,6 +121,15 @@ class TestSocket < Test::Unit::TestCase } 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 @@ -150,11 +163,22 @@ class TestSocket < Test::Unit::TestCase def random_port # IANA suggests dynamic port for 49152 to 65535 # http://www.iana.org/assignments/port-numbers - 49152 + rand(65535-49152+1) + case RUBY_PLATFORM + when /mingw|mswin/ + rand(50000..65535) + else + rand(49152..65535) + end end def errors_addrinuse - [Errno::EADDRINUSE] + 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 @@ -238,9 +262,12 @@ class TestSocket < Test::Unit::TestCase unix_server = Socket.unix_server_socket("#{tmpdir}/sock") tcp_servers.each {|s| addr = s.connect_address - assert_nothing_raised("connect to #{addr.inspect}") { + 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}") { @@ -316,10 +343,14 @@ class TestSocket < Test::Unit::TestCase 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 - skip "Socket.getifaddrs not implemented" + omit "Socket.getifaddrs not implemented" end ifconfig = nil @@ -373,11 +404,10 @@ class TestSocket < Test::Unit::TestCase 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 - else - 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 + 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 @@ -414,16 +444,18 @@ class TestSocket < Test::Unit::TestCase } rescue NotImplementedError, Errno::ENOSYS skipped = true - skip "need sendmsg and recvmsg: #{$!}" + omit "need sendmsg and recvmsg: #{$!}" + rescue RuntimeError + skipped = true + omit "UDP server is no response: #{$!}" ensure if th - if skipped - Thread.kill th unless th.join(10) - else + unless skipped Addrinfo.udp("127.0.0.1", port).connect {|s| s.sendmsg "exit" } - unless th.join(10) - Thread.kill th - th.join(10) + end + unless th.join(10) + th.kill.join(10) + unless skipped raise "thread killed" end end @@ -449,25 +481,52 @@ class TestSocket < Test::Unit::TestCase } 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 + def test_timestamp - return if /linux|freebsd|netbsd|openbsd|solaris|darwin/ !~ RUBY_PLATFORM - return if !defined?(Socket::AncillaryData) + 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) - s2.send "a", 0, s1.local_address - msg, _, _, stamp = s1.recvmsg - assert_equal("a", msg) - assert(stamp.cmsg_is?(:SOCKET, :TIMESTAMP)) + stamp = timestamp_retry_rw(s1, s2, t1, :TIMESTAMP) } } - 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")) pat = /\.#{"%06d" % t.usec}/ assert_match(pat, stamp.inspect) end @@ -484,17 +543,10 @@ class TestSocket < Test::Unit::TestCase # SO_TIMESTAMPNS is available since Linux 2.6.22 return end - s2.send "a", 0, s1.local_address - msg, _, _, stamp = s1.recvmsg - assert_equal("a", msg) - assert(stamp.cmsg_is?(:SOCKET, :TIMESTAMPNS)) + stamp = timestamp_retry_rw(s1, s2, t1, :TIMESTAMPNS) } } - 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")) pat = /\.#{"%09d" % t.nsec}/ assert_match(pat, stamp.inspect) end @@ -529,18 +581,20 @@ class TestSocket < Test::Unit::TestCase begin sleep(0.1) end until serv_thread.stop? sock = TCPSocket.new("localhost", server.addr[1]) client_thread = Thread.new do - sock.readline + assert_raise(IOError, bug4390) { + sock.readline + } end begin sleep(0.1) end until client_thread.stop? Timeout.timeout(1) do sock.close sock = nil - assert_raise(IOError, bug4390) {client_thread.join} + client_thread.join end ensure serv_thread.value.close server.close - end + end unless RUBY_PLATFORM.include?("freebsd") def test_connect_timeout host = "127.0.0.1" @@ -556,7 +610,7 @@ class TestSocket < Test::Unit::TestCase # 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_raises(Errno::ETIMEDOUT) do + 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], @@ -651,4 +705,398 @@ class TestSocket < Test::Unit::TestCase end end + 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 + 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 index 2ee06dbecd..7e343e8c36 100644 --- a/test/socket/test_sockopt.rb +++ b/test/socket/test_sockopt.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'test/unit' require 'socket' @@ -23,6 +25,19 @@ class TestSocketOption < Test::Unit::TestCase 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 diff --git a/test/socket/test_tcp.rb b/test/socket/test_tcp.rb index 7328897d1e..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" @@ -6,10 +8,25 @@ end 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) + } + } + 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 choosen because probably they are not used as a host address. + # 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 = [ @@ -32,16 +49,58 @@ class TestSocket_TCPSocket < Test::Unit::TestCase server_addr = '127.0.0.1' server_port = 80 - begin + 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) - flunk "expected SystemCallError" - rescue SystemCallError => e - assert_match "for \"#{client_addr}\" port #{client_port}", e.message + 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 - ensure - t.close if t && !t.closed? end def test_recvfrom @@ -76,4 +135,289 @@ class TestSocket_TCPSocket < Test::Unit::TestCase 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 + 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 b07a4b73b3..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" @@ -13,6 +15,21 @@ class TestSocket_UDPSocket < Test::Unit::TestCase 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 @@ -48,7 +65,7 @@ class TestSocket_UDPSocket < Test::Unit::TestCase s = UDPSocket.new - e = assert_raises(Errno::EADDRINUSE) do + e = assert_raise(Errno::EADDRINUSE) do s.bind(host, port) end @@ -61,7 +78,7 @@ class TestSocket_UDPSocket < Test::Unit::TestCase def test_send_too_long u = UDPSocket.new - e = assert_raises Errno::EMSGSIZE do + e = assert_raise(Errno::EMSGSIZE) do u.send "\0" * 100_000, 0, "127.0.0.1", 7 # echo end @@ -69,4 +86,31 @@ class TestSocket_UDPSocket < Test::Unit::TestCase 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 866c83906e..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 @@ -7,7 +9,6 @@ require "test/unit" require "tempfile" require "timeout" require "tmpdir" -require "thread" require "io/nonblock" class TestSocket_UNIXSocket < Test::Unit::TestCase @@ -35,6 +36,34 @@ class TestSocket_UNIXSocket < 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) @@ -117,13 +146,14 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase 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 = Mutex.new + lock = Thread::Mutex.new nr = 0 x = 2 - y = 1000 + y = 400 begin s1.send_io(nil) rescue NotImplementedError @@ -263,6 +293,20 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase 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| UNIXSocket.open(path) {|c| @@ -297,62 +341,70 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase 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 @@ -373,9 +425,10 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase s1.recv_nonblock(10) fail rescue => e - assert(IO::EAGAINWaitReadable === e) - assert(IO::WaitReadable === e) + assert_kind_of(IO::EWOULDBLOCKWaitReadable, e) + assert_kind_of(IO::WaitReadable, e) end + s2.send("", 0) s2.send("haha", 0) s2.send("", 0) @@ -385,12 +438,86 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase assert_equal("", s1.recv(10)) assert_equal("", s1.recv(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) @@ -413,9 +540,17 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase 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(Errno::EPIPE) { s1.write "a" } + assert_raise(error) { s1.write "a" } assert_equal(nil, s2.read(1)) s2.write "a" assert_equal("a", s1.read(1)) @@ -449,6 +584,45 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase } 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| @@ -504,16 +678,20 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase def test_getcred_xucred return if /freebsd|darwin/ !~ RUBY_PLATFORM - Dir.mktmpdir {|d| + Dir.mktmpdir do |d| sockpath = "#{d}/sock" serv = Socket.unix_server_socket(sockpath) - Socket.unix(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 @@ -663,4 +841,11 @@ class TestSocket_UNIXSocket < Test::Unit::TestCase 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 |
