socket_helper: remove out-of-date comment for TCP_NODELAY
[unicorn.git] / lib / unicorn / socket_helper.rb
blob168a4873f99595e84ab4ea8296bab923bb92b116
1 # -*- encoding: binary -*-
2 # :enddoc:
3 require 'socket'
5 module Unicorn
6   module SocketHelper
7     # :stopdoc:
8     include Socket::Constants
10     # prevents IO objects in here from being GC-ed
11     IO_PURGATORY = []
13     # internal interface, only used by Rainbows!/Zbatery
14     DEFAULTS = {
15       # The semantics for TCP_DEFER_ACCEPT changed in Linux 2.6.32+
16       # with commit d1b99ba41d6c5aa1ed2fc634323449dd656899e9
17       # This change shouldn't affect Unicorn users behind nginx (a
18       # value of 1 remains an optimization), but Rainbows! users may
19       # want to use a higher value on Linux 2.6.32+ to protect against
20       # denial-of-service attacks
21       :tcp_defer_accept => 1,
23       # FreeBSD, we need to override this to 'dataready' if we
24       # eventually get HTTPS support
25       :accept_filter => 'httpready',
27       # same default value as Mongrel
28       :backlog => 1024,
30       # favor latency over bandwidth savings
31       :tcp_nopush => false,
32       :tcp_nodelay => true,
33     }
34     #:startdoc:
36     # configure platform-specific options (only tested on Linux 2.6 so far)
37     case RUBY_PLATFORM
38     when /linux/
39       # from /usr/include/linux/tcp.h
40       TCP_DEFER_ACCEPT = 9 unless defined?(TCP_DEFER_ACCEPT)
42       # do not send out partial frames (Linux)
43       TCP_CORK = 3 unless defined?(TCP_CORK)
44     when /freebsd/
45       # do not send out partial frames (FreeBSD)
46       TCP_NOPUSH = 4 unless defined?(TCP_NOPUSH)
48       def accf_arg(af_name)
49         [ af_name, nil ].pack('a16a240')
50       end if defined?(SO_ACCEPTFILTER)
51     end
53     def set_tcp_sockopt(sock, opt)
54       if defined?(TCP_NODELAY)
55         val = opt[:tcp_nodelay]
56         val = DEFAULTS[:tcp_nodelay] if nil == val
57         sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, val ? 1 : 0)
58       end
60       val = opt[:tcp_nopush]
61       val = DEFAULTS[:tcp_nopush] if nil == val
62       val = val ? 1 : 0
63       if defined?(TCP_CORK) # Linux
64         sock.setsockopt(IPPROTO_TCP, TCP_CORK, val)
65       elsif defined?(TCP_NOPUSH) # TCP_NOPUSH is untested (FreeBSD)
66         sock.setsockopt(IPPROTO_TCP, TCP_NOPUSH, val)
67       end
69       # No good reason to ever have deferred accepts off
70       # (except maybe benchmarking)
71       if defined?(TCP_DEFER_ACCEPT)
72         # this differs from nginx, since nginx doesn't allow us to
73         # configure the the timeout...
74         seconds = opt[:tcp_defer_accept]
75         seconds = DEFAULTS[:tcp_defer_accept] if [true,nil].include?(seconds)
76         seconds = 0 unless seconds # nil/false means disable this
77         sock.setsockopt(SOL_TCP, TCP_DEFER_ACCEPT, seconds)
78       elsif respond_to?(:accf_arg)
79         name = opt[:accept_filter]
80         name = DEFAULTS[:accept_filter] if nil == name
81         begin
82           sock.setsockopt(SOL_SOCKET, SO_ACCEPTFILTER, accf_arg(name))
83         rescue => e
84           logger.error("#{sock_name(sock)} " \
85                        "failed to set accept_filter=#{name} (#{e.inspect})")
86         end
87       end
88     end
90     def set_server_sockopt(sock, opt)
91       opt = DEFAULTS.merge(opt || {})
93       TCPSocket === sock and set_tcp_sockopt(sock, opt)
95       if opt[:rcvbuf] || opt[:sndbuf]
96         log_buffer_sizes(sock, "before: ")
97         sock.setsockopt(SOL_SOCKET, SO_RCVBUF, opt[:rcvbuf]) if opt[:rcvbuf]
98         sock.setsockopt(SOL_SOCKET, SO_SNDBUF, opt[:sndbuf]) if opt[:sndbuf]
99         log_buffer_sizes(sock, " after: ")
100       end
101       sock.listen(opt[:backlog])
102       rescue => e
103         Unicorn.log_error(logger, "#{sock_name(sock)} #{opt.inspect}", e)
104     end
106     def log_buffer_sizes(sock, pfx = '')
107       rcvbuf = sock.getsockopt(SOL_SOCKET, SO_RCVBUF).unpack('i')
108       sndbuf = sock.getsockopt(SOL_SOCKET, SO_SNDBUF).unpack('i')
109       logger.info "#{pfx}#{sock_name(sock)} rcvbuf=#{rcvbuf} sndbuf=#{sndbuf}"
110     end
112     # creates a new server, socket. address may be a HOST:PORT or
113     # an absolute path to a UNIX socket.  address can even be a Socket
114     # object in which case it is immediately returned
115     def bind_listen(address = '0.0.0.0:8080', opt = {})
116       return address unless String === address
118       sock = if address[0] == ?/
119         if File.exist?(address)
120           if File.socket?(address)
121             begin
122               UNIXSocket.new(address).close
123               # fall through, try to bind(2) and fail with EADDRINUSE
124               # (or succeed from a small race condition we can't sanely avoid).
125             rescue Errno::ECONNREFUSED
126               logger.info "unlinking existing socket=#{address}"
127               File.unlink(address)
128             end
129           else
130             raise ArgumentError,
131                   "socket=#{address} specified but it is not a socket!"
132           end
133         end
134         old_umask = File.umask(opt[:umask] || 0)
135         begin
136           Kgio::UNIXServer.new(address)
137         ensure
138           File.umask(old_umask)
139         end
140       elsif /\A\[([a-fA-F0-9:]+)\]:(\d+)\z/ =~ address
141         new_ipv6_server($1, $2.to_i, opt)
142       elsif /\A(\d+\.\d+\.\d+\.\d+):(\d+)\z/ =~ address
143         Kgio::TCPServer.new($1, $2.to_i)
144       else
145         raise ArgumentError, "Don't know how to bind: #{address}"
146       end
147       set_server_sockopt(sock, opt)
148       sock
149     end
151     def new_ipv6_server(addr, port, opt)
152       opt.key?(:ipv6only) or return Kgio::TCPServer.new(addr, port)
153       defined?(IPV6_V6ONLY) or
154         abort "Socket::IPV6_V6ONLY not defined, upgrade Ruby and/or your OS"
155       sock = Socket.new(AF_INET6, SOCK_STREAM, 0)
156       sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, opt[:ipv6only] ? 1 : 0)
157       sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
158       sock.bind(Socket.pack_sockaddr_in(port, addr))
159       IO_PURGATORY << sock
160       Kgio::TCPServer.for_fd(sock.fileno)
161     end
163     # returns rfc2732-style (e.g. "[::1]:666") addresses for IPv6
164     def tcp_name(sock)
165       port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
166       /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
167     end
168     module_function :tcp_name
170     # Returns the configuration name of a socket as a string.  sock may
171     # be a string value, in which case it is returned as-is
172     # Warning: TCP sockets may not always return the name given to it.
173     def sock_name(sock)
174       case sock
175       when String then sock
176       when UNIXServer
177         Socket.unpack_sockaddr_un(sock.getsockname)
178       when TCPServer
179         tcp_name(sock)
180       when Socket
181         begin
182           tcp_name(sock)
183         rescue ArgumentError
184           Socket.unpack_sockaddr_un(sock.getsockname)
185         end
186       else
187         raise ArgumentError, "Unhandled class #{sock.class}: #{sock.inspect}"
188       end
189     end
191     module_function :sock_name
193     # casts a given Socket to be a TCPServer or UNIXServer
194     def server_cast(sock)
195       begin
196         Socket.unpack_sockaddr_in(sock.getsockname)
197         Kgio::TCPServer.for_fd(sock.fileno)
198       rescue ArgumentError
199         Kgio::UNIXServer.for_fd(sock.fileno)
200       end
201     end
203   end # module SocketHelper
204 end # module Unicorn