Class: Puma::Binder

Inherits:
Object
  • Object
show all
Includes:
Const
Defined in:
lib/puma/binder.rb

Constant Summary collapse

RACK_VERSION =
[1,6].freeze

Constants included from Const

Const::BANNED_HEADER_KEY, Const::CGI_VER, Const::CHUNKED, Const::CHUNK_SIZE, Const::CLOSE, Const::CLOSE_CHUNKED, Const::CODE_NAME, Const::COLON, Const::CONNECTION_CLOSE, Const::CONNECTION_KEEP_ALIVE, Const::CONTENT_LENGTH, Const::CONTENT_LENGTH2, Const::CONTENT_LENGTH_S, Const::CONTINUE, Const::DQUOTE, Const::EARLY_HINTS, Const::ERROR_RESPONSE, Const::FAST_TRACK_KA_TIMEOUT, Const::FIRST_DATA_TIMEOUT, Const::GATEWAY_INTERFACE, Const::HALT_COMMAND, Const::HEAD, Const::HIJACK, Const::HIJACK_IO, Const::HIJACK_P, Const::HTTP, Const::HTTPS, Const::HTTPS_KEY, Const::HTTP_10_200, Const::HTTP_11, Const::HTTP_11_100, Const::HTTP_11_200, Const::HTTP_CONNECTION, Const::HTTP_EXPECT, Const::HTTP_HEADER_DELIMITER, Const::HTTP_HOST, Const::HTTP_VERSION, Const::HTTP_X_FORWARDED_FOR, Const::HTTP_X_FORWARDED_PROTO, Const::HTTP_X_FORWARDED_SCHEME, Const::HTTP_X_FORWARDED_SSL, Const::ILLEGAL_HEADER_KEY_REGEX, Const::ILLEGAL_HEADER_VALUE_REGEX, Const::KEEP_ALIVE, Const::LINE_END, Const::LOCALHOST, Const::LOCALHOST_IP, Const::MAX_BODY, Const::MAX_FAST_INLINE, Const::MAX_HEADER, Const::NEWLINE, Const::PATH_INFO, Const::PERSISTENT_TIMEOUT, Const::PORT_443, Const::PORT_80, Const::PUMA_CONFIG, Const::PUMA_PEERCERT, Const::PUMA_SERVER_STRING, Const::PUMA_SOCKET, Const::PUMA_TMP_BASE, Const::PUMA_VERSION, Const::QUERY_STRING, Const::RACK_AFTER_REPLY, Const::RACK_INPUT, Const::RACK_URL_SCHEME, Const::REMOTE_ADDR, Const::REQUEST_METHOD, Const::REQUEST_PATH, Const::REQUEST_URI, Const::RESTART_COMMAND, Const::SERVER_NAME, Const::SERVER_PORT, Const::SERVER_PROTOCOL, Const::SERVER_SOFTWARE, Const::STOP_COMMAND, Const::TRANSFER_ENCODING, Const::TRANSFER_ENCODING2, Const::TRANSFER_ENCODING_CHUNKED, Const::WORKER_CHECK_INTERVAL, Const::WRITE_TIMEOUT

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(events, conf = Configuration.new) ⇒ Binder

Returns a new instance of Binder.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/puma/binder.rb', line 31

def initialize(events, conf = Configuration.new)
  @events = events
  @listeners = []
  @inherited_fds = {}
  @activated_sockets = {}
  @unix_paths = []

  @proto_env = {
    "rack.version".freeze => RACK_VERSION,
    "rack.errors".freeze => events.stderr,
    "rack.multithread".freeze => conf.options[:max_threads] > 1,
    "rack.multiprocess".freeze => conf.options[:workers] >= 1,
    "rack.run_once".freeze => false,
    RACK_URL_SCHEME => conf.options[:rack_url_scheme],
    "SCRIPT_NAME".freeze => ENV['SCRIPT_NAME'] || "",

    # I'd like to set a default CONTENT_TYPE here but some things
    # depend on their not being a default set and inferring
    # it from the content. And so if i set it here, it won't
    # infer properly.

    "QUERY_STRING".freeze => "",
    SERVER_PROTOCOL => HTTP_11,
    SERVER_SOFTWARE => PUMA_SERVER_STRING,
    GATEWAY_INTERFACE => CGI_VER
  }

  @envs = {}
  @ios = []
end

Instance Attribute Details

#activated_socketsObject (readonly)

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def activated_sockets
  @activated_sockets
end

#connected_portsObject (readonly)

Version:

  • 5.0.0



80
81
82
# File 'lib/puma/binder.rb', line 80

def connected_ports
  ios.map { |io| io.addr[1] }.uniq
end

#envsObject (readonly)

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def envs
  @envs
end

#inherited_fdsObject (readonly)

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def inherited_fds
  @inherited_fds
end

#iosObject

Returns the value of attribute ios.



62
63
64
# File 'lib/puma/binder.rb', line 62

def ios
  @ios
end

#listenersObject

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def listeners
  @listeners
end

#proto_envObject (readonly)

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def proto_env
  @proto_env
end

#unix_pathsObject (readonly)

Version:

  • 5.0.0



65
66
67
# File 'lib/puma/binder.rb', line 65

def unix_paths
  @unix_paths
end

Instance Method Details

#add_ssl_listener(host, port, ctx, optimize_for_latency = true, backlog = 1024) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/puma/binder.rb', line 322

def add_ssl_listener(host, port, ctx,
                     optimize_for_latency=true, backlog=1024)

  raise "Puma compiled without SSL support" unless HAS_SSL

  if host == "localhost"
    loopback_addresses.each do |addr|
      add_ssl_listener addr, port, ctx, optimize_for_latency, backlog
    end
    return
  end

  host = host[1..-2] if host[0..0] == '['
  s = TCPServer.new(host, port)
  if optimize_for_latency
    s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
  end
  s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
  s.listen backlog

  ssl = MiniSSL::Server.new s, ctx
  env = @proto_env.dup
  env[HTTPS_KEY] = HTTPS
  @envs[ssl] = env

  @ios << ssl
  s
end

#add_tcp_listener(host, port, optimize_for_latency = true, backlog = 1024) ⇒ Object

Tell the server to listen on host host, port port. If optimize_for_latency is true (the default) then clients connecting will be optimized for latency over throughput.

backlog indicates how many unaccepted connections the kernel should allow to accumulate before returning connection refused.



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/puma/binder.rb', line 295

def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
  if host == "localhost"
    loopback_addresses.each do |addr|
      add_tcp_listener addr, port, optimize_for_latency, backlog
    end
    return
  end

  host = host[1..-2] if host and host[0..0] == '['
  tcp_server = TCPServer.new(host, port)
  if optimize_for_latency
    tcp_server.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
  end
  tcp_server.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
  tcp_server.listen backlog

  @ios << tcp_server
  tcp_server
end

#add_unix_listener(path, umask = nil, mode = nil, backlog = 1024) ⇒ Object

Tell the server to listen on path as a UNIX domain socket.



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/puma/binder.rb', line 369

def add_unix_listener(path, umask=nil, mode=nil, backlog=1024)
  # Let anyone connect by default
  umask ||= 0

  begin
    old_mask = File.umask(umask)

    if File.exist? path
      begin
        old = UNIXSocket.new path
      rescue SystemCallError, IOError
        File.unlink path
      else
        old.close
        raise "There is already a server bound to: #{path}"
      end
    end
    s = UNIXServer.new path.sub(/\A@/, "\0") # check for abstract UNIXSocket
    s.listen backlog
    @ios << s
  ensure
    File.umask old_mask
  end

  if mode
    File.chmod mode, path
  end

  env = @proto_env.dup
  env[REMOTE_ADDR] = "127.0.0.1"
  @envs[s] = env

  s
end

#closeObject



74
75
76
# File 'lib/puma/binder.rb', line 74

def close
  @ios.each { |i| i.close }
end

#close_listenersObject



416
417
418
419
420
421
422
423
424
# File 'lib/puma/binder.rb', line 416

def close_listeners
  @listeners.each do |l, io|
    io.close unless io.closed?
    uri = URI.parse l
    next unless uri.scheme == 'unix'
    unix_path = "#{uri.host}#{uri.path}"
    File.unlink unix_path if @unix_paths.include?(unix_path) && File.exist?(unix_path)
  end
end

#create_activated_fds(env_hash) ⇒ Object

systemd socket activation. LISTEN_FDS = number of listening sockets. e.g. 2 means accept on 2 sockets w/descriptors 3 and 4. LISTEN_PID = PID of the service process, aka us



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/puma/binder.rb', line 98

def create_activated_fds(env_hash)
  @events.debug "ENV['LISTEN_FDS'] #{ENV['LISTEN_FDS'].inspect}  env_hash['LISTEN_PID'] #{env_hash['LISTEN_PID'].inspect}"
  return [] unless env_hash['LISTEN_FDS'] && env_hash['LISTEN_PID'].to_i == $$
  env_hash['LISTEN_FDS'].to_i.times do |index|
    sock = TCPServer.for_fd(socket_activation_fd(index))
    key = begin # Try to parse as a path
      [:unix, Socket.unpack_sockaddr_un(sock.getsockname)]
    rescue ArgumentError # Try to parse as a port/ip
      port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
      addr = "[#{addr}]" if addr =~ /\:/
      [:tcp, addr, port]
    end
    @activated_sockets[key] = sock
    @events.debug "Registered #{key.join ':'} for activation from LISTEN_FDS"
  end
  ["LISTEN_FDS", "LISTEN_PID"] # Signal to remove these keys from ENV
end

#create_inherited_fds(env_hash) ⇒ Object

Version:

  • 5.0.0



85
86
87
88
89
90
# File 'lib/puma/binder.rb', line 85

def create_inherited_fds(env_hash)
  env_hash.select {|k,v| k =~ /PUMA_INHERIT_\d+/}.each do |_k, v|
    fd, url = v.split(":", 2)
    @inherited_fds[url] = fd.to_i
  end.keys # pass keys back for removal
end

#env(sock) ⇒ Object



70
71
72
# File 'lib/puma/binder.rb', line 70

def env(sock)
  @envs.fetch(sock, @proto_env)
end

#inherit_ssl_listener(fd, ctx) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/puma/binder.rb', line 351

def inherit_ssl_listener(fd, ctx)
  raise "Puma compiled without SSL support" unless HAS_SSL

  s = fd.kind_of?(::TCPServer) ? fd : ::TCPServer.for_fd(fd)

  ssl = MiniSSL::Server.new(s, ctx)

  env = @proto_env.dup
  env[HTTPS_KEY] = HTTPS
  @envs[ssl] = env

  @ios << ssl

  s
end

#inherit_tcp_listener(host, port, fd) ⇒ Object



315
316
317
318
319
320
# File 'lib/puma/binder.rb', line 315

def inherit_tcp_listener(host, port, fd)
  s = fd.kind_of?(::TCPServer) ? fd : ::TCPServer.for_fd(fd)

  @ios << s
  s
end

#inherit_unix_listener(path, fd) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
# File 'lib/puma/binder.rb', line 404

def inherit_unix_listener(path, fd)
  s = fd.kind_of?(::TCPServer) ? fd : ::UNIXServer.for_fd(fd)

  @ios << s

  env = @proto_env.dup
  env[REMOTE_ADDR] = "127.0.0.1"
  @envs[s] = env

  s
end

#parse(binds, logger, log_msg = 'Listening') ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/puma/binder.rb', line 153

def parse(binds, logger, log_msg = 'Listening')
  binds.each do |str|
    uri = URI.parse str
    case uri.scheme
    when "tcp"
      if fd = @inherited_fds.delete(str)
        io = inherit_tcp_listener uri.host, uri.port, fd
        logger.log "* Inherited #{str}"
      elsif sock = @activated_sockets.delete([ :tcp, uri.host, uri.port ])
        io = inherit_tcp_listener uri.host, uri.port, sock
        logger.log "* Activated #{str}"
      else
        ios_len = @ios.length
        params = Util.parse_query uri.query

        opt = params.key?('low_latency') && params['low_latency'] != 'false'
        bak = params.fetch('backlog', 1024).to_i

        io = add_tcp_listener uri.host, uri.port, opt, bak

        @ios[ios_len..-1].each do |i|
          addr = loc_addr_str i
          logger.log "* #{log_msg} on http://#{addr}"
        end
      end

      @listeners << [str, io] if io
    when "unix"
      path = "#{uri.host}#{uri.path}".gsub("%20", " ")
      abstract = false
      if str.start_with? 'unix://@'
        raise "OS does not support abstract UNIXSockets" unless Puma.abstract_unix_socket?
        abstract = true
        path = "@#{path}"
      end

      if fd = @inherited_fds.delete(str)
        @unix_paths << path unless abstract
        io = inherit_unix_listener path, fd
        logger.log "* Inherited #{str}"
      elsif sock = @activated_sockets.delete([ :unix, path ]) ||
          @activated_sockets.delete([ :unix, File.realdirpath(path) ])
        @unix_paths << path unless abstract || File.exist?(path)
        io = inherit_unix_listener path, sock
        logger.log "* Activated #{str}"
      else
        umask = nil
        mode = nil
        backlog = 1024

        if uri.query
          params = Util.parse_query uri.query
          if u = params['umask']
            # Use Integer() to respect the 0 prefix as octal
            umask = Integer(u)
          end

          if u = params['mode']
            mode = Integer('0'+u)
          end

          if u = params['backlog']
            backlog = Integer(u)
          end
        end

        @unix_paths << path unless abstract || File.exist?(path)
        io = add_unix_listener path, umask, mode, backlog
        logger.log "* #{log_msg} on #{str}"
      end

      @listeners << [str, io]
    when "ssl"

      raise "Puma compiled without SSL support" unless HAS_SSL

      params = Util.parse_query uri.query
      ctx = MiniSSL::ContextBuilder.new(params, @events).context

      if fd = @inherited_fds.delete(str)
        logger.log "* Inherited #{str}"
        io = inherit_ssl_listener fd, ctx
      elsif sock = @activated_sockets.delete([ :tcp, uri.host, uri.port ])
        io = inherit_ssl_listener sock, ctx
        logger.log "* Activated #{str}"
      else
        ios_len = @ios.length
        io = add_ssl_listener uri.host, uri.port, ctx

        @ios[ios_len..-1].each do |i|
          addr = loc_addr_str i
          logger.log "* #{log_msg} on ssl://#{addr}?#{uri.query}"
        end
      end

      @listeners << [str, io] if io
    else
      logger.error "Invalid URI: #{str}"
    end
  end

  # If we inherited fds but didn't use them (because of a
  # configuration change), then be sure to close them.
  @inherited_fds.each do |str, fd|
    logger.log "* Closing unused inherited connection: #{str}"

    begin
      IO.for_fd(fd).close
    rescue SystemCallError
    end

    # We have to unlink a unix socket path that's not being used
    uri = URI.parse str
    if uri.scheme == "unix"
      path = "#{uri.host}#{uri.path}"
      File.unlink path
    end
  end

  # Also close any unused activated sockets
  unless @activated_sockets.empty?
    fds = @ios.map(&:to_i)
    @activated_sockets.each do |key, sock|
      next if fds.include? sock.to_i
      logger.log "* Closing unused activated socket: #{key.first}://#{key[1..-1].join ':'}"
      begin
        sock.close
      rescue SystemCallError
      end
      # We have to unlink a unix socket path that's not being used
      File.unlink key[1] if key.first == :unix
    end
  end
end

#redirects_for_restartObject



426
427
428
429
430
# File 'lib/puma/binder.rb', line 426

def redirects_for_restart
  redirects = @listeners.map { |a| [a[1].to_i, a[1].to_i] }.to_h
  redirects[:close_others] = true
  redirects
end

#redirects_for_restart_envObject

Version:

  • 5.0.0



433
434
435
436
437
# File 'lib/puma/binder.rb', line 433

def redirects_for_restart_env
  @listeners.each_with_object({}).with_index do |(listen, memo), i|
    memo["PUMA_INHERIT_#{i}"] = "#{listen[1].to_i}:#{listen[0]}"
  end
end

#synthesize_binds_from_activated_fs(binds, only_matching) ⇒ Object

Synthesize binds from systemd socket activation

When systemd socket activation is enabled, it can be tedious to keep the binds in sync. This method can synthesize any binds based on the received activated sockets. Any existing matching binds will be respected.

When only_matching is true in, all binds that do not match an activated socket is removed in place.

It’s a noop if no activated sockets were received.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/puma/binder.rb', line 126

def synthesize_binds_from_activated_fs(binds, only_matching)
  return binds unless activated_sockets.any?

  activated_binds = []

  activated_sockets.keys.each do |proto, addr, port|
    if port
      tcp_url = "#{proto}://#{addr}:#{port}"
      ssl_url = "ssl://#{addr}:#{port}"
      ssl_url_prefix = "#{ssl_url}?"

      existing = binds.find { |bind| bind == tcp_url || bind == ssl_url || bind.start_with?(ssl_url_prefix) }

      activated_binds << (existing || tcp_url)
    else
      # TODO: can there be a SSL bind without a port?
      activated_binds << "#{proto}://#{addr}"
    end
  end

  if only_matching
    activated_binds
  else
    binds | activated_binds
  end
end