implement TCP Fast Open support (client + server)
[kgio.git] / test / test_tfo.rb
blob846e273dc065d73c3264d78d4750fe85a9ee6a87
1 require 'test/unit'
2 require 'kgio'
4 class TestTFO < Test::Unit::TestCase
5   def test_constants
6     if `uname -s`.chomp == "Linux" && `uname -r`.to_f >= 3.7
7       assert_equal 23, Kgio::TCP_FASTOPEN
8       assert_equal 0x20000000, Kgio::MSG_FASTOPEN
9     end
10   end
12   def fastopen_ok?
13     if RUBY_PLATFORM =~ /linux/
14       tfo = File.read("/proc/sys/net/ipv4/tcp_fastopen").to_i
15       client_enable = 1
16       server_enable = 2
17       enable = client_enable | server_enable
18       (tfo & enable) == enable
19     else
20       false
21     end
22   end
24   def test_tfo_client_server
25     unless fastopen_ok?
26       warn "TCP Fast Open not enabled on this system (check kernel docs)"
27       return
28     end
29     addr = '127.0.0.1'
30     qlen = 1024
31     s = Kgio::TCPServer.new(addr, 0)
32     s.setsockopt(:TCP, Kgio::TCP_FASTOPEN, qlen)
33     port = s.local_address.ip_port
34     addr = Socket.pack_sockaddr_in(port, addr)
35     c = Kgio::Socket.new(:INET, :STREAM)
36     assert_nil c.fastopen("HELLO", addr)
37     a = s.accept
38     assert_equal "HELLO", a.read(5)
39     c.close
40     a.close
42     # ensure empty sends work
43     c = Kgio::Socket.new(:INET, :STREAM)
44     assert_nil c.fastopen("", addr)
45     a = s.accept
46     Thread.new { c.close }
47     assert_nil a.read(1)
48     a.close
50     # try a monster packet
51     buf = 'x' * (1024 * 1024 * 320)
53     c = Kgio::Socket.new(:INET, :STREAM)
54     thr = Thread.new do
55       a = s.accept
56       assert_equal buf.size, a.read(buf.size).size
57       a.close
58     end
59     assert_nil c.fastopen(buf, addr)
60     thr.join
61     c.close
63     # allow timeouts
64     c = Kgio::Socket.new(:INET, :STREAM)
65     c.setsockopt(:SOCKET, :SNDTIMEO, [ 0, 10 ].pack("l_l_"))
66     unsent = c.fastopen(buf, addr)
67     c.close
68     assert_equal s.accept.read.size + unsent.size, buf.size
69   end if defined?(Addrinfo) && defined?(Kgio::TCP_FASTOPEN)
70 end