repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_skip_sigusr2.rb
test/test_skip_sigusr2.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/integration" require "puma/plugin" class TestSkipSigusr2 < TestIntegration def setup skip_unless_signal_exist? :TERM skip_unless_signal_exist? :USR2 super end def teardown super unless skipped? end def test_sigusr2_handler_not_installed cli_server "test/rackup/hello.ru", env: { 'PUMA_SKIP_SIGUSR2' => 'true' }, config: <<~CONFIG app do |_| [200, {}, [Signal.trap('SIGUSR2', 'IGNORE').to_s]] end CONFIG assert_equal 'DEFAULT', read_body(connect) stop_server end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_thread_pool.rb
test/test_thread_pool.rb
# frozen_string_literal: true require_relative "helper" require "puma/thread_pool" class TestThreadPool < PumaTest parallelize_me! def teardown @pool.shutdown(1) if defined?(@pool) end def new_pool(min, max, pool_shutdown_grace_time: nil, &block) block = proc { } unless block options = { min_threads: min, max_threads: max, pool_shutdown_grace_time: pool_shutdown_grace_time, } @pool = Puma::ThreadPool.new('tst', options, &block) end def mutex_pool(min, max, pool_shutdown_grace_time: nil, &block) block = proc { } unless block options = { min_threads: min, max_threads: max, pool_shutdown_grace_time: pool_shutdown_grace_time, } @pool = MutexPool.new('tst', options, &block) end # Wraps ThreadPool work in mutex for better concurrency control. class MutexPool < Puma::ThreadPool # Wait until the added work is completed before returning. # Array argument is treated as a batch of work items to be added. # Block will run after work is added but before it is executed on a worker thread. def <<(work, &block) work = [work] unless work.is_a?(Array) with_mutex do work.each {|arg| super arg} yield if block @not_full.wait(@mutex) end end def signal @not_full.signal end # If +wait+ is true, wait until the trim request is completed before returning. def trim(force=false, wait: true) super(force) return unless wait loop do # While we wait until @trim_requested is 0, the test might inspect other values # such as @spawned which may be modified after this variable is modified in the loop # Lock for race safety with_mutex do return if @trim_requested == 0 end Thread.pass end end end def test_append_spawns saw = [] pool = mutex_pool(0, 1) do |work| saw << work end pool << 1 assert_equal 1, pool.spawned assert_equal [1], saw end def test_thread_name skip 'Thread.name not supported' unless Thread.current.respond_to?(:name) thread_name = nil pool = mutex_pool(0, 1) {thread_name = Thread.current.name} pool << 1 assert_equal('puma tst tp 001', thread_name) end def test_thread_name_linux skip 'Thread.name not supported' unless Thread.current.respond_to?(:name) task_dir = File.join('', 'proc', Process.pid.to_s, 'task') skip 'This test only works under Linux and MRI Ruby with appropriate permissions' if !(File.directory?(task_dir) && File.readable?(task_dir) && Puma::IS_MRI) expected_thread_name = 'puma tst tp 001' found_thread = false pool = mutex_pool(0, 1) do # Read every /proc/<pid>/task/<tid>/comm file to find the thread name Dir.entries(task_dir).select {|tid| File.directory?(File.join(task_dir, tid))}.each do |tid| comm_file = File.join(task_dir, tid, 'comm') next unless File.file?(comm_file) && File.readable?(comm_file) if File.read(comm_file).strip == expected_thread_name found_thread = true break end end end pool << 1 assert(found_thread, "Did not find thread with name '#{expected_thread_name}'") end def test_converts_pool_sizes pool = new_pool('0', '1') assert_equal 0, pool.spawned pool << 1 assert_equal 1, pool.spawned end def test_append_queues_on_max pool = new_pool(0, 0) do "Hello World!" end pool << 1 pool << 2 pool << 3 assert_equal 3, pool.backlog end def test_thread_start_hook started = Queue.new options = { min_threads: 0, max_threads: 1, before_thread_start: [ { id: nil, block: proc { started << 1 }, cluster_only: false, } ] } block = proc { } pool = MutexPool.new('tst', options, &block) pool << 1 assert_equal 1, pool.spawned assert_equal 1, started.length end def test_out_of_band_hook out_of_band_called = Queue.new options = { min_threads: 0, max_threads: 1, out_of_band: [ { id: nil, block: proc { out_of_band_called << 1 }, cluster_only: false, } ] } block = proc { true } pool = MutexPool.new('tst', options, &block) pool << 1 assert_equal 1, pool.spawned assert_equal 1, out_of_band_called.length end def test_trim pool = mutex_pool(0, 1) pool << 1 assert_equal 1, pool.spawned pool.trim(wait: true) assert_equal 0, pool.spawned end def test_trim_leaves_min pool = mutex_pool(1, 2) pool << [1, 2] assert_equal 2, pool.spawned pool.trim(wait: true) assert_equal 1, pool.spawned pool.trim(wait: true) assert_equal 1, pool.spawned end def test_force_trim_doesnt_overtrim pool = mutex_pool(1, 2) pool.<< [1, 2] do assert_equal 2, pool.spawned pool.trim true, wait: false pool.trim true, wait: false end assert_equal 1, pool.spawned end def test_trim_is_ignored_if_no_waiting_threads pool = mutex_pool(1, 2) pool.<< [1, 2] do assert_equal 2, pool.spawned pool.trim pool.trim end assert_equal 2, pool.spawned assert_equal 0, pool.trim_requested end def test_trim_thread_exit_hook exited = Queue.new options = { min_threads: 0, max_threads: 1, before_thread_exit: [ { id: nil, block: proc { exited << 1 }, cluster_only: false, } ] } block = proc { } pool = MutexPool.new('tst', options, &block) pool << 1 assert_equal 1, pool.spawned # Thread.pass helps with intermittent tests, JRuby pool.trim Thread.pass sleep 0.1 unless Puma::IS_MRI # intermittent without assert_equal 0, pool.spawned Thread.pass sleep 0.1 unless Puma::IS_MRI # intermittent without assert_equal 1, exited.length end def test_autotrim pool = mutex_pool(1, 2) timeout = 0 pool.auto_trim! timeout pool.<< [1, 2] do assert_equal 2, pool.spawned end start = Time.now Thread.pass until pool.spawned == 1 || Time.now - start > 1 assert_equal 1, pool.spawned end def test_reap_only_dead_threads pool = mutex_pool(2,2) do th = Thread.current Thread.new {th.join; pool.signal} th.kill end assert_equal 2, pool.spawned pool << 1 assert_equal 2, pool.spawned pool.reap assert_equal 1, pool.spawned pool << 2 assert_equal 1, pool.spawned pool.reap assert_equal 0, pool.spawned end def test_auto_reap_dead_threads pool = mutex_pool(2,2) do th = Thread.current Thread.new {th.join; pool.signal} th.kill end timeout = 0 pool.auto_reap! timeout assert_equal 2, pool.spawned pool << 1 pool << 2 start = Time.now Thread.pass until pool.spawned == 0 || Time.now - start > 1 assert_equal 0, pool.spawned end def test_force_shutdown_immediately rescued = false pool = mutex_pool(0, 1) do begin pool.with_force_shutdown do pool.signal sleep end rescue Puma::ThreadPool::ForceShutdown rescued = true end end pool << 1 pool.shutdown(0) assert_equal 0, pool.spawned assert rescued end def test_waiting_on_startup pool = new_pool(1, 2) assert_equal 1, pool.waiting end def test_shutdown_with_grace timeout = 0.01 grace = 0.01 # JRuby Array#<< is not thread-safe rescued = Queue.new pool = mutex_pool(2, 2, pool_shutdown_grace_time: grace) do begin pool.with_force_shutdown do pool.signal sleep end rescue Puma::ThreadPool::ForceShutdown rescued << Thread.current sleep end end pool << 1 pool << 2 pool.shutdown(timeout) assert_equal 0, pool.spawned assert_equal 2, rescued.length until rescued.empty? thread = rescued.pop refute thread.alive? end end def test_correct_waiting_count_for_killed_threads pool = new_pool(1, 1) { |_| } sleep 1 # simulate our waiting worker thread getting killed for whatever reason pool.instance_eval { @workers[0].kill } sleep 1 pool.reap sleep 1 pool << 0 sleep 1 assert_equal 0, pool.backlog end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_integration_ssl_session.rb
test/test_integration_ssl_session.rb
# frozen_string_literal: true require_relative 'helper' require_relative 'helpers/integration' # These tests are used to verify that Puma works with SSL sockets. Only # integration tests isolate the server from the test environment, so there # should be a few SSL tests. # # For instance, since other tests make use of 'client' SSLSockets created by # net/http, OpenSSL is loaded in the CI process. By shelling out with IO.popen, # the server process isn't affected by whatever is loaded in the CI process. class TestIntegrationSSLSession < TestIntegration parallelize_me! if Puma::IS_MRI require "openssl" unless defined?(::OpenSSL::SSL) OSSL = ::OpenSSL::SSL CLIENT_HAS_TLS1_3 = OSSL.const_defined? :TLS1_3_VERSION GET = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n" RESP = "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 5\r\n\r\nhttps" CERT_PATH = File.expand_path "../examples/puma/client_certs", __dir__ def teardown return if skipped? # stop server sock = TCPSocket.new HOST, control_tcp_port @ios_to_close << sock sock.syswrite "GET /stop?token=#{TOKEN} HTTP/1.1\r\n\r\n" sock.read assert_match 'Goodbye!', @server.read @server.close unless @server&.closed? @server = nil super end def bind_port @bind_port ||= UniquePort.call end def control_tcp_port @control_tcp_port ||= UniquePort.call end def set_reuse(reuse) <<~RUBY key = '#{File.expand_path '../examples/puma/client_certs/server.key', __dir__}' cert = '#{File.expand_path '../examples/puma/client_certs/server.crt', __dir__}' ca = '#{File.expand_path '../examples/puma/client_certs/ca.crt', __dir__}' ssl_bind '#{HOST}', '#{bind_port}', { cert: cert, key: key, ca: ca, verify_mode: 'none', reuse: #{reuse} } activate_control_app 'tcp://#{HOST}:#{control_tcp_port}', { auth_token: '#{TOKEN}' } app do |env| [200, {}, [env['rack.url_scheme']]] end RUBY end def with_server(config) config_file = Tempfile.new %w(config .rb) config_file.write config config_file.close config_file.path # start server cmd = "#{BASE} bin/puma -C #{config_file.path}" @server = IO.popen cmd, 'r' wait_for_server_to_boot log: false @pid = @server.pid yield end def run_session(reuse, tls = nil) config = set_reuse reuse with_server(config) { ssl_client tls_vers: tls } end def test_dflt reused = run_session true assert reused, 'session was not reused' end def test_dflt_tls1_2 reused = run_session true, :TLS1_2 assert reused, 'session was not reused' end def test_dflt_tls1_3 skip 'TLSv1.3 unavailable' unless Puma::MiniSSL::HAS_TLS1_3 && CLIENT_HAS_TLS1_3 reused = run_session true, :TLS1_3 assert reused, 'session was not reused' end def test_1000_tls1_2 reused = run_session '{size: 1_000}', :TLS1_2 assert reused, 'session was not reused' end def test_1000_10_tls1_2 reused = run_session '{size: 1000, timeout: 10}', :TLS1_2 assert reused, 'session was not reused' end def test__10_tls1_2 reused = run_session '{timeout: 10}', :TLS1_2 assert reused, 'session was not reused' end def test_off_tls1_2 ssl_vers = Puma::MiniSSL::OPENSSL_LIBRARY_VERSION old_ssl = ssl_vers.include?(' 1.0.') || ssl_vers.match?(/ 1\.1\.1[ a-e]/) skip 'Requires 1.1.1f or later' if old_ssl reused = run_session 'nil', :TLS1_2 assert reused, 'session was not reused' end # TLSv1.3 reuse is always on def test_off_tls1_3 skip 'TLSv1.3 unavailable' unless Puma::MiniSSL::HAS_TLS1_3 && CLIENT_HAS_TLS1_3 reused = run_session 'nil' assert reused, 'TLSv1.3 session was not reused' end def client_skt(tls_vers = nil, session_pems = [], queue = nil) ctx = OSSL::SSLContext.new ctx.verify_mode = OSSL::VERIFY_NONE ctx.session_cache_mode = OSSL::SSLContext::SESSION_CACHE_CLIENT if tls_vers if ctx.respond_to? :max_version= ctx.max_version = tls_vers ctx.min_version = tls_vers else ctx.ssl_version = tls_vers.to_s.sub('TLS', 'TLSv').to_sym end end ctx.session_new_cb = ->(ary) { queue << true if queue session_pems << ary.last.to_pem } skt = OSSL::SSLSocket.new TCPSocket.new(HOST, bind_port), ctx skt.sync_close = true skt end def ssl_client(tls_vers: nil) queue = Thread::Queue.new session_pems = [] skt = client_skt tls_vers, session_pems, queue skt.connect skt.syswrite GET skt.to_io.wait_readable 2 assert_equal RESP, skt.sysread(1_024) skt.sysclose queue.pop # wait for cb session to be added to first client skt = client_skt tls_vers, session_pems skt.session = OSSL::Session.new(session_pems[0]) skt.connect skt.syswrite GET skt.to_io.wait_readable 2 assert_equal RESP, skt.sysread(1_024) queue.close queue = nil skt.session_reused? ensure skt&.sysclose unless skt&.closed? end end if Puma::HAS_SSL && Puma::IS_MRI
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_request_single.rb
test/test_request_single.rb
# frozen_string_literal: true require_relative "helper" require 'puma/client' require 'puma/const' require 'puma/puma_http11' # this file tests both valid and invalid requests using only `Puma::Client'. # It cannot test behavior with multiple requests, for that, see # `test_request_invalid_mulitple.rb` class TestRequestBase < PumaTest include Puma::Const PEER_ADDR = -> () { ["AF_INET", 80, "127.0.0.1", "127.0.0.1"] } GET_PREFIX = "GET / HTTP/1.1\r\nConnection: close\r\n" CHUNKED = "1\r\nH\r\n4\r\nello\r\n5\r\nWorld\r\n0\r\n\r\n" def create_client(request, &blk) env = {} @rd, @wr = IO.pipe @rd.define_singleton_method :peeraddr, PEER_ADDR @client = Puma::Client.new @rd, env @parser = @client.instance_variable_get :@parser yield if blk written = 0 ttl = request.bytesize - 1 until written >= ttl # Old Rubies, JRuby, and Windows Ruby all have issues with # writing large strings to pipe IO's. Hence, the limit. written += @wr.write request[written..(written + 32 * 1024)] break if @client.try_to_finish end end def assert_invalid(req, msg, err = Puma::HttpParserError) error = assert_raises(err) { create_client req } assert_equal msg, error.message assert_equal 'close', @client.env[HTTP_CONNECTION], "env['HTTP_CONNECTION'] should be set to 'close'" end def teardown @wr&.close @rd&.close @parser = nil @client = nil end end # Tests requests that require special handling of headers class TestRequestValid < TestRequestBase def test_underscore_header_1 request = <<~REQ.gsub("\n", "\r\n").rstrip GET / HTTP/1.1 x-forwarded_for: 2.2.2.2 x-forwarded-for: 1.1.1.1 Content-Length: 11 Hello World REQ create_client request if @parser.finished? assert_equal "1.1.1.1", @client.env['HTTP_X_FORWARDED_FOR'] assert_equal "Hello World", @client.body.string else fail end end def test_underscore_header_2 hdrs = [ "X-FORWARDED-FOR: 1.1.1.1", # proper "X-FORWARDED-FOR: 2.2.2.2", # proper "X_FORWARDED-FOR: 3.3.3.3", # invalid, contains underscore "Content-Length: 5", ].join "\r\n" create_client "#{GET_PREFIX}#{hdrs}\r\n\r\nHello\r\n\r\n" if @parser.finished? assert_equal "1.1.1.1, 2.2.2.2", @client.env['HTTP_X_FORWARDED_FOR'] assert_equal "Hello", @client.body.string else fail end end def test_underscore_header_3 hdrs = [ "X_FORWARDED-FOR: 3.3.3.3", # invalid, contains underscore "X-FORWARDED-FOR: 2.2.2.2", # proper "X-FORWARDED-FOR: 1.1.1.1", # proper "Content-Length: 5", ].join "\r\n" create_client "#{GET_PREFIX}#{hdrs}\r\n\r\nHello\r\n\r\n" if @parser.finished? assert_equal "2.2.2.2, 1.1.1.1", @client.env['HTTP_X_FORWARDED_FOR'] assert_equal "Hello", @client.body.string else fail end end def test_unmaskable_headers request = <<~REQ.gsub("\n", "\r\n").rstrip GET / HTTP/1.1 Transfer_Encoding: chunked Content_Length: 11 Hello World REQ create_client request if @parser.finished? assert_equal '11', @client.env['HTTP_CONTENT,LENGTH'] assert_equal 'chunked', @client.env['HTTP_TRANSFER,ENCODING'] assert_instance_of Puma::NullIO, @client.body else fail end end def test_gzip_chunked te = "gzip \t , \t chunked" request = <<~REQ.gsub("\n", "\r\n").rstrip GET / HTTP/1.1 Transfer_Encoding: #{te} Content_Length: 11 Hello World REQ create_client request if @parser.finished? assert_equal '11', @client.env['HTTP_CONTENT,LENGTH'] assert_equal te, @client.env['HTTP_TRANSFER,ENCODING'] assert_instance_of Puma::NullIO, @client.body else fail end end end # Tests request start line, which sets `env` values for: # # * HTTP_CONNECTION # * QUERY_STRING # * REQUEST_PATH # * REQUEST_URI # * SERVER_PROTOCOL # class TestRequestLineInvalid < TestRequestBase # An ssl request will probably be scrambled def test_maybe_ssl assert_invalid "a_}{n", "Invalid HTTP format, parsing fails. Are you trying to open an SSL connection to a non-SSL Puma?" end def test_method_lower_case assert_invalid "get /?a=1 HTTP/1.1\r\n\r\n", "Invalid HTTP format, parsing fails. Bad method get" end def test_path_non_printable assert_invalid "GET /\e?a=1 HTTP/1.1\r\n\r\n", "Invalid HTTP format, parsing fails. Bad path /\e" end def test_query_non_printable assert_invalid "GET /?a=\e1 HTTP/1.1\r\n\r\n", "Invalid HTTP format, parsing fails. Bad query a=\e1" end def test_protocol_prefix_lower_case assert_invalid "GET /test?a=1 http/1.1\r\n\r\n", "Invalid HTTP format, parsing fails. Bad protocol http/1.1" end def test_protocol_suffix assert_invalid "GET /test?a=1 HTTP/1.a\r\n\r\n", "Invalid HTTP format, parsing fails. Bad protocol HTTP/1.a" end end # Tests limits set in `ext/puma_http11/puma_http11.c` class TestRequestOversizeItem < TestRequestBase # limit is 256 def test_header_name request = "GET /test1 HTTP/1.1\r\n#{'a' * 257}: val\r\n\r\n" msg = Puma::IS_JRUBY ? "HTTP element FIELD_NAME is longer than the 256 allowed length." : "HTTP element FIELD_NAME is longer than the 256 allowed length (was 257)" assert_invalid request, msg end # limit is 80 * 1024 def test_header_value request = "GET /test1 HTTP/1.1\r\ntest: #{'a' * (80 * 1_024 + 1)}\r\n\r\n" msg = Puma::IS_JRUBY ? "HTTP element FIELD_VALUE is longer than the 81920 allowed length." : "HTTP element FIELD_VALUE is longer than the 80 * 1024 allowed length (was 81921)" assert_invalid request, msg end # limit is 1024 def test_request_fragment request = "GET /##{'a' * 1025} HTTP/1.1\r\n\r\n" msg = Puma::IS_JRUBY ? "HTTP element FRAGMENT is longer than the 1024 allowed length." : "HTTP element FRAGMENT is longer than the 1024 allowed length (was 1025)" assert_invalid request, msg end # limit is (80 + 32) * 1024 def test_headers hdrs = "#{'a' * 256}: #{'a' * (2048 - 256)}\r\n" * 56 msg = Puma::IS_JRUBY ? "HTTP element HEADER is longer than the 114688 allowed length." : "HTTP element HEADER is longer than the (1024 * (80 + 32)) allowed length (was 114930)" assert_invalid "GET / HTTP/1.1\r\n#{hdrs}\r\n", msg end # limit is 10 * 1024 def test_query_string request = "GET /?#{'a' * (5 * 1024)}=#{'b' * (5 * 1024)} HTTP/1.1\r\n\r\n" msg = Puma::IS_JRUBY ? "HTTP element QUERY_STRING is longer than the 10240 allowed length." : "HTTP element QUERY_STRING is longer than the (1024 * 10) allowed length (was 10241)" assert_invalid request, msg end # limit is 8 * 1024 def test_request_path msg = Puma::IS_JRUBY ? "HTTP element REQUEST_PATH is longer than the 8192 allowed length." : "HTTP element REQUEST_PATH is longer than the (8192) allowed length (was 8193)" assert_invalid "GET /#{'a' * (8 * 1024)} HTTP/1.1\r\n\r\n", msg end # limit is 12 * 1024 def test_request_uri request = "GET /#{'a' * 6 * 1024}?#{'a' * 3 * 1024}=#{'a' * 3 * 1024} HTTP/1.1\r\n\r\n" msg = Puma::IS_JRUBY ? "HTTP element REQUEST_URI is longer than the 12288 allowed length." : "HTTP element REQUEST_URI is longer than the (1024 * 12) allowed length (was 12291)" assert_invalid request, msg end end # Tests the headers section of the request class TestRequestHeadersInvalid < TestRequestBase def test_malformed_headers_no_return request = "GET / HTTP/1.1\r\nno-return: 10\nContent-Length: 11\r\n\r\nHello World" msg = Puma::IS_JRUBY ? "Invalid HTTP format, parsing fails. Bad headers\nno-return: 10\\nContent-Length: 11" : "Invalid HTTP format, parsing fails. Bad headers\nNO_RETURN: 10\\nContent-Length: 11" assert_invalid request, msg end def test_malformed_headers_no_newline request = "GET / HTTP/1.1\r\nno-newline: 10\rContent-Length: 11\r\n\r\nHello World" msg = Puma::IS_JRUBY ? "Invalid HTTP format, parsing fails. Bad headers\nno-newline: 10\rContent-Length: 11" : "Invalid HTTP format, parsing fails. Bad headers\nNO_NEWLINE: 10\rContent-Length: 11" assert_invalid request, msg end end # Tests requests with invalid Content-Length header class TestRequestContentLengthInvalid < TestRequestBase def test_multiple cl = [ 'Content-Length: 5', 'Content-Length: 5' ].join "\r\n" assert_invalid "#{GET_PREFIX}#{cl}\r\n\r\nHello\r\n\r\n", 'Invalid Content-Length: "5, 5"' end def test_bad_characters_1 cl = 'Content-Length: 5.01' assert_invalid "#{GET_PREFIX}#{cl}\r\n\r\nHello\r\n\r\n", 'Invalid Content-Length: "5.01"' end def test_bad_characters_2 cl = 'Content-Length: +5' assert_invalid "#{GET_PREFIX}#{cl}\r\n\r\nHello\r\n\r\n", 'Invalid Content-Length: "+5"' end def test_bad_characters_3 cl = 'Content-Length: 5 test' assert_invalid "#{GET_PREFIX}#{cl}\r\n\r\nHello\r\n\r\n", 'Invalid Content-Length: "5 test"' end end # Tests invalid chunked requests class TestRequestChunkedInvalid < TestRequestBase def test_chunked_size_bad_characters_1 te = 'Transfer-Encoding: chunked' chunked ='5.01' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n" \ "1\r\nh\r\n#{chunked}\r\nHello\r\n0\r\n\r\n", "Invalid chunk size: '5.01'" end def test_chunked_size_bad_characters_2 te = 'Transfer-Encoding: chunked' chunked ='+5' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n" \ "1\r\nh\r\n#{chunked}\r\nHello\r\n0\r\n\r\n", "Invalid chunk size: '+5'" end def test_chunked_size_bad_characters_3 te = 'Transfer-Encoding: chunked' chunked ='5 bad' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n" \ "1\r\nh\r\n#{chunked}\r\nHello\r\n0\r\n\r\n", "Invalid chunk size: '5 bad'" end def test_chunked_size_bad_characters_4 te = 'Transfer-Encoding: chunked' chunked ='0xA' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n" \ "1\r\nh\r\n#{chunked}\r\nHelloHello\r\n0\r\n\r\n", "Invalid chunk size: '0xA'" end # size is less than bytesize, 4 < 'world'.bytesize def test_chunked_size_mismatch_1 te = 'Transfer-Encoding: chunked' chunked = "5\r\nHello\r\n" \ "4\r\nWorld\r\n" \ "0\r\n\r\n" assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{chunked}", "Chunk size mismatch" end # size is greater than bytesize, 6 > 'world'.bytesize def test_chunked_size_mismatch_2 te = 'Transfer-Encoding: chunked' chunked = "5\r\nHello\r\n" \ "6\r\nWorld\r\n" \ "0\r\n\r\n" assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{chunked}", "Chunk size mismatch" end end # Tests invalid Transfer-Ecoding headers class TestTransferEncodingInvalid < TestRequestBase def test_chunked_not_last te = [ 'Transfer-Encoding: chunked', 'Transfer-Encoding: gzip' ].join "\r\n" assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{CHUNKED}", "Invalid Transfer-Encoding, last value must be chunked: 'chunked, gzip'" end def test_chunked_multiple te = [ 'Transfer-Encoding: chunked', 'Transfer-Encoding: gzip', 'Transfer-Encoding: chunked' ].join "\r\n" assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{CHUNKED}", "Invalid Transfer-Encoding, multiple chunked: 'chunked, gzip, chunked'" end def test_invalid_single te = 'Transfer-Encoding: xchunked' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{CHUNKED}", "Invalid Transfer-Encoding, unknown value: 'xchunked'", Puma::HttpParserError501 end def test_invalid_multiple te = [ 'Transfer-Encoding: x_gzip', 'Transfer-Encoding: gzip', 'Transfer-Encoding: chunked' ].join "\r\n" assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{CHUNKED}", "Invalid Transfer-Encoding, unknown value: 'x_gzip, gzip, chunked'", Puma::HttpParserError501 end def test_single_not_chunked te = 'Transfer-Encoding: gzip' assert_invalid "#{GET_PREFIX}#{te}\r\n\r\n#{CHUNKED}", "Invalid Transfer-Encoding, single value must be chunked: 'gzip'" end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_state_file.rb
test/test_state_file.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/tmp_path" require 'puma/state_file' class TestStateFile < PumaTest include TmpPath def test_load_empty_value_as_nil state_path = tmp_path('.state') File.write state_path, <<-STATE --- pid: 123456 control_url: control_auth_token: running_from: "/path/to/app" STATE sf = Puma::StateFile.new sf.load(state_path) assert_equal 123456, sf.pid assert_equal '/path/to/app', sf.running_from assert_nil sf.control_url assert_nil sf.control_auth_token end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_bundle_pruner.rb
test/test_bundle_pruner.rb
# frozen_string_literal: true require_relative 'helper' require 'puma/events' class TestBundlePruner < PumaTest PUMA_VERS = "puma-#{Puma::Const::PUMA_VERSION}" def test_paths_to_require_after_prune_is_correctly_built_for_no_extra_deps skip_if :no_bundler dirs = bundle_pruner.send(:paths_to_require_after_prune) assert_equal(2, dirs.length) assert_equal(File.join(PROJECT_ROOT, "lib"), dirs[0]) # lib dir assert_operator dirs[1], :end_with?, PUMA_VERS # native extension dir refute_match(%r{gems/minitest-[\d.]+/lib$}, dirs[2]) end def test_paths_to_require_after_prune_is_correctly_built_with_extra_deps skip_if :no_bundler dirs = bundle_pruner([], ['minitest']).send(:paths_to_require_after_prune) assert_equal(3, dirs.length) assert_equal(File.join(PROJECT_ROOT, "lib"), dirs[0]) # lib dir assert_operator dirs[1], :end_with?, PUMA_VERS # native extension dir assert_match(%r{gems/minitest-[\d.]+/lib$}, dirs[2]) # minitest dir end def test_extra_runtime_deps_paths_is_empty_for_no_config assert_equal([], bundle_pruner.send(:extra_runtime_deps_paths)) end def test_extra_runtime_deps_paths_is_correctly_built skip_if :no_bundler dep_dirs = bundle_pruner([], ['minitest']).send(:extra_runtime_deps_paths) assert_equal(1, dep_dirs.length) assert_match(%r{gems/minitest-[\d.]+/lib$}, dep_dirs.first) end def test_puma_wild_path_is_an_absolute_path skip_if :no_bundler puma_wild_path = bundle_pruner.send(:puma_wild_path) assert_match(%r{bin/puma-wild$}, puma_wild_path) # assert no "/../" in path refute_match(%r{/\.\./}, puma_wild_path) end private def bundle_pruner(original_argv = nil, extra_runtime_dependencies = nil) @bundle_pruner ||= Puma::Launcher::BundlePruner.new(original_argv, extra_runtime_dependencies, Puma::LogWriter.null) end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_plugin_systemd_jruby.rb
test/test_plugin_systemd_jruby.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/integration" require "puma/plugin" class TestPluginSystemdJruby < TestIntegration def setup skip_unless :linux skip_unless :jruby super end def teardown super unless skipped? end def test_systemd_plugin_not_loaded cli_server "test/rackup/hello.ru", env: {'NOTIFY_SOCKET' => '/tmp/doesntmatter' }, config: <<~CONFIG app do |_| [200, {}, [Puma::Plugins.instance_variable_get(:@plugins)['systemd'].to_s]] end CONFIG assert_empty read_body(connect) stop_server end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_binder.rb
test/test_binder.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/ssl" if ::Puma::HAS_SSL require_relative "helpers/tmp_path" require "puma/binder" require "puma/events" require "puma/configuration" class TestBinderBase < PumaTest include SSLHelper if ::Puma::HAS_SSL include TmpPath def setup @log_writer = Puma::LogWriter.strings @config = Puma::Configuration.new @config.clamp @binder = Puma::Binder.new(@log_writer, @config.options) end def teardown @binder.ios.reject! { |io| Minitest::Mock === io || io.to_io.closed? } @binder.close @binder.unix_paths.select! { |path| File.exist? path } @binder.close_listeners end private def ssl_context_for_binder(binder = @binder) binder.ios[0].instance_variable_get(:@ctx) end end class TestBinderParallel < TestBinderBase parallelize_me! def test_synthesize_binds_from_activated_fds_no_sockets binds = ['tcp://0.0.0.0:3000'] result = @binder.synthesize_binds_from_activated_fs(binds, true) assert_equal ['tcp://0.0.0.0:3000'], result end def test_synthesize_binds_from_activated_fds_non_matching_together binds = ['tcp://0.0.0.0:3000'] sockets = {['tcp', '0.0.0.0', '5000'] => nil} @binder.instance_variable_set(:@activated_sockets, sockets) result = @binder.synthesize_binds_from_activated_fs(binds, false) assert_equal ['tcp://0.0.0.0:3000', 'tcp://0.0.0.0:5000'], result end def test_synthesize_binds_from_activated_fds_non_matching_only binds = ['tcp://0.0.0.0:3000'] sockets = {['tcp', '0.0.0.0', '5000'] => nil} @binder.instance_variable_set(:@activated_sockets, sockets) result = @binder.synthesize_binds_from_activated_fs(binds, true) assert_equal ['tcp://0.0.0.0:5000'], result end def test_synthesize_binds_from_activated_fds_complex_binds binds = [ 'tcp://0.0.0.0:3000', 'ssl://192.0.2.100:5000', 'ssl://192.0.2.101:5000?no_tlsv1=true', 'unix:///run/puma.sock' ] sockets = { ['tcp', '0.0.0.0', '5000'] => nil, ['tcp', '192.0.2.100', '5000'] => nil, ['tcp', '192.0.2.101', '5000'] => nil, ['unix', '/run/puma.sock'] => nil } @binder.instance_variable_set(:@activated_sockets, sockets) result = @binder.synthesize_binds_from_activated_fs(binds, false) expected = ['tcp://0.0.0.0:3000', 'ssl://192.0.2.100:5000', 'ssl://192.0.2.101:5000?no_tlsv1=true', 'unix:///run/puma.sock', 'tcp://0.0.0.0:5000'] assert_equal expected, result end def test_runs_before_parse_hooks mock = Minitest::Mock.new proc = -> { mock.call } @binder.before_parse(&proc) mock.expect(:call, nil) @binder.parse ["tcp://localhost:0"] assert_mock mock assert_equal @binder.instance_variable_get(:@before_parse), [proc] end def test_localhost_addresses_dont_alter_listeners_for_tcp_addresses @binder.parse ["tcp://localhost:0"], @log_writer assert_empty @binder.listeners end def test_home_alters_listeners_for_tcp_addresses port = UniquePort.call @binder.parse ["tcp://127.0.0.1:#{port}"], @log_writer assert_equal "tcp://127.0.0.1:#{port}", @binder.listeners[0][0] assert_kind_of TCPServer, @binder.listeners[0][1] end def test_connected_ports ports = (1..3).map { |_| UniquePort.call } @binder.parse(ports.map { |p| "tcp://localhost:#{p}" }, @log_writer) assert_equal ports, @binder.connected_ports end def test_localhost_addresses_dont_alter_listeners_for_ssl_addresses skip_unless :ssl @binder.parse ["ssl://localhost:0?#{ssl_query}"], @log_writer assert_empty @binder.listeners end def test_home_alters_listeners_for_ssl_addresses skip_unless :ssl port = UniquePort.call @binder.parse ["ssl://127.0.0.1:#{port}?#{ssl_query}"], @log_writer assert_equal "ssl://127.0.0.1:#{port}?#{ssl_query}", @binder.listeners[0][0] assert_kind_of TCPServer, @binder.listeners[0][1] end def test_correct_zero_port @binder.parse ["tcp://localhost:0"], @log_writer m = %r!http://127.0.0.1:(\d+)!.match(@log_writer.stdout.string) port = m[1].to_i refute_equal 0, port end def test_correct_zero_port_ssl skip_unless :ssl ssl_regex = %r!ssl://127.0.0.1:(\d+)! @binder.parse ["ssl://localhost:0?#{ssl_query}"], @log_writer port = ssl_regex.match(@log_writer.stdout.string)[1].to_i refute_equal 0, port end def test_logs_all_localhost_bindings @binder.parse ["tcp://localhost:0"], @log_writer assert_match %r!http://127.0.0.1:(\d+)!, @log_writer.stdout.string if Socket.ip_address_list.any? {|i| i.ipv6_loopback? } assert_match %r!http://\[::1\]:(\d+)!, @log_writer.stdout.string end end def test_logs_all_localhost_bindings_ssl skip_unless :ssl @binder.parse ["ssl://localhost:0?#{ssl_query}"], @log_writer assert_match %r!ssl://127.0.0.1:(\d+)!, @log_writer.stdout.string if Socket.ip_address_list.any? {|i| i.ipv6_loopback? } assert_match %r!ssl://\[::1\]:(\d+)!, @log_writer.stdout.string end end def test_allows_both_ssl_and_tcp assert_parsing_logs_uri [:ssl, :tcp] end def test_allows_both_unix_and_tcp skip_if :jruby # Undiagnosed thread race. TODO fix assert_parsing_logs_uri [:unix, :tcp] end def test_allows_both_tcp_and_unix assert_parsing_logs_uri [:tcp, :unix] end def test_pre_existing_unix skip_unless :unix unix_path = tmp_path('.sock') File.open(unix_path, mode: 'wb') { |f| f.puts 'pre existing' } @binder.parse ["unix://#{unix_path}"], @log_writer assert_match %r!unix://#{unix_path}!, @log_writer.stdout.string refute_includes @binder.unix_paths, unix_path @binder.close_listeners assert File.exist?(unix_path) ensure if UNIX_SKT_EXIST File.unlink unix_path if File.exist? unix_path end end def test_binder_tcp_defaults_to_low_latency_off skip_if :jruby @binder.parse ["tcp://0.0.0.0:0"], @log_writer socket = @binder.listeners.first.last refute socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_tcp_parses_nil_low_latency skip_if :jruby @binder.parse ["tcp://0.0.0.0:0?low_latency"], @log_writer socket = @binder.listeners.first.last assert socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_tcp_parses_true_low_latency skip_if :jruby @binder.parse ["tcp://0.0.0.0:0?low_latency=true"], @log_writer socket = @binder.listeners.first.last assert socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_parses_false_low_latency skip_if :jruby @binder.parse ["tcp://0.0.0.0:0?low_latency=false"], @log_writer socket = @binder.listeners.first.last refute socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_ssl_defaults_to_true_low_latency skip_unless :ssl skip_if :jruby @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}"], @log_writer socket = @binder.listeners.first.last assert socket.to_io.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_ssl_parses_false_low_latency skip_unless :ssl skip_if :jruby @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}&low_latency=false"], @log_writer socket = @binder.listeners.first.last refute socket.to_io.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY).bool end def test_binder_parses_tlsv1_disabled skip_unless :ssl @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}&no_tlsv1=true"], @log_writer assert ssl_context_for_binder.no_tlsv1 end def test_binder_parses_tlsv1_enabled skip_unless :ssl @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}&no_tlsv1=false"], @log_writer refute ssl_context_for_binder.no_tlsv1 end def test_binder_parses_tlsv1_tlsv1_1_unspecified_defaults_to_enabled skip_unless :ssl @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}"], @log_writer refute ssl_context_for_binder.no_tlsv1 refute ssl_context_for_binder.no_tlsv1_1 end def test_binder_parses_tlsv1_1_disabled skip_unless :ssl @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}&no_tlsv1_1=true"], @log_writer assert ssl_context_for_binder.no_tlsv1_1 end def test_binder_parses_tlsv1_1_enabled skip_unless :ssl @binder.parse ["ssl://0.0.0.0:0?#{ssl_query}&no_tlsv1_1=false"], @log_writer refute ssl_context_for_binder.no_tlsv1_1 end def test_env_contains_protoenv skip_unless :ssl @binder.parse ["ssl://localhost:0?#{ssl_query}"], @log_writer env_hash = @binder.envs[@binder.ios.first] @binder.proto_env.each do |k,v| assert env_hash[k] == v end end def test_env_contains_stderr skip_unless :ssl @binder.parse ["ssl://localhost:0?#{ssl_query}"], @log_writer env_hash = @binder.envs[@binder.ios.first] assert_equal @log_writer.stderr, env_hash["rack.errors"] end def test_close_calls_close_on_ios @mocked_ios = [Minitest::Mock.new, Minitest::Mock.new] @mocked_ios.each { |m| m.expect(:close, true) } @binder.ios = @mocked_ios @binder.close assert @mocked_ios.map(&:verify).all? end def test_redirects_for_restart_creates_a_hash @binder.parse ["tcp://127.0.0.1:0"], @log_writer result = @binder.redirects_for_restart ios = @binder.listeners.map { |_l, io| io.to_i } ios.each { |int| assert_equal int, result[int] } assert result[:close_others] end def test_redirects_for_restart_env @binder.parse ["tcp://127.0.0.1:0"], @log_writer result = @binder.redirects_for_restart_env @binder.listeners.each_with_index do |l, i| assert_equal "#{l[1].to_i}:#{l[0]}", result["PUMA_INHERIT_#{i}"] end end def test_close_listeners_closes_ios @binder.parse ["tcp://127.0.0.1:#{UniquePort.call}"], @log_writer refute @binder.listeners.any? { |_l, io| io.closed? } @binder.close_listeners assert @binder.listeners.all? { |_l, io| io.closed? } end def test_close_listeners_closes_ios_unless_closed? @binder.parse ["tcp://127.0.0.1:0"], @log_writer bomb = @binder.listeners.first[1] bomb.close def bomb.close; raise "Boom!"; end # the bomb has been planted assert @binder.listeners.any? { |_l, io| io.closed? } @binder.close_listeners assert @binder.listeners.all? { |_l, io| io.closed? } end def test_listeners_file_unlink_if_unix_listener skip_unless :unix unix_path = tmp_path('.sock') @binder.parse ["unix://#{unix_path}"], @log_writer assert File.socket?(unix_path) @binder.close_listeners refute File.socket?(unix_path) end def test_import_from_env_listen_inherit @binder.parse ["tcp://127.0.0.1:0"], @log_writer removals = @binder.create_inherited_fds(@binder.redirects_for_restart_env) @binder.listeners.each do |l, io| assert_equal io.to_i, @binder.inherited_fds[l] end assert_includes removals, "PUMA_INHERIT_0" end # Socket activation tests. We have to skip all of these on non-UNIX platforms # because the check that we do in the code only works if you support UNIX sockets. # This is OK, because systemd obviously only works on Linux. def test_socket_activation_tcp skip_unless :unix url = "127.0.0.1" port = UniquePort.call sock = Addrinfo.tcp(url, port).listen assert_activates_sockets(url: url, port: port, sock: sock) end def test_socket_activation_tcp_ipv6 skip_unless :unix url = "::" port = UniquePort.call sock = Addrinfo.tcp(url, port).listen assert_activates_sockets(url: url, port: port, sock: sock) end def test_socket_activation_unix skip_if :jruby # Failing with what I think is a JRuby bug skip_unless :unix state_path = tmp_path('.state') sock = Addrinfo.unix(state_path).listen assert_activates_sockets(path: state_path, sock: sock) ensure File.unlink(state_path) rescue nil # JRuby race? end def test_rack_multithread_default_configuration assert @binder.proto_env["rack.multithread"] end def test_rack_multithread_custom_configuration conf = Puma::Configuration.new(max_threads: 1) conf.clamp binder = Puma::Binder.new(@log_writer, conf.options) refute binder.proto_env["rack.multithread"] end def test_rack_multiprocess_default_configuration refute @binder.proto_env["rack.multiprocess"] end def test_rack_multiprocess_custom_configuration conf = Puma::Configuration.new(workers: 1) conf.clamp binder = Puma::Binder.new(@log_writer, conf.options) assert binder.proto_env["rack.multiprocess"] end private def assert_activates_sockets(path: nil, port: nil, url: nil, sock: nil) hash = { "LISTEN_FDS" => 1, "LISTEN_PID" => $$ } @log_writer.instance_variable_set(:@debug, true) @binder.instance_variable_set(:@sock_fd, sock.fileno) def @binder.socket_activation_fd(int); @sock_fd; end @result = @binder.create_activated_fds(hash) url = "[::]" if url == "::" ary = path ? [:unix, path] : [:tcp, url, port] assert_kind_of TCPServer, @binder.activated_sockets[ary] assert_match "Registered #{ary.join(":")} for activation from LISTEN_FDS", @log_writer.stdout.string assert_equal ["LISTEN_FDS", "LISTEN_PID"], @result end def assert_parsing_logs_uri(order = [:unix, :tcp]) skip MSG_UNIX if order.include?(:unix) && !UNIX_SKT_EXIST skip_unless :ssl unix_path = tmp_path('.sock') prepared_paths = { ssl: "ssl://127.0.0.1:#{UniquePort.call}?#{ssl_query}", tcp: "tcp://127.0.0.1:#{UniquePort.call}", unix: "unix://#{unix_path}" } expected_logs = prepared_paths.dup.tap do |logs| logs[:tcp] = logs[:tcp].gsub('tcp://', 'http://') end tested_paths = [prepared_paths[order[0]], prepared_paths[order[1]]] @binder.parse tested_paths, @log_writer stdout = @log_writer.stdout.string order.each do |prot| assert_match expected_logs[prot], stdout end ensure @binder.close_listeners if order.include?(:unix) && UNIX_SKT_EXIST end end class TestBinderSingle < TestBinderBase def test_ssl_binder_sets_backlog skip_unless :ssl host = '127.0.0.1' port = UniquePort.call tcp_server = TCPServer.new(host, port) tcp_server.define_singleton_method(:listen) do |backlog| Thread.current[:backlog] = backlog super(backlog) end TCPServer.stub(:new, tcp_server) do @binder.parse ["ssl://#{host}:#{port}?#{ssl_query}&backlog=2048"], @log_writer end assert_equal 2048, Thread.current[:backlog] end end class TestBinderJRuby < TestBinderBase def test_binder_parses_jruby_ssl_options skip_unless :ssl cipher_suites = ['TLS_DHE_RSA_WITH_AES_128_CBC_SHA', 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256'] @binder.parse ["ssl://0.0.0.0:8080?#{ssl_query}"], @log_writer assert_equal @keystore, ssl_context_for_binder.keystore assert_equal cipher_suites, ssl_context_for_binder.cipher_suites assert_equal cipher_suites, ssl_context_for_binder.ssl_cipher_list end def test_binder_parses_jruby_ssl_protocols_and_cipher_suites_options skip_unless :ssl keystore = File.expand_path "../../examples/puma/keystore.jks", __FILE__ cipher = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" ssl_query = "keystore=#{keystore}&keystore-pass=jruby_puma&cipher_suites=#{cipher}&protocols=TLSv1.3,TLSv1.2" @binder.parse ["ssl://0.0.0.0:8080?#{ssl_query}"], @log_writer assert_equal [ 'TLSv1.3', 'TLSv1.2' ], ssl_context_for_binder.protocols assert_equal [ cipher ], ssl_context_for_binder.cipher_suites end end if ::Puma::IS_JRUBY class TestBinderMRI < TestBinderBase def test_binder_parses_ssl_cipher_filter skip_unless :ssl ssl_cipher_filter = "AES@STRENGTH" @binder.parse ["ssl://0.0.0.0?#{ssl_query}&ssl_cipher_filter=#{ssl_cipher_filter}"], @log_writer assert_equal ssl_cipher_filter, ssl_context_for_binder.ssl_cipher_filter end def test_binder_parses_ssl_ciphersuites skip_unless :ssl skip('Requires TLSv1.3') unless Puma::MiniSSL::HAS_TLS1_3 ssl_ciphersuites = "TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256" @binder.parse ["ssl://0.0.0.0?#{ssl_query}&ssl_ciphersuites=#{ssl_ciphersuites}"], @log_writer assert_equal ssl_ciphersuites, ssl_context_for_binder.ssl_ciphersuites end def test_binder_parses_ssl_verification_flags_one skip_unless :ssl input = "&verification_flags=TRUSTED_FIRST" @binder.parse ["ssl://0.0.0.0?#{ssl_query}#{input}"], @log_writer assert_equal 0x8000, ssl_context_for_binder.verification_flags end def test_binder_parses_ssl_verification_flags_multiple skip_unless :ssl input = "&verification_flags=TRUSTED_FIRST,NO_CHECK_TIME" @binder.parse ["ssl://0.0.0.0?#{ssl_query}#{input}"], @log_writer assert_equal 0x8000 | 0x200000, ssl_context_for_binder.verification_flags end end unless ::Puma::IS_JRUBY
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_http11.rb
test/test_http11.rb
# frozen_string_literal: true # Copyright (c) 2011 Evan Phoenix # Copyright (c) 2005 Zed A. Shaw require_relative "helper" require_relative "helpers/integration" require "digest" require "puma/puma_http11" class Http11ParserTest < TestIntegration parallelize_me! unless ::Puma::IS_JRUBY && RUBY_DESCRIPTION.include?('x86_64-darwin') def test_parse_simple parser = Puma::HttpParser.new req = {} http = "GET /?a=1 HTTP/1.1\r\n\r\n" nread = parser.execute(req, http, 0) assert nread == http.length, "Failed to parse the full HTTP request" assert parser.finished?, "Parser didn't finish" assert !parser.error?, "Parser had error" assert nread == parser.nread, "Number read returned from execute does not match" assert_equal '/', req['REQUEST_PATH'] assert_equal 'HTTP/1.1', req['SERVER_PROTOCOL'] assert_equal '/?a=1', req['REQUEST_URI'] assert_equal 'GET', req['REQUEST_METHOD'] assert_nil req['FRAGMENT'] assert_equal "a=1", req['QUERY_STRING'] parser.reset assert parser.nread == 0, "Number read after reset should be 0" end def test_parse_escaping_in_query parser = Puma::HttpParser.new req = {} http = "GET /admin/users?search=%27%%27 HTTP/1.1\r\n\r\n" nread = parser.execute(req, http, 0) assert nread == http.length, "Failed to parse the full HTTP request" assert parser.finished?, "Parser didn't finish" assert !parser.error?, "Parser had error" assert nread == parser.nread, "Number read returned from execute does not match" assert_equal '/admin/users?search=%27%%27', req['REQUEST_URI'] assert_equal "search=%27%%27", req['QUERY_STRING'] parser.reset assert parser.nread == 0, "Number read after reset should be 0" end def test_parse_absolute_uri parser = Puma::HttpParser.new req = {} http = "GET http://192.168.1.96:3000/api/v1/matches/test?1=1 HTTP/1.1\r\n\r\n" nread = parser.execute(req, http, 0) assert nread == http.length, "Failed to parse the full HTTP request" assert parser.finished?, "Parser didn't finish" assert !parser.error?, "Parser had error" assert nread == parser.nread, "Number read returned from execute does not match" assert_equal "GET", req['REQUEST_METHOD'] assert_equal 'http://192.168.1.96:3000/api/v1/matches/test?1=1', req['REQUEST_URI'] assert_equal 'HTTP/1.1', req['SERVER_PROTOCOL'] assert_nil req['REQUEST_PATH'] assert_nil req['FRAGMENT'] assert_nil req['QUERY_STRING'] parser.reset assert parser.nread == 0, "Number read after reset should be 0" end def test_parse_dumbfuck_headers parser = Puma::HttpParser.new req = {} should_be_good = "GET / HTTP/1.1\r\naaaaaaaaaaaaa:++++++++++\r\n\r\n" nread = parser.execute(req, should_be_good, 0) assert_equal should_be_good.length, nread assert parser.finished? assert !parser.error? end def test_parse_error parser = Puma::HttpParser.new req = {} bad_http = "GET / SsUTF/1.1" error = false begin parser.execute(req, bad_http, 0) rescue error = true end assert error, "failed to throw exception" assert !parser.finished?, "Parser shouldn't be finished" assert parser.error?, "Parser SHOULD have error" end def test_fragment_in_uri parser = Puma::HttpParser.new req = {} get = "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n\r\n" parser.execute(req, get, 0) assert parser.finished? assert_equal '/forums/1/topics/2375?page=1', req['REQUEST_URI'] assert_equal 'posts-17408', req['FRAGMENT'] end def test_semicolon_in_path parser = Puma::HttpParser.new req = {} get = "GET /forums/1/path;stillpath/2375?page=1 HTTP/1.1\r\n\r\n" parser.execute(req, get, 0) assert parser.finished? assert_equal '/forums/1/path;stillpath/2375?page=1', req['REQUEST_URI'] assert_equal '/forums/1/path;stillpath/2375', req['REQUEST_PATH'] end # lame random garbage maker def rand_data(min, max, readable=true) count = min + ((rand(max)+1) *10).to_i res = count.to_s + "/" if readable res << Digest(:SHA1).hexdigest(rand(count * 100).to_s) * (count / 40) else res << Digest(:SHA1).digest(rand(count * 100).to_s) * (count / 20) end res end def test_get_const_length skip_unless :jruby envs = %w[ PUMA_REQUEST_URI_MAX_LENGTH PUMA_REQUEST_PATH_MAX_LENGTH PUMA_QUERY_STRING_MAX_LENGTH ] default_exp = [1024 * 12, 8192, 10 * 1024] tests = [{ envs: %w[60000 61000 62000], exp: [60000, 61000, 62000], error_indexes: [] }, { envs: ['', 'abc', nil], exp: default_exp, error_indexes: [1] }, { envs: %w[-4000 0 3000.45], exp: default_exp, error_indexes: [0, 1, 2] }] cli_config = <<~CONFIG app do |_| [200, {}, [JSONSerialization.generate({ MAX_REQUEST_URI_LENGTH: org.jruby.puma.Http11::MAX_REQUEST_URI_LENGTH, MAX_REQUEST_PATH_LENGTH: org.jruby.puma.Http11::MAX_REQUEST_PATH_LENGTH, MAX_QUERY_STRING_LENGTH: org.jruby.puma.Http11::MAX_QUERY_STRING_LENGTH, MAX_REQUEST_URI_LENGTH_ERR: org.jruby.puma.Http11::MAX_REQUEST_URI_LENGTH_ERR, MAX_REQUEST_PATH_LENGTH_ERR: org.jruby.puma.Http11::MAX_REQUEST_PATH_LENGTH_ERR, MAX_QUERY_STRING_LENGTH_ERR: org.jruby.puma.Http11::MAX_QUERY_STRING_LENGTH_ERR })]] end CONFIG tests.each do |conf| cli_server 'test/rackup/hello.ru', env: {envs[0] => conf[:envs][0], envs[1] => conf[:envs][1], envs[2] => conf[:envs][2]}, merge_err: true, config: cli_config sleep 0.25 result = JSON.parse read_body(connect) assert_equal conf[:exp][0], result['MAX_REQUEST_URI_LENGTH'] assert_equal conf[:exp][1], result['MAX_REQUEST_PATH_LENGTH'] assert_equal conf[:exp][2], result['MAX_QUERY_STRING_LENGTH'] assert_includes result['MAX_REQUEST_URI_LENGTH_ERR'], "longer than the #{conf[:exp][0]} allowed length" assert_includes result['MAX_REQUEST_PATH_LENGTH_ERR'], "longer than the #{conf[:exp][1]} allowed length" assert_includes result['MAX_QUERY_STRING_LENGTH_ERR'], "longer than the #{conf[:exp][2]} allowed length" conf[:error_indexes].each do |index| assert_includes @server_log, "The value #{conf[:envs][index]} for #{envs[index]} is invalid. "\ "Using default value #{default_exp[index]} instead" end stop_server end end def test_max_uri_path_length parser = Puma::HttpParser.new req = {} # Support URI path length to a max of 8192 path = "/" + rand_data(7000, 100) http = "GET #{path} HTTP/1.1\r\n\r\n" parser.execute(req, http, 0) assert_equal path, req['REQUEST_PATH'] parser.reset # Raise exception if URI path length > 8192 path = "/" + rand_data(9000, 100) http = "GET #{path} HTTP/1.1\r\n\r\n" assert_raises Puma::HttpParserError do parser.execute(req, http, 0) parser.reset end end def test_horrible_queries parser = Puma::HttpParser.new # then that large header names are caught 10.times do |c| get = "GET /#{rand_data(10,120)} HTTP/1.1\r\nX-#{rand_data(1024, 1024+(c*1024))}: Test\r\n\r\n" assert_raises Puma::HttpParserError do parser.execute({}, get, 0) parser.reset end end # then that large mangled field values are caught 10.times do |c| get = "GET /#{rand_data(10,120)} HTTP/1.1\r\nX-Test: #{rand_data(1024, 1024+(c*1024), false)}\r\n\r\n" assert_raises Puma::HttpParserError do parser.execute({}, get, 0) parser.reset end end # then large headers are rejected too get = "GET /#{rand_data(10,120)} HTTP/1.1\r\n" get += "X-Test: test\r\n" * (80 * 1024) assert_raises Puma::HttpParserError do parser.execute({}, get, 0) parser.reset end # finally just that random garbage gets blocked all the time 10.times do |c| get = "GET #{rand_data(1024, 1024+(c*1024), false)} #{rand_data(1024, 1024+(c*1024), false)}\r\n\r\n" assert_raises Puma::HttpParserError do parser.execute({}, get, 0) parser.reset end end end def test_trims_whitespace_from_headers parser = Puma::HttpParser.new req = {} http = "GET / HTTP/1.1\r\nX-Strip-Me: \t Strip This \t \r\n\r\n" parser.execute(req, http, 0) assert_equal "Strip This", req["HTTP_X_STRIP_ME"] end def test_newline_smuggler parser = Puma::HttpParser.new req = {} http = "GET / HTTP/1.1\r\nHost: localhost:8080\r\nDummy: x\nDummy2: y\r\n\r\n" parser.execute(req, http, 0) rescue nil # We test the raise elsewhere. assert parser.error?, "Parser SHOULD have error" end def test_newline_smuggler_two parser = Puma::HttpParser.new req = {} http = "GET / HTTP/1.1\r\nHost: localhost:8080\r\nDummy: x\r\nDummy: y\nDummy2: z\r\n\r\n" parser.execute(req, http, 0) rescue nil assert parser.error?, "Parser SHOULD have error" end def test_htab_in_header_val parser = Puma::HttpParser.new req = {} http = "GET / HTTP/1.1\r\nHost: localhost:8080\r\nDummy: Valid\tValue\r\n\r\n" parser.execute(req, http, 0) assert_equal "Valid\tValue", req['HTTP_DUMMY'] end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_puma_server_ssl.rb
test/test_puma_server_ssl.rb
# frozen_string_literal: true # Nothing in this file runs if Puma isn't compiled with ssl support # # helper is required first since it loads Puma, which needs to be # loaded so HAS_SSL is defined require_relative "helper" if ::Puma::HAS_SSL require "puma/minissl" require_relative "helpers/test_puma/puma_socket" if ENV['PUMA_TEST_DEBUG'] require "openssl" unless Object.const_defined? :OpenSSL if Puma::IS_JRUBY puts "", RUBY_DESCRIPTION, "RUBYOPT: #{ENV['RUBYOPT']}", " OpenSSL", "OPENSSL_LIBRARY_VERSION: #{OpenSSL::OPENSSL_LIBRARY_VERSION}", " OPENSSL_VERSION: #{OpenSSL::OPENSSL_VERSION}", "" else puts "", RUBY_DESCRIPTION, "RUBYOPT: #{ENV['RUBYOPT']}", " Puma::MiniSSL OpenSSL", "OPENSSL_LIBRARY_VERSION: #{Puma::MiniSSL::OPENSSL_LIBRARY_VERSION.ljust 32}#{OpenSSL::OPENSSL_LIBRARY_VERSION}", " OPENSSL_VERSION: #{Puma::MiniSSL::OPENSSL_VERSION.ljust 32}#{OpenSSL::OPENSSL_VERSION}", "" end end end class TestPumaServerSSL < PumaTest parallelize_me! include TestPuma include TestPuma::PumaSocket PROTOCOL_USE_MIN_MAX = OpenSSL::SSL::SSLContext.public_instance_methods(false).include?(:min_version=) OPENSSL_3 = OpenSSL::OPENSSL_LIBRARY_VERSION.match?(/OpenSSL 3\.\d\.\d/) def setup @server = nil end def teardown @server&.stop true end # yields ctx to block, use for ctx setup & configuration def start_server(&server_ctx) app = lambda { |env| [200, {}, [env['rack.url_scheme']]] } ctx = Puma::MiniSSL::Context.new if Puma.jruby? ctx.keystore = File.expand_path "../examples/puma/keystore.jks", __dir__ ctx.keystore_pass = 'jruby_puma' else ctx.key = File.expand_path "../examples/puma/puma_keypair.pem", __dir__ ctx.cert = File.expand_path "../examples/puma/cert_puma.pem", __dir__ end ctx.verify_mode = Puma::MiniSSL::VERIFY_NONE yield ctx if server_ctx @log_stdout = StringIO.new @log_stderr = StringIO.new @log_writer = SSLLogWriterHelper.new @log_stdout, @log_stderr @server = Puma::Server.new app, nil, {log_writer: @log_writer} @port = (@server.add_ssl_listener HOST, 0, ctx).addr[1] @bind_port = @port @server.run end def test_url_scheme_for_https start_server assert_equal "https", send_http_read_resp_body(ctx: new_ctx) end def test_request_wont_block_thread start_server # Open a connection and give enough data to trigger a read, then wait ctx = OpenSSL::SSL::SSLContext.new ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE @bind_port = @server.connected_ports[0] socket = send_http "HEAD", ctx: new_ctx sleep 0.1 # Capture the amount of threads being used after connecting and being idle thread_pool = @server.instance_variable_get(:@thread_pool) busy_threads = thread_pool.spawned - thread_pool.waiting socket.close # The thread pool should be empty since the request would block on read # and our request should have been moved to the reactor. assert busy_threads.zero?, "Our connection is monopolizing a thread" end def test_very_large_return # This test frequntly fails on Darwin TruffleRuby, 512k was used chosen # becuase 1mb also failed # failure is OpenSSL::SSL::SSLError: SSL_read: record layer failure body_size = Puma::IS_OSX && TRUFFLE ? 512 * 1_024 : 2_056_610 start_server giant = "x" * body_size @server.app = proc { [200, {}, [giant]] } body = send_http_read_resp_body(ctx: new_ctx) assert_equal giant.bytesize, body.bytesize end def test_form_submit start_server @server.app = proc { |env| [200, {}, [env['rack.url_scheme'], "\n", env['rack.input'].read]] } req = "POST / HTTP/1.1\r\nContent-Type: text/plain\r\nContent-Length: 7\r\n\r\na=1&b=2" body = send_http_read_resp_body req, ctx: new_ctx assert_equal "https\na=1&b=2", body end def rejection(server_ctx, min_max, ssl_version) if server_ctx start_server(&server_ctx) else start_server end msg = nil assert_raises(OpenSSL::SSL::SSLError) do begin send_http_read_response ctx: new_ctx { |ctx| if PROTOCOL_USE_MIN_MAX && min_max ctx.max_version = min_max else ctx.ssl_version = ssl_version end } rescue => e msg = e.message raise e end end expected = Puma::IS_JRUBY ? /No appropriate protocol \(protocol is disabled or cipher suites are inappropriate\)/ : /SSL_connect SYSCALL returned=5|wrong version number|(unknown|unsupported) protocol|no protocols available|version too low|unknown SSL method/ assert_match expected, msg # make sure a good request succeeds assert_equal "https", send_http_read_resp_body(ctx: new_ctx) end def test_ssl_v3_rejection skip("SSLv3 protocol is unavailable") if Puma::MiniSSL::OPENSSL_NO_SSL3 rejection nil, nil, :SSLv3 end def test_tls_v1_rejection rejection ->(ctx) { ctx.no_tlsv1 = true }, :TLS1, :TLSv1 end def test_tls_v1_1_rejection rejection ->(ctx) { ctx.no_tlsv1_1 = true }, :TLS1_1, :TLSv1_1 end def test_tls_v1_3 skip("TLSv1.3 protocol can not be set") unless OpenSSL::SSL::SSLContext.instance_methods(false).include?(:min_version=) start_server body = send_http_read_resp_body ctx: new_ctx { |c| if PROTOCOL_USE_MIN_MAX c.min_version = :TLS1_3 else c.ssl_version = :TLSv1_3 end } assert_equal "https", body end def test_http_rejection body_http = nil body_https = nil start_server tcp = Thread.new do assert_raises(Errno::ECONNREFUSED, EOFError, IOError, Timeout::Error) do body_http = send_http_read_resp_body timeout: 4 end end ssl = Thread.new do begin body_https = send_http_read_resp_body ctx: new_ctx rescue => e body_https = "test_http_rejection error in SSL #{e.class}\n#{e.message}\n" end end tcp.join ssl.join sleep 1.0 assert_nil body_http assert_equal "https", body_https thread_pool = @server.instance_variable_get(:@thread_pool) busy_threads = thread_pool.spawned - thread_pool.waiting assert busy_threads.zero?, "Our connection wasn't dropped" end def test_http_10_close_no_errors start_server assert_equal 'https', send_http_read_response(GET_10, ctx: new_ctx).body assert_empty @log_stderr.string end def test_http_11_close_no_errors start_server skt = send_http ctx: new_ctx assert_equal 'https', skt.read_response.body skt.close assert_empty @log_stderr.string end unless Puma.jruby? def test_invalid_cert assert_raises(Puma::MiniSSL::SSLError) do start_server { |ctx| ctx.cert = __FILE__ } end end def test_invalid_key assert_raises(Puma::MiniSSL::SSLError) do start_server { |ctx| ctx.key = __FILE__ } end end def test_invalid_cert_pem assert_raises(Puma::MiniSSL::SSLError) do start_server { |ctx| ctx.instance_variable_set(:@cert, nil) ctx.cert_pem = 'Not a valid pem' } end end def test_invalid_key_pem assert_raises(Puma::MiniSSL::SSLError) do start_server { |ctx| ctx.instance_variable_set(:@key, nil) ctx.key_pem = 'Not a valid pem' } end end def test_invalid_ca assert_raises(Puma::MiniSSL::SSLError) do start_server { |ctx| ctx.ca = __FILE__ } end end # this may require updates if TLSv1.3 default ciphers change def test_ssl_ciphersuites skip('Requires TLSv1.3') unless Puma::MiniSSL::HAS_TLS1_3 start_server default_cipher = send_http(ctx: new_ctx).cipher[0] @server&.stop true cipher_suite = 'TLS_CHACHA20_POLY1305_SHA256' start_server { |ctx| ctx.ssl_ciphersuites = cipher_suite} cipher = send_http(ctx: new_ctx).cipher refute_equal default_cipher, cipher[0] assert_equal cipher_suite , cipher[0] assert_equal cipher[1], 'TLSv1.3' end end end if ::Puma::HAS_SSL # client-side TLS authentication tests class TestPumaServerSSLClient < PumaTest parallelize_me! unless ::Puma.jruby? include TestPuma include TestPuma::PumaSocket CERT_PATH = File.expand_path "../examples/puma/client_certs", __dir__ # Context can be shared, may help with JRuby CTX = Puma::MiniSSL::Context.new.tap { |ctx| if Puma.jruby? ctx.keystore = "#{CERT_PATH}/keystore.jks" ctx.keystore_pass = 'jruby_puma' else ctx.key = "#{CERT_PATH}/server.key" ctx.cert = "#{CERT_PATH}/server.crt" ctx.ca = "#{CERT_PATH}/ca.crt" end ctx.verify_mode = Puma::MiniSSL::VERIFY_PEER | Puma::MiniSSL::VERIFY_FAIL_IF_NO_PEER_CERT } def assert_ssl_client_error_match(error, subject: nil, context: CTX, &blk) port = 0 app = lambda { |env| [200, {}, [env['rack.url_scheme']]] } log_writer = SSLLogWriterHelper.new STDOUT, STDERR server = Puma::Server.new app, nil, {log_writer: log_writer} server.add_ssl_listener LOCALHOST, port, context host_addrs = server.binder.ios.map { |io| io.to_io.addr[2] } @bind_port = server.connected_ports[0] server.run ctx = OpenSSL::SSL::SSLContext.new yield ctx expected_errors = [ EOFError, IOError, OpenSSL::SSL::SSLError, Errno::ECONNABORTED, Errno::ECONNRESET ] client_error = false begin send_http_read_resp_body host: LOCALHOST, ctx: ctx rescue *expected_errors => e client_error = e end sleep 0.1 assert_equal !!error, !!client_error, client_error if error && !error.eql?(true) assert_match error, log_writer.error.message assert_includes host_addrs, log_writer.addr end assert_equal subject, log_writer.cert.subject.to_s if subject ensure server&.stop true end def test_verify_fail_if_no_client_cert error = Puma.jruby? ? /Empty client certificate chain/ : 'peer did not return a certificate' assert_ssl_client_error_match(error) do |client_ctx| # nothing end end def test_verify_fail_if_client_unknown_ca error = Puma.jruby? ? /No trusted certificate found/ : /self[- ]signed certificate in certificate chain/ cert_subject = Puma.jruby? ? '/DC=net/DC=puma/CN=localhost' : '/DC=net/DC=puma/CN=CAU' assert_ssl_client_error_match(error, subject: cert_subject) do |client_ctx| key = "#{CERT_PATH}/client_unknown.key" crt = "#{CERT_PATH}/client_unknown.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/unknown_ca.crt" end end def test_verify_fail_if_client_expired_cert error = Puma.jruby? ? /NotAfter:/ : 'certificate has expired' assert_ssl_client_error_match(error, subject: '/DC=net/DC=puma/CN=localhost') do |client_ctx| key = "#{CERT_PATH}/client_expired.key" crt = "#{CERT_PATH}/client_expired.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" end end def test_verify_client_cert assert_ssl_client_error_match(false) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER end end def test_verify_client_cert_with_truststore ctx = Puma::MiniSSL::Context.new ctx.keystore = "#{CERT_PATH}/server.p12" ctx.keystore_type = 'pkcs12' ctx.keystore_pass = 'jruby_puma' ctx.truststore = "#{CERT_PATH}/ca_store.p12" ctx.truststore_type = 'pkcs12' ctx.truststore_pass = 'jruby_puma' ctx.verify_mode = Puma::MiniSSL::VERIFY_PEER assert_ssl_client_error_match(false, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER end end if Puma.jruby? def test_verify_client_cert_without_truststore ctx = Puma::MiniSSL::Context.new ctx.keystore = "#{CERT_PATH}/server.p12" ctx.keystore_type = 'pkcs12' ctx.keystore_pass = 'jruby_puma' ctx.truststore = "#{CERT_PATH}/unknown_ca_store.p12" ctx.truststore_type = 'pkcs12' ctx.truststore_pass = 'jruby_puma' ctx.verify_mode = Puma::MiniSSL::VERIFY_PEER assert_ssl_client_error_match(true, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER end end if Puma.jruby? def test_allows_using_default_truststore ctx = Puma::MiniSSL::Context.new ctx.keystore = "#{CERT_PATH}/server.p12" ctx.keystore_type = 'pkcs12' ctx.keystore_pass = 'jruby_puma' ctx.truststore = :default # NOTE: a little hard to test - we're at least asserting that setting :default does not raise errors ctx.verify_mode = Puma::MiniSSL::VERIFY_NONE assert_ssl_client_error_match(false, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER end end if Puma.jruby? def test_allows_to_specify_cipher_suites_and_protocols ctx = CTX.dup ctx.cipher_suites = [ 'TLS_RSA_WITH_AES_128_GCM_SHA256' ] ctx.protocols = 'TLSv1.2' assert_ssl_client_error_match(false, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER client_ctx.ssl_version = :TLSv1_2 client_ctx.ciphers = [ 'TLS_RSA_WITH_AES_128_GCM_SHA256' ] end end if Puma.jruby? def test_fails_when_no_cipher_suites_in_common ctx = CTX.dup ctx.cipher_suites = [ 'TLS_RSA_WITH_AES_128_GCM_SHA256' ] ctx.protocols = 'TLSv1.2' assert_ssl_client_error_match(/no cipher suites in common/, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER client_ctx.ssl_version = :TLSv1_2 client_ctx.ciphers = [ 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' ] end end if Puma.jruby? def test_verify_client_cert_with_truststore_without_pass ctx = Puma::MiniSSL::Context.new ctx.keystore = "#{CERT_PATH}/server.p12" ctx.keystore_type = 'pkcs12' ctx.keystore_pass = 'jruby_puma' ctx.truststore = "#{CERT_PATH}/ca_store.jks" # cert entry can be read without password ctx.truststore_type = 'jks' ctx.verify_mode = Puma::MiniSSL::VERIFY_PEER assert_ssl_client_error_match(false, context: ctx) do |client_ctx| key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" client_ctx.key = OpenSSL::PKey::RSA.new File.read(key) client_ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) client_ctx.ca_file = "#{CERT_PATH}/ca.crt" client_ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER end end if Puma.jruby? end if ::Puma::HAS_SSL class TestPumaServerSSLClientCloseError < PumaTest parallelize_me! unless ::Puma.jruby? include TestPuma include TestPuma::PumaSocket CERT_PATH = File.expand_path "../examples/puma/client_certs", __dir__ # Context can be shared, may help with JRuby CTX = Puma::MiniSSL::Context.new.tap { |ctx| if Puma.jruby? ctx.keystore = "#{CERT_PATH}/keystore.jks" ctx.keystore_pass = 'jruby_puma' else ctx.key = "#{CERT_PATH}/server.key" ctx.cert = "#{CERT_PATH}/server.crt" ctx.ca = "#{CERT_PATH}/ca.crt" end ctx.verify_mode = Puma::MiniSSL::VERIFY_PEER | Puma::MiniSSL::VERIFY_FAIL_IF_NO_PEER_CERT } def assert_ssl_client_error_match(close_error, log_writer: SSLLogWriterHelper.new(STDOUT, STDERR), &blk) app = lambda { |env| [200, {}, [env['rack.url_scheme']]] } server = Puma::Server.new app, nil, {log_writer: log_writer} server.add_ssl_listener LOCALHOST, 0, CTX @bind_port = server.connected_ports[0] server.define_singleton_method(:new_client) do |io, sock| client = super(io, sock) client.define_singleton_method(:close) do raise close_error end client end server.run ctx = OpenSSL::SSL::SSLContext.new key = "#{CERT_PATH}/client.key" crt = "#{CERT_PATH}/client.crt" ctx.key = OpenSSL::PKey::RSA.new File.read(key) ctx.cert = OpenSSL::X509::Certificate.new File.read(crt) ctx.ca_file = "#{CERT_PATH}/ca.crt" ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER skt = new_socket host: LOCALHOST, ctx: ctx yield skt sleep 0.1 assert_equal close_error, log_writer.errors.last ensure server&.stop true end def test_client_close_raises_ssl_error_in_http10 assert_ssl_client_error_match(::Puma::MiniSSL::SSLError.new) do |skt| skt << GET_10 skt.read_response end end def test_client_both_read_and_close_raise_ssl_error log_writer = SSLLogWriterHelper.new(STDOUT, STDERR) close_error = ::Puma::MiniSSL::SSLError.new("close error") assert_ssl_client_error_match(close_error, log_writer: log_writer) do |skt| skt << GET_11 skt.read_response skt.to_io << "puma is really a great web server" # break the record layer skt.close end assert_equal 2, log_writer.errors.size assert_instance_of Puma::MiniSSL::SSLError, log_writer.errors[0] assert_match "close error", log_writer.errors[1].message end end if ::Puma::HAS_SSL class TestPumaServerSSLWithCertPemAndKeyPem < PumaTest include TestPuma include TestPuma::PumaSocket CERT_PATH = File.expand_path "../examples/puma/client_certs", __dir__ def test_server_ssl_with_cert_pem_and_key_pem ctx = Puma::MiniSSL::Context.new ctx.cert_pem = File.read "#{CERT_PATH}/server.crt" ctx.key_pem = File.read "#{CERT_PATH}/server.key" app = lambda { |env| [200, {}, [env['rack.url_scheme']]] } log_writer = SSLLogWriterHelper.new STDOUT, STDERR server = Puma::Server.new app, nil, {log_writer: log_writer} server.add_ssl_listener LOCALHOST, 0, ctx @bind_port = server.connected_ports[0] server.run client_error = nil begin send_http_read_resp_body host: LOCALHOST, ctx: new_ctx { |c| c.ca_file = "#{CERT_PATH}/ca.crt" c.verify_mode = OpenSSL::SSL::VERIFY_PEER } rescue OpenSSL::SSL::SSLError, EOFError, Errno::ECONNRESET => e # Errno::ECONNRESET TruffleRuby client_error = e end assert_nil client_error ensure server&.stop true end end if ::Puma::HAS_SSL && !Puma::IS_JRUBY # # Test certificate chain support, The certs and the whole certificate chain for # this tests are located in ../examples/puma/chain_cert and were generated with # the following commands: # # bundle exec ruby ../examples/puma/chain_cert/generate_chain_test.rb # class TestPumaSSLCertChain < PumaTest include TestPuma include TestPuma::PumaSocket CHAIN_DIR = File.expand_path '../examples/puma/chain_cert', __dir__ # OpenSSL::X509::Name#to_utf8 only available in Ruby 2.5 and later USE_TO_UTFT8 = OpenSSL::X509::Name.instance_methods(false).include? :to_utf8 def cert_chain(&blk) app = lambda { |env| [200, {}, [env['rack.url_scheme']]] } @log_stdout = StringIO.new @log_stderr = StringIO.new @log_writer = SSLLogWriterHelper.new @log_stdout, @log_stderr @server = Puma::Server.new app, nil, {log_writer: @log_writer} mini_ctx = Puma::MiniSSL::Context.new mini_ctx.key = "#{CHAIN_DIR}/cert.key" yield mini_ctx @bind_port = (@server.add_ssl_listener HOST, 0, mini_ctx).addr[1] @server.run socket = new_socket ctx: new_ctx subj_chain = socket.peer_cert_chain.map(&:subject) subj_map = USE_TO_UTFT8 ? subj_chain.map { |subj| subj.to_utf8[/CN=(.+ - )?([^,]+)/,2] } : subj_chain.map { |subj| subj.to_s(OpenSSL::X509::Name::RFC2253)[/CN=(.+ - )?([^,]+)/,2] } @server&.stop true assert_equal ['test.puma.localhost', 'intermediate.puma.localhost', 'ca.puma.localhost'], subj_map end def test_single_cert_file_with_ca cert_chain { |mini_ctx| mini_ctx.cert = "#{CHAIN_DIR}/cert.crt" mini_ctx.ca = "#{CHAIN_DIR}/ca_chain.pem" } end def test_chain_cert_file_without_ca cert_chain { |mini_ctx| mini_ctx.cert = "#{CHAIN_DIR}/cert_chain.pem" } end def test_single_cert_string_with_ca cert_chain { |mini_ctx| mini_ctx.cert_pem = File.read "#{CHAIN_DIR}/cert.crt" mini_ctx.ca = "#{CHAIN_DIR}/ca_chain.pem" } end def test_chain_cert_string_without_ca cert_chain { |mini_ctx| mini_ctx.cert_pem = File.read "#{CHAIN_DIR}/cert_chain.pem" } end end if ::Puma::HAS_SSL && !::Puma::IS_JRUBY
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_rack_server.rb
test/test_rack_server.rb
# frozen_string_literal: true require_relative "helper" require "net/http" # don't load Rack, as it autoloads everything begin require "rack/body_proxy" require "rack/lint" require "rack/version" require "rack/common_logger" rescue LoadError # Rack 1.6 require "rack" end # Rack::Chunked is loaded by Rack v2, needs to be required by Rack 3.0, # and is removed in Rack 3.1 require "rack/chunked" if Rack.release.start_with? '3.0' require "nio" class TestRackServer < PumaTest parallelize_me! HOST = '127.0.0.1' STR_1KB = "──#{SecureRandom.hex 507}─\n".freeze class ErrorChecker def initialize(app) @app = app @exception = nil end attr_reader :exception, :env def call(env) begin @app.call(env) rescue Exception => e @exception = e [ 500, {}, ["Error detected"] ] end end end class ServerLint < Rack::Lint def call(env) if Rack.release < '3' check_env env else Wrapper.new(@app, env).check_environment env end @app.call(env) end end def setup @simple = lambda { |env| [200, { "x-header" => "Works" }, ["Hello"]] } @server = Puma::Server.new @simple, nil, log_writer: Puma::LogWriter.null @port = (@server.add_tcp_listener HOST, 0).addr[1] @tcp = "http://#{HOST}:#{@port}" @stopped = false end def stop @server.stop(true) @stopped = true end def teardown @server.stop(true) unless @stopped end def header_hash(socket) t = socket.readline("\r\n\r\n").split("\r\n") t.shift; t.map! { |line| line.split(/:\s?/) } t.to_h end def test_lint @checker = ErrorChecker.new ServerLint.new(@simple) @server.app = @checker @server.run hit(["#{@tcp}/test"]) stop refute @checker.exception, "Checker raised exception" end def test_large_post_body @checker = ErrorChecker.new ServerLint.new(@simple) @server.app = @checker @server.run big = "x" * (1024 * 16) Net::HTTP.post_form URI.parse("#{@tcp}/test"), { "big" => big } stop refute @checker.exception, "Checker raised exception" end def test_path_info input = nil @server.app = lambda { |env| input = env; @simple.call(env) } @server.run hit(["#{@tcp}/test/a/b/c"]) stop assert_equal "/test/a/b/c", input['PATH_INFO'] end def test_after_reply closed = false @server.app = lambda do |env| env['rack.after_reply'] << lambda { closed = true } @simple.call(env) end @server.run hit(["#{@tcp}/test"]) stop assert_equal true, closed end def test_after_reply_error_handling called = [] @server.app = lambda do |env| env['rack.after_reply'] << lambda { called << :before } env['rack.after_reply'] << lambda { raise ArgumentError, "oops" } env['rack.after_reply'] << lambda { called << :after } @simple.call(env) end @server.run hit(["#{@tcp}/test"]) stop assert_equal [:before, :after], called end def test_after_reply_exception @server.app = lambda do |env| env['rack.after_reply'] << lambda { raise ArgumentError, "oops" } @simple.call(env) end @server.run socket = TCPSocket.open HOST, @port socket.puts "GET /test HTTP/1.1\r\n" socket.puts "Connection: Keep-Alive\r\n" socket.puts "\r\n" headers = header_hash socket content_length = headers["content-length"].to_i real_response_body = socket.read(content_length) assert_equal "Hello", real_response_body # When after_reply breaks the connection it will write the expected HTTP # response followed by a second HTTP response: HTTP/1.1 500 # # This sleeps to give the server time to write the invalid/extra HTTP # response. # # * If we can read from the socket, we know that extra content has been # written to the connection and assert that it's our erroneous 500 # response. # * If we would block trying to read from the socket, we can assume that # the erroneous 500 response wasn't/won't be written. sleep 0.1 assert_raises IO::WaitReadable do content = socket.read_nonblock(12) refute_includes content, "500" end socket.close stop end def test_rack_response_finished calls = [] @server.app = lambda do |env| env['rack.response_finished'] << lambda { |c_env, status, headers, error| calls << 1 assert_same env, c_env assert_equal 200, status assert_instance_of Hash, headers assert_nil error } env['rack.response_finished'] << lambda { |env, status, headers, error| calls << 2; raise "Oops" } env['rack.response_finished'] << lambda { |env, status, headers, error| calls << 3 } @simple.call(env) end @server.run hit(["#{@tcp}/test"]) stop assert_equal [3, 2, 1], calls end def test_rack_response_finished_on_error calls = [] @server.app = lambda do |env| env['rack.response_finished'] << lambda { |c_env, status, headers, error| begin assert_same env, c_env assert_equal 500, status assert_instance_of Hash, headers assert_instance_of RuntimeError, error assert_equal "test_rack_response_finished_on_error", error.message calls << 1 end } raise "test_rack_response_finished_on_error" end @server.run hit(["#{@tcp}/test"]) stop assert_equal [1], calls end def test_rack_body_proxy closed = false body = Rack::BodyProxy.new(["Hello"]) { closed = true } @server.app = lambda { |env| [200, { "X-Header" => "Works" }, body] } @server.run hit(["#{@tcp}/test"]) stop assert_equal true, closed end def test_rack_body_proxy_content_length str_ary = %w[0123456789 0123456789 0123456789 0123456789] str_ary_bytes = str_ary.to_ary.inject(0) { |sum, el| sum + el.bytesize } body = Rack::BodyProxy.new(str_ary) { } @server.app = lambda { |env| [200, { "X-Header" => "Works" }, body] } @server.run socket = TCPSocket.open HOST, @port socket.puts "GET /test HTTP/1.1\r\n" socket.puts "Connection: Keep-Alive\r\n" socket.puts "\r\n" headers = header_hash socket socket.close stop if Rack.release.start_with? '1.' assert_equal "chunked", headers["transfer-encoding"] else assert_equal str_ary_bytes, headers["content-length"].to_i end end def test_common_logger log = StringIO.new logger = Rack::CommonLogger.new(@simple, log) @server.app = logger @server.run hit(["#{@tcp}/test"]) stop assert_match %r!GET /test HTTP/1\.1!, log.string end def test_rack_chunked_array1 body = [STR_1KB] app = lambda { |env| [200, { 'content-type' => 'text/plain; charset=utf-8' }, body] } rack_app = Rack::Chunked.new app @server.app = rack_app @server.run resp = Net::HTTP.get_response URI(@tcp) assert_equal 'chunked', resp['transfer-encoding'] assert_equal STR_1KB, resp.body.force_encoding(Encoding::UTF_8) end if Rack.release < '3.1' def test_rack_chunked_array10 body = Array.new 10, STR_1KB app = lambda { |env| [200, { 'content-type' => 'text/plain; charset=utf-8' }, body] } rack_app = Rack::Chunked.new app @server.app = rack_app @server.run resp = Net::HTTP.get_response URI(@tcp) assert_equal 'chunked', resp['transfer-encoding'] assert_equal STR_1KB * 10, resp.body.force_encoding(Encoding::UTF_8) end if Rack.release < '3.1' def test_puma_enum body = Array.new(10, STR_1KB).to_enum @server.app = lambda { |env| [200, { 'content-type' => 'text/plain; charset=utf-8' }, body] } @server.run resp = Net::HTTP.get_response URI(@tcp) assert_equal 'chunked', resp['transfer-encoding'] assert_equal STR_1KB * 10, resp.body.force_encoding(Encoding::UTF_8) end def test_version_header @server.app = lambda do |env| body = env['HTTP_VERSION'] [200, {}, [body]] end @server.run socket = TCPSocket.open HOST, @port socket.syswrite "GET / HTTP/1.1\r\nversion: version\r\n\r\n" body = socket.sysread(256).split("\r\n\r\n").last if Object.const_defined?(:Rack) && ::Rack.respond_to?(:release) && Gem::Version.new(Rack.release) < Gem::Version.new('3.1.0') assert_equal "HTTP/1.1", body else assert_equal "version", body end ensure socket&.close end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_persistent.rb
test/test_persistent.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/test_puma/puma_socket" class TestPersistent < PumaTest parallelize_me! include ::TestPuma::PumaSocket HOST = "127.0.0.1" def setup @body = ["Hello"] @valid_request = "GET / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\n\r\n" @valid_response = <<~RESP.gsub("\n", "\r\n").rstrip HTTP/1.1 200 OK x-header: Works content-length: 5 Hello RESP @close_request = "GET / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n" @http10_request = "GET / HTTP/1.0\r\nHost: test.com\r\nContent-Type: text/plain\r\n\r\n" @keep_request = "GET / HTTP/1.0\r\nHost: test.com\r\nContent-Type: text/plain\r\nConnection: Keep-Alive\r\n\r\n" @valid_post = "POST / HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello" @valid_no_body = "GET / HTTP/1.1\r\nHost: test.com\r\nX-Status: 204\r\nContent-Type: text/plain\r\n\r\n" @headers = { "X-Header" => "Works" } @inputs = [] @simple = lambda do |env| @inputs << env['rack.input'] status = Integer(env['HTTP_X_STATUS'] || 200) [status, @headers, @body] end opts = {min_thread: 1, max_threads: 1} @server = Puma::Server.new @simple, nil, opts @bind_port = (@server.add_tcp_listener HOST, 0).addr[1] @server.run sleep 0.15 if Puma.jruby? end def teardown @server.stop(true) end def test_one_with_content_length response = send_http_read_response @valid_request assert_equal @valid_response, response end def test_two_back_to_back socket = send_http @valid_request response = socket.read_response assert_equal @valid_response, response response = socket.req_write(@valid_request).read_response assert_equal @valid_response, response end def test_post_then_get socket = send_http @valid_post response = socket.read_response expected = <<~RESP.gsub("\n", "\r\n").rstrip HTTP/1.1 200 OK x-header: Works content-length: 5 Hello RESP assert_equal expected, response response = socket.req_write(@valid_request).read_response assert_equal @valid_response, response end def test_no_body_then_get socket = send_http @valid_no_body response = socket.read_response assert_equal "HTTP/1.1 204 No Content\r\nx-header: Works\r\n\r\n", response response = socket.req_write(@valid_request).read_response assert_equal @valid_response, response end def test_chunked @body << "Chunked" @body = @body.to_enum response = send_http_read_response @valid_request assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ntransfer-encoding: chunked\r\n\r\n" \ "5\r\nHello\r\n7\r\nChunked\r\n0\r\n\r\n", response end def test_chunked_with_empty_part @body << "" @body << "Chunked" @body = @body.to_enum response = send_http_read_response @valid_request assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ntransfer-encoding: chunked\r\n\r\n" \ "5\r\nHello\r\n7\r\nChunked\r\n0\r\n\r\n", response end def test_no_chunked_in_http10 @body << "Chunked" @body = @body.to_enum socket = send_http GET_10 sleep 0.01 if ::Puma::IS_JRUBY response = socket.read_response assert_equal "HTTP/1.0 200 OK\r\nx-header: Works\r\n\r\n" \ "HelloChunked", response end def test_hex str = "This is longer and will be in hex" @body << str @body = @body.to_enum response = send_http_read_response @valid_request assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ntransfer-encoding: chunked\r\n\r\n" \ "5\r\nHello\r\n#{str.size.to_s(16)}\r\n#{str}\r\n0\r\n\r\n", response end def test_client11_close response = send_http_read_response @close_request assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\nconnection: close\r\ncontent-length: 5\r\n\r\n" \ "Hello", response end def test_client10_close response = send_http_read_response GET_10 assert_equal "HTTP/1.0 200 OK\r\nx-header: Works\r\ncontent-length: 5\r\n\r\n" \ "Hello", response end def test_one_with_keep_alive_header response = send_http_read_response @keep_request assert_equal "HTTP/1.0 200 OK\r\nx-header: Works\r\nconnection: keep-alive\r\ncontent-length: 5\r\n\r\n" \ "Hello", response end def test_persistent_timeout @server.instance_variable_set(:@persistent_timeout, 1) socket = send_http @valid_request response = socket.read_response assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ncontent-length: 5\r\n\r\n" \ "Hello", response sleep 2 assert_raises EOFError do socket.read_nonblock(1) end end def test_app_sets_content_length @body = ["hello", " world"] @headers['Content-Length'] = "11" response = send_http_read_response @valid_request assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ncontent-length: 11\r\n\r\n" \ "hello world", response end def test_allow_app_to_chunk_itself @headers = {'Transfer-Encoding' => "chunked" } @body = ["5\r\nhello\r\n0\r\n\r\n"] response = send_http_read_response @valid_request assert_equal "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n" \ "5\r\nhello\r\n0\r\n\r\n", response end def test_two_requests_in_one_chunk @server.instance_variable_set(:@persistent_timeout, 3) req = @valid_request.to_s req += "GET /second HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\n\r\n" response = send_http_read_all req assert_equal @valid_response * 2, response end def test_second_request_not_in_first_req_body @server.instance_variable_set(:@persistent_timeout, 3) req = @valid_request.to_s req += "GET /second HTTP/1.1\r\nHost: test.com\r\nContent-Type: text/plain\r\n\r\n" response = send_http_read_all req assert_equal @valid_response * 2, response assert_kind_of Puma::NullIO, @inputs[0] assert_kind_of Puma::NullIO, @inputs[1] end def test_keepalive_doesnt_starve_clients send_http @valid_request c2 = send_http @valid_request assert c2.wait_readable(1), "2nd request starved" response = c2.read_response assert_equal "HTTP/1.1 200 OK\r\nx-header: Works\r\ncontent-length: 5\r\n\r\n" \ "Hello", response end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/test_plugin_systemd.rb
test/test_plugin_systemd.rb
# frozen_string_literal: true require_relative "helper" require_relative "helpers/integration" class TestPluginSystemd < TestIntegration parallelize_me! if ::Puma::IS_MRI THREAD_LOG = TRUFFLE ? "{ 0/16 threads, 16 available, 0 backlog }" : "{ 0/5 threads, 5 available, 0 backlog }" def setup skip_unless :linux skip_if :jruby super @sockaddr = tmp_path '.systemd' @socket = Socket.new(:UNIX, :DGRAM, 0) @socket.bind Addrinfo.unix(@sockaddr) @env = { "NOTIFY_SOCKET" => @sockaddr } @message = +'' end def teardown return if skipped? @socket&.close @socket = nil super end def test_systemd_notify_usr1_phased_restart_cluster skip_unless :fork assert_restarts_with_systemd :USR1 end def test_systemd_notify_usr2_hot_restart_cluster skip_unless :fork assert_restarts_with_systemd :USR2 end def test_systemd_notify_usr2_hot_restart_single assert_restarts_with_systemd :USR2, workers: 0 end def test_systemd_watchdog wd_env = @env.merge({"WATCHDOG_USEC" => "1_000_000"}) cli_server "test/rackup/hello.ru", env: wd_env assert_message "READY=1" assert_message "WATCHDOG=1" stop_server assert_message "STOPPING=1" end def test_systemd_notify cli_server "test/rackup/hello.ru", env: @env assert_message "READY=1" assert_message "STATUS=Puma #{Puma::Const::VERSION}: worker: #{THREAD_LOG}" stop_server assert_message "STOPPING=1" end def test_systemd_cluster_notify skip_unless :fork cli_server "-w2 test/rackup/hello.ru", env: @env assert_message "READY=1" assert_message( "STATUS=Puma #{Puma::Const::VERSION}: cluster: 2/2, worker_status: [#{THREAD_LOG},#{THREAD_LOG}]") stop_server assert_message "STOPPING=1" end private def assert_restarts_with_systemd(signal, workers: 2) skip_unless(:fork) unless workers.zero? cli_server "test/rackup/hello.ru", env: @env, config: <<~CONFIG workers #{workers} #{"preload_app! false" if signal == :USR1} CONFIG get_worker_pids(0, workers) if workers == 2 assert_message 'READY=1' phase_ary = signal == :USR1 ? [1,2] : [0,0] Process.kill signal, @pid get_worker_pids(phase_ary[0], workers) if workers == 2 assert_message 'RELOADING=1' assert_message 'READY=1' Process.kill signal, @pid get_worker_pids(phase_ary[1], workers) if workers == 2 assert_message 'RELOADING=1' assert_message 'READY=1' stop_server assert_message 'STOPPING=1' end def assert_message(msg) @socket.wait_readable 1 @message << @socket.sysread(msg.bytesize) # below is kind of hacky, but seems to work correctly when slow CI systems # write partial status messages if @message.start_with?('STATUS=') && !msg.start_with?('STATUS=') @message << @socket.sysread(512) while @socket.wait_readable(1) && !@message.include?(msg) assert_includes @message, msg @message = @message.split(msg, 2).last else assert_equal msg, @message @message = +'' end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/minitest/verbose.rb
test/minitest/verbose.rb
require "minitest" require_relative "verbose_progress_plugin" Minitest.load_plugins Minitest.extensions << 'verbose_progress' unless Minitest.extensions.include?('verbose_progress')
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/minitest/verbose_progress_plugin.rb
test/minitest/verbose_progress_plugin.rb
module Minitest # Adds minimal support for parallel tests to the default verbose progress reporter. def self.plugin_verbose_progress_init(options) if options[:verbose] self.reporter.reporters. delete_if {|r| r.is_a?(ProgressReporter)}. push(VerboseProgressReporter.new(options[:io], options)) end end # Verbose progress reporter that supports parallel test execution. class VerboseProgressReporter < Reporter def prerecord(klass, name) @current ||= nil @current = [klass.name, name].tap { |t| print_start t } end def record(result) print_start [result.klass, result.name] @current = nil io.print "%.2f s = " % [result.time] io.print result.result_code io.puts end def print_start(test) unless @current == test io.puts '…' if @current io.print "%s#%s = " % test io.flush end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/ssl.rb
test/helpers/ssl.rb
# frozen_string_literal: true module SSLHelper def ssl_query @ssl_query ||= if Puma.jruby? @keystore = File.expand_path "../../examples/puma/keystore.jks", __dir__ @ssl_cipher_list = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" "keystore=#{@keystore}&keystore-pass=jruby_puma&ssl_cipher_list=#{@ssl_cipher_list}" else @cert = File.expand_path "../../examples/puma/cert_puma.pem", __dir__ @key = File.expand_path "../../examples/puma/puma_keypair.pem", __dir__ "key=#{@key}&cert=#{@cert}" end end # sets and returns an opts hash for use with Puma::DSL.ssl_bind_str def ssl_opts @ssl_opts ||= if Puma.jruby? @ssl_opts = {} @ssl_opts[:keystore] = File.expand_path '../../examples/puma/keystore.jks', __dir__ @ssl_opts[:keystore_pass] = 'jruby_puma' @ssl_opts[:ssl_cipher_list] = 'TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' else @ssl_opts = {} @ssl_opts[:cert] = File.expand_path '../../examples/puma/cert_puma.pem', __dir__ @ssl_opts[:key] = File.expand_path '../../examples/puma/puma_keypair.pem', __dir__ end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/test_puma.rb
test/helpers/test_puma.rb
# frozen_string_literal: true require 'socket' module TestPuma RESP_SPLIT = "\r\n\r\n" LINE_SPLIT = "\r\n" RE_HOST_TO_IP = /\A\[|\]\z/o HOST4 = begin t = Socket.ip_address_list.select(&:ipv4_loopback?).map(&:ip_address) .uniq.sort_by(&:length) # puts "IPv4 Loopback #{t}" str = t.include?('127.0.0.1') ? +'127.0.0.1' : +"#{t.first}" str.define_singleton_method(:ip) { self } str.freeze end HOST6 = begin t = Socket.ip_address_list.select(&:ipv6_loopback?).map(&:ip_address) .uniq.sort_by(&:length) # puts "IPv6 Loopback #{t}" str = t.include?('::1') ? +'[::1]' : +"[#{t.first}]" str.define_singleton_method(:ip) { self.gsub RE_HOST_TO_IP, '' } str.freeze end LOCALHOST = ENV.fetch 'PUMA_CI_DFLT_HOST', 'localhost' if ENV['PUMA_CI_DFLT_IP'] =='IPv6' HOST = HOST6 ALT_HOST = HOST4 else HOST = HOST4 ALT_HOST = HOST6 end DARWIN = RUBY_PLATFORM.include? 'darwin' TOKEN = "xxyyzz" # Returns an available port by using `TCPServer.open(host, 0)` def new_port(host = HOST) TCPServer.open(host, 0) { |server| server.connect_address.ip_port } end def bind_uri_str if @bind_port "tcp://#{HOST}:#{@bind_port}" elsif @bind_path "unix://#{HOST}:#{@bind_path}" end end def control_uri_str if @control_port "tcp://#{HOST}:#{@control_port}" elsif @control_path "unix://#{HOST}:#{@control_path}" end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/integration.rb
test/helpers/integration.rb
# frozen_string_literal: true require "puma/control_cli" require "json" require "open3" require_relative 'tmp_path' # Only single mode tests go here. Cluster and pumactl tests # have their own files, use those instead class TestIntegration < PumaTest include TmpPath HOST = "127.0.0.1" TOKEN = "xxyyzz" RESP_READ_LEN = 65_536 RESP_READ_TIMEOUT = 10 RESP_SPLIT = "\r\n\r\n" # used in wait_for_server_to_* methods LOG_TIMEOUT = Puma::IS_JRUBY ? 20 : 10 LOG_WAIT_READ = Puma::IS_JRUBY ? 5 : 2 LOG_ERROR_SLEEP = 0.2 LOG_ERROR_QTY = 5 # rubyopt requires bundler/setup, so we don't need it here BASE = "#{Gem.ruby} -Ilib" def setup @server = nil @server_log = +'' @server_stopped = false @config_file = nil @pid = nil @ios_to_close = [] @bind_path = tmp_path('.sock') @control_path = nil @control_tcp_port = nil end def teardown if @server && @control_tcp_port && Puma.windows? cli_pumactl 'stop' # don't close if we've already done so elsif @server && @pid && !@server_stopped && !Puma.windows? stop_server @pid, signal: :INT end @ios_to_close&.each do |io| begin io.close if io.respond_to?(:close) && !io.closed? rescue ensure io = nil end end if @bind_path refute File.exist?(@bind_path), "Bind path must be removed after stop" File.unlink(@bind_path) rescue nil end # wait until the end for OS buffering? if @server begin @server.close unless @server.closed? rescue ensure @server = nil end end if @config_file File.unlink(@config_file.path) rescue nil @config_file = nil end end private def silent_and_checked_system_command(*args) assert(system(*args, out: File::NULL, err: File::NULL)) end def with_unbundled_env bundler_ver = Gem::Version.new(Bundler::VERSION) if bundler_ver < Gem::Version.new('2.1.0') Bundler.with_clean_env { yield } else Bundler.with_unbundled_env { yield } end end def cli_server(argv, # rubocop:disable Metrics/ParameterLists unix: false, # uses a UNIXSocket for the server listener when true config: nil, # string to use for config file no_bind: nil, # bind is defined by args passed or config file merge_err: false, # merge STDERR into STDOUT log: false, # output server log to console (for debugging) no_wait: false, # don't wait for server to boot puma_debug: nil, # set env['PUMA_DEBUG'] = 'true' env: {}) # pass env setting to Puma process in IO.popen if config @config_file = Tempfile.create(%w(config .rb)) @config_file.syswrite config # not supported on some OS's, all GitHub Actions OS's support it @config_file.fsync rescue nil @config_file.close config = "-C #{@config_file.path}" end puma_path = File.expand_path '../../../bin/puma', __FILE__ cmd = if no_bind "#{BASE} #{puma_path} #{config} #{argv}" elsif unix "#{BASE} #{puma_path} #{config} -b unix://#{@bind_path} #{argv}" else @tcp_port = UniquePort.call @bind_port = @tcp_port "#{BASE} #{puma_path} #{config} -b tcp://#{HOST}:#{@tcp_port} #{argv}" end env['PUMA_DEBUG'] = 'true' if puma_debug STDOUT.syswrite "\n#{full_name}\n #{cmd}\n" if log if merge_err @server = IO.popen(env, cmd, :err=>[:child, :out]) else @server = IO.popen(env, cmd) end @pid = @server.pid wait_for_server_to_boot(log: log) unless no_wait @server end # rescue statements are just in case method is called with a server # that is already stopped/killed, especially since Process.wait2 is # blocking def stop_server(pid = @pid, signal: :TERM) @server_stopped = true begin Process.kill signal, pid rescue Errno::ESRCH end begin Process.wait2 pid rescue Errno::ECHILD end end # Most integration tests do not stop/shutdown the server, which is handled by # `teardown` in this file. # For tests that do stop/shutdown the server, use this method to check with `wait2`, # and also clear variables so `teardown` will not run its code. def wait_server(exit_code = 0, pid: @pid) return unless pid begin _, status = Process.wait2 pid status = status.exitstatus % 128 if ::Puma::IS_JRUBY assert_equal exit_code, status rescue Errno::ECHILD # raised on Windows ? end ensure @server.close unless @server.closed? @server = nil end def restart_server_and_listen(argv, env: {}, log: false) cli_server argv, env: env, log: log connection = connect initial_reply = read_body(connection) restart_server connection, log: log [initial_reply, read_body(connect)] end # reuses an existing connection to make sure that works def restart_server(connection, log: false) Process.kill :USR2, @pid wait_for_server_to_include 'Restarting', log: log connection.write "GET / HTTP/1.1\r\n\r\n" # trigger it to start by sending a new request wait_for_server_to_boot log: log end # wait for server to say it booted # @server and/or @server.gets may be nil on slow CI systems def wait_for_server_to_boot(timeout: LOG_TIMEOUT, log: false) @puma_pid = wait_for_server_to_match(/(?:Master| ) PID: (\d+)$/, 1, timeout: timeout, log: log)&.to_i @pid = @puma_pid if @pid != @puma_pid wait_for_server_to_include 'Ctrl-C', timeout: timeout, log: log end # Returns true if and when server log includes str. Will timeout otherwise. def wait_for_server_to_include(str, timeout: LOG_TIMEOUT, log: false) time_timeout = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout line = '' puts "\nβ€”β€”β€” #{full_name} waiting for '#{str}'" if log line = server_gets(str, time_timeout, log: log) until line&.include?(str) true end # Returns line if and when server log matches re, unless idx is specified, # then returns regex match. Will timeout otherwise. def wait_for_server_to_match(re, idx = nil, timeout: LOG_TIMEOUT, log: false) time_timeout = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout line = '' puts "\nβ€”β€”β€” #{full_name} waiting for '#{re.inspect}'" if log line = server_gets(re, time_timeout, log: log) until line&.match?(re) idx ? line[re, idx] : line end def server_gets(match_obj, time_timeout, log: false) error_retries = 0 line = '' sleep 0.05 until @server.is_a?(IO) || Process.clock_gettime(Process::CLOCK_MONOTONIC) > time_timeout raise Minitest::Assertion, "@server is not an IO" unless @server.is_a?(IO) if Process.clock_gettime(Process::CLOCK_MONOTONIC) > time_timeout raise Minitest::Assertion, "Timeout waiting for server to log #{match_obj.inspect}" end begin if @server.wait_readable(LOG_WAIT_READ) and line = @server&.gets @server_log << line puts " #{line}" if log end rescue StandardError => e error_retries += 1 raise(Minitest::Assertion, "Waiting for server to log #{match_obj.inspect} raised #{e.class}") if error_retries == LOG_ERROR_QTY sleep LOG_ERROR_SLEEP retry end if Process.clock_gettime(Process::CLOCK_MONOTONIC) > time_timeout raise Minitest::Assertion, "Timeout waiting for server to log #{match_obj.inspect}" end line end def connect(path = nil, unix: false) s = unix ? UNIXSocket.new(@bind_path) : TCPSocket.new(HOST, @tcp_port) @ios_to_close << s s << "GET /#{path} HTTP/1.1\r\n\r\n" s end # use only if all socket writes are fast # does not wait for a read def fast_connect(path = nil, unix: false) s = unix ? UNIXSocket.new(@bind_path) : TCPSocket.new(HOST, @tcp_port) @ios_to_close << s fast_write s, "GET /#{path} HTTP/1.1\r\n\r\n" s end def fast_write(io, str) n = 0 while true begin n = io.syswrite str rescue Errno::EAGAIN, Errno::EWOULDBLOCK => e unless io.wait_writable 5 raise e end retry rescue Errno::EPIPE, SystemCallError, IOError => e raise e end return if n == str.bytesize str = str.byteslice(n..-1) end end def read_body(connection, timeout = nil) read_response(connection, timeout).last end def read_response(connection, timeout = nil) timeout ||= RESP_READ_TIMEOUT content_length = nil chunked = nil response = +'' t_st = Process.clock_gettime Process::CLOCK_MONOTONIC if connection.to_io.wait_readable timeout loop do begin part = connection.read_nonblock(RESP_READ_LEN, exception: false) case part when String unless content_length || chunked chunked ||= part.include? "\r\nTransfer-Encoding: chunked\r\n" content_length = (t = part[/^Content-Length: (\d+)/i , 1]) ? t.to_i : nil end response << part hdrs, body = response.split RESP_SPLIT, 2 unless body.nil? # below could be simplified, but allows for debugging... ret = if content_length body.bytesize == content_length elsif chunked body.end_with? "\r\n0\r\n\r\n" elsif !hdrs.empty? && !body.empty? true else false end if ret return [hdrs, body] end end sleep 0.000_1 when :wait_readable, :wait_writable # :wait_writable for ssl sleep 0.000_2 when nil raise EOFError end if timeout < Process.clock_gettime(Process::CLOCK_MONOTONIC) - t_st raise Timeout::Error, 'Client Read Timeout' end end end else raise Timeout::Error, 'Client Read Timeout' end end # gets worker pids from @server output def get_worker_pids(phase = 0, size = workers, log: false) pids = [] re = /PID: (\d+)\) booted in [.0-9]+s, phase: #{phase}/ while pids.size < size if pid = wait_for_server_to_match(re, 1, log: log) pids << pid end end pids.map(&:to_i) end # used to define correct 'refused' errors def thread_run_refused(unix: false) if unix DARWIN ? [IOError, Errno::ENOENT, Errno::EPIPE, Errno::EBADF] : [IOError, Errno::ENOENT] else # Errno::ECONNABORTED is thrown intermittently on TCPSocket.new # Errno::ECONNABORTED is thrown by Windows on read or write DARWIN ? [IOError, Errno::ECONNREFUSED, Errno::EPIPE, Errno::EBADF, EOFError, Errno::ECONNABORTED] : [IOError, Errno::ECONNREFUSED, Errno::EPIPE, Errno::ECONNABORTED] end end def set_pumactl_args(unix: false) if unix @control_path = tmp_path('.cntl_sock') "--control-url unix://#{@control_path} --control-token #{TOKEN}" else @control_tcp_port = UniquePort.call "--control-url tcp://#{HOST}:#{@control_tcp_port} --control-token #{TOKEN}" end end def cli_pumactl(argv, unix: false, no_bind: nil) arg = if no_bind argv.split(/ +/) elsif @control_path && !@control_tcp_port %W[-C unix://#{@control_path} -T #{TOKEN} #{argv}] elsif @control_tcp_port && !@control_path %W[-C tcp://#{HOST}:#{@control_tcp_port} -T #{TOKEN} #{argv}] end r, w = IO.pipe @ios_to_close << r Puma::ControlCLI.new(arg, w, w).run w.close r end def cli_pumactl_spawn(argv, unix: false, no_bind: nil) arg = if no_bind argv elsif @control_path && !@control_tcp_port %Q[-C unix://#{@control_path} -T #{TOKEN} #{argv}] elsif @control_tcp_port && !@control_path %Q[-C tcp://#{HOST}:#{@control_tcp_port} -T #{TOKEN} #{argv}] end pumactl_path = File.expand_path '../../../bin/pumactl', __FILE__ cmd = "#{BASE} #{pumactl_path} #{arg}" io = IO.popen(cmd, :err=>[:child, :out]) @ios_to_close << io io end def get_stats read_pipe = cli_pumactl "stats" read_pipe.wait_readable 2 # `split("\n", 2).last` removes "Command stats sent success" line JSON.parse read_pipe.read.split("\n", 2).last end def restart_does_not_drop_connections( num_threads: 1, total_requests: 500, config: nil, unix: nil, signal: nil, log: nil ) skipped = true skip_if :jruby, suffix: <<-MSG - file descriptors are not preserved on exec on JRuby; connection reset errors are expected during restarts MSG skip_if :truffleruby, suffix: ' - Undiagnosed failures on TruffleRuby' clustered = (workers || 0) >= 2 args = "-w #{workers} -t 5:5 -q test/rackup/hello_with_delay.ru" if Puma.windows? cli_server "#{set_pumactl_args} #{args}", unix: unix, config: config, log: log else cli_server args, unix: unix, config: config, log: log end skipped = false replies = Hash.new 0 refused = thread_run_refused unix: false message = 'A' * 16_256 # 2^14 - 128 mutex = Mutex.new restart_count = 0 client_threads = [] num_requests = (total_requests/num_threads).to_i num_threads.times do |thread| client_threads << Thread.new do num_requests.times do |req_num| begin begin socket = unix ? UNIXSocket.new(@bind_path) : TCPSocket.new(HOST, @tcp_port) fast_write socket, "POST / HTTP/1.1\r\nContent-Length: #{message.bytesize}\r\n\r\n#{message}" rescue => e replies[:write_error] += 1 raise e end body = read_body(socket, 10) if body == "Hello World" mutex.synchronize { replies[:success] += 1 replies[:restart] += 1 if restart_count > 0 } else mutex.synchronize { replies[:unexpected_response] += 1 } end rescue Errno::ECONNRESET, Errno::EBADF, Errno::ENOTCONN, Errno::ENOTSOCK # connection was accepted but then closed # client would see an empty response # Errno::EBADF Windows may not be able to make a connection mutex.synchronize { replies[:reset] += 1 } rescue *refused, IOError # IOError intermittently thrown by Ubuntu, add to allow retry mutex.synchronize { replies[:refused] += 1 } rescue ::Timeout::Error mutex.synchronize { replies[:read_timeout] += 1 } ensure if socket.is_a?(IO) && !socket.closed? begin socket.close rescue Errno::EBADF end end end end # STDOUT.puts "#{thread} #{replies[:success]}" end end run = true restart_thread = Thread.new do # Wait for some connections before first restart sleep 0.2 while run if Puma.windows? cli_pumactl 'restart' else Process.kill signal, @pid end if signal == :USR2 # If 'wait_for_server_to_boot' times out, error in thread shuts down CI begin wait_for_server_to_boot timeout: 5 rescue Minitest::Assertion # Timeout run = false end end restart_count += 1 if Puma.windows? sleep 2.0 elsif clustered phase = signal == :USR2 ? 0 : restart_count # If 'get_worker_pids phase' times out, error in thread shuts down CI begin get_worker_pids phase, log: log # Wait with an exponential backoff before signaling next restart sleep 0.15 * restart_count rescue Minitest::Assertion # Timeout run = false rescue Errno::EBADF # bad restart? run = false end else sleep 0.1 end end end # cycle thru threads rather than one at a time until client_threads.empty? client_threads.each_with_index do |t, i| client_threads[i] = nil if t.join(1) end client_threads.compact! end run = false restart_thread.join if Puma.windows? cli_pumactl 'stop' wait_server else stop_server end @server = nil msg = (" %4d unexpected_response\n" % replies.fetch(:unexpected_response,0)).dup msg << " %4d refused\n" % replies.fetch(:refused,0) msg << " %4d read timeout\n" % replies.fetch(:read_timeout,0) msg << " %4d reset\n" % replies.fetch(:reset,0) msg << " %4d write_errors\n" % replies.fetch(:write_error,0) msg << " %4d success\n" % replies.fetch(:success,0) msg << " %4d success after restart\n" % replies.fetch(:restart,0) msg << " %4d restart count\n" % restart_count actual_requests = num_threads * num_requests allowed_errors = (actual_requests * 0.002).round refused = replies[:refused] reset = replies[:reset] assert_operator restart_count, :>=, 2, msg if Puma.windows? assert_equal actual_requests - reset - refused, replies[:success] else assert_operator replies[:success], :>=, actual_requests - allowed_errors, msg end ensure return if skipped if passed? msg = " #{restart_count} restarts, #{reset} resets, #{refused} refused, #{replies[:restart]} success after restart, #{replies[:write_error]} write error" $debugging_info << "#{full_name}\n#{msg}\n" else client_threads.each { |thr| thr.kill if thr.is_a? Thread } $debugging_info << "#{full_name}\n#{msg}\n" end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/tmp_path.rb
test/helpers/tmp_path.rb
# frozen_string_literal: true module TmpPath def clean_tmp_paths while path = tmp_paths.pop delete_tmp_path(path) end end private # With some macOS configurations, the following error may be raised when # creating a UNIXSocket: # # too long unix socket path (106 bytes given but 104 bytes max) (ArgumentError) # PUMA_TMPDIR = begin if RUBY_DESCRIPTION.include? 'darwin' # adds subdirectory 'tmp' in repository folder dir_temp = File.absolute_path("#{__dir__}/../../tmp") Dir.mkdir dir_temp unless Dir.exist? dir_temp './tmp' else nil end end def tmp_path(extension=nil) path = Tempfile.create(['', extension], PUMA_TMPDIR) { |f| f.path } tmp_paths << path path end def tmp_paths @tmp_paths ||= [] end def delete_tmp_path(path) File.unlink(path) rescue Errno::ENOENT end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/apps.rb
test/helpers/apps.rb
# frozen_string_literal: true module TestApps # call with "GET /sleep<d> HTTP/1.1\r\n\r\n", where is the number of # seconds to sleep # same as rackup/sleep.ru SLEEP = -> (env) do dly = (env['REQUEST_PATH'][/\/sleep(\d+)/,1] || '0').to_i sleep dly [200, {"Content-Type" => "text/plain"}, ["Slept #{dly}"]] end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/test_puma/puma_socket.rb
test/helpers/test_puma/puma_socket.rb
# frozen_string_literal: true require 'socket' require_relative '../test_puma' require_relative 'response' module TestPuma # @!macro [new] req # @param req [String, GET_11] request path # @!macro [new] skt # @param host [String] tcp/ssl host # @param port [Integer/String] tcp/ssl port # @param path [String] unix socket, full path # @param ctx [OpenSSL::SSL::SSLContext] ssl context # @param session: [OpenSSL::SSL::Session] ssl session # @!macro [new] resp # @param timeout [Float, nil] total socket read timeout, defaults to `RESP_READ_TIMEOUT` # @param len [ Integer, nil] the `read_nonblock` maxlen, defaults to `RESP_READ_LEN` # This module is included in CI test files, and provides methods to create # client sockets. Normally, the socket parameters are defined by the code # creating the Puma server (in-process or spawned), so they do not need to be # specified. Regardless, many of the less frequently used parameters still # have keyword arguments and they can be set to whatever is required. # # This module closes all sockets and performs all reads non-blocking and all # writes using syswrite. These are helpful for reliable tests. Please do not # use native Ruby sockets except if absolutely necessary. # # #### Methods that return a socket or sockets: # * `new_socket` - Opens a socket # * `send_http` - Opens a socket and sends a request, which defaults to `GET_11` # * `send_http_array` - Creates an array of sockets. It opens each and sends a request on each # # All methods that create a socket have the following optional keyword parameters: # * `host:` - tcp/ssl host (`String`) # * `port:` - tcp/ssl port (`Integer`, `String`) # * `path:` - unix socket, full path (`String`) # * `ctx:` - ssl context (`OpenSSL::SSL::SSLContext`) # * `session:` - ssl session (`OpenSSL::SSL::Session`) # # #### Methods that process the response: # * `send_http_read_response` - sends a request and returns the whole response # * `send_http_read_resp_body` - sends a request and returns the response body # * `send_http_read_resp_headers` - sends a request and returns the response with the body removed as an array of lines # # All methods that process the response have the following optional keyword parameters: # * `timeout:` - total socket read timeout, defaults to `RESP_READ_TIMEOUT` (`Float`) # * `len:` - the `read_nonblock` maxlen, defaults to `RESP_READ_LEN` (`Integer`) # # #### Methods added to socket instances: # * `read_response` - reads the response and returns it, uses `READ_RESPONSE` # * `read_body` - reads the response and returns the body, uses `READ_BODY` # * `<<` - overrides the standard method, writes to the socket with `syswrite`, returns the socket # module PumaSocket GET_10 = "GET / HTTP/1.0\r\n\r\n" GET_11 = "GET / HTTP/1.1\r\n\r\n" HELLO_11 = "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\n" \ "Content-Length: 11\r\n\r\nHello World" RESP_READ_LEN = 65_536 RESP_READ_TIMEOUT = 10 NO_ENTITY_BODY = Puma::STATUS_WITH_NO_ENTITY_BODY EMPTY_200 = [200, {}, ['']] HAS_APPEND_AS_BYTES = ::String.new.respond_to? :append_as_bytes UTF8 = ::Encoding::UTF_8 SET_TCP_NODELAY = Socket.const_defined?(:IPPROTO_TCP) && ::Socket.const_defined?(:TCP_NODELAY) def before_setup @ios_to_close ||= [] @bind_port = nil @bind_path = nil @control_port = nil @control_path = nil super end # Closes all io's in `@ios_to_close`, also deletes them if they are files def after_teardown return if skipped? super # Errno::EBADF raised on macOS @ios_to_close.each do |io| begin if io.respond_to? :sysclose io.sync_close = true io.sysclose unless io.closed? else io.close if io.respond_to?(:close) && !io.closed? if io.is_a?(File) && (path = io&.path) && File.exist?(path) File.unlink path end end rescue Errno::EBADF, Errno::ENOENT, IOError ensure io = nil end end # not sure about below, may help with gc... @ios_to_close.clear @ios_to_close = nil end # rubocop: disable Metrics/ParameterLists # Sends a request and returns the response header lines as an array of strings. # Includes the status line. # @!macro req # @!macro skt # @!macro resp # @return [Array<String>] array of header lines in the response def send_http_read_resp_headers(req = GET_11, host: nil, port: nil, path: nil, ctx: nil, session: nil, len: nil, timeout: nil) skt = send_http req, host: host, port: port, path: path, ctx: ctx, session: session resp = skt.read_response timeout: timeout, len: len resp.split(RESP_SPLIT, 2).first.split "\r\n" end # Sends a request and returns the HTTP response body. # @!macro req # @!macro skt # @!macro resp # @return [Response] the body portion of the HTTP response def send_http_read_resp_body(req = GET_11, host: nil, port: nil, path: nil, ctx: nil, session: nil, len: nil, timeout: nil) skt = send_http req, host: host, port: port, path: path, ctx: ctx, session: session skt.read_body timeout: timeout, len: len end # Sends a request and returns whatever can be read. Use when multiple # responses are sent by the server # @!macro req # @!macro skt # @!macro resp # @return [String] socket read string def send_http_read_all(req = GET_11, host: nil, port: nil, path: nil, ctx: nil, session: nil, len: RESP_READ_LEN, timeout: 15) end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout skt = send_http req, host: host, port: port, path: path, ctx: ctx, session: session read = String.new # rubocop: disable Performance/UnfreezeString counter = 0 prev_size = 0 loop do raise(Timeout::Error, 'Client Read Timeout') if Process.clock_gettime(Process::CLOCK_MONOTONIC) > end_time if skt.wait_readable 1 read << skt.sysread(len) end ttl_read = read.bytesize return read if prev_size == ttl_read && !ttl_read.zero? prev_size = ttl_read counter += 1 end rescue EOFError return read rescue => e raise e end # Sends a request and returns the HTTP response. Assumes one response is sent # @!macro req # @!macro skt # @!macro resp # @return [Response] the HTTP response def send_http_read_response(req = GET_11, host: nil, port: nil, path: nil, ctx: nil, session: nil, len: nil, timeout: nil) skt = send_http req, host: host, port: port, path: path, ctx: ctx, session: session skt.read_response timeout: timeout, len: len end # Sends a request and returns the socket # @param req [String, nil] The request stirng. # @!macro req # @!macro skt # @return [OpenSSL::SSL::SSLSocket, TCPSocket, UNIXSocket] the created socket def send_http(req = GET_11, host: nil, port: nil, path: nil, ctx: nil, session: nil) skt = new_socket host: host, port: port, path: path, ctx: ctx, session: session skt << req end # Determines whether the socket has been closed by the server. Only works when # `Socket::TCP_INFO is defined`, linux/Ubuntu # @param socket [OpenSSL::SSL::SSLSocket, TCPSocket, UNIXSocket] # @return [Boolean] true if closed by server, false is indeterminate, as # it may not be writable # def skt_closed_by_server(socket) skt = socket.to_io return false unless skt.kind_of?(TCPSocket) begin tcp_info = skt.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_INFO) rescue IOError, SystemCallError false else state = tcp_info.unpack('C')[0] # TIME_WAIT: 6, CLOSE: 7, CLOSE_WAIT: 8, LAST_ACK: 9, CLOSING: 11 (state >= 6 && state <= 9) || state == 11 end end READ_BODY = -> (timeout: nil, len: nil) { self.read_response(timeout: nil, len: nil) .split(RESP_SPLIT, 2).last } READ_RESPONSE = -> (timeout: nil, len: nil) do content_length = nil chunked = nil status = nil no_body = nil response = Response.new read_len = len || RESP_READ_LEN timeout ||= RESP_READ_TIMEOUT time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC) time_end = time_start + timeout times = [] time_read = nil loop do begin self.to_io.wait_readable timeout time_read ||= Process.clock_gettime(Process::CLOCK_MONOTONIC) part = self.read_nonblock(read_len, exception: false) case part when String times << (Process.clock_gettime(Process::CLOCK_MONOTONIC) - time_read).round(4) status ||= part[/\AHTTP\/1\.[01] (\d{3})/, 1] if status no_body ||= NO_ENTITY_BODY.key?(status.to_i) || status.to_i < 200 end if no_body && part.end_with?(RESP_SPLIT) response.times = times if HAS_APPEND_AS_BYTES return response.append_as_bytes(part) else return response << part.b end end unless content_length || chunked chunked ||= part.downcase.include? "\r\ntransfer-encoding: chunked\r\n" content_length = (t = part[/^Content-Length: (\d+)/i , 1]) ? t.to_i : nil end if HAS_APPEND_AS_BYTES response.append_as_bytes part else response << part.b end hdrs, body = response.split RESP_SPLIT, 2 unless body.nil? # below could be simplified, but allows for debugging... finished = if content_length body.bytesize == content_length elsif chunked body.end_with? "0\r\n\r\n" elsif !hdrs.empty? && !body.empty? true else false end response.times = times return response if finished end sleep 0.000_1 when :wait_readable # continue loop when :wait_writable # :wait_writable for ssl to = time_end - Process.clock_gettime(Process::CLOCK_MONOTONIC) self.to_io.wait_writable to when nil if response.empty? raise EOFError else response.times = times return response end end timeout = time_end - Process.clock_gettime(Process::CLOCK_MONOTONIC) if timeout <= 0 raise Timeout::Error, 'Client Read Timeout' end end end end # @todo verify whole string is written REQ_WRITE = -> (str) do sent = 0 size = str.bytesize sent += self.syswrite(str.byteslice(sent, size - sent)) while sent < size self end # Helper for creating an `OpenSSL::SSL::SSLContext`. # @param &blk [Block] Passed the SSLContext. # @yield [OpenSSL::SSL::SSLContext] # @return [OpenSSL::SSL::SSLContext] The new socket def new_ctx(&blk) ctx = OpenSSL::SSL::SSLContext.new if blk yield ctx else ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE end ctx end # Creates a new client socket. TCP, SSL, and UNIX are supported # @!macro req # @return [OpenSSL::SSL::SSLSocket, TCPSocket, UNIXSocket] the created socket # def new_socket(host: nil, port: nil, path: nil, ctx: nil, session: nil) port ||= @bind_port path ||= @bind_path ip ||= (host || HOST.ip).gsub RE_HOST_TO_IP, '' # in case a URI style IPv6 is passed skt = if path && !port && !ctx UNIXSocket.new path.sub(/\A@/, "\0") # sub is for abstract elsif port # && !path tcp = TCPSocket.new ip, port.to_i tcp.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) if SET_TCP_NODELAY if ctx ::OpenSSL::SSL::SSLSocket.new tcp, ctx else tcp end else raise 'port or path must be set!' end skt.define_singleton_method :read_response, READ_RESPONSE skt.define_singleton_method :read_body, READ_BODY skt.define_singleton_method :<<, REQ_WRITE skt.define_singleton_method :req_write, REQ_WRITE # used for chaining @ios_to_close << skt if ctx @ios_to_close << tcp skt.session = session if session skt.sync_close = true skt.connect end skt end # Creates an array of sockets, sending a request on each # @param req [String] the request # @param len [Integer] the number of requests to send # @return [Array<OpenSSL::SSL::SSLSocket, TCPSocket, UNIXSocket>] # def send_http_array(req = GET_11, len, dly: 0.000_1, max_retries: 5) Array.new(len) { retries = 0 begin skt = send_http req sleep dly skt rescue Errno::ECONNREFUSED retries += 1 if retries < max_retries retry else flunk 'Generate requests failed from Errno::ECONNREFUSED' end end } end # Reads an array of sockets that have already had requests sent. # @param skts [Array<Sockets]] an array of sockets that have already had # requests sent # @return [Array<String, Class>] an array matching the order of the parameter # `skts`, contains the response or the error class generated by the socket. # def read_response_array(skts, resp_count: nil, body_only: nil) results = Array.new skts.length Thread.new do until skts.compact.empty? skts.each_with_index do |skt, idx| next if skt.nil? begin next unless skt.wait_readable 0.000_5 if resp_count resp = skt.read_response.dup cntr = 0 until resp.split(RESP_SPLIT).length == resp_count + 1 || cntr > 20 cntr += 1 Thread.pass if skt.wait_readable 0.001 begin resp << skt.read_response rescue EOFError break end end end results[idx] = resp else results[idx] = body_only ? skt.read_body : skt.read_response end rescue StandardError => e results[idx] = e.class end begin skt.close unless skt.closed? # skt.close may return Errno::EBADF rescue StandardError => e results[idx] ||= e.class end skts[idx] = nil end end end.join 15 results end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/test_puma/assertions.rb
test/helpers/test_puma/assertions.rb
# frozen_string_literal: true module TestPuma module Assertions # iso8601 2022-12-14T00:05:49Z RE_8601 = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\z/ def assert_start_with(obj, str, msg = nil) msg = message(msg) { "Expected\n#{obj}\nto start with #{str}" } assert_respond_to obj, :start_with? assert obj.start_with?(str), msg end def assert_end_with(obj, str, msg = nil) msg = message(msg) { "Expected\n#{obj}\nto end with #{str}" } assert_respond_to obj, :end_with? assert obj.end_with?(str), msg end def refute_start_with(obj, str, msg = nil) msg = message(msg) { "Expected\n#{obj}\nto not start with #{str}" } assert_respond_to obj, :start_with? refute obj.start_with?(str), msg end def refute_end_with(obj, str, msg = nil) msg = message(msg) { "Expected\n#{obj}\nto not end with #{str}" } assert_respond_to obj, :end_with? refute obj.end_with?(str), msg end # if obj is longer than 80 characters, show as string, not inspected def assert_match(matcher, obj, msg = nil) msg = if obj.length < 80 message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" } else message(msg) { "Expected #{mu_pp matcher} to match:\n#{obj}\n" } end assert_respond_to matcher, :"=~" matcher = Regexp.new Regexp.escape matcher if String === matcher assert matcher =~ obj, msg end def assert_hash(exp, act) exp.each do |exp_k, exp_v| if exp_v.is_a? Class assert_instance_of exp_v, act[exp_k], "Key #{exp_k} has invalid class" elsif exp_v.is_a? ::Regexp assert_match exp_v, act[exp_k], "Key #{exp_k} has invalid match" elsif exp_v.is_a?(Array) || exp_v.is_a?(Range) assert_includes exp_v, act[exp_k], "Key #{exp_k} isn't included" else assert_equal exp_v, act[exp_k], "Key #{exp_k} bad value" end end end end end module Minitest module Assertions prepend TestPuma::Assertions end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/helpers/test_puma/response.rb
test/helpers/test_puma/response.rb
# frozen_string_literal: true module TestPuma # A subclass of String, allows processing the response returned by # `PumaSocket#send_http_read_response` and the `read_response` method added # to native socket instances (created with `PumaSocket#new_socket` and # `PumaSocket#send_http`. # class Response < String attr_accessor :times # Returns response headers as an array of lines # @return [Array<String>] def headers @headers ||= begin ary = self.split(RESP_SPLIT, 2).first.split LINE_SPLIT @status = ary.shift ary end end # Returns response headers as a hash. All keys and values are strings. # @return [Hash] def headers_hash @headers_hash ||= headers.map { |hdr| hdr.split ': ', 2 }.to_h end def status headers @status end def body self.split(RESP_SPLIT, 2).last end # Decodes a chunked body # @return [String] the decoded body def decode_body decoded = String.new # rubocop: disable Performance/UnfreezeString body = self.split(RESP_SPLIT, 2).last body = body.byteslice 0, body.bytesize - 5 # remove terminating bytes loop do size, body = body.split LINE_SPLIT, 2 size = size.to_i 16 decoded << body.byteslice(0, size) body = body.byteslice (size+2)..-1 # remove segment ending "\r\n" break if body.empty? || body.nil? end decoded end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/bundle_preservation_test/version1/config/puma.rb
test/bundle_preservation_test/version1/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/bundle_preservation_test/version2/config/puma.rb
test/bundle_preservation_test/version2/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/t4_conf.rb
test/config/t4_conf.rb
stdout_redirect "t4-stdout" pidfile "t4-pid" class CustomLogger def initialize(output=STDOUT) @output = output end def write(msg) @output.puts 'Custom logging: ' + msg @output.flush end end log_requests custom_logger CustomLogger.new(STDOUT)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/state_file_testing_config.rb
test/config/state_file_testing_config.rb
pidfile "t3-pid" workers 3 before_worker_boot do |index| File.open("t3-worker-#{index}-pid", "w") { |f| f.puts Process.pid } end before_fork { 1 } before_worker_shutdown { 1 } before_worker_boot { 1 } before_worker_fork { 1 } before_restart { 1 } after_worker_boot { 1 } lowlevel_error_handler { 1 }
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/t1_conf.rb
test/config/t1_conf.rb
log_requests stdout_redirect "t1-stdout" pidfile "t1-pid"
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/prune_bundler_print_json_defined.rb
test/config/prune_bundler_print_json_defined.rb
prune_bundler true before_fork do puts "defined?(::JSON): #{defined?(::JSON).inspect}" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/t2_conf.rb
test/config/t2_conf.rb
log_requests stdout_redirect "t2-stdout" pidfile "t2-pid"
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/ssl_config.rb
test/config/ssl_config.rb
key = File.expand_path "../../../examples/puma/puma_keypair.pem", __FILE__ cert = File.expand_path "../../../examples/puma/cert_puma.pem", __FILE__ ca = File.expand_path "../../../examples/puma/client_certs/ca.crt", __FILE__ ssl_bind "0.0.0.0", 9292, :cert => cert, :key => key, :verify_mode => "peer", :ca => ca app do |env| [200, {}, ["embedded app"]] end lowlevel_error_handler do |err| [200, {}, ["error page"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/workers_2.rb
test/config/workers_2.rb
workers 2
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/fork_worker.rb
test/config/fork_worker.rb
fork_worker 1_000
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/event_after_booted_and_after_stopped.rb
test/config/event_after_booted_and_after_stopped.rb
after_booted do puts "after_booted called" end after_stopped do puts "after_stopped called" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/with_rackup_from_dsl.rb
test/config/with_rackup_from_dsl.rb
rackup "test/rackup/hello-env.ru"
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/custom_log_formatter.rb
test/config/custom_log_formatter.rb
log_formatter do |str| "[#{Process.pid}] [#{Socket.gethostname}] #{Time.now}: #{str}" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/max_fast_inline_infinity.rb
test/config/max_fast_inline_infinity.rb
max_keep_alive Float::INFINITY
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/prune_bundler_with_multiple_workers.rb
test/config/prune_bundler_with_multiple_workers.rb
require 'bundler/setup' Bundler.setup prune_bundler true workers 2 app do |env| [200, {}, ["embedded app"]] end lowlevel_error_handler do |err| [200, {}, ["error page"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/ssl_self_signed_config.rb
test/config/ssl_self_signed_config.rb
require "localhost" ssl_bind "0.0.0.0", 9292 app do |env| [200, {}, ["self-signed certificate app"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/max_keep_alive_infinity.rb
test/config/max_keep_alive_infinity.rb
max_keep_alive Float::INFINITY
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/app.rb
test/config/app.rb
port ENV.fetch('PORT', 0) app do |env| [200, {}, ["embedded app"]] end lowlevel_error_handler do |err| [200, {}, ["error page"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/settings.rb
test/config/settings.rb
port 3000 threads 3, 5
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/ab_rs.rb
test/config/ab_rs.rb
url = ARGV.shift count = (ARGV.shift || 1000).to_i STDOUT.sync = true 1.upto(5) do |i| print "#{i}: " str = `ab -n #{count} -c #{i} #{url} 2>/dev/null` rs = /Requests per second:\s+([\d.]+)\s/.match(str) puts rs[1] end puts "Keep Alive:" 1.upto(5) do |i| print "#{i}: " str = `ab -n #{count} -k -c #{i} #{url} 2>/dev/null` rs = /Requests per second:\s+([\d.]+)\s/.match(str) puts rs[1] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/workers_0.rb
test/config/workers_0.rb
workers 0
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/suppress_exception.rb
test/config/suppress_exception.rb
raise_exception_on_sigterm false
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/with_symbol_convert.rb
test/config/with_symbol_convert.rb
io_selector_backend :ruby
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/config_with_deprecated.rb
test/config/config_with_deprecated.rb
on_booted { puts "never called" } app do |env| [200, {}, ["embedded app"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/cli_config.rb
test/config/cli_config.rb
if Puma.cli_config._options[:workers] == 2 Puma.cli_config._options[:workers] = 4 end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/process_detach_before_fork.rb
test/config/process_detach_before_fork.rb
worker_shutdown_timeout 0 before_fork do pid = fork do sleep 30 # This has to exceed the test timeout end pid_filename = File.join(Dir.tmpdir, 'process_detach_test.pid') File.write(pid_filename, pid) Process.detach(pid) end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/rack_url_scheme.rb
test/config/rack_url_scheme.rb
rack_url_scheme "https"
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/prune_bundler_with_deps.rb
test/config/prune_bundler_with_deps.rb
prune_bundler true extra_runtime_dependencies ["minitest"] before_fork do $LOAD_PATH.each do |path| puts "LOAD_PATH: #{path}" end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/event_after_booted_exit.rb
test/config/event_after_booted_exit.rb
after_booted do pid = Process.pid begin Process.kill :TERM, pid rescue Errno::ESRCH end begin Process.wait2 pid rescue Errno::ECHILD end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/after_shutdown_hook.rb
test/config/after_shutdown_hook.rb
workers 2 after_worker_shutdown do |worker| STDOUT.syswrite "\nafter_worker_shutdown worker=#{worker.index} status=#{worker.process_status.to_i}" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/cpu_spin.rb
test/config/cpu_spin.rb
# call with "GET /cpu/<d> HTTP/1.1\r\n\r\n", # where <d> is the number of iterations require 'benchmark' # configure `wait_for_less_busy_workers` based on ENV, default `true` wait_for_less_busy_worker ENV.fetch('PUMA_WAIT_FOR_LESS_BUSY_WORKERS', '0.005').to_f app do |env| iterations = (env['REQUEST_PATH'][/\/cpu\/(\d.*)/,1] || '1000').to_i duration = Benchmark.measure do iterations.times { rand } end [200, {"Content-Type" => "text/plain"}, ["Run for #{duration.total} #{Process.pid}"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/worker_respawn.rb
test/config/worker_respawn.rb
worker_shutdown_timeout 2 # Workers may be respawned with either :TERM or phased restart (:USR1), # preloading is not compatible with the latter. preload_app! false
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/prune_bundler_print_nio_defined.rb
test/config/prune_bundler_print_nio_defined.rb
prune_bundler true before_fork do puts "defined?(::NIO): #{defined?(::NIO).inspect}" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/with_integer_convert.rb
test/config/with_integer_convert.rb
persistent_timeout "6" first_data_timeout "3" workers "2" threads "4", "8" worker_timeout "90" worker_boot_timeout "120" worker_shutdown_timeout "150"
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/t3_conf.rb
test/config/t3_conf.rb
pidfile "t3-pid" workers 3 before_worker_boot do |index| File.open("t3-worker-#{index}-pid", "w") { |f| f.puts Process.pid } end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/hook_data.rb
test/config/hook_data.rb
workers 2 before_worker_boot(:test) do |index, data| data[:test] = index end before_worker_shutdown(:test) do |index, data| STDOUT.syswrite "\nindex #{index} data #{data[:test]}" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/custom_logger.rb
test/config/custom_logger.rb
class CustomLogger def initialize(output=STDOUT) @output = output end def write(msg) @output.puts 'Custom logging: ' + msg @output.flush end end log_requests custom_logger CustomLogger.new(STDOUT)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/config/control_no_token.rb
test/config/control_no_token.rb
activate_control_app 'unix:///tmp/pumactl.sock', { no_token: true } app do |env| [200, {}, ["embedded app"]] end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/old_nio4r/config/puma.rb
test/worker_gem_independence_test/old_nio4r/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/old_json/config/puma.rb
test/worker_gem_independence_test/old_json/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/new_nio4r/config/puma.rb
test/worker_gem_independence_test/new_nio4r/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/new_json/config/puma.rb
test/worker_gem_independence_test/new_json/config/puma.rb
directory File.expand_path("../../current", __dir__)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/old_json_with_puma_stats_after_fork/config/puma.rb
test/worker_gem_independence_test/old_json_with_puma_stats_after_fork/config/puma.rb
directory File.expand_path("../../current", __dir__) after_worker_fork { Puma.stats }
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/test/worker_gem_independence_test/new_json_with_puma_stats_after_fork/config/puma.rb
test/worker_gem_independence_test/new_json_with_puma_stats_after_fork/config/puma.rb
directory File.expand_path("../../current", __dir__) after_worker_fork { Puma.stats }
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/ext/puma_http11/extconf.rb
ext/puma_http11/extconf.rb
require 'mkmf' dir_config("puma_http11") if $mingw append_cflags '-fstack-protector-strong -D_FORTIFY_SOURCE=2' append_ldflags '-fstack-protector-strong -l:libssp.a' have_library 'ssp' end unless ENV["PUMA_DISABLE_SSL"] # don't use pkg_config('openssl') if '--with-openssl-dir' is used has_openssl_dir = dir_config('openssl').any? || RbConfig::CONFIG['configure_args']&.include?('openssl') found_pkg_config = !has_openssl_dir && pkg_config('openssl') found_ssl = if !$mingw && found_pkg_config puts '──── Using OpenSSL pkgconfig (openssl.pc) ────' true elsif have_library('libcrypto', 'BIO_read') && have_library('libssl', 'SSL_CTX_new') true elsif %w'crypto libeay32'.find {|crypto| have_library(crypto, 'BIO_read')} && %w'ssl ssleay32'.find {|ssl| have_library(ssl, 'SSL_CTX_new')} true else puts '** Puma will be compiled without SSL support' false end if found_ssl have_header "openssl/bio.h" ssl_h = "openssl/ssl.h".freeze puts "\n──── Below are yes for 1.0.2 & later ────" have_func "DTLS_method" , ssl_h have_func "SSL_CTX_set_session_cache_mode(NULL, 0)", ssl_h puts "\n──── Below are yes for 1.1.0 & later ────" have_func "TLS_server_method" , ssl_h have_func "SSL_CTX_set_min_proto_version(NULL, 0)" , ssl_h puts "\n──── Below is yes for 1.1.0 and later, but isn't documented until 3.0.0 ────" # https://github.com/openssl/openssl/blob/OpenSSL_1_1_0/include/openssl/ssl.h#L1159 have_func "SSL_CTX_set_dh_auto(NULL, 0)" , ssl_h puts "\n──── Below is yes for 1.1.1 & later ────" have_func "SSL_CTX_set_ciphersuites(NULL, \"\")" , ssl_h puts "\n──── Below is yes for 3.0.0 & later ────" have_func "SSL_get1_peer_certificate" , ssl_h puts '' end end if ENV["PUMA_MAKE_WARNINGS_INTO_ERRORS"] # Make all warnings into errors # Except `implicit-fallthrough` since most failures comes from ragel state machine generated code append_cflags(config_string('WERRORFLAG') || '-Werror') append_cflags '-Wno-implicit-fallthrough' end create_makefile("puma/puma_http11")
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/examples/generate_server_test.rb
examples/generate_server_test.rb
# frozen_string_literal: true =begin regenerates cert_puma.pem and puma_keypair.pem dates, key length & sign_algorithm are changed =end require 'openssl' module GenerateServerCerts KEY_LEN = 2048 SIGN_ALGORITHM = OpenSSL::Digest::SHA256 FNC = 'cert_puma.pem' FNK = 'puma_keypair.pem' class << self def run path = "#{__dir__}/puma" ca_key = OpenSSL::PKey::RSA.new KEY_LEN key = OpenSSL::PKey::RSA.new KEY_LEN raw = File.read File.join(path, FNC), mode: 'rb' cert = OpenSSL::X509::Certificate.new raw puts "\nOld:", cert.to_text, "" now = Time.now.utc mo = now.month yr = now.year zone = '+00:00' cert.not_before = Time.new yr , mo, 1, 0, 0, 0, zone cert.not_after = Time.new yr+4, mo, 1, 0, 0, 0, zone cert.public_key = key.public_key cert.sign ca_key, SIGN_ALGORITHM.new puts "New:", cert.to_text, "" Dir.chdir path do File.write FNC, cert.to_pem, mode: 'wb' File.write FNK, key.to_pem , mode: 'wb' end rescue => e puts "error: #{e.message}" exit 1 end end end GenerateServerCerts.run
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/examples/generate_client_test.rb
examples/generate_client_test.rb
# frozen_string_literal: false =begin run code to generate all certs certs before date will be the first of the current month =end require "openssl" module GenerateClientCerts KEY_LEN = 2048 SIGN_ALGORITHM = OpenSSL::Digest::SHA256 CA_EXTS = [ ["basicConstraints","CA:TRUE",true], ["keyUsage","cRLSign,keyCertSign",true], ] EE_EXTS = [ #["keyUsage","keyEncipherment,digitalSignature",true], ["keyUsage","keyEncipherment,dataEncipherment,digitalSignature",true], ] class << self def run set_dates output_info setup_issue write_files rescue => e puts "error: #{e.message}" exit 1 end private def setup_issue ca = OpenSSL::X509::Name.parse "/DC=net/DC=puma/CN=CA" ca_u = OpenSSL::X509::Name.parse "/DC=net/DC=puma/CN=CAU" svr = OpenSSL::X509::Name.parse "/DC=net/DC=puma/CN=localhost" cli = OpenSSL::X509::Name.parse "/DC=net/DC=puma/CN=localhost" cli_u = OpenSSL::X509::Name.parse "/DC=net/DC=puma/CN=localhost" [:@ca_key, :@svr_key, :@cli_key, :@ca_key_u, :@cli_key_u].each do |k| instance_variable_set k, OpenSSL::PKey::RSA.generate(KEY_LEN) end @ca_cert = issue_cert ca , @ca_key , 3, @before, @after, CA_EXTS, nil , nil , SIGN_ALGORITHM.new @svr_cert = issue_cert svr, @svr_key, 7, @before, @after, EE_EXTS, @ca_cert, @ca_key, SIGN_ALGORITHM.new @cli_cert = issue_cert cli, @cli_key, 11, @before, @after, EE_EXTS, @ca_cert, @ca_key, SIGN_ALGORITHM.new # unknown certs @ca_cert_u = issue_cert ca_u , @ca_key_u , 17, @before, @after, CA_EXTS, nil , nil , SIGN_ALGORITHM.new @cli_cert_u = issue_cert cli_u, @cli_key_u, 19, @before, @after, EE_EXTS, @ca_cert_u, @ca_key_u, SIGN_ALGORITHM.new # expired cert is identical to client cert with different dates @cli_cert_exp = issue_cert cli, @cli_key, 23, @b_exp, @a_exp, EE_EXTS, @ca_cert, @ca_key, SIGN_ALGORITHM.new end def issue_cert(dn, key, serial, not_before, not_after, extensions, issuer, issuer_key, digest) cert = OpenSSL::X509::Certificate.new issuer = cert unless issuer issuer_key = key unless issuer_key cert.version = 2 cert.serial = serial cert.subject = dn cert.issuer = issuer.subject cert.public_key = key.public_key cert.not_before = not_before cert.not_after = not_after ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = cert ef.issuer_certificate = issuer extensions.each { |oid, value, critical| cert.add_extension(ef.create_extension(oid, value, critical)) } cert.sign(issuer_key, digest) cert end def write_files path = "#{__dir__}/puma/client_certs" Dir.chdir path do File.write "ca.crt" , @ca_cert.to_pem , mode: 'wb' File.write "ca.key" , @ca_key.to_pem , mode: 'wb' File.write "server.crt", @svr_cert.to_pem, mode: 'wb' File.write "server.key", @svr_key.to_pem , mode: 'wb' File.write "client.crt", @cli_cert.to_pem, mode: 'wb' File.write "client.key", @cli_key.to_pem , mode: 'wb' File.write "unknown_ca.crt", @ca_cert_u.to_pem, mode: 'wb' File.write "unknown_ca.key", @ca_key_u.to_pem , mode: 'wb' File.write "client_unknown.crt", @cli_cert_u.to_pem, mode: 'wb' File.write "client_unknown.key", @cli_key_u.to_pem , mode: 'wb' File.write "client_expired.crt", @cli_cert_exp.to_pem, mode: 'wb' File.write "client_expired.key", @cli_key.to_pem , mode: 'wb' end end def set_dates now = Time.now.utc mo = now.month yr = now.year zone = '+00:00' @before = Time.new yr , mo, 1, 0, 0, 0, zone @after = Time.new yr+4, mo, 1, 0, 0, 0, zone @b_exp = Time.new yr-1, mo, 1, 0, 0, 0, zone @a_exp = Time.new yr , mo, 1, 0, 0, 0, zone end def output_info puts <<~INFO Key length: #{KEY_LEN} sign_algorithm: #{SIGN_ALGORITHM} Normal cert dates: #{@before} to #{@after} Expired cert dates: #{@b_exp} to #{@a_exp} INFO end end end GenerateClientCerts.run
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/examples/generate_chain_test.rb
examples/generate_chain_test.rb
# frozen_string_literal: true =begin regenerates ca.pem, ca_keypair.pem, subca.pem, subca_keypair.pem, cert.pem, cert_keypair.pem ca_chain.pem, cert_chain.pem certs before date will be the first of the current month =end require 'bundler/inline' gemfile(true) do source 'https://rubygems.org' gem 'certificate_authority' end module GenerateChainCerts CA = "ca.crt" CA_KEY = "ca.key" INTERMEDIATE = "intermediate.crt" INTERMEDIATE_KEY = "intermediate.key" CERT = "cert.crt" CERT_KEY = "cert.key" CA_CHAIN = "ca_chain.pem" CERT_CHAIN = "cert_chain.pem" class << self def before_after @before_after ||= ( now = Time.now.utc mo = now.month yr = now.year zone = '+00:00' { not_before: Time.new(yr, mo, 1, 0, 0, 0, zone), not_after: Time.new(yr+4, mo, 1, 0, 0, 0, zone) } ) end def root_ca @root_ca ||= generate_ca end def intermediate_ca @intermediate_ca ||= generate_ca(common_name: "intermediate.puma.localhost", parent: root_ca) end def generate_ca(common_name: "ca.puma.localhost", parent: nil) ca = CertificateAuthority::Certificate.new ca.subject.common_name = common_name ca.signing_entity = true ca.not_before = before_after[:not_before] ca.not_after = before_after[:not_after] ca.key_material.generate_key if parent ca.serial_number.number = parent.serial_number.number + 10 ca.parent = parent else ca.serial_number.number = 1 end signing_profile = {"extensions" => {"keyUsage" => {"usage" => ["critical", "keyCertSign"] }} } ca.sign!(signing_profile) ca end def generate_cert(common_name: "test.puma.localhost", parent: intermediate_ca) cert = CertificateAuthority::Certificate.new cert.subject.common_name = common_name cert.serial_number.number = parent.serial_number.number + 100 cert.parent = parent cert.key_material.generate_key cert.sign! cert end def run cert = generate_cert path = "#{__dir__}/puma/chain_cert" Dir.chdir path do File.write CA, root_ca.to_pem, mode: 'wb' File.write CA_KEY, root_ca.key_material.private_key.to_pem, mode: 'wb' File.write INTERMEDIATE, intermediate_ca.to_pem, mode: 'wb' File.write INTERMEDIATE_KEY, intermediate_ca.key_material.private_key.to_pem, mode: 'wb' File.write CERT, cert.to_pem, mode: 'wb' File.write CERT_KEY, cert.key_material.private_key.to_pem, mode: 'wb' ca_chain = intermediate_ca.to_pem + root_ca.to_pem File.write CA_CHAIN, ca_chain, mode: 'wb' cert_chain = cert.to_pem + ca_chain File.write CERT_CHAIN, cert_chain, mode: 'wb' end rescue => e puts "error: #{e.message}" exit 1 end end end GenerateChainCerts.run
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/examples/puma/client_certs/run_server_with_certs.rb
examples/puma/client_certs/run_server_with_certs.rb
require "bundler/setup" require "puma" require "puma/detect" require "puma/puma_http11" require "puma/minissl" app = proc {|env| p env['puma.peercert'] [200, {}, [ env['puma.peercert'] ]] } log_writer = Puma::LogWriter.new($stdout, $stderr) server = Puma::Server.new(app, log_writer) context = Puma::MiniSSL::Context.new context.key = "certs/server.key" context.cert = "certs/server.crt" context.ca = "certs/ca.crt" #context.verify_mode = Puma::MiniSSL::VERIFY_NONE #context.verify_mode = Puma::MiniSSL::VERIFY_PEER context.verify_mode = Puma::MiniSSL::VERIFY_PEER | Puma::MiniSSL::VERIFY_FAIL_IF_NO_PEER_CERT server.add_ssl_listener("127.0.0.1", 4000, context) server.run sleep #server.stop(true)
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/examples/plugins/redis_stop_puma.rb
examples/plugins/redis_stop_puma.rb
require 'puma/plugin' require 'redis' # How to stop Puma on Heroku # - You can't use normal methods because the dyno is not accessible # - There's no file system, no way to send signals # but ... # - You can use Redis or Memcache; any network distributed key-value # store # 1. Add this plugin to your 'lib' directory # 2. In the `puma.rb` config file add the following lines # === Plugins === # require './lib/puma/plugin/redis_stop_puma' # plugin 'redis_stop_puma' # 3. Now, when you set the redis key "puma::restart::web.1", your web.1 dyno # will restart # 4. Sniffing the Heroku logs for R14 errors is application (and configuration) # specific. I use the Logentries service, watch for the pattern and the call # a webhook back into my app to set the Redis key. YMMV # You can test this locally by setting the DYNO environment variable when # when starting puma, e.g. `DYNO=pants.1 puma` Puma::Plugin.create do def start(launcher) hostname = ENV['DYNO'] return unless hostname redis = Redis.new(url: ENV.fetch('REDIS_URL', nil)) return unless redis.ping == 'PONG' in_background do while true sleep 2 if message = redis.get("puma::restart::#{hostname}") redis.del("puma::restart::#{hostname}") $stderr.puts message launcher.stop break end end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma.rb
lib/puma.rb
# frozen_string_literal: true # Standard libraries require 'socket' require 'tempfile' require 'uri' require 'stringio' require 'thread' # use require, see https://github.com/puma/puma/pull/2381 require 'puma/puma_http11' require_relative 'puma/detect' require_relative 'puma/json_serialization' module Puma # when Puma is loaded via `Puma::CLI`, all files are loaded via # `require_relative`. The below are for non-standard loading autoload :Const, "#{__dir__}/puma/const" autoload :Server, "#{__dir__}/puma/server" autoload :Launcher, "#{__dir__}/puma/launcher" autoload :LogWriter, "#{__dir__}/puma/log_writer" # at present, MiniSSL::Engine is only defined in extension code (puma_http11), # not in minissl.rb HAS_SSL = const_defined?(:MiniSSL, false) && MiniSSL.const_defined?(:Engine, false) HAS_UNIX_SOCKET = Object.const_defined?(:UNIXSocket) && !IS_WINDOWS if HAS_SSL require_relative 'puma/minissl' else module MiniSSL # this class is defined so that it exists when Puma is compiled # without ssl support, as Server and Reactor use it in rescue statements. class SSLError < StandardError ; end end end def self.ssl? HAS_SSL end def self.abstract_unix_socket? @abstract_unix ||= if HAS_UNIX_SOCKET begin ::UNIXServer.new("\0puma.temp.unix").close true rescue ArgumentError # darwin false end else false end end # @!attribute [rw] stats_object= def self.stats_object=(val) @get_stats = val end # @!attribute [rw] stats_object def self.stats Puma::JSONSerialization.generate @get_stats.stats end # @!attribute [r] stats_hash # @version 5.0.0 def self.stats_hash @get_stats.stats end def self.set_thread_name(name) Thread.current.name = "puma #{name}" end # Shows deprecated warning for renamed methods. # @example # Puma.deprecate_method_change :on_booted, __callee__, __method__ # def self.deprecate_method_change(method_old, method_caller, method_new) if method_old == method_caller warn "Use '#{method_new}', '#{method_caller}' is deprecated and will be removed in v8" end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/events.rb
lib/puma/events.rb
# frozen_string_literal: true module Puma # This is an event sink used by `Puma::Server` to handle # lifecycle events such as :after_booted, :before_restart, and :after_stopped. # Using `Puma::DSL` it is possible to register callback hooks # for each event type. class Events def initialize @hooks = Hash.new { |h,k| h[k] = [] } end # Fire callbacks for the named hook def fire(hook, *args) @hooks[hook].each { |t| t.call(*args) } end # Register a callback for a given hook def register(hook, obj=nil, &blk) if obj and blk raise "Specify either an object or a block, not both" end h = obj || blk @hooks[hook] << h h end def after_booted(&block) register(:after_booted, &block) end def before_restart(&block) register(:before_restart, &block) end def after_stopped(&block) register(:after_stopped, &block) end def on_booted(&block) Puma.deprecate_method_change :on_booted, __callee__, :after_booted after_booted(&block) end def on_restart(&block) Puma.deprecate_method_change :on_restart, __callee__, :before_restart before_restart(&block) end def on_stopped(&block) Puma.deprecate_method_change :on_stopped, __callee__, :after_stopped after_stopped(&block) end def fire_after_booted! fire(:after_booted) end def fire_before_restart! fire(:before_restart) end def fire_after_stopped! fire(:after_stopped) end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/commonlogger.rb
lib/puma/commonlogger.rb
# frozen_string_literal: true module Puma # Rack::CommonLogger forwards every request to the given +app+, and # logs a line in the # {Apache common log format}[https://httpd.apache.org/docs/2.4/logs.html#common] # to the +logger+. # # If +logger+ is nil, CommonLogger will fall back +rack.errors+, which is # an instance of Rack::NullLogger. # # +logger+ can be any class, including the standard library Logger, and is # expected to have either +write+ or +<<+ method, which accepts the CommonLogger::FORMAT. # According to the SPEC, the error stream must also respond to +puts+ # (which takes a single argument that responds to +to_s+), and +flush+ # (which is called without arguments in order to make the error appear for # sure) class CommonLogger # Common Log Format: https://httpd.apache.org/docs/2.4/logs.html#common # # lilith.local - - [07/Aug/2006 23:58:02 -0400] "GET / HTTP/1.1" 500 - # # %{%s - %s [%s] "%s %s%s %s" %d %s\n} % FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n} HIJACK_FORMAT = %{%s - %s [%s] "%s %s%s %s" HIJACKED -1 %0.4f\n} LOG_TIME_FORMAT = '%d/%b/%Y:%H:%M:%S %z' CONTENT_LENGTH = 'Content-Length' # should be lower case from app, # Util::HeaderHash allows mixed HTTP_X_FORWARDED_FOR = Const::HTTP_X_FORWARDED_FOR PATH_INFO = Const::PATH_INFO QUERY_STRING = Const::QUERY_STRING REMOTE_ADDR = Const::REMOTE_ADDR REMOTE_USER = 'REMOTE_USER' REQUEST_METHOD = Const::REQUEST_METHOD SERVER_PROTOCOL = Const::SERVER_PROTOCOL def initialize(app, logger=nil) @app = app @logger = logger end def call(env) began_at = Time.now status, header, body = @app.call(env) header = Util::HeaderHash.new(header) # If we've been hijacked, then output a special line if env['rack.hijack_io'] log_hijacking(env, 'HIJACK', header, began_at) else ary = env['rack.after_reply'] ary << lambda { log(env, status, header, began_at) } end [status, header, body] end private def log_hijacking(env, status, header, began_at) now = Time.now msg = HIJACK_FORMAT % [ env[HTTP_X_FORWARDED_FOR] || env[REMOTE_ADDR] || "-", env[REMOTE_USER] || "-", now.strftime(LOG_TIME_FORMAT), env[REQUEST_METHOD], env[PATH_INFO], env[QUERY_STRING].empty? ? "" : "?#{env[QUERY_STRING]}", env[SERVER_PROTOCOL], now - began_at ] write(msg) end def log(env, status, header, began_at) now = Time.now length = extract_content_length(header) msg = FORMAT % [ env[HTTP_X_FORWARDED_FOR] || env[REMOTE_ADDR] || "-", env[REMOTE_USER] || "-", now.strftime(LOG_TIME_FORMAT), env[REQUEST_METHOD], env[PATH_INFO], env[QUERY_STRING].empty? ? "" : "?#{env[QUERY_STRING]}", env[SERVER_PROTOCOL], status.to_s[0..3], length, now - began_at ] write(msg) end def write(msg) logger = @logger || env['rack.errors'] # Standard library logger doesn't support write but it supports << which actually # calls to write on the log device without formatting if logger.respond_to?(:write) logger.write(msg) else logger << msg end end def extract_content_length(headers) value = headers[CONTENT_LENGTH] or return '-' value.to_s == '0' ? '-' : value end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/cluster.rb
lib/puma/cluster.rb
# frozen_string_literal: true require_relative 'runner' require_relative 'util' require_relative 'plugin' require_relative 'cluster/worker_handle' require_relative 'cluster/worker' module Puma # This class is instantiated by the `Puma::Launcher` and used # to boot and serve a Ruby application when puma "workers" are needed # i.e. when using multi-processes. For example `$ puma -w 5` # # An instance of this class will spawn the number of processes passed in # via the `spawn_workers` method call. Each worker will have it's own # instance of a `Puma::Server`. class Cluster < Runner def initialize(launcher) super(launcher) @phase = 0 @workers = [] @next_check = Time.now @worker_max = [] # keeps track of 'max' stat values @pending_phased_restart = false end # Returns the list of cluster worker handles. # @return [Array<Puma::Cluster::WorkerHandle>] attr_reader :workers def stop_workers log "- Gracefully shutting down workers..." @workers.each { |x| x.term } begin loop do wait_workers break if @workers.reject {|w| w.pid.nil?}.empty? sleep 0.2 end rescue Interrupt log "! Cancelled waiting for workers" end end def start_phased_restart(refork = false) @events.fire_before_restart! @phase += 1 if refork log "- Starting worker refork, phase: #{@phase}" else log "- Starting phased worker restart, phase: #{@phase}" end # Be sure to change the directory again before loading # the app. This way we can pick up new code. dir = @launcher.restart_dir log "+ Changing to #{dir}" Dir.chdir dir end def redirect_io super @workers.each { |x| x.hup } end def spawn_workers diff = @options[:workers] - @workers.size return if diff < 1 master = Process.pid if @options[:fork_worker] @fork_writer << "-1\n" end diff.times do idx = next_worker_index if @options[:fork_worker] && idx != 0 @fork_writer << "#{idx}\n" pid = nil else pid = spawn_worker(idx, master) end debug "Spawned worker: #{pid}" @workers << WorkerHandle.new(idx, pid, @phase, @options) end if @options[:fork_worker] && all_workers_in_phase? @fork_writer << "0\n" if worker_at(0).phase > 0 @fork_writer << "-2\n" end end end # @version 5.0.0 def spawn_worker(idx, master) @config.run_hooks(:before_worker_fork, idx, @log_writer) pid = fork { worker(idx, master) } if !pid log "! Complete inability to spawn new workers detected" log "! Seppuku is the only choice." exit! 1 end @config.run_hooks(:after_worker_fork, idx, @log_writer) pid end def cull_workers diff = @workers.size - @options[:workers] return if diff < 1 debug "Culling #{diff} workers" workers = workers_to_cull(diff) debug "Workers to cull: #{workers.inspect}" workers.each do |worker| log "- Worker #{worker.index} (PID: #{worker.pid}) terminating" worker.term end end def workers_to_cull(diff) workers = @workers.sort_by(&:started_at) # In fork_worker mode, worker 0 acts as our master process. # We should avoid culling it to preserve copy-on-write memory gains. workers.reject! { |w| w.index == 0 } if @options[:fork_worker] workers[cull_start_index(diff), diff] end def cull_start_index(diff) case @options[:worker_culling_strategy] when :oldest 0 else # :youngest -diff end end # @!attribute [r] next_worker_index def next_worker_index occupied_positions = @workers.map(&:index) idx = 0 idx += 1 until !occupied_positions.include?(idx) idx end def worker_at(idx) @workers.find { |w| w.index == idx } end def all_workers_booted? @workers.count { |w| !w.booted? } == 0 end def all_workers_in_phase? @workers.all? { |w| w.phase == @phase } end def all_workers_idle_timed_out? (@workers.map(&:pid) - idle_timed_out_worker_pids).empty? end def check_workers(refork = false) return if @next_check >= Time.now @next_check = Time.now + @options[:worker_check_interval] timeout_workers wait_workers cull_workers spawn_workers if all_workers_booted? # If we're running at proper capacity, check to see if # we need to phase any workers out (which will restart # in the right phase). # w = @workers.find { |x| x.phase < @phase } if w if refork log "- Stopping #{w.pid} for refork..." else log "- Stopping #{w.pid} for phased upgrade..." end unless w.term? w.term log "- #{w.signal} sent to #{w.pid}..." end end end t = @workers.reject(&:term?) t.map!(&:ping_timeout) @next_check = [t.min, @next_check].compact.min end def worker(index, master) @workers = [] @master_read.close @suicide_pipe.close @fork_writer.close pipes = { check_pipe: @check_pipe, worker_write: @worker_write } if @options[:fork_worker] pipes[:fork_pipe] = @fork_pipe pipes[:wakeup] = @wakeup end new_worker = Worker.new index: index, master: master, launcher: @launcher, pipes: pipes, app: (app if preload?) new_worker.run end def restart @restart = true stop end def phased_restart(refork = false) return false if @options[:preload_app] && !refork @pending_phased_restart = refork ? :refork : true wakeup! true end def stop @status = :stop wakeup! end def stop_blocked @status = :stop if @status == :run wakeup! @control&.stop true Process.waitall end def halt @status = :halt wakeup! end def reload_worker_directory dir = @launcher.restart_dir log "+ Changing to #{dir}" Dir.chdir dir end # Inside of a child process, this will return all zeroes, as @workers is only populated in # the master process. Calling this also resets stat 'max' values to zero. # @!attribute [r] stats # @return [Hash] def stats old_worker_count = @workers.count { |w| w.phase != @phase } worker_status = @workers.map do |w| w.reset_max { started_at: utc_iso8601(w.started_at), pid: w.pid, index: w.index, phase: w.phase, booted: w.booted?, last_checkin: utc_iso8601(w.last_checkin), last_status: w.last_status, } end { started_at: utc_iso8601(@started_at), workers: @workers.size, phase: @phase, booted_workers: worker_status.count { |w| w[:booted] }, old_workers: old_worker_count, worker_status: worker_status, }.merge(super) end def preload? @options[:preload_app] end # @version 5.0.0 def fork_worker! if (worker = worker_at 0) worker.phase += 1 end phased_restart(true) end # We do this in a separate method to keep the lambda scope # of the signals handlers as small as possible. def setup_signals if @options[:fork_worker] Signal.trap "SIGURG" do fork_worker! end # Auto-fork after the specified number of requests. if (fork_requests = @options[:fork_worker].to_i) > 0 @events.register(:ping!) do |w| fork_worker! if w.index == 0 && w.phase == 0 && w.last_status[:requests_count] >= fork_requests end end end Signal.trap "SIGCHLD" do wakeup! end Signal.trap "TTIN" do @options[:workers] += 1 wakeup! end Signal.trap "TTOU" do @options[:workers] -= 1 if @options[:workers] >= 2 wakeup! end master_pid = Process.pid Signal.trap "SIGTERM" do # The worker installs their own SIGTERM when booted. # Until then, this is run by the worker and the worker # should just exit if they get it. if Process.pid != master_pid log "Early termination of worker" exit! 0 else @launcher.close_binder_listeners stop_workers stop @events.fire_after_stopped! raise(SignalException, "SIGTERM") if @options[:raise_exception_on_sigterm] exit 0 # Clean exit, workers were stopped end end end def run @status = :run output_header "cluster" # This is aligned with the output from Runner, see Runner#output_header log "* Workers: #{@options[:workers]}" if preload? # Threads explicitly marked as fork safe will be ignored. Used in Rails, # but may be used by anyone. fork_safe = ->(t) { t.thread_variable_get(:fork_safe) } before = Thread.list.reject(&fork_safe) log "* Restarts: (\u2714) hot (\u2716) phased (#{@options[:fork_worker] ? "\u2714" : "\u2716"}) refork" log "* Preloading application" load_and_bind after = Thread.list.reject(&fork_safe) if after.size > before.size threads = (after - before) if threads.first.respond_to? :backtrace log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot:" threads.each do |t| log "! #{t.inspect} - #{t.backtrace ? t.backtrace.first : ''}" end else log "! WARNING: Detected #{after.size-before.size} Thread(s) started in app boot" end end else log "* Restarts: (\u2714) hot (\u2714) phased (#{@options[:fork_worker] ? "\u2714" : "\u2716"}) refork" unless @config.app_configured? error "No application configured, nothing to run" exit 1 end @launcher.binder.parse @options[:binds] end read, @wakeup = Puma::Util.pipe setup_signals # Used by the workers to detect if the master process dies. # If select says that @check_pipe is ready, it's because the # master has exited and @suicide_pipe has been automatically # closed. # @check_pipe, @suicide_pipe = Puma::Util.pipe # Separate pipe used by worker 0 to receive commands to # fork new worker processes. @fork_pipe, @fork_writer = Puma::Util.pipe log "Use Ctrl-C to stop" warn_ruby_mn_threads single_worker_warning redirect_io Plugins.fire_background @launcher.write_state start_control @master_read, @worker_write = read, @wakeup @options[:worker_write] = @worker_write @config.run_hooks(:before_fork, nil, @log_writer) spawn_workers Signal.trap "SIGINT" do stop end begin booted = false in_phased_restart = false workers_not_booted = @options[:workers] while @status == :run begin if @options[:idle_timeout] && all_workers_idle_timed_out? log "- All workers reached idle timeout" break end if @pending_phased_restart start_phased_restart(@pending_phased_restart == :refork) in_phased_restart = @pending_phased_restart @pending_phased_restart = false workers_not_booted = @options[:workers] # worker 0 is not restarted on refork workers_not_booted -= 1 if in_phased_restart == :refork end check_workers(in_phased_restart == :refork) if read.wait_readable([0, @next_check - Time.now].max) req = read.read_nonblock(1) next unless req if req == PIPE_WAKEUP @next_check = Time.now next end result = read.gets pid = result.to_i if req == PIPE_BOOT || req == PIPE_FORK pid, idx = result.split(':').map(&:to_i) w = worker_at idx w.pid = pid if w.pid.nil? end if w = @workers.find { |x| x.pid == pid } case req when PIPE_BOOT w.boot! log "- Worker #{w.index} (PID: #{pid}) booted in #{w.uptime.round(2)}s, phase: #{w.phase}" @next_check = Time.now workers_not_booted -= 1 when PIPE_EXTERNAL_TERM # external term, see worker method, Signal.trap "SIGTERM" w.term! when PIPE_TERM w.term unless w.term? when PIPE_PING status = result.sub(/^\d+/,'').chomp w.ping!(status) @events.fire(:ping!, w) if in_phased_restart && @options[:fork_worker] && workers_not_booted.positive? && w0 = worker_at(0) w0.ping!(status) @events.fire(:ping!, w0) end if !booted && @workers.none? {|worker| worker.last_status.empty?} @events.fire_after_booted! debug_loaded_extensions("Loaded Extensions - master:") if @log_writer.debug? booted = true end when PIPE_IDLE if idle_workers[pid] idle_workers.delete pid else idle_workers[pid] = true end end else log "! Out-of-sync worker list, no #{pid} worker" end end if in_phased_restart && workers_not_booted.zero? @events.fire_after_booted! debug_loaded_extensions("Loaded Extensions - master:") if @log_writer.debug? in_phased_restart = false end rescue Interrupt @status = :stop end end stop_workers unless @status == :halt ensure @check_pipe.close @suicide_pipe.close read.close @wakeup.close end end private def single_worker_warning return if @options[:workers] != 1 || @options[:silence_single_worker_warning] log "! WARNING: Detected running cluster mode with 1 worker." log "! Running Puma in cluster mode with a single worker is often a misconfiguration." log "! Consider running Puma in single-mode (workers = 0) in order to reduce memory overhead." log "! Set the `silence_single_worker_warning` option to silence this warning message." end # loops thru @workers, removing workers that exited, and calling # `#term` if needed def wait_workers # Reap all children, known workers or otherwise. # If puma has PID 1, as it's common in containerized environments, # then it's responsible for reaping orphaned processes, so we must reap # all our dead children, regardless of whether they are workers we spawned # or some reattached processes. reaped_children = {} loop do begin pid, status = Process.wait2(-1, Process::WNOHANG) break unless pid reaped_children[pid] = status rescue Errno::ECHILD break end end @workers.reject! do |w| next false if w.pid.nil? begin # We may need to check the PID individually because: # 1. From Ruby versions 2.6 to 3.2, `Process.detach` can prevent or delay # `Process.wait2(-1)` from detecting a terminated process: https://bugs.ruby-lang.org/issues/19837. # 2. When `fork_worker` is enabled, some worker may not be direct children, # but grand children. Because of this they won't be reaped by `Process.wait2(-1)`. if (status = reaped_children.delete(w.pid) || Process.wait2(w.pid, Process::WNOHANG)&.last) w.process_status = status @config.run_hooks(:after_worker_shutdown, w, @log_writer) true else w.term if w.term? nil end rescue Errno::ECHILD begin Process.kill(0, w.pid) # child still alive but has another parent (e.g., using fork_worker) w.term if w.term? false rescue Errno::ESRCH, Errno::EPERM true # child is already terminated end end end # Log unknown children reaped_children.each do |pid, status| log "! reaped unknown child process pid=#{pid} status=#{status}" end end # @version 5.0.0 def timeout_workers @workers.each do |w| if !w.term? && w.ping_timeout <= Time.now details = if w.booted? "(Worker #{w.index} failed to check in within #{@options[:worker_timeout]} seconds)" else "(Worker #{w.index} failed to boot within #{@options[:worker_boot_timeout]} seconds)" end log "! Terminating timed out worker #{details}: #{w.pid}" w.kill end end end def idle_timed_out_worker_pids idle_workers.keys end def idle_workers @idle_workers ||= {} end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/rack_default.rb
lib/puma/rack_default.rb
# frozen_string_literal: true require_relative '../rack/handler/puma' # rackup was removed in Rack 3, it is now a separate gem if Object.const_defined? :Rackup module Rackup module Handler def self.default(options = {}) ::Rackup::Handler::Puma end end end elsif Object.const_defined?(:Rack) && Rack.release < '3' module Rack module Handler def self.default(options = {}) ::Rack::Handler::Puma end end end else raise "Rack 3 must be used with the Rackup gem" end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/reactor.rb
lib/puma/reactor.rb
# frozen_string_literal: true module Puma class UnsupportedBackend < StandardError; end # Monitors a collection of IO objects, calling a block whenever # any monitored object either receives data or times out, or when the Reactor shuts down. # # The waiting/wake up is performed with nio4r, which will use the appropriate backend (libev, # Java NIO or just plain IO#select). The call to `NIO::Selector#select` will # 'wakeup' any IO object that receives data. # # This class additionally tracks a timeout for every added object, # and wakes up any object when its timeout elapses. # # The implementation uses a Queue to synchronize adding new objects from the internal select loop. class Reactor # @!attribute [rw] reactor_max # Maximum number of clients in the selector. Reset with calls to `Server.stats`. attr_accessor :reactor_max attr_reader :reactor_size # Create a new Reactor to monitor IO objects added by #add. # The provided block will be invoked when an IO has data available to read, # its timeout elapses, or when the Reactor shuts down. def initialize(backend, &block) require 'nio' valid_backends = [:auto, *::NIO::Selector.backends] unless valid_backends.include?(backend) raise ArgumentError.new("unsupported IO selector backend: #{backend} (available backends: #{valid_backends.join(', ')})") end @selector = ::NIO::Selector.new(NIO::Selector.backends.delete(backend)) @input = Queue.new @timeouts = [] @block = block @reactor_size = 0 @reactor_max = 0 end # Run the internal select loop, using a background thread by default. def run(background=true) if background @thread = Thread.new do Puma.set_thread_name "reactor" select_loop end else select_loop end end # Add a new client to monitor. # The object must respond to #timeout and #timeout_at. # Returns false if the reactor is already shut down. def add(client) @input << client @selector.wakeup true rescue ClosedQueueError, IOError # Ignore if selector is already closed false end # Shutdown the reactor, blocking until the background thread is finished. def shutdown @input.close begin @selector.wakeup rescue IOError # Ignore if selector is already closed end @thread&.join end private def select_loop begin until @input.closed? && @input.empty? # Wakeup any registered object that receives incoming data. # Block until the earliest timeout or Selector#wakeup is called. timeout = (earliest = @timeouts.first) && earliest.timeout @selector.select(timeout) do |monitor| wakeup!(monitor.value) end # Wakeup all objects that timed out. timed_out = @timeouts.take_while { |client| client.timeout == 0 } timed_out.each { |client| wakeup!(client) } unless @input.empty? until @input.empty? client = @input.pop register(client) if client.io_ok? end @timeouts.sort_by!(&:timeout_at) end end rescue StandardError => e STDERR.puts "Error in reactor loop escaped: #{e.message} (#{e.class})" STDERR.puts e.backtrace retry end # Wakeup all remaining objects on shutdown. @timeouts.each(&@block) @selector.close end # Start monitoring the object. def register(client) @selector.register(client.to_io, :r).value = client @reactor_size += 1 @reactor_max = @reactor_size if @reactor_max < @reactor_size @timeouts << client rescue ArgumentError # unreadable clients raise error when processed by NIO end # 'Wake up' a monitored object by calling the provided block. # Stop monitoring the object if the block returns `true`. def wakeup!(client) if @block.call client @selector.deregister client.to_io @reactor_size -= 1 @timeouts.delete client end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/minissl.rb
lib/puma/minissl.rb
# frozen_string_literal: true begin require 'io/wait' unless Puma::HAS_NATIVE_IO_WAIT rescue LoadError end require 'open3' # need for Puma::MiniSSL::OPENSSL constants used in `HAS_TLS1_3` # use require, see https://github.com/puma/puma/pull/2381 require 'puma/puma_http11' module Puma module MiniSSL # Define constant at runtime, as it's easy to determine at built time, # but Puma could (it shouldn't) be loaded with an older OpenSSL version # @version 5.0.0 HAS_TLS1_3 = IS_JRUBY || ((OPENSSL_VERSION[/ \d+\.\d+\.\d+/].split('.').map(&:to_i) <=> [1,1,1]) != -1 && (OPENSSL_LIBRARY_VERSION[/ \d+\.\d+\.\d+/].split('.').map(&:to_i) <=> [1,1,1]) !=-1) class Socket def initialize(socket, engine) @socket = socket @engine = engine @peercert = nil @reuse = nil end # @!attribute [r] to_io def to_io @socket end def closed? @socket.closed? end # Returns a two element array, # first is protocol version (SSL_get_version), # second is 'handshake' state (SSL_state_string) # # Used for dropping tcp connections to ssl. # See OpenSSL ssl/ssl_stat.c SSL_state_string for info # @!attribute [r] ssl_version_state # @version 5.0.0 # def ssl_version_state IS_JRUBY ? [nil, nil] : @engine.ssl_vers_st end # Used to check the handshake status, in particular when a TCP connection # is made with TLSv1.3 as an available protocol # @version 5.0.0 def bad_tlsv1_3? HAS_TLS1_3 && ssl_version_state == ['TLSv1.3', 'SSLERR'] end private :bad_tlsv1_3? def readpartial(size) while true output = @engine.read return output if output data = @socket.readpartial(size) @engine.inject(data) output = @engine.read return output if output while neg_data = @engine.extract @socket.write neg_data end end end def engine_read_all output = @engine.read while output and additional_output = @engine.read output << additional_output end output end def read_nonblock(size, *_) # *_ is to deal with keyword args that were added # at some point (and being used in the wild) while true output = engine_read_all return output if output data = @socket.read_nonblock(size, exception: false) if data == :wait_readable || data == :wait_writable # It would make more sense to let @socket.read_nonblock raise # EAGAIN if necessary but it seems like it'll misbehave on Windows. # I don't have a Windows machine to debug this so I can't explain # exactly whats happening in that OS. Please let me know if you # find out! # # In the meantime, we can emulate the correct behavior by # capturing :wait_readable & :wait_writable and raising EAGAIN # ourselves. raise IO::EAGAINWaitReadable elsif data.nil? raise SSLError.exception "HTTP connection?" if bad_tlsv1_3? return nil end @engine.inject(data) output = engine_read_all return output if output while neg_data = @engine.extract @socket.write neg_data end end end def write(data) return 0 if data.empty? data_size = data.bytesize need = data_size while true wrote = @engine.write data enc_wr = +'' while (enc = @engine.extract) enc_wr << enc end @socket.write enc_wr unless enc_wr.empty? need -= wrote return data_size if need == 0 data = data.byteslice(wrote..-1) end end alias_method :syswrite, :write alias_method :<<, :write # This is a temporary fix to deal with websockets code using # write_nonblock. # The problem with implementing it properly # is that it means we'd have to have the ability to rewind # an engine because after we write+extract, the socket # write_nonblock call might raise an exception and later # code would pass the same data in, but the engine would think # it had already written the data in. # # So for the time being (and since write blocking is quite rare), # go ahead and actually block in write_nonblock. # def write_nonblock(data, *_) write data end def flush @socket.flush end def close begin unless @engine.shutdown while alert_data = @engine.extract @socket.write alert_data end end rescue IOError, SystemCallError # nothing ensure @socket.close end end # @!attribute [r] peeraddr def peeraddr @socket.peeraddr end # OpenSSL is loaded in `MiniSSL::ContextBuilder` when # `MiniSSL::Context#verify_mode` is not `VERIFY_NONE`. # When `VERIFY_NONE`, `MiniSSL::Engine#peercert` is nil, regardless of # whether the client sends a cert. # @return [OpenSSL::X509::Certificate, nil] # @!attribute [r] peercert def peercert return @peercert if @peercert raw = @engine.peercert return nil unless raw @peercert = OpenSSL::X509::Certificate.new raw end end if IS_JRUBY OPENSSL_NO_SSL3 = false OPENSSL_NO_TLS1 = false end class Context attr_accessor :verify_mode attr_reader :no_tlsv1, :no_tlsv1_1 def initialize @no_tlsv1 = false @no_tlsv1_1 = false @key = nil @cert = nil @key_pem = nil @cert_pem = nil @reuse = nil @reuse_cache_size = nil @reuse_timeout = nil end def check_file(file, desc) raise ArgumentError, "#{desc} file '#{file}' does not exist" unless File.exist? file raise ArgumentError, "#{desc} file '#{file}' is not readable" unless File.readable? file end if IS_JRUBY # jruby-specific Context properties: java uses a keystore and password pair rather than a cert/key pair attr_reader :keystore attr_reader :keystore_type attr_accessor :keystore_pass attr_reader :truststore attr_reader :truststore_type attr_accessor :truststore_pass attr_reader :cipher_suites attr_reader :protocols def keystore=(keystore) check_file keystore, 'Keystore' @keystore = keystore end def truststore=(truststore) # NOTE: historically truststore was assumed the same as keystore, this is kept for backwards # compatibility, to rely on JVM's trust defaults we allow setting `truststore = :default` unless truststore.eql?(:default) raise ArgumentError, "No such truststore file '#{truststore}'" unless File.exist?(truststore) end @truststore = truststore end def keystore_type=(type) raise ArgumentError, "Invalid keystore type: #{type.inspect}" unless ['pkcs12', 'jks', nil].include?(type) @keystore_type = type end def truststore_type=(type) raise ArgumentError, "Invalid truststore type: #{type.inspect}" unless ['pkcs12', 'jks', nil].include?(type) @truststore_type = type end def cipher_suites=(list) list = list.split(',').map(&:strip) if list.is_a?(String) @cipher_suites = list end # aliases for backwards compatibility alias_method :ssl_cipher_list, :cipher_suites alias_method :ssl_cipher_list=, :cipher_suites= def protocols=(list) list = list.split(',').map(&:strip) if list.is_a?(String) @protocols = list end def check raise "Keystore not configured" unless @keystore # @truststore defaults to @keystore due backwards compatibility end else # non-jruby Context properties attr_reader :key attr_reader :key_password_command attr_reader :cert attr_reader :ca attr_reader :cert_pem attr_reader :key_pem attr_accessor :ssl_cipher_filter attr_accessor :ssl_ciphersuites attr_accessor :verification_flags attr_reader :reuse, :reuse_cache_size, :reuse_timeout def key=(key) check_file key, 'Key' @key = key end def key_password_command=(key_password_command) @key_password_command = key_password_command end def cert=(cert) check_file cert, 'Cert' @cert = cert end def ca=(ca) check_file ca, 'ca' @ca = ca end def cert_pem=(cert_pem) raise ArgumentError, "'cert_pem' is not a String" unless cert_pem.is_a? String @cert_pem = cert_pem end def key_pem=(key_pem) raise ArgumentError, "'key_pem' is not a String" unless key_pem.is_a? String @key_pem = key_pem end def check raise "Key not configured" if @key.nil? && @key_pem.nil? raise "Cert not configured" if @cert.nil? && @cert_pem.nil? end # Executes the command to return the password needed to decrypt the key. def key_password raise "Key password command not configured" if @key_password_command.nil? stdout_str, stderr_str, status = Open3.capture3(@key_password_command) return stdout_str.chomp if status.success? raise "Key password failed with code #{status.exitstatus}: #{stderr_str}" end # Controls session reuse. Allowed values are as follows: # * 'off' - matches the behavior of Puma 5.6 and earlier. This is included # in case reuse 'on' is made the default in future Puma versions. # * 'dflt' - sets session reuse on, with OpenSSL default cache size of # 20k and default timeout of 300 seconds. # * 's,t' - where s and t are integer strings, for size and timeout. # * 's' - where s is an integer strings for size. # * ',t' - where t is an integer strings for timeout. # def reuse=(reuse_str) case reuse_str when 'off' @reuse = nil when 'dflt' @reuse = true when /\A\d+\z/ @reuse = true @reuse_cache_size = reuse_str.to_i when /\A\d+,\d+\z/ @reuse = true size, time = reuse_str.split ',' @reuse_cache_size = size.to_i @reuse_timeout = time.to_i when /\A,\d+\z/ @reuse = true @reuse_timeout = reuse_str.delete(',').to_i end end end # disables TLSv1 # @!attribute [w] no_tlsv1= def no_tlsv1=(tlsv1) raise ArgumentError, "Invalid value of no_tlsv1=" unless ['true', 'false', true, false].include?(tlsv1) @no_tlsv1 = tlsv1 end # disables TLSv1 and TLSv1.1. Overrides `#no_tlsv1=` # @!attribute [w] no_tlsv1_1= def no_tlsv1_1=(tlsv1_1) raise ArgumentError, "Invalid value of no_tlsv1_1=" unless ['true', 'false', true, false].include?(tlsv1_1) @no_tlsv1_1 = tlsv1_1 end end VERIFY_NONE = 0 VERIFY_PEER = 1 VERIFY_FAIL_IF_NO_PEER_CERT = 2 # https://github.com/openssl/openssl/blob/master/include/openssl/x509_vfy.h.in # /* Certificate verify flags */ VERIFICATION_FLAGS = { "USE_CHECK_TIME" => 0x2, "CRL_CHECK" => 0x4, "CRL_CHECK_ALL" => 0x8, "IGNORE_CRITICAL" => 0x10, "X509_STRICT" => 0x20, "ALLOW_PROXY_CERTS" => 0x40, "POLICY_CHECK" => 0x80, "EXPLICIT_POLICY" => 0x100, "INHIBIT_ANY" => 0x200, "INHIBIT_MAP" => 0x400, "NOTIFY_POLICY" => 0x800, "EXTENDED_CRL_SUPPORT" => 0x1000, "USE_DELTAS" => 0x2000, "CHECK_SS_SIGNATURE" => 0x4000, "TRUSTED_FIRST" => 0x8000, "SUITEB_128_LOS_ONLY" => 0x10000, "SUITEB_192_LOS" => 0x20000, "SUITEB_128_LOS" => 0x30000, "PARTIAL_CHAIN" => 0x80000, "NO_ALT_CHAINS" => 0x100000, "NO_CHECK_TIME" => 0x200000 }.freeze class Server def initialize(socket, ctx) @socket = socket @ctx = ctx @eng_ctx = IS_JRUBY ? @ctx : SSLContext.new(ctx) end def accept @ctx.check io = @socket.accept engine = Engine.server @eng_ctx Socket.new io, engine end def accept_nonblock @ctx.check io = @socket.accept_nonblock engine = Engine.server @eng_ctx Socket.new io, engine end # @!attribute [r] to_io def to_io @socket end # @!attribute [r] addr # @version 5.0.0 def addr @socket.addr end def close @socket.close unless @socket.closed? # closed? call is for Windows end def closed? @socket.closed? end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/const.rb
lib/puma/const.rb
#encoding: utf-8 # frozen_string_literal: true module Puma class UnsupportedOption < RuntimeError end # Every standard HTTP code mapped to the appropriate message. These are # used so frequently that they are placed directly in Puma for easy # access rather than Puma::Const itself. # Every standard HTTP code mapped to the appropriate message. # Generated with: # curl -s https://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv | \ # ruby -ne 'm = /^(\d{3}),(?!Unassigned|\(Unused\))([^,]+)/.match($_) and \ # puts "#{m[1]} => \x27#{m[2].strip}\x27,"' HTTP_STATUS_CODES = { 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 103 => 'Early Hints', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 208 => 'Already Reported', 226 => 'IM Used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Content Too Large', 414 => 'URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Range Not Satisfiable', 417 => 'Expectation Failed', 421 => 'Misdirected Request', 422 => 'Unprocessable Content', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Too Early', 426 => 'Upgrade Required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 451 => 'Unavailable For Legal Reasons', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended (OBSOLETED)', 511 => 'Network Authentication Required' }.freeze # For some HTTP status codes the client only expects headers. # STATUS_WITH_NO_ENTITY_BODY = { 204 => true, 205 => true, 304 => true }.freeze # Frequently used constants when constructing requests or responses. Many times # the constant just refers to a string with the same contents. Using these constants # gave about a 3% to 10% performance improvement over using the strings directly. # # The constants are frozen because Hash#[]= when called with a String key dups # the String UNLESS the String is frozen. This saves us therefore 2 object # allocations when creating the env hash later. # # While Puma does try to emulate the CGI/1.2 protocol, it does not use the REMOTE_IDENT, # REMOTE_USER, or REMOTE_HOST parameters since those are either a security problem or # too taxing on performance. module Const PUMA_VERSION = VERSION = "7.1.0" CODE_NAME = "Neon Witch" PUMA_SERVER_STRING = ["puma", PUMA_VERSION, CODE_NAME].join(" ").freeze # How long to wait when getting some write blocking on the socket when # sending data back WRITE_TIMEOUT = 10 # The original URI requested by the client. REQUEST_URI= "REQUEST_URI" REQUEST_PATH = "REQUEST_PATH" QUERY_STRING = "QUERY_STRING" CONTENT_LENGTH = "CONTENT_LENGTH" PATH_INFO = "PATH_INFO" PUMA_TMP_BASE = "puma" ERROR_RESPONSE = { # Indicate that we couldn't parse the request 400 => "HTTP/1.1 400 Bad Request\r\n\r\n", # The standard empty 404 response for bad requests. Use Error4040Handler for custom stuff. 404 => "HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n", # The standard empty 408 response for requests that timed out. 408 => "HTTP/1.1 408 Request Timeout\r\nconnection: close\r\n\r\n", # Indicate that there was an internal error, obviously. 500 => "HTTP/1.1 500 Internal Server Error\r\n\r\n", # Incorrect or invalid header value 501 => "HTTP/1.1 501 Not Implemented\r\n\r\n", # A common header for indicating the server is too busy. Not used yet. 503 => "HTTP/1.1 503 Service Unavailable\r\n\r\n" }.freeze # The basic max request size we'll try to read. CHUNK_SIZE = 64 * 1024 # This is the maximum header that is allowed before a client is booted. The parser detects # this, but we'd also like to do this as well. MAX_HEADER = 1024 * (80 + 32) # Maximum request body size before it is moved out of memory and into a tempfile for reading. MAX_BODY = MAX_HEADER REQUEST_METHOD = "REQUEST_METHOD" HEAD = "HEAD" # based on https://www.rfc-editor.org/rfc/rfc9110.html#name-overview, # with CONNECT removed, and PATCH added SUPPORTED_HTTP_METHODS = %w[HEAD GET POST PUT DELETE OPTIONS TRACE PATCH].freeze # list from https://www.iana.org/assignments/http-methods/http-methods.xhtml # as of 04-May-23 IANA_HTTP_METHODS = %w[ ACL BASELINE-CONTROL BIND CHECKIN CHECKOUT CONNECT COPY DELETE GET HEAD LABEL LINK LOCK MERGE MKACTIVITY MKCALENDAR MKCOL MKREDIRECTREF MKWORKSPACE MOVE OPTIONS ORDERPATCH PATCH POST PRI PROPFIND PROPPATCH PUT REBIND REPORT SEARCH TRACE UNBIND UNCHECKOUT UNLINK UNLOCK UPDATE UPDATEREDIRECTREF VERSION-CONTROL ].freeze # ETag is based on the apache standard of hex mtime-size-inode (inode is 0 on win32) LINE_END = "\r\n" REMOTE_ADDR = "REMOTE_ADDR" HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR" HTTP_X_FORWARDED_SSL = "HTTP_X_FORWARDED_SSL" HTTP_X_FORWARDED_SCHEME = "HTTP_X_FORWARDED_SCHEME" HTTP_X_FORWARDED_PROTO = "HTTP_X_FORWARDED_PROTO" SERVER_NAME = "SERVER_NAME" SERVER_PORT = "SERVER_PORT" HTTP_HOST = "HTTP_HOST" PORT_80 = "80" PORT_443 = "443" LOCALHOST = "localhost" LOCALHOST_IPV4 = "127.0.0.1" LOCALHOST_IPV6 = "::1" UNSPECIFIED_IPV4 = "0.0.0.0" UNSPECIFIED_IPV6 = "::" SERVER_PROTOCOL = "SERVER_PROTOCOL" HTTP_11 = "HTTP/1.1" SERVER_SOFTWARE = "SERVER_SOFTWARE" GATEWAY_INTERFACE = "GATEWAY_INTERFACE" CGI_VER = "CGI/1.2" STOP_COMMAND = "?" HALT_COMMAND = "!" RESTART_COMMAND = "R" RACK_INPUT = "rack.input" RACK_URL_SCHEME = "rack.url_scheme" RACK_AFTER_REPLY = "rack.after_reply" RACK_RESPONSE_FINISHED = "rack.response_finished" PUMA_SOCKET = "puma.socket" PUMA_CONFIG = "puma.config" PUMA_PEERCERT = "puma.peercert" HTTP = "http" HTTPS = "https" HTTPS_KEY = "HTTPS" HTTP_VERSION = "HTTP_VERSION" HTTP_CONNECTION = "HTTP_CONNECTION" HTTP_EXPECT = "HTTP_EXPECT" CONTINUE = "100-continue" HTTP_11_100 = "HTTP/1.1 100 Continue\r\n\r\n" HTTP_11_200 = "HTTP/1.1 200 OK\r\n" HTTP_10_200 = "HTTP/1.0 200 OK\r\n" CLOSE = "close" KEEP_ALIVE = "keep-alive" CONTENT_LENGTH2 = "content-length" CONTENT_LENGTH_S = "content-length: " TRANSFER_ENCODING = "transfer-encoding" TRANSFER_ENCODING2 = "HTTP_TRANSFER_ENCODING" CONNECTION_CLOSE = "connection: close\r\n" CONNECTION_KEEP_ALIVE = "connection: keep-alive\r\n" TRANSFER_ENCODING_CHUNKED = "transfer-encoding: chunked\r\n" CLOSE_CHUNKED = "0\r\n\r\n" CHUNKED = "chunked" COLON = ": " NEWLINE = "\n" HIJACK_P = "rack.hijack?" HIJACK = "rack.hijack" HIJACK_IO = "rack.hijack_io" EARLY_HINTS = "rack.early_hints" # Illegal character in the key or value of response header DQUOTE = "\"" HTTP_HEADER_DELIMITER = Regexp.escape("(),/:;<=>?@[]{}\\").freeze ILLEGAL_HEADER_KEY_REGEX = /[\x00-\x20#{DQUOTE}#{HTTP_HEADER_DELIMITER}]/.freeze # header values can contain HTAB? ILLEGAL_HEADER_VALUE_REGEX = /[\x00-\x08\x0A-\x1F]/.freeze # The keys of headers that should not be convert to underscore # normalized versions. These headers are ignored at the request reading layer, # but if we normalize them after reading, it's just confusing for the application. UNMASKABLE_HEADERS = { "HTTP_TRANSFER,ENCODING" => true, "HTTP_CONTENT,LENGTH" => true, } # Banned keys of response header BANNED_HEADER_KEY = /\A(rack\.|status\z)/.freeze PROXY_PROTOCOL_V1_REGEX = /^PROXY (?:TCP4|TCP6|UNKNOWN) ([^\r]+)\r\n/.freeze # All constants are prefixed with `PIPE_` to avoid name collisions. module PipeRequest PIPE_WAKEUP = "!" PIPE_BOOT = "b" PIPE_FORK = "f" PIPE_EXTERNAL_TERM = "e" PIPE_TERM = "t" PIPE_PING = "p" PIPE_IDLE = "i" end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/null_io.rb
lib/puma/null_io.rb
# frozen_string_literal: true module Puma # Provides an IO-like object that always appears to contain no data. # Used as the value for rack.input when the request has no body. # class NullIO def gets nil end def string "" end def each end def pos 0 end # Mimics IO#read with no data. # def read(length = nil, buffer = nil) if length.to_i < 0 raise ArgumentError, "(negative length #{length} given)" end buffer = if buffer.nil? "".b else String.try_convert(buffer) or raise TypeError, "no implicit conversion of #{buffer.class} into String" end buffer.clear if length.to_i > 0 nil else buffer end end def rewind end def seek(pos, whence = 0) raise ArgumentError, "negative length #{pos} given" if pos.negative? 0 end def close end def size 0 end def eof? true end def sync true end def sync=(v) end def puts(*ary) end def write(*ary) end def flush self end # This is used as singleton class, so can't have state. def closed? false end def set_encoding(enc) self end # per rack spec def external_encoding Encoding::ASCII_8BIT end def binmode self end def binmode? true end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/log_writer.rb
lib/puma/log_writer.rb
# frozen_string_literal: true require_relative 'null_io' require_relative 'error_logger' require 'stringio' require 'io/wait' unless Puma::HAS_NATIVE_IO_WAIT module Puma # Handles logging concerns for both standard messages # (+stdout+) and errors (+stderr+). class LogWriter class DefaultFormatter def call(str) str end end class PidFormatter def call(str) "[#{$$}] #{str}" end end LOG_QUEUE = Queue.new attr_reader :stdout, :stderr attr_accessor :formatter, :custom_logger # Create a LogWriter that prints to +stdout+ and +stderr+. def initialize(stdout, stderr, env: ENV) @formatter = DefaultFormatter.new @custom_logger = nil @stdout = stdout @stderr = stderr @debug = env.key?('PUMA_DEBUG') @error_logger = ErrorLogger.new(@stderr, env: env) end DEFAULT = new(STDOUT, STDERR) # Returns an LogWriter object which writes its status to # two StringIO objects. def self.strings(env: ENV) LogWriter.new(StringIO.new, StringIO.new, env: env) end def self.stdio(env: ENV) LogWriter.new($stdout, $stderr, env: env) end def self.null(env: ENV) n = NullIO.new LogWriter.new(n, n, env: env) end # Write +str+ to +@stdout+ def log(str) if @custom_logger&.respond_to?(:write) @custom_logger.write(format(str)) else internal_write "#{@formatter.call str}\n" end end def write(str) internal_write @formatter.call(str) end def internal_write(str) LOG_QUEUE << str while (w_str = LOG_QUEUE.pop(true)) do begin @stdout.is_a?(IO) and @stdout.wait_writable(1) @stdout.write w_str @stdout.flush unless @stdout.sync rescue Errno::EPIPE, Errno::EBADF, IOError, Errno::EINVAL # 'Invalid argument' (Errno::EINVAL) may be raised by flush end end rescue ThreadError end private :internal_write def debug? @debug end def debug(str) log("% #{str}") if @debug end # Write +str+ to +@stderr+ def error(str) @error_logger.info(text: @formatter.call("ERROR: #{str}")) exit 1 end def format(str) formatter.call(str) end # An HTTP connection error has occurred. # +error+ a connection exception, +req+ the request, # and +text+ additional info # @version 5.0.0 def connection_error(error, req, text="HTTP connection error") @error_logger.info(error: error, req: req, text: text) end # An HTTP parse error has occurred. # +error+ a parsing exception, # and +req+ the request. def parse_error(error, req) @error_logger.info(error: error, req: req, text: 'HTTP parse error, malformed request') end # An SSL error has occurred. # @param error <Puma::MiniSSL::SSLError> # @param ssl_socket <Puma::MiniSSL::Socket> def ssl_error(error, ssl_socket) peeraddr = ssl_socket.peeraddr.last rescue "<unknown>" peercert = ssl_socket.peercert subject = peercert&.subject @error_logger.info(error: error, text: "SSL error, peer: #{peeraddr}, peer cert: #{subject}") end # An unknown error has occurred. # +error+ an exception object, +req+ the request, # and +text+ additional info def unknown_error(error, req=nil, text="Unknown error") @error_logger.info(error: error, req: req, text: text) end # Log occurred error debug dump. # +error+ an exception object, +req+ the request, # and +text+ additional info # @version 5.0.0 def debug_error(error, req=nil, text="") @error_logger.debug(error: error, req: req, text: text) end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/sd_notify.rb
lib/puma/sd_notify.rb
# frozen_string_literal: true require "socket" module Puma # The MIT License # # Copyright (c) 2017-2022 Agis Anastasopoulos # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # This is a copy of https://github.com/agis/ruby-sdnotify as of commit cca575c # The only changes made was "rehoming" it within the Puma module to avoid # namespace collisions and applying standard's code formatting style. # # SdNotify is a pure-Ruby implementation of sd_notify(3). It can be used to # notify systemd about state changes. Methods of this package are no-op on # non-systemd systems (eg. Darwin). # # The API maps closely to the original implementation of sd_notify(3), # therefore be sure to check the official man pages prior to using SdNotify. # # @see https://www.freedesktop.org/software/systemd/man/sd_notify.html module SdNotify # Exception raised when there's an error writing to the notification socket class NotifyError < RuntimeError; end READY = "READY=1" RELOADING = "RELOADING=1" STOPPING = "STOPPING=1" STATUS = "STATUS=" ERRNO = "ERRNO=" MAINPID = "MAINPID=" WATCHDOG = "WATCHDOG=1" FDSTORE = "FDSTORE=1" def self.ready(unset_env=false) notify(READY, unset_env) end def self.reloading(unset_env=false) notify(RELOADING, unset_env) end def self.stopping(unset_env=false) notify(STOPPING, unset_env) end # @param status [String] a custom status string that describes the current # state of the service def self.status(status, unset_env=false) notify("#{STATUS}#{status}", unset_env) end # @param errno [Integer] def self.errno(errno, unset_env=false) notify("#{ERRNO}#{errno}", unset_env) end # @param pid [Integer] def self.mainpid(pid, unset_env=false) notify("#{MAINPID}#{pid}", unset_env) end def self.watchdog(unset_env=false) notify(WATCHDOG, unset_env) end def self.fdstore(unset_env=false) notify(FDSTORE, unset_env) end # @param [Boolean] true if the service manager expects watchdog keep-alive # notification messages to be sent from this process. # # If the $WATCHDOG_USEC environment variable is set, # and the $WATCHDOG_PID variable is unset or set to the PID of the current # process # # @note Unlike sd_watchdog_enabled(3), this method does not mutate the # environment. def self.watchdog? wd_usec = ENV["WATCHDOG_USEC"] wd_pid = ENV["WATCHDOG_PID"] return false if !wd_usec begin wd_usec = Integer(wd_usec) rescue return false end return false if wd_usec <= 0 return true if !wd_pid || wd_pid == $$.to_s false end # Notify systemd with the provided state, via the notification socket, if # any. # # Generally this method will be used indirectly through the other methods # of the library. # # @param state [String] # @param unset_env [Boolean] # # @return [Fixnum, nil] the number of bytes written to the notification # socket or nil if there was no socket to report to (eg. the program wasn't # started by systemd) # # @raise [NotifyError] if there was an error communicating with the systemd # socket # # @see https://www.freedesktop.org/software/systemd/man/sd_notify.html def self.notify(state, unset_env=false) sock = ENV["NOTIFY_SOCKET"] return nil if !sock ENV.delete("NOTIFY_SOCKET") if unset_env begin Addrinfo.unix(sock, :DGRAM).connect { |s| s.write state } rescue StandardError => e raise NotifyError, "#{e.class}: #{e.message}", e.backtrace end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/plugin.rb
lib/puma/plugin.rb
# frozen_string_literal: true module Puma class UnknownPlugin < RuntimeError; end class PluginLoader def initialize @instances = [] end def create(name) if cls = Plugins.find(name) plugin = cls.new @instances << plugin return plugin end raise UnknownPlugin, "File failed to register properly named plugin" end def fire_starts(launcher) @instances.each do |i| if i.respond_to? :start i.start(launcher) end end end end class PluginRegistry def initialize @plugins = {} @background = [] end def register(name, cls) @plugins[name] = cls end def find(name) name = name.to_s if cls = @plugins[name] return cls end begin require "puma/plugin/#{name}" rescue LoadError raise UnknownPlugin, "Unable to find plugin: #{name}" end if cls = @plugins[name] return cls end raise UnknownPlugin, "file failed to register a plugin" end def add_background(blk) @background << blk end def fire_background @background.each_with_index do |b, i| Thread.new do Puma.set_thread_name "plgn bg #{i}" b.call end end end end Plugins = PluginRegistry.new class Plugin # Matches # "C:/Ruby22/lib/ruby/gems/2.2.0/gems/puma-3.0.1/lib/puma/plugin/tmp_restart.rb:3:in `<top (required)>'" # AS # C:/Ruby22/lib/ruby/gems/2.2.0/gems/puma-3.0.1/lib/puma/plugin/tmp_restart.rb CALLER_FILE = / \A # start of string .+ # file path (one or more characters) (?= # stop previous match when :\d+ # a colon is followed by one or more digits :in # followed by a colon followed by in ) /x def self.extract_name(ary) path = ary.first[CALLER_FILE] m = %r!puma/plugin/([^/]*)\.rb$!.match(path) m[1] end def self.create(&blk) name = extract_name(caller) cls = Class.new(self) cls.class_eval(&blk) Plugins.register name, cls end def in_background(&blk) Plugins.add_background blk end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/control_cli.rb
lib/puma/control_cli.rb
# frozen_string_literal: true require 'optparse' require_relative 'const' require_relative 'detect' require 'uri' require 'socket' module Puma class ControlCLI # values must be string or nil # value of `nil` means command cannot be processed via signal # @version 5.0.3 CMD_PATH_SIG_MAP = { 'gc' => nil, 'gc-stats' => nil, 'halt' => 'SIGQUIT', 'info' => 'SIGINFO', 'phased-restart' => 'SIGUSR1', 'refork' => 'SIGURG', 'reload-worker-directory' => nil, 'reopen-log' => 'SIGHUP', 'restart' => 'SIGUSR2', 'start' => nil, 'stats' => nil, 'status' => '', 'stop' => 'SIGTERM', 'thread-backtraces' => nil, 'worker-count-down' => 'SIGTTOU', 'worker-count-up' => 'SIGTTIN' }.freeze # commands that cannot be used in a request NO_REQ_COMMANDS = %w[info reopen-log worker-count-down worker-count-up].freeze # @version 5.0.0 PRINTABLE_COMMANDS = %w[gc-stats stats thread-backtraces].freeze def initialize(argv, stdout=STDOUT, stderr=STDERR, env: ENV) @state = nil @quiet = false @pidfile = nil @pid = nil @control_url = nil @control_auth_token = nil @config_file = nil @command = nil @environment = env['APP_ENV'] || env['RACK_ENV'] || env['RAILS_ENV'] @argv = argv.dup @stdout = stdout @stderr = stderr @cli_options = {} opts = OptionParser.new do |o| o.banner = "Usage: pumactl (-p PID | -P pidfile | -S status_file | -C url -T token | -F config.rb) (#{CMD_PATH_SIG_MAP.keys.join("|")})" o.on "-S", "--state PATH", "Where the state file to use is" do |arg| @state = arg end o.on "-Q", "--quiet", "Do not display messages" do |arg| @quiet = true end o.on "-P", "--pidfile PATH", "Pid file" do |arg| @pidfile = arg end o.on "-p", "--pid PID", "Pid" do |arg| @pid = arg.to_i end o.on "-C", "--control-url URL", "The bind url to use for the control server" do |arg| @control_url = arg end o.on "-T", "--control-token TOKEN", "The token to use as authentication for the control server" do |arg| @control_auth_token = arg end o.on "-F", "--config-file PATH", "Puma config script" do |arg| @config_file = arg end o.on "-e", "--environment ENVIRONMENT", "The environment to run the Rack app on (default development)" do |arg| @environment = arg end o.on_tail("-H", "--help", "Show this message") do @stdout.puts o exit end o.on_tail("-V", "--version", "Show version") do @stdout.puts Const::PUMA_VERSION exit end end opts.order!(argv) { |a| opts.terminate a } opts.parse! @command = argv.shift # check presence of command unless @command raise "Available commands: #{CMD_PATH_SIG_MAP.keys.join(", ")}" end unless CMD_PATH_SIG_MAP.key? @command raise "Invalid command: #{@command}" end unless @config_file == '-' environment = @environment || 'development' if @config_file.nil? @config_file = %W(config/puma/#{environment}.rb config/puma.rb).find do |f| File.exist?(f) end end if @config_file # needed because neither `Puma::CLI` or `Puma::Server` are loaded require_relative '../puma' require_relative 'configuration' require_relative 'log_writer' config = Puma::Configuration.new({ config_files: [@config_file] }, {} , env) config.clamp @state ||= config.options[:state] @control_url ||= config.options[:control_url] @control_auth_token ||= config.options[:control_auth_token] @pidfile ||= config.options[:pidfile] end end rescue => e @stdout.puts e.message exit 1 end def message(msg) @stdout.puts msg unless @quiet end def prepare_configuration if @state unless File.exist? @state raise "State file not found: #{@state}" end require_relative 'state_file' sf = Puma::StateFile.new sf.load @state @control_url = sf.control_url @control_auth_token = sf.control_auth_token @pid = sf.pid elsif @pidfile # get pid from pid_file @pid = File.read(@pidfile, mode: 'rb:UTF-8').to_i end end def send_request uri = URI.parse @control_url host = uri.host # create server object by scheme server = case uri.scheme when 'ssl' require 'openssl' host = host[1..-2] if host&.start_with? '[' OpenSSL::SSL::SSLSocket.new( TCPSocket.new(host, uri.port), OpenSSL::SSL::SSLContext.new) .tap { |ssl| ssl.sync_close = true } # default is false .tap(&:connect) when 'tcp' host = host[1..-2] if host&.start_with? '[' TCPSocket.new host, uri.port when 'unix' # check for abstract UNIXSocket UNIXSocket.new(@control_url.start_with?('unix://@') ? "\0#{host}#{uri.path}" : "#{host}#{uri.path}") else raise "Invalid scheme: #{uri.scheme}" end if @command == 'status' message 'Puma is started' else url = "/#{@command}" if @control_auth_token url = url + "?token=#{@control_auth_token}" end server.syswrite "GET #{url} HTTP/1.0\r\n\r\n" unless data = server.read raise 'Server closed connection before responding' end response = data.split("\r\n") if response.empty? raise "Server sent empty response" end @http, @code, @message = response.first.split(' ',3) if @code == '403' raise 'Unauthorized access to server (wrong auth token)' elsif @code == '404' raise "Command error: #{response.last}" elsif @code != '200' raise "Bad response from server: #{@code}" end message "Command #{@command} sent success" message response.last if PRINTABLE_COMMANDS.include?(@command) end ensure if server if uri.scheme == 'ssl' server.sysclose else server.close unless server.closed? end end end def send_signal unless @pid raise 'Neither pid nor control url available' end begin sig = CMD_PATH_SIG_MAP[@command] if sig.nil? @stdout.puts "'#{@command}' not available via pid only" @stdout.flush unless @stdout.sync return elsif sig.start_with? 'SIG' if Signal.list.key? sig.delete_prefix('SIG') Process.kill sig, @pid else raise "Signal '#{sig}' not available'" end elsif @command == 'status' begin Process.kill 0, @pid @stdout.puts 'Puma is started' @stdout.flush unless @stdout.sync rescue Errno::ESRCH raise 'Puma is not running' end return end rescue SystemCallError if @command == 'restart' start else raise "No pid '#{@pid}' found" end end message "Command #{@command} sent success" end def run return start if @command == 'start' prepare_configuration if Puma.windows? || @control_url && !NO_REQ_COMMANDS.include?(@command) send_request else send_signal end rescue => e message e.message exit 1 end private def start require_relative 'cli' run_args = [] run_args += ["-S", @state] if @state run_args += ["-q"] if @quiet run_args += ["--pidfile", @pidfile] if @pidfile run_args += ["--control-url", @control_url] if @control_url run_args += ["--control-token", @control_auth_token] if @control_auth_token run_args += ["-C", @config_file] if @config_file run_args += ["-e", @environment] if @environment log_writer = Puma::LogWriter.new(@stdout, @stderr) # replace $0 because puma use it to generate restart command puma_cmd = $0.gsub(/pumactl$/, 'puma') $0 = puma_cmd if File.exist?(puma_cmd) cli = Puma::CLI.new run_args, log_writer cli.run end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/single.rb
lib/puma/single.rb
# frozen_string_literal: true require_relative 'runner' require_relative 'detect' require_relative 'plugin' module Puma # This class is instantiated by the `Puma::Launcher` and used # to boot and serve a Ruby application when no puma "workers" are needed # i.e. only using "threaded" mode. For example `$ puma -t 1:5` # # At the core of this class is running an instance of `Puma::Server` which # gets created via the `start_server` method from the `Puma::Runner` class # that this inherits from. class Single < Runner # @!attribute [r] stats def stats { started_at: utc_iso8601(@started_at) }.merge(@server&.stats || {}).merge(super) end def restart @server&.begin_restart end def stop @server&.stop false end def halt @server&.halt end def stop_blocked log "- Gracefully stopping, waiting for requests to finish" @control&.stop true @server&.stop true end def run output_header "single" load_and_bind Plugins.fire_background @launcher.write_state start_control @server = start_server server_thread = @server.run log "Use Ctrl-C to stop" warn_ruby_mn_threads redirect_io @events.fire_after_booted! debug_loaded_extensions("Loaded Extensions:") if @log_writer.debug? begin server_thread.join rescue Interrupt # Swallow it end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/dsl.rb
lib/puma/dsl.rb
# frozen_string_literal: true require_relative 'const' require_relative 'util' module Puma # The methods that are available for use inside the configuration file. # These same methods are used in Puma cli and the rack handler # internally. # # Used manually (via CLI class): # # config = Configuration.new({}) do |user_config| # user_config.port 3001 # end # config.clamp # # puts config.options[:binds] # => "tcp://127.0.0.1:3001" # # Used to load file: # # $ cat puma_config.rb # port 3002 # # Resulting configuration: # # config = Configuration.new(config_file: "puma_config.rb") # config.clamp # # puts config.options[:binds] # => "tcp://127.0.0.1:3002" # # You can also find many examples being used by the test suite in # +test/config+. # # Puma v6 adds the option to specify a key name (String or Symbol) to the # hooks that run inside the forked workers. All the hooks run inside the # {Puma::Cluster::Worker#run} method. # # Previously, the worker index and the LogWriter instance were passed to the # hook blocks/procs. If a key name is specified, a hash is passed as the last # parameter. This allows storage of data, typically objects that are created # before the worker that need to be passed to the hook when the worker is shutdown. # # The following hooks have been updated: # # | DSL Method | Options Key | Fork Block Location | # | before_worker_boot | :before_worker_boot | inside, before | # | before_worker_shutdown | :before_worker_shutdown | inside, after | # | before_refork | :before_refork | inside | # | after_refork | :after_refork | inside | # class DSL ON_WORKER_KEY = [String, Symbol].freeze # Convenience method so logic can be used in CI. # # @see ssl_bind # def self.ssl_bind_str(host, port, opts) verify = opts.fetch(:verify_mode, 'none').to_s tls_str = if opts[:no_tlsv1_1] then '&no_tlsv1_1=true' elsif opts[:no_tlsv1] then '&no_tlsv1=true' else '' end ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify) low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : '' backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : '' if defined?(JRUBY_VERSION) cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites] protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}" keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type] if opts[:truststore] truststore_additions = "&truststore=#{opts[:truststore]}" truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass] truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type] end "ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \ "&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}" else ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil reuse_flag = if (reuse = opts[:reuse]) if reuse == true '&reuse=dflt' elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout)) val = +'' if (size = reuse[:size]) && Integer === size val << size.to_s end if (timeout = reuse[:timeout]) && Integer === timeout val << ",#{timeout}" end if val.empty? nil else "&reuse=#{val}" end else nil end else nil end "ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \ "#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}" end end def initialize(options, config) @config = config @options = options @plugins = [] end def _load_from(path) if path @path = path instance_eval(File.read(path), path, 1) end ensure _offer_plugins end def _offer_plugins @plugins.each do |o| if o.respond_to? :config @options.shift o.config self end end @plugins.clear end def set_default_host(host) @options[:default_host] = host end def default_host @options[:default_host] || Configuration::DEFAULTS[:tcp_host] end def inject(&blk) instance_eval(&blk) end def get(key,default=nil) @options[key.to_sym] || default end # Load the named plugin for use by this configuration. # # @example # plugin :tmp_restart # def plugin(name) @plugins << @config.load_plugin(name) end # Use an object or block as the rack application. This allows the # configuration file to be the application itself. # # @example # app do |env| # body = 'Hello, World!' # # [ # 200, # { # 'Content-Type' => 'text/plain', # 'Content-Length' => body.length.to_s # }, # [body] # ] # end # # @see Puma::Configuration#app # def app(obj=nil, &block) obj ||= block raise "Provide either a #call'able or a block" unless obj @options[:app] = obj end # Start the Puma control rack application on +url+. This application can # be communicated with to control the main server. Additionally, you can # provide an authentication token, so all requests to the control server # will need to include that token as a query parameter. This allows for # simple authentication. # # Check out {Puma::App::Status} to see what the app has available. # # @example # activate_control_app 'unix:///var/run/pumactl.sock' # @example # activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' } # @example # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true } # @example # activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true, data_only: true} # def activate_control_app(url="auto", opts={}) if url == "auto" path = Configuration.temp_path @options[:control_url] = "unix://#{path}" @options[:control_url_temp] = path else @options[:control_url] = url end if opts[:no_token] # We need to use 'none' rather than :none because this value will be # passed on to an instance of OptionParser, which doesn't support # symbols as option values. # # See: https://github.com/puma/puma/issues/1193#issuecomment-305995488 auth_token = 'none' else auth_token = opts[:auth_token] auth_token ||= Configuration.random_token end @options[:control_auth_token] = auth_token @options[:control_url_umask] = opts[:umask] if opts[:umask] @options[:control_data_only] = opts[:data_only] if opts[:data_only] end # Load additional configuration from a file. # Files get loaded later via Configuration#load. # # @example # load 'config/puma/production.rb' # def load(file) @options[:config_files] ||= [] @options[:config_files] << file end # Bind the server to +url+. "tcp://", "unix://" and "ssl://" are the only # accepted protocols. Multiple urls can be bound to, calling +bind+ does # not overwrite previous bindings. # # The default is "tcp://0.0.0.0:9292". # # You can use query parameters within the url to specify options: # # * Set the socket backlog depth with +backlog+, default is 1024. # * Set up an SSL certificate with +key+ & +cert+. # * Set up an SSL certificate for mTLS with +key+, +cert+, +ca+ and +verify_mode+. # * Set whether to optimize for low latency instead of throughput with # +low_latency+, default is to not optimize for low latency. This is done # via +Socket::TCP_NODELAY+. # * Set socket permissions with +umask+. # # @example Backlog depth # bind 'unix:///var/run/puma.sock?backlog=512' # @example SSL cert # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem' # @example SSL cert for mutual TLS (mTLS) # bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer' # @example Disable optimization for low latency # bind 'tcp://0.0.0.0:9292?low_latency=false' # @example Socket permissions # bind 'unix:///var/run/puma.sock?umask=0111' # # @see Puma::Runner#load_and_bind # @see Puma::Cluster#run # def bind(url) @options[:binds] ||= [] @options[:binds] << url end def clear_binds! @options[:binds] = [] end # Bind to (systemd) activated sockets, regardless of configured binds. # # Systemd can present sockets as file descriptors that are already opened. # By default Puma will use these but only if it was explicitly told to bind # to the socket. If not, it will close the activated sockets. This means # all configuration is duplicated. # # Binds can contain additional configuration, but only SSL config is really # relevant since the unix and TCP socket options are ignored. # # This means there is a lot of duplicated configuration for no additional # value in most setups. This method tells the launcher to bind to all # activated sockets, regardless of existing bind. # # To clear configured binds, the value only can be passed. This will clear # out any binds that may have been configured. # # @example Use any systemd activated sockets as well as configured binds # bind_to_activated_sockets # # @example Only bind to systemd activated sockets, ignoring other binds # bind_to_activated_sockets 'only' # def bind_to_activated_sockets(bind=true) @options[:bind_to_activated_sockets] = bind end # Define the TCP port to bind to. Use `bind` for more advanced options. # # The default is +9292+. # # @example # port 3000 # def port(port, host=nil) host ||= default_host bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s end # Define how long the tcp socket stays open, if no data has been received. # # The default is 30 seconds. # # @example # first_data_timeout 40 # # @see Puma::Server.new # def first_data_timeout(seconds) @options[:first_data_timeout] = Integer(seconds) end # Define how long persistent connections can be idle before Puma closes them. # # The default is 20 seconds. # # @example # persistent_timeout 30 # # @see Puma::Server.new # def persistent_timeout(seconds) @options[:persistent_timeout] = Integer(seconds) end # If a new request is not received within this number of seconds, begin shutting down. # # The default is +nil+. # # @example # idle_timeout 60 # # @see Puma::Server.new # def idle_timeout(seconds) @options[:idle_timeout] = Integer(seconds) end # Use a clean fiber per request which ensures a clean slate for fiber # locals and fiber storage. Also provides a cleaner backtrace with less # Puma internal stack frames. # # The default is +false+. # # @example # fiber_per_request # def fiber_per_request(which=true) @options[:fiber_per_request] = which end alias clean_thread_locals fiber_per_request # When shutting down, drain the accept socket of pending connections and # process them. This loops over the accept socket until there are no more # read events and then stops looking and waits for the requests to finish. # # @see Puma::Server#graceful_shutdown # def drain_on_shutdown(which=true) @options[:drain_on_shutdown] = which end # Set the environment in which the rack's app will run. The value must be # a string. # # The default is "development". # # @example # environment 'production' # def environment(environment) @options[:environment] = environment end # How long to wait for threads to stop when shutting them down. # Specifying :immediately will cause Puma to kill the threads immediately. # Otherwise the value is the number of seconds to wait. # # Puma always waits a few seconds after killing a thread for it to try # to finish up it's work, even in :immediately mode. # # The default is +:forever+. # # @see Puma::Server#graceful_shutdown # def force_shutdown_after(val=:forever) i = case val when :forever -1 when :immediately 0 else Float(val) end @options[:force_shutdown_after] = i end # Code to run before doing a restart. This code should # close log files, database connections, etc. # # This can be called multiple times to add code each time. # # @example # before_restart do # puts 'On restart...' # end # def before_restart(&block) Puma.deprecate_method_change :on_restart, __callee__, __method__ process_hook :before_restart, nil, block end alias_method :on_restart, :before_restart # Command to use to restart Puma. This should be just how to # load Puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments # to Puma, as those are the same as the original process. # # @example # restart_command '/u/app/lolcat/bin/restart_puma' # def restart_command(cmd) @options[:restart_cmd] = cmd.to_s end # Store the pid of the server in the file at "path". # # @example # pidfile '/u/apps/lolcat/tmp/pids/puma.pid' # def pidfile(path) @options[:pidfile] = path.to_s end # Disable request logging, the inverse of `log_requests`. # # The default is +true+. # # @example # quiet # def quiet(which=true) @options[:log_requests] = !which end # Enable request logging, the inverse of `quiet`. # # The default is +false+. # # @example # log_requests # def log_requests(which=true) @options[:log_requests] = which end # Pass in a custom logging class instance # # @example # custom_logger Logger.new('t.log') # def custom_logger(custom_logger) @options[:custom_logger] = custom_logger end # Show debugging info # # The default is +false+. # # @example # debug # def debug @options[:debug] = true end # Load +path+ as a rackup file. # # The default is "config.ru". # # @example # rackup '/u/apps/lolcat/config.ru' # def rackup(path) @options[:rackup] ||= path.to_s end # Allows setting `env['rack.url_scheme']`. # Only necessary if X-Forwarded-Proto is not being set by your proxy # Normal values are 'http' or 'https'. # def rack_url_scheme(scheme=nil) @options[:rack_url_scheme] = scheme end # Enable HTTP 103 Early Hints responses. # # The default is +nil+. # # @example # early_hints # def early_hints(answer=true) @options[:early_hints] = answer end # Redirect +STDOUT+ and +STDERR+ to files specified. The +append+ parameter # specifies whether the output is appended. # # The default is +false+. # # @example # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr' # @example # stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true # def stdout_redirect(stdout=nil, stderr=nil, append=false) @options[:redirect_stdout] = stdout @options[:redirect_stderr] = stderr @options[:redirect_append] = append end def log_formatter(&block) @options[:log_formatter] = block end # Configure the number of threads to use to answer requests. # # It can be a single fixed number, or a +min+ and a +max+. # # The default is the environment variables +PUMA_MIN_THREADS+ / +PUMA_MAX_THREADS+ # (or +MIN_THREADS+ / +MAX_THREADS+ if the +PUMA_+ variables aren't set). # # If these environment variables aren't set, the default is "0, 5" in MRI or "0, 16" for other interpreters. # # @example # threads 5 # @example # threads 0, 16 # @example # threads 5, 5 # def threads(min, max = min) min = Integer(min) max = Integer(max) if min > max raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})" end if max < 1 raise "The maximum number of threads (#{max}) must be greater than 0" end @options[:min_threads] = min @options[:max_threads] = max end # Instead of using +bind+ and manually constructing a URI like: # # bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path' # # you can use the this method. # # When binding on localhost you don't need to specify +cert+ and +key+, # Puma will assume you are using the +localhost+ gem and try to load the # appropriate files. # # When using the options hash parameter, the `reuse:` value is either # `true`, which sets reuse 'on' with default values, or a hash, with `:size` # and/or `:timeout` keys, each with integer values. # # The `cert:` options hash parameter can be the path to a certificate # file including all intermediate certificates in PEM format. # # The `cert_pem:` options hash parameter can be String containing the # cerificate and all intermediate certificates in PEM format. # # @example # ssl_bind '127.0.0.1', '9292', { # cert: path_to_cert, # key: path_to_key, # ssl_cipher_filter: cipher_filter, # optional # ssl_ciphersuites: ciphersuites, # optional # verify_mode: verify_mode, # default 'none' # verification_flags: flags, # optional, not supported by JRuby # reuse: true # optional # } # # @example Using self-signed certificate with the +localhost+ gem: # ssl_bind '127.0.0.1', '9292' # # @example Alternatively, you can provide +cert_pem+ and +key_pem+: # ssl_bind '127.0.0.1', '9292', { # cert_pem: File.read(path_to_cert), # key_pem: File.read(path_to_key), # reuse: {size: 2_000, timeout: 20} # optional # } # # @example For JRuby, two keys are required: +keystore+ & +keystore_pass+ # ssl_bind '127.0.0.1', '9292', { # keystore: path_to_keystore, # keystore_pass: password, # ssl_cipher_list: cipher_list, # optional # verify_mode: verify_mode # default 'none' # } # def ssl_bind(host, port, opts = {}) add_pem_values_to_options_store(opts) bind self.class.ssl_bind_str(host, port, opts) end # Use +path+ as the file to store the server info state. This is # used by +pumactl+ to query and control the server. # # @example # state_path '/u/apps/lolcat/tmp/pids/puma.state' # def state_path(path) @options[:state] = path.to_s end # Use +permission+ to restrict permissions for the state file. By convention, # +permission+ is an octal number (e.g. `0640` or `0o640`). # # @example # state_permission 0600 # def state_permission(permission) @options[:state_permission] = permission end # How many worker processes to run. Typically this is set to # the number of available cores. # # The default is the value of the environment variable +WEB_CONCURRENCY+ if # set, otherwise 0. # # @note Cluster mode only. # # @example # workers 2 # # @see Puma::Cluster # def workers(count) @options[:workers] = count.to_i end # Disable warning message when running in cluster mode with a single worker. # # Cluster mode has some overhead of running an additional 'control' process # in order to manage the cluster. If only running a single worker it is # likely not worth paying that overhead vs running in single mode with # additional threads instead. # # There are some scenarios where running cluster mode with a single worker # may still be warranted and valid under certain deployment scenarios, see # https://github.com/puma/puma/issues/2534 # # Moving from workers = 1 to workers = 0 will save 10-30% of memory use. # # The default is +false+. # # @note Cluster mode only. # # @example # silence_single_worker_warning # def silence_single_worker_warning @options[:silence_single_worker_warning] = true end # Disable warning message when running single mode with callback hook defined. # # The default is +false+. # # @example # silence_fork_callback_warning # def silence_fork_callback_warning @options[:silence_fork_callback_warning] = true end # Code to run immediately before master process # forks workers (once on boot). These hooks can block if necessary # to wait for background operations unknown to Puma to finish before # the process terminates. # This can be used to close any connections to remote servers (database, # Redis, ...) that were opened when preloading the code. # # This can be called multiple times to add several hooks. # # @note Cluster mode only. # # @example # before_fork do # puts "Starting workers..." # end # def before_fork(&block) process_hook :before_fork, nil, block, cluster_only: true end # Code to run in a worker when it boots to setup # the process before booting the app. # # This can be called multiple times to add several hooks. # # @note Cluster mode only. # # @example # before_worker_boot do # puts 'Before worker boot...' # end # def before_worker_boot(key = nil, &block) Puma.deprecate_method_change :on_worker_boot, __callee__, __method__ process_hook :before_worker_boot, key, block, cluster_only: true end alias_method :on_worker_boot, :before_worker_boot # Code to run immediately before a worker shuts # down (after it has finished processing HTTP requests). The worker's # index is passed as an argument. These hooks # can block if necessary to wait for background operations unknown # to Puma to finish before the process terminates. # # This can be called multiple times to add several hooks. # # @note Cluster mode only. # # @example # before_worker_shutdown do # puts 'On worker shutdown...' # end # def before_worker_shutdown(key = nil, &block) Puma.deprecate_method_change :on_worker_shutdown, __callee__, __method__ process_hook :before_worker_shutdown, key, block, cluster_only: true end alias_method :on_worker_shutdown, :before_worker_shutdown # Code to run in the master right before a worker is started. The worker's # index is passed as an argument. # # This can be called multiple times to add several hooks. # # @note Cluster mode only. # # @example # before_worker_fork do # puts 'Before worker fork...' # end # def before_worker_fork(&block) Puma.deprecate_method_change :on_worker_fork, __callee__, __method__ process_hook :before_worker_fork, nil, block, cluster_only: true end alias_method :on_worker_fork, :before_worker_fork # Code to run in the master after a worker has been started. The worker's # index is passed as an argument. # # This is called everytime a worker is to be started. # # @note Cluster mode only. # # @example # after_worker_fork do # puts 'After worker fork...' # end # def after_worker_fork(&block) process_hook :after_worker_fork, nil, block, cluster_only: true end alias_method :after_worker_boot, :after_worker_fork # Code to run in the master right after a worker has stopped. The worker's # index and Process::Status are passed as arguments. # # @note Cluster mode only. # # @example # after_worker_shutdown do |worker_handle| # puts 'Worker crashed' unless worker_handle.process_status.success? # end # def after_worker_shutdown(&block) process_hook :after_worker_shutdown, nil, block, cluster_only: true end # Code to run after puma is booted (works for both single and cluster modes). # # @example # after_booted do # puts 'After booting...' # end # def after_booted(&block) Puma.deprecate_method_change :on_booted, __callee__, __method__ @config.events.after_booted(&block) end alias_method :on_booted, :after_booted # Code to run after puma is stopped (works for both: single and clustered) # # @example # after_stopped do # puts 'After stopping...' # end # def after_stopped(&block) Puma.deprecate_method_change :on_stopped, __callee__, __method__ @config.events.after_stopped(&block) end alias_method :on_stopped, :after_stopped # When `fork_worker` is enabled, code to run in Worker 0 # before all other workers are re-forked from this process, # after the server has temporarily stopped serving requests # (once per complete refork cycle). # # This can be used to trigger extra garbage-collection to maximize # copy-on-write efficiency, or close any connections to remote servers # (database, Redis, ...) that were opened while the server was running. # # This can be called multiple times to add several hooks. # # @note Cluster mode with `fork_worker` enabled only. # # @example # before_refork do # 3.times {GC.start} # end # # @version 5.0.0 # def before_refork(key = nil, &block) Puma.deprecate_method_change :on_refork, __callee__, __method__ process_hook :before_refork, key, block, cluster_only: true end alias_method :on_refork, :before_refork # When `fork_worker` is enabled, code to run in Worker 0 # after all other workers are re-forked from this process, # after the server has temporarily stopped serving requests # (once per complete refork cycle). # # This can be used to re-open any connections to remote servers # (database, Redis, ...) that were closed via before_refork. # # This can be called multiple times to add several hooks. # # @note Cluster mode with `fork_worker` enabled only. # # @example # after_refork do # puts 'After refork...' # end # def after_refork(key = nil, &block) process_hook :after_refork, key, block end # Provide a block to be executed just before a thread is added to the thread # pool. Be careful: while the block executes, thread creation is delayed, and # probably a request will have to wait too! The new thread will not be added to # the threadpool until the provided block returns. # # Return values are ignored. # Raising an exception will log a warning. # # This hook is useful for doing something when the thread pool grows. # # This can be called multiple times to add several hooks. # # @example # before_thread_start do # puts 'On thread start...' # end # def before_thread_start(&block) Puma.deprecate_method_change :on_thread_start, __callee__, __method__ process_hook :before_thread_start, nil, block end alias_method :on_thread_start, :before_thread_start # Provide a block to be executed after a thread is trimmed from the thread # pool. Be careful: while this block executes, Puma's main loop is # blocked, so no new requests will be picked up. # # This hook only runs when a thread in the threadpool is trimmed by Puma. # It does not run when a thread dies due to exceptions or any other cause. # # Return values are ignored. # Raising an exception will log a warning. # # This hook is useful for cleaning up thread local resources when a thread # is trimmed. # # This can be called multiple times to add several hooks. # # @example # before_thread_exit do # puts 'On thread exit...' # end # def before_thread_exit(&block) Puma.deprecate_method_change :on_thread_exit, __callee__, __method__ process_hook :before_thread_exit, nil, block end alias_method :on_thread_exit, :before_thread_exit # Code to run out-of-band when the worker is idle. # These hooks run immediately after a request has finished # processing and there are no busy threads on the worker. # The worker doesn't accept new requests until this code finishes. # # This hook is useful for running out-of-band garbage collection # or scheduling asynchronous tasks to execute after a response. # # This can be called multiple times to add several hooks. # def out_of_band(&block) process_hook :out_of_band, nil, block end # The directory to operate out of. # # The default is the current directory. # # @example # directory '/u/apps/lolcat' # def directory(dir) @options[:directory] = dir.to_s end # Preload the application before forking the workers; this conflicts with # the phased restart feature. # # The default is +true+ if your app uses more than 1 worker. # # @note Cluster mode only. # @note When using `fork_worker`, this only applies to worker 0. # # @example # preload_app! # def preload_app!(answer=true) @options[:preload_app] = answer end # Use +obj+ or +block+ as the low level error handler. This allows the # configuration file to change the default error on the server. # # @example # lowlevel_error_handler do |err| # [200, {}, ["error page"]] # end # def lowlevel_error_handler(obj=nil, &block) obj ||= block raise "Provide either a #call'able or a block" unless obj @options[:lowlevel_error_handler] = obj end # This option is used to allow your app and its gems to be # properly reloaded when not using preload. # # When set, if Puma detects that it's been invoked in the # context of Bundler, it will cleanup the environment and # re-run itself outside the Bundler environment, but directly # using the files that Bundler has setup. # # This means that Puma is now decoupled from your Bundler # context and when each worker loads, it will be loading a # new Bundler context and thus can float around as the release # dictates. #
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
true
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/state_file.rb
lib/puma/state_file.rb
# frozen_string_literal: true module Puma # Puma::Launcher uses StateFile to write a yaml file for use with Puma::ControlCLI. # # In previous versions of Puma, YAML was used to read/write the state file. # Since Puma is similar to Bundler/RubyGems in that it may load before one's app # does, minimizing the dependencies that may be shared with the app is desired. # # At present, it only works with numeric and string values. It is still a valid # yaml file, and the CI tests parse it with Psych. # class StateFile ALLOWED_FIELDS = %w!control_url control_auth_token pid running_from! def initialize @options = {} end def save(path, permission = nil) contents = +"---\n" @options.each do |k,v| next unless ALLOWED_FIELDS.include? k case v when Numeric contents << "#{k}: #{v}\n" when String next if v.strip.empty? contents << (k == 'running_from' || v.to_s.include?(' ') ? "#{k}: \"#{v}\"\n" : "#{k}: #{v}\n") end end if permission File.write path, contents, mode: 'wb:UTF-8', perm: permission else File.write path, contents, mode: 'wb:UTF-8' end end def load(path) File.read(path).lines.each do |line| next if line.start_with? '#' k,v = line.split ':', 2 next unless v && ALLOWED_FIELDS.include?(k) v = v.strip @options[k] = case v when '' then nil when /\A\d+\z/ then v.to_i when /\A\d+\.\d+\z/ then v.to_f else v.gsub(/\A"|"\z/, '') end end end ALLOWED_FIELDS.each do |f| define_method f.to_sym do @options[f] end define_method :"#{f}=" do |v| @options[f] = v end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/io_buffer.rb
lib/puma/io_buffer.rb
# frozen_string_literal: true require 'stringio' module Puma class IOBuffer < StringIO def initialize super.binmode end def empty? length.zero? end def reset truncate 0 rewind end def to_s rewind read end # Read & Reset - returns contents and resets # @return [String] StringIO contents def read_and_reset rewind str = read truncate 0 rewind str end alias_method :clear, :reset # Create an `IoBuffer#append` method that accepts multiple strings and writes them if RUBY_ENGINE == 'truffleruby' # truffleruby (24.2.1, like ruby 3.3.7) # StringIO.new.write("a", "b") # => `write': wrong number of arguments (given 2, expected 1) (ArgumentError) def append(*strs) strs.each { |str| write str } end else # Ruby 3+ # StringIO.new.write("a", "b") # => 2 alias_method :append, :write end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/configuration.rb
lib/puma/configuration.rb
# frozen_string_literal: true require_relative 'plugin' require_relative 'const' require_relative 'dsl' require_relative 'events' module Puma # A class used for storing "leveled" configuration options. # # In this class any "user" specified options take precedence over any # "file" specified options, take precedence over any "default" options. # # User input is preferred over "defaults": # user_options = { foo: "bar" } # default_options = { foo: "zoo" } # options = UserFileDefaultOptions.new(user_options, default_options) # puts options[:foo] # # => "bar" # # All values can be accessed via `all_of` # # puts options.all_of(:foo) # # => ["bar", "zoo"] # # A "file" option can be set. This config will be preferred over "default" options # but will defer to any available "user" specified options. # # user_options = { foo: "bar" } # default_options = { rackup: "zoo.rb" } # options = UserFileDefaultOptions.new(user_options, default_options) # options.file_options[:rackup] = "sup.rb" # puts options[:rackup] # # => "sup.rb" # # The "default" options can be set via procs. These are resolved during runtime # via calls to `finalize_values` class UserFileDefaultOptions def initialize(user_options, default_options) @user_options = user_options @file_options = {} @default_options = default_options end attr_reader :user_options, :file_options, :default_options def [](key) fetch(key) end def []=(key, value) user_options[key] = value end def fetch(key, default_value = nil) return user_options[key] if user_options.key?(key) return file_options[key] if file_options.key?(key) return default_options[key] if default_options.key?(key) default_value end def all_of(key) user = user_options[key] file = file_options[key] default = default_options[key] user = [user] unless user.is_a?(Array) file = [file] unless file.is_a?(Array) default = [default] unless default.is_a?(Array) user.compact! file.compact! default.compact! user + file + default end def finalize_values @default_options.each do |k,v| if v.respond_to? :call @default_options[k] = v.call end end end def final_options default_options .merge(file_options) .merge(user_options) end end # The main configuration class of Puma. # # It can be initialized with a set of "user" options and "default" options. # Defaults will be merged with `Configuration.puma_default_options`. # # This class works together with 2 main other classes the `UserFileDefaultOptions` # which stores configuration options in order so the precedence is that user # set configuration wins over "file" based configuration wins over "default" # configuration. These configurations are set via the `DSL` class. This # class powers the Puma config file syntax and does double duty as a configuration # DSL used by the `Puma::CLI` and Puma rack handler. # # It also handles loading plugins. # # [Note:] # `:port` and `:host` are not valid keys. By the time they make it to the # configuration options they are expected to be incorporated into a `:binds` key. # Under the hood the DSL maps `port` and `host` calls to `:binds` # # config = Configuration.new({}) do |user_config, file_config, default_config| # user_config.port 3003 # end # config.clamp # puts config.options[:port] # # => 3003 # # It is expected that `load` is called on the configuration instance after setting # config. This method expands any values in `config_file` and puts them into the # correct configuration option hash. # # Once all configuration is complete it is expected that `clamp` will be called # on the instance. This will expand any procs stored under "default" values. This # is done because an environment variable may have been modified while loading # configuration files. class Configuration class NotLoadedError < StandardError; end class NotClampedError < StandardError; end DEFAULTS = { auto_trim_time: 30, binds: ['tcp://0.0.0.0:9292'.freeze], fiber_per_request: !!ENV.fetch("PUMA_FIBER_PER_REQUEST", false), debug: false, enable_keep_alives: true, early_hints: nil, environment: 'development'.freeze, # Number of seconds to wait until we get the first data for the request. first_data_timeout: 30, # Number of seconds to wait until the next request before shutting down. idle_timeout: nil, io_selector_backend: :auto, log_requests: false, logger: STDOUT, # Limits how many requests a keep alive connection can make. # The connection will be closed after it reaches `max_keep_alive` # requests. max_keep_alive: 999, max_threads: Puma.mri? ? 5 : 16, min_threads: 0, mode: :http, mutate_stdout_and_stderr_to_sync_on_write: true, out_of_band: [], # Number of seconds for another request within a persistent session. persistent_timeout: 65, # PUMA_PERSISTENT_TIMEOUT prune_bundler: false, queue_requests: true, rackup: 'config.ru'.freeze, raise_exception_on_sigterm: true, reaping_time: 1, remote_address: :socket, silence_single_worker_warning: false, silence_fork_callback_warning: false, tag: File.basename(Dir.getwd), tcp_host: '0.0.0.0'.freeze, tcp_port: 9292, wait_for_less_busy_worker: 0.005, worker_boot_timeout: 60, worker_check_interval: 5, worker_culling_strategy: :youngest, worker_shutdown_timeout: 30, worker_timeout: 60, workers: 0, http_content_length_limit: nil } def initialize(user_options={}, default_options = {}, env = ENV, &block) default_options = self.puma_default_options(env).merge(default_options) @_options = UserFileDefaultOptions.new(user_options, default_options) @plugins = PluginLoader.new @events = @_options[:events] || Events.new @hooks = {} @user_dsl = DSL.new(@_options.user_options, self) @file_dsl = DSL.new(@_options.file_options, self) @default_dsl = DSL.new(@_options.default_options, self) @puma_bundler_pruned = env.key? 'PUMA_BUNDLER_PRUNED' if block configure(&block) end @loaded = false @clamped = false end attr_reader :plugins, :events, :hooks, :_options def options raise NotClampedError, "ensure clamp is called before accessing options" unless @clamped @_options end def configure yield @user_dsl, @file_dsl, @default_dsl ensure @user_dsl._offer_plugins @file_dsl._offer_plugins @default_dsl._offer_plugins end def initialize_copy(other) @conf = nil @cli_options = nil @_options = @_options.dup end def flatten dup.flatten! end def flatten! @_options = @_options.flatten self end def puma_default_options(env = ENV) defaults = DEFAULTS.dup puma_options_from_env(env).each { |k,v| defaults[k] = v if v } defaults end def puma_options_from_env(env = ENV) min = env['PUMA_MIN_THREADS'] || env['MIN_THREADS'] max = env['PUMA_MAX_THREADS'] || env['MAX_THREADS'] persistent_timeout = env['PUMA_PERSISTENT_TIMEOUT'] workers = if env['WEB_CONCURRENCY'] == 'auto' require_processor_counter ::Concurrent.available_processor_count else env['WEB_CONCURRENCY'] end { min_threads: min && min != "" && Integer(min), max_threads: max && max != "" && Integer(max), persistent_timeout: persistent_timeout && persistent_timeout != "" && Integer(persistent_timeout), workers: workers && workers != "" && Integer(workers), environment: env['APP_ENV'] || env['RACK_ENV'] || env['RAILS_ENV'], } end def load @loaded = true config_files.each { |config_file| @file_dsl._load_from(config_file) } @_options end def config_files raise NotLoadedError, "ensure load is called before accessing config_files" unless @loaded files = @_options.all_of(:config_files) return [] if files == ['-'] return files if files.any? first_default_file = %W(config/puma/#{@_options[:environment]}.rb config/puma.rb).find do |f| File.exist?(f) end [first_default_file] end # Call once all configuration (included from rackup files) # is loaded to finalize defaults and lock in the configuration. # # This also calls load if it hasn't been called yet. def clamp load unless @loaded set_conditional_default_options @_options.finalize_values @clamped = true warn_hooks options end # Injects the Configuration object into the env class ConfigMiddleware def initialize(config, app) @config = config @app = app end def call(env) env[Const::PUMA_CONFIG] = @config @app.call(env) end end # Indicate if there is a properly configured app # def app_configured? options[:app] || File.exist?(rackup) end def rackup options[:rackup] end # Load the specified rackup file, pull options from # the rackup file, and set @app. # def app found = options[:app] || load_rackup if options[:log_requests] require_relative 'commonlogger' logger = options[:custom_logger] ? options[:custom_logger] : options[:logger] found = CommonLogger.new(found, logger) end ConfigMiddleware.new(self, found) end # Return which environment we're running in def environment options[:environment] end def load_plugin(name) @plugins.create name end # @param key [:Symbol] hook to run # @param arg [Launcher, Int] `:before_restart` passes Launcher # def run_hooks(key, arg, log_writer, hook_data = nil) log_writer.debug "Running #{key} hooks" options.all_of(key).each do |hook_options| begin block = hook_options[:block] if id = hook_options[:id] hook_data[id] ||= Hash.new block.call arg, hook_data[id] else block.call arg end rescue => e log_writer.log "WARNING hook #{key} failed with exception (#{e.class}) #{e.message}" log_writer.debug e.backtrace.join("\n") end end end def final_options options.final_options end def self.temp_path require 'tmpdir' t = (Time.now.to_f * 1000).to_i "#{Dir.tmpdir}/puma-status-#{t}-#{$$}" end def self.random_token require 'securerandom' unless defined?(SecureRandom) SecureRandom.hex(16) end private def require_processor_counter require 'concurrent/utility/processor_counter' rescue LoadError warn <<~MESSAGE WEB_CONCURRENCY=auto requires the "concurrent-ruby" gem to be installed. Please add "concurrent-ruby" to your Gemfile. MESSAGE raise end # Load and use the normal Rack builder if we can, otherwise # fallback to our minimal version. def rack_builder # Load bundler now if we can so that we can pickup rack from # a Gemfile if @puma_bundler_pruned begin require 'bundler/setup' rescue LoadError end end begin require 'rack' require 'rack/builder' ::Rack::Builder rescue LoadError require_relative 'rack/builder' Puma::Rack::Builder end end def load_rackup raise "Missing rackup file '#{rackup}'" unless File.exist?(rackup) rack_app, rack_options = rack_builder.parse_file(rackup) rack_options = rack_options || {} options.file_options.merge!(rack_options) config_ru_binds = [] rack_options.each do |k, v| config_ru_binds << v if k.to_s.start_with?("bind") end options.file_options[:binds] = config_ru_binds unless config_ru_binds.empty? rack_app end def set_conditional_default_options @_options.default_options[:preload_app] = !@_options[:prune_bundler] && (@_options[:workers] > 1) && Puma.forkable? end def warn_hooks return if options[:workers] > 0 return if options[:silence_fork_callback_warning] log_writer = LogWriter.stdio @hooks.each_key do |hook| options.all_of(hook).each do |hook_options| next unless hook_options[:cluster_only] log_writer.log(<<~MSG.tr("\n", " ")) Warning: The code in the `#{hook}` block will not execute in the current Puma configuration. The `#{hook}` block only executes in Puma's cluster mode. To fix this, either remove the `#{hook}` call or increase Puma's worker count above zero. MSG end end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/runner.rb
lib/puma/runner.rb
# frozen_string_literal: true require_relative 'server' require_relative 'const' module Puma # Generic class that is used by `Puma::Cluster` and `Puma::Single` to # serve requests. This class spawns a new instance of `Puma::Server` via # a call to `start_server`. class Runner include ::Puma::Const::PipeRequest def initialize(launcher) @launcher = launcher @log_writer = launcher.log_writer @events = launcher.events @config = launcher.config @options = launcher.options @app = nil @control = nil @started_at = Time.now @wakeup = nil end # Returns the hash of configuration options. # @return [Puma::UserFileDefaultOptions] attr_reader :options def wakeup! return unless @wakeup @wakeup.write PIPE_WAKEUP unless @wakeup.closed? rescue SystemCallError, IOError end def development? @options[:environment] == "development" end def test? @options[:environment] == "test" end def log(str) @log_writer.log str end # @version 5.0.0 def stop_control @control&.stop true end def error(str) @log_writer.error str end def debug(str) @log_writer.log "- #{str}" if @options[:debug] end def start_control str = @options[:control_url] return unless str require_relative 'app/status' if token = @options[:control_auth_token] token = nil if token.empty? || token == 'none' end app = Puma::App::Status.new @launcher, token: token, data_only: @options[:control_data_only] # A Reactor is not created and nio4r is not loaded when 'queue_requests: false' # Use `nil` for events, no hooks in control server control = Puma::Server.new app, nil, { min_threads: 0, max_threads: 1, queue_requests: false, log_writer: @log_writer } begin control.binder.parse [str], nil, 'Starting control server' rescue Errno::EADDRINUSE, Errno::EACCES => e raise e, "Error: Control server address '#{str}' is already in use. Original error: #{e.message}" end control.run thread_name: 'ctl' @control = control end # @version 5.0.0 def close_control_listeners @control.binder.close_listeners if @control end def output_header(mode) min_t = @options[:min_threads] max_t = @options[:max_threads] environment = @options[:environment] log "Puma starting in #{mode} mode..." log "* Puma version: #{Puma::Const::PUMA_VERSION} (\"#{Puma::Const::CODE_NAME}\")" log "* Ruby version: #{RUBY_DESCRIPTION}" log "* Min threads: #{min_t}" log "* Max threads: #{max_t}" log "* Environment: #{environment}" if mode == "cluster" log "* Master PID: #{Process.pid}" else log "* PID: #{Process.pid}" end end def warn_ruby_mn_threads return if !ENV.key?('RUBY_MN_THREADS') log "! WARNING: Detected `RUBY_MN_THREADS=#{ENV['RUBY_MN_THREADS']}`" log "! This setting is known to cause performance regressions with Puma." log "! Consider disabling this environment variable: https://github.com/puma/puma/issues/3720" end def redirected_io? @options[:redirect_stdout] || @options[:redirect_stderr] end def redirect_io stdout = @options[:redirect_stdout] stderr = @options[:redirect_stderr] append = @options[:redirect_append] if stdout ensure_output_directory_exists(stdout, 'STDOUT') STDOUT.reopen stdout, (append ? "a" : "w") STDOUT.puts "=== puma startup: #{Time.now} ===" STDOUT.flush unless STDOUT.sync end if stderr ensure_output_directory_exists(stderr, 'STDERR') STDERR.reopen stderr, (append ? "a" : "w") STDERR.puts "=== puma startup: #{Time.now} ===" STDERR.flush unless STDERR.sync end if @options[:mutate_stdout_and_stderr_to_sync_on_write] STDOUT.sync = true STDERR.sync = true end end def load_and_bind unless @config.app_configured? error "No application configured, nothing to run" exit 1 end begin @app = @config.app rescue Exception => e log "! Unable to load application: #{e.class}: #{e.message}" raise e end @launcher.binder.parse @options[:binds] end # @!attribute [r] app def app @app ||= @config.app end def start_server server = Puma::Server.new(app, @events, @options) server.inherit_binder(@launcher.binder) server end private def ensure_output_directory_exists(path, io_name) unless Dir.exist?(File.dirname(path)) raise "Cannot redirect #{io_name} to #{path}" end end def utc_iso8601(val) "#{val.utc.strftime '%FT%T'}Z" end def stats { versions: { puma: Puma::Const::PUMA_VERSION, ruby: { engine: RUBY_ENGINE, version: RUBY_VERSION, patchlevel: RUBY_PATCHLEVEL } } } end # this method call should always be guarded by `@log_writer.debug?` def debug_loaded_extensions(str) @log_writer.debug "────────────────────────────────── #{str}" re_ext = /\.#{RbConfig::CONFIG['DLEXT']}\z/i $LOADED_FEATURES.grep(re_ext).each { |f| @log_writer.debug(" #{f}") } end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/jruby_restart.rb
lib/puma/jruby_restart.rb
# frozen_string_literal: true require 'ffi' module Puma module JRubyRestart extend FFI::Library ffi_lib 'c' attach_function :chdir, [:string], :int end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/detect.rb
lib/puma/detect.rb
# frozen_string_literal: true # This file can be loaded independently of puma.rb, so it cannot have any code # that assumes puma.rb is loaded. module Puma # @version 5.2.1 HAS_FORK = ::Process.respond_to? :fork HAS_NATIVE_IO_WAIT = ::IO.public_instance_methods(false).include? :wait_readable IS_JRUBY = Object.const_defined? :JRUBY_VERSION IS_OSX = RUBY_DESCRIPTION.include? 'darwin' IS_WINDOWS = RUBY_DESCRIPTION.match?(/mswin|ming|cygwin/) IS_LINUX = !(IS_OSX || IS_WINDOWS) IS_ARM = RUBY_PLATFORM.include? 'aarch64' # @version 5.2.0 IS_MRI = RUBY_ENGINE == 'ruby' def self.jruby? IS_JRUBY end def self.osx? IS_OSX end def self.windows? IS_WINDOWS end # @version 5.0.0 def self.mri? IS_MRI end # @version 5.0.0 def self.forkable? HAS_FORK end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/thread_pool.rb
lib/puma/thread_pool.rb
# frozen_string_literal: true require 'thread' require_relative 'io_buffer' module Puma # Add `Thread#puma_server` and `Thread#puma_server=` Thread.attr_accessor(:puma_server) # Internal Docs for A simple thread pool management object. # # Each Puma "worker" has a thread pool to process requests. # # First a connection to a client is made in `Puma::Server`. It is wrapped in a # `Puma::Client` instance and then passed to the `Puma::Reactor` to ensure # the whole request is buffered into memory. Once the request is ready, it is passed into # a thread pool via the `Puma::ThreadPool#<<` operator where it is stored in a `@todo` array. # # Each thread in the pool has an internal loop where it pulls a request from the `@todo` array # and processes it. class ThreadPool class ForceShutdown < RuntimeError end # How long, after raising the ForceShutdown of a thread during # forced shutdown mode, to wait for the thread to try and finish # up its work before leaving the thread to die on the vine. SHUTDOWN_GRACE_TIME = 5 # seconds attr_reader :out_of_band_running # Maintain a minimum of +min+ and maximum of +max+ threads # in the pool. # # The block passed is the work that will be performed in each # thread. # def initialize(name, options = {}, server: nil, &block) @server = server @not_empty = ConditionVariable.new @not_full = ConditionVariable.new @mutex = Mutex.new @todo = Queue.new @backlog_max = 0 @spawned = 0 @waiting = 0 @name = name @min = Integer(options[:min_threads]) @max = Integer(options[:max_threads]) # Not an 'exposed' option, options[:pool_shutdown_grace_time] is used in CI # to shorten @shutdown_grace_time from SHUTDOWN_GRACE_TIME. Parallel CI # makes stubbing constants difficult. @shutdown_grace_time = Float(options[:pool_shutdown_grace_time] || SHUTDOWN_GRACE_TIME) @block = block @out_of_band = options[:out_of_band] @out_of_band_running = false @out_of_band_condvar = ConditionVariable.new @before_thread_start = options[:before_thread_start] @before_thread_exit = options[:before_thread_exit] @reaping_time = options[:reaping_time] @auto_trim_time = options[:auto_trim_time] @shutdown = false @trim_requested = 0 @out_of_band_pending = false @workers = [] @auto_trim = nil @reaper = nil @mutex.synchronize do @min.times do spawn_thread @not_full.wait(@mutex) end end @force_shutdown = false @shutdown_mutex = Mutex.new end attr_reader :spawned, :trim_requested, :waiting # generate stats hash so as not to perform multiple locks # @return [Hash] hash containing stat info from ThreadPool def stats with_mutex do temp = @backlog_max @backlog_max = 0 { backlog: @todo.size, running: @spawned, pool_capacity: @waiting + (@max - @spawned), busy_threads: @spawned - @waiting + @todo.size, backlog_max: temp } end end def reset_max with_mutex { @backlog_max = 0 } end # How many objects have yet to be processed by the pool? # def backlog with_mutex { @todo.size } end # The maximum size of the backlog # def backlog_max with_mutex { @backlog_max } end # @!attribute [r] pool_capacity def pool_capacity waiting + (@max - spawned) end # @!attribute [r] busy_threads # @version 5.0.0 def busy_threads with_mutex { @spawned - @waiting + @todo.size } end # :nodoc: # # Must be called with @mutex held! # def spawn_thread @spawned += 1 trigger_before_thread_start_hooks th = Thread.new(@spawned) do |spawned| Puma.set_thread_name '%s tp %03i' % [@name, spawned] # Advertise server into the thread Thread.current.puma_server = @server todo = @todo block = @block mutex = @mutex not_empty = @not_empty not_full = @not_full while true work = nil mutex.synchronize do while todo.empty? if @trim_requested > 0 @trim_requested -= 1 @spawned -= 1 @workers.delete th not_full.signal trigger_before_thread_exit_hooks Thread.exit end @waiting += 1 if @out_of_band_pending && trigger_out_of_band_hook @out_of_band_pending = false end not_full.signal begin not_empty.wait mutex ensure @waiting -= 1 end end work = todo.shift end begin @out_of_band_pending = true if block.call(work) rescue Exception => e STDERR.puts "Error reached top of thread-pool: #{e.message} (#{e.class})" end end end @workers << th th end private :spawn_thread def trigger_before_thread_start_hooks return unless @before_thread_start&.any? @before_thread_start.each do |b| begin b[:block].call rescue Exception => e STDERR.puts "WARNING before_thread_start hook failed with exception (#{e.class}) #{e.message}" end end nil end private :trigger_before_thread_start_hooks def trigger_before_thread_exit_hooks return unless @before_thread_exit&.any? @before_thread_exit.each do |b| begin b[:block].call rescue Exception => e STDERR.puts "WARNING before_thread_exit hook failed with exception (#{e.class}) #{e.message}" end end nil end private :trigger_before_thread_exit_hooks # @version 5.0.0 def trigger_out_of_band_hook return false unless @out_of_band&.any? # we execute on idle hook when all threads are free return false unless @spawned == @waiting @out_of_band_running = true @out_of_band.each { |b| b[:block].call } true rescue Exception => e STDERR.puts "Exception calling out_of_band_hook: #{e.message} (#{e.class})" true ensure @out_of_band_running = false @out_of_band_condvar.broadcast end private :trigger_out_of_band_hook def wait_while_out_of_band_running return unless @out_of_band_running with_mutex do @out_of_band_condvar.wait(@mutex) while @out_of_band_running end end # @version 5.0.0 def with_mutex(&block) @mutex.owned? ? yield : @mutex.synchronize(&block) end # Add +work+ to the todo list for a Thread to pickup and process. def <<(work) with_mutex do if @shutdown raise "Unable to add work while shutting down" end @todo << work t = @todo.size @backlog_max = t if t > @backlog_max if @waiting < @todo.size and @spawned < @max spawn_thread end @not_empty.signal end end # If there are any free threads in the pool, tell one to go ahead # and exit. If +force+ is true, then a trim request is requested # even if all threads are being utilized. # def trim(force=false) with_mutex do free = @waiting - @todo.size if (force or free > 0) and @spawned - @trim_requested > @min @trim_requested += 1 @not_empty.signal end end end # If there are dead threads in the pool make them go away while decreasing # spawned counter so that new healthy threads could be created again. def reap with_mutex do dead_workers = @workers.reject(&:alive?) dead_workers.each do |worker| worker.kill @spawned -= 1 end @workers.delete_if do |w| dead_workers.include?(w) end end end class Automaton def initialize(pool, timeout, thread_name, message) @pool = pool @timeout = timeout @thread_name = thread_name @message = message @running = false end def start! @running = true @thread = Thread.new do Puma.set_thread_name @thread_name while @running @pool.public_send(@message) sleep @timeout end end end def stop @running = false @thread.wakeup end end def auto_trim!(timeout=@auto_trim_time) @auto_trim = Automaton.new(self, timeout, "#{@name} tp trim", :trim) @auto_trim.start! end def auto_reap!(timeout=@reaping_time) @reaper = Automaton.new(self, timeout, "#{@name} tp reap", :reap) @reaper.start! end # Allows ThreadPool::ForceShutdown to be raised within the # provided block if the thread is forced to shutdown during execution. def with_force_shutdown t = Thread.current @shutdown_mutex.synchronize do raise ForceShutdown if @force_shutdown t[:with_force_shutdown] = true end yield ensure t[:with_force_shutdown] = false end # Tell all threads in the pool to exit and wait for them to finish. # Wait +timeout+ seconds then raise +ForceShutdown+ in remaining threads. # Next, wait an extra +@shutdown_grace_time+ seconds then force-kill remaining # threads. Finally, wait 1 second for remaining threads to exit. # def shutdown(timeout=-1) threads = with_mutex do @shutdown = true @trim_requested = @spawned @not_empty.broadcast @not_full.broadcast @auto_trim&.stop @reaper&.stop # dup workers so that we join them all safely @workers.dup end if timeout == -1 # Wait for threads to finish without force shutdown. threads.each(&:join) else join = ->(inner_timeout) do start = Process.clock_gettime(Process::CLOCK_MONOTONIC) threads.reject! do |t| elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start t.join inner_timeout - elapsed end end # Wait +timeout+ seconds for threads to finish. join.call(timeout) # If threads are still running, raise ForceShutdown and wait to finish. @shutdown_mutex.synchronize do @force_shutdown = true threads.each do |t| t.raise ForceShutdown if t[:with_force_shutdown] end end join.call(@shutdown_grace_time) # If threads are _still_ running, forcefully kill them and wait to finish. threads.each(&:kill) join.call(1) end @spawned = 0 @workers = [] end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/cli.rb
lib/puma/cli.rb
# frozen_string_literal: true require 'optparse' require 'uri' require_relative '../puma' require_relative 'configuration' require_relative 'launcher' require_relative 'const' require_relative 'log_writer' module Puma class << self # The CLI exports a Puma::Configuration instance here to allow # apps to pick it up. An app must load this object conditionally # because it is not set if the app is launched via any mechanism # other than the CLI class. attr_accessor :cli_config end # Handles invoke a Puma::Server in a command line style. # class CLI # Create a new CLI object using +argv+ as the command line # arguments. # def initialize(argv, log_writer = LogWriter.stdio, events = Events.new, env: ENV) @debug = false @argv = argv.dup @log_writer = log_writer @events = events @conf = nil @stdout = nil @stderr = nil @append = false @control_url = nil @control_options = {} begin setup_options env if file = @argv.shift @conf.configure do |user_config, file_config| file_config.rackup file end end rescue UnsupportedOption exit 1 end @conf.configure do |user_config, file_config| if @stdout || @stderr user_config.stdout_redirect @stdout, @stderr, @append end if @control_url user_config.activate_control_app @control_url, @control_options end end @launcher = Puma::Launcher.new(@conf, env: ENV, log_writer: @log_writer, events: @events, argv: argv) end attr_reader :launcher # Parse the options, load the rackup, start the server and wait # for it to finish. # def run @launcher.run end private def unsupported(str) @log_writer.error(str) raise UnsupportedOption end def configure_control_url(command_line_arg) if command_line_arg @control_url = command_line_arg elsif Puma.jruby? unsupported "No default url available on JRuby" end end # Build the OptionParser object to handle the available options. # def setup_options(env = ENV) @conf = Configuration.new({}, { events: @events }, env) do |user_config, file_config| @parser = OptionParser.new do |o| o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg| user_config.bind arg end o.on "--bind-to-activated-sockets [only]", "Bind to all activated sockets" do |arg| user_config.bind_to_activated_sockets(arg || true) end o.on "-C", "--config PATH", "Load PATH as a config file" do |arg| file_config.load arg end # Identical to supplying --config "-", but more semantic o.on "--no-config", "Prevent Puma from searching for a config file" do |arg| file_config.load "-" end o.on "--control-url URL", "The bind url to use for the control server. Use 'auto' to use temp unix server" do |arg| configure_control_url(arg) end o.on "--control-token TOKEN", "The token to use as authentication for the control server" do |arg| @control_options[:auth_token] = arg end o.on "--debug", "Log lowlevel debugging information" do user_config.debug end o.on "--dir DIR", "Change to DIR before starting" do |d| user_config.directory d end o.on "-e", "--environment ENVIRONMENT", "The environment to run the Rack app on (default development)" do |arg| user_config.environment arg end o.on "-f", "--fork-worker=[REQUESTS]", OptionParser::DecimalInteger, "Fork new workers from existing worker. Cluster mode only", "Auto-refork after REQUESTS (default 1000)" do |*args| user_config.fork_worker(*args.compact) end o.on "-I", "--include PATH", "Specify $LOAD_PATH directories" do |arg| $LOAD_PATH.unshift(*arg.split(':')) end o.on "--idle-timeout SECONDS", "Number of seconds until the next request before automatic shutdown" do |arg| user_config.idle_timeout arg end o.on "-p", "--port PORT", "Define the TCP port to bind to", "Use -b for more advanced options" do |arg| user_config.bind "tcp://#{Configuration::DEFAULTS[:tcp_host]}:#{arg}" end o.on "--pidfile PATH", "Use PATH as a pidfile" do |arg| user_config.pidfile arg end o.on "--plugin PLUGIN", "Load the given PLUGIN. Can be used multiple times to load multiple plugins." do |arg| user_config.plugin arg end o.on "--preload", "Preload the app. Cluster mode only" do user_config.preload_app! end o.on "--prune-bundler", "Prune out the bundler env if possible" do user_config.prune_bundler end o.on "--extra-runtime-dependencies GEM1,GEM2", "Defines any extra needed gems when using --prune-bundler" do |arg| user_config.extra_runtime_dependencies arg.split(',') end o.on "-q", "--quiet", "Do not log requests internally (default true)" do user_config.quiet end o.on "-v", "--log-requests", "Log requests as they occur" do user_config.log_requests end o.on "-R", "--restart-cmd CMD", "The puma command to run during a hot restart", "Default: inferred" do |cmd| user_config.restart_command cmd end o.on "-s", "--silent", "Do not log prompt messages other than errors" do @log_writer = LogWriter.new(NullIO.new, $stderr) end o.on "-S", "--state PATH", "Where to store the state details" do |arg| user_config.state_path arg end o.on '-t', '--threads INT', "min:max threads to use (default 0:16)" do |arg| min, max = arg.split(":") if max user_config.threads min, max else user_config.threads min, min end end o.on "--early-hints", "Enable early hints support" do user_config.early_hints end o.on "-V", "--version", "Print the version information" do puts "puma version #{Puma::Const::VERSION}" exit 0 end o.on "-w", "--workers COUNT", "Activate cluster mode: How many worker processes to create" do |arg| user_config.workers arg end o.on "--tag NAME", "Additional text to display in process listing" do |arg| user_config.tag arg end o.on "--redirect-stdout FILE", "Redirect STDOUT to a specific file" do |arg| @stdout = arg.to_s end o.on "--redirect-stderr FILE", "Redirect STDERR to a specific file" do |arg| @stderr = arg.to_s end o.on "--[no-]redirect-append", "Append to redirected files" do |val| @append = val end o.banner = "puma <options> <rackup file>" o.on_tail "-h", "--help", "Show help" do $stdout.puts o exit 0 end end.parse! @argv end end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/launcher.rb
lib/puma/launcher.rb
# frozen_string_literal: true require_relative 'log_writer' require_relative 'events' require_relative 'detect' require_relative 'cluster' require_relative 'single' require_relative 'const' require_relative 'binder' module Puma # Puma::Launcher is the single entry point for starting a Puma server based on user # configuration. It is responsible for taking user supplied arguments and resolving them # with configuration in `config/puma.rb` or `config/puma/<env>.rb`. # # It is responsible for either launching a cluster of Puma workers or a single # puma server. class Launcher autoload :BundlePruner, 'puma/launcher/bundle_pruner' # Returns an instance of Launcher # # +conf+ A Puma::Configuration object indicating how to run the server. # # +launcher_args+ A Hash that has a few optional keys. # - +:log_writer+:: Expected to hold an object similar to `Puma::LogWriter.stdio`. # This object will be responsible for broadcasting Puma's internal state # to a logging destination. # - +:events+:: Expected to hold an object similar to `Puma::Events`. # - +:argv+:: Expected to be an array of strings. # - +:env+:: Expected to hold a hash of environment variables. # # These arguments are re-used when restarting the puma server. # # Examples: # # conf = Puma::Configuration.new do |user_config| # user_config.threads 1, 10 # user_config.app do |env| # [200, {}, ["hello world"]] # end # end # Puma::Launcher.new(conf, log_writer: Puma::LogWriter.stdio).run def initialize(conf, launcher_args={}) ## Minimal initialization before potential early restart (e.g. from bundle pruning) @config = conf # Advertise the CLI Configuration before config files are loaded Puma.cli_config = @config if defined?(Puma.cli_config) @config.clamp @options = @config.options @log_writer = launcher_args[:log_writer] || LogWriter::DEFAULT @log_writer.formatter = LogWriter::PidFormatter.new if clustered? @log_writer.formatter = @options[:log_formatter] if @options[:log_formatter] @log_writer.custom_logger = @options[:custom_logger] if @options[:custom_logger] @options[:log_writer] = @log_writer @options[:logger] = @log_writer if clustered? @events = launcher_args[:events] || Events.new @argv = launcher_args[:argv] || [] @original_argv = @argv.dup ## End minimal initialization generate_restart_data Dir.chdir(@restart_dir) prune_bundler! env = launcher_args.delete(:env) || ENV # Log after prune_bundler! to avoid duplicate logging if a restart occurs log_config if env['PUMA_LOG_CONFIG'] @binder = Binder.new(@log_writer, @options) @binder.create_inherited_fds(env).each { |k| env.delete k } @binder.create_activated_fds(env).each { |k| env.delete k } @environment = @config.environment # Load the systemd integration if we detect systemd's NOTIFY_SOCKET. # Skip this on JRuby though, because it is incompatible with the systemd # integration due to https://github.com/jruby/jruby/issues/6504 if ENV["NOTIFY_SOCKET"] && !Puma.jruby? && !ENV["PUMA_SKIP_SYSTEMD"] @config.plugins.create('systemd') end if @options[:bind_to_activated_sockets] @options[:binds] = @binder.synthesize_binds_from_activated_fs( @options[:binds], @options[:bind_to_activated_sockets] == 'only' ) end if clustered? && !Puma.forkable? unsupported "worker mode not supported on #{RUBY_ENGINE} on this platform" end @environment = @options[:environment] if @options[:environment] set_rack_environment if clustered? @runner = Cluster.new(self) else @runner = Single.new(self) end Puma.stats_object = @runner @status = :run end attr_reader :binder, :log_writer, :events, :config, :options, :restart_dir # Return stats about the server def stats @runner.stats end # Write a state file that can be used by pumactl to control # the server def write_state write_pid path = @options[:state] permission = @options[:state_permission] return unless path require_relative 'state_file' sf = StateFile.new sf.pid = Process.pid sf.control_url = @options[:control_url] sf.control_auth_token = @options[:control_auth_token] sf.running_from = File.expand_path('.') sf.save path, permission end # Delete the configured pidfile def delete_pidfile path = @options[:pidfile] begin File.unlink(path) if path rescue Errno::ENOENT end end # Begin async shutdown of the server def halt @status = :halt @runner.halt end # Begin async shutdown of the server gracefully def stop @status = :stop @runner.stop end # Begin async restart of the server def restart @status = :restart @runner.restart end # Begin a phased restart if supported def phased_restart unless @runner.respond_to?(:phased_restart) and @runner.phased_restart log "* phased-restart called but not available, restarting normally." return restart end if @options.file_options[:tag].nil? dir = File.realdirpath(@restart_dir) @options[:tag] = File.basename(dir) set_process_title end true end # Begin a refork if supported def refork if clustered? && @runner.respond_to?(:fork_worker!) && @options[:fork_worker] @runner.fork_worker! true else log "* refork called but not available." false end end # Run the server. This blocks until the server is stopped def run previous_env = get_env @config.clamp @config.plugins.fire_starts self setup_signals set_process_title # This blocks until the server is stopped @runner.run do_run_finished(previous_env) end # Return all tcp ports the launcher may be using, TCP or SSL # @!attribute [r] connected_ports # @version 5.0.0 def connected_ports @binder.connected_ports end # @!attribute [r] restart_args def restart_args cmd = @options[:restart_cmd] if cmd cmd.split(' ') + @original_argv else @restart_argv end end def close_binder_listeners @runner.close_control_listeners @binder.close_listeners unless @status == :restart log "=== puma shutdown: #{Time.now} ===" log "- Goodbye!" end end # @!attribute [r] thread_status # @version 5.0.0 def thread_status Thread.list.each do |thread| name = "Thread: TID-#{thread.object_id.to_s(36)}" name += " #{thread['label']}" if thread['label'] name += " #{thread.name}" if thread.respond_to?(:name) && thread.name backtrace = thread.backtrace || ["<no backtrace available>"] yield name, backtrace end end private def get_env if defined?(Bundler) env = Bundler::ORIGINAL_ENV.dup # add -rbundler/setup so we load from Gemfile when restarting bundle = "-rbundler/setup" env["RUBYOPT"] = [env["RUBYOPT"], bundle].join(" ").lstrip unless env["RUBYOPT"].to_s.include?(bundle) env else ENV.to_h end end def do_run_finished(previous_env) case @status when :halt do_forceful_stop when :run, :stop do_graceful_stop when :restart do_restart(previous_env) end close_binder_listeners unless @status == :restart end def do_forceful_stop log "* Stopping immediately!" @runner.stop_control end def do_graceful_stop @events.fire_after_stopped! @runner.stop_blocked end def do_restart(previous_env) log "* Restarting..." ENV.replace(previous_env) @runner.stop_control restart! end def restart! @events.fire_before_restart! @config.run_hooks :before_restart, self, @log_writer if Puma.jruby? close_binder_listeners require_relative 'jruby_restart' argv = restart_args JRubyRestart.chdir(@restart_dir) Kernel.exec(*argv) elsif Puma.windows? close_binder_listeners argv = restart_args Dir.chdir(@restart_dir) Kernel.exec(*argv) else argv = restart_args Dir.chdir(@restart_dir) ENV.update(@binder.redirects_for_restart_env) argv += [@binder.redirects_for_restart] Kernel.exec(*argv) end end # If configured, write the pid of the current process out # to a file. def write_pid path = @options[:pidfile] return unless path cur_pid = Process.pid File.write path, cur_pid, mode: 'wb:UTF-8' at_exit do delete_pidfile if cur_pid == Process.pid end end def reload_worker_directory @runner.reload_worker_directory if @runner.respond_to?(:reload_worker_directory) end def log(str) @log_writer.log(str) end def clustered? (@options[:workers] || 0) > 0 end def unsupported(str) @log_writer.error(str) raise UnsupportedOption end def set_process_title Process.respond_to?(:setproctitle) ? Process.setproctitle(title) : $0 = title end # @!attribute [r] title def title buffer = "puma #{Puma::Const::VERSION} (#{@options[:binds].join(',')})" buffer += " [#{@options[:tag]}]" if @options[:tag] && !@options[:tag].empty? buffer end def set_rack_environment @options[:environment] = environment ENV['RACK_ENV'] = environment end # @!attribute [r] environment def environment @environment end def prune_bundler? @options[:prune_bundler] && clustered? && !@options[:preload_app] end def prune_bundler! return unless prune_bundler? BundlePruner.new(@original_argv, @options[:extra_runtime_dependencies], @log_writer).prune end def generate_restart_data if dir = @options[:directory] @restart_dir = dir elsif Puma.windows? # I guess the value of PWD is garbage on windows so don't bother # using it. @restart_dir = Dir.pwd # Use the same trick as unicorn, namely favor PWD because # it will contain an unresolved symlink, useful for when # the pwd is /data/releases/current. elsif dir = ENV['PWD'] s_env = File.stat(dir) s_pwd = File.stat(Dir.pwd) if s_env.ino == s_pwd.ino and (Puma.jruby? or s_env.dev == s_pwd.dev) @restart_dir = dir end end @restart_dir ||= Dir.pwd # if $0 is a file in the current directory, then restart # it the same, otherwise add -S on there because it was # picked up in PATH. # if File.exist?($0) arg0 = [Gem.ruby, $0] else arg0 = [Gem.ruby, "-S", $0] end # Detect and reinject -Ilib from the command line, used for testing without bundler # cruby has an expanded path, jruby has just "lib" lib = File.expand_path "lib" arg0[1,0] = ["-I", lib] if [lib, "lib"].include?($LOAD_PATH[0]) if defined? Puma::WILD_ARGS @restart_argv = arg0 + Puma::WILD_ARGS + @original_argv else @restart_argv = arg0 + @original_argv end end def setup_signals unless ENV["PUMA_SKIP_SIGUSR2"] begin Signal.trap "SIGUSR2" do restart end rescue Exception log "*** SIGUSR2 not implemented, signal based restart unavailable!" end end unless Puma.jruby? begin Signal.trap "SIGUSR1" do phased_restart end rescue Exception log "*** SIGUSR1 not implemented, signal based restart unavailable!" end end begin Signal.trap "SIGTERM" do # Shortcut the control flow in case raise_exception_on_sigterm is true do_graceful_stop raise(SignalException, "SIGTERM") if @options[:raise_exception_on_sigterm] end rescue Exception log "*** SIGTERM not implemented, signal based gracefully stopping unavailable!" end begin Signal.trap "SIGINT" do stop end rescue Exception log "*** SIGINT not implemented, signal based gracefully stopping unavailable!" end begin Signal.trap "SIGHUP" do if @runner.redirected_io? @runner.redirect_io else stop end end rescue Exception log "*** SIGHUP not implemented, signal based logs reopening unavailable!" end begin unless Puma.jruby? # INFO in use by JVM already Signal.trap "SIGINFO" do thread_status do |name, backtrace| @log_writer.log(name) @log_writer.log(backtrace.map { |bt| " #{bt}" }) end end end rescue Exception # Not going to log this one, as SIGINFO is *BSD only and would be pretty annoying # to see this constantly on Linux. end end def log_config log "Configuration:" @config.final_options .each { |config_key, value| log "- #{config_key}: #{value}" } log "\n" end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/client.rb
lib/puma/client.rb
# frozen_string_literal: true require_relative 'detect' require_relative 'io_buffer' require 'tempfile' if Puma::IS_JRUBY # We have to work around some OpenSSL buffer/io-readiness bugs # so we pull it in regardless of if the user is binding # to an SSL socket require 'openssl' end module Puma class ConnectionError < RuntimeError; end class HttpParserError501 < IOError; end #β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” DO NOT USE β€” this class is for internal use only β€”β€”β€” # An instance of this class represents a unique request from a client. # For example, this could be a web request from a browser or from CURL. # # An instance of `Puma::Client` can be used as if it were an IO object # by the reactor. The reactor is expected to call `#to_io` # on any non-IO objects it polls. For example, nio4r internally calls # `IO::try_convert` (which may call `#to_io`) when a new socket is # registered. # # Instances of this class are responsible for knowing if # the header and body are fully buffered via the `try_to_finish` method. # They can be used to "time out" a response via the `timeout_at` reader. # class Client # :nodoc: # this tests all values but the last, which must be chunked ALLOWED_TRANSFER_ENCODING = %w[compress deflate gzip].freeze # chunked body validation CHUNK_SIZE_INVALID = /[^\h]/.freeze CHUNK_VALID_ENDING = Const::LINE_END CHUNK_VALID_ENDING_SIZE = CHUNK_VALID_ENDING.bytesize # The maximum number of bytes we'll buffer looking for a valid # chunk header. MAX_CHUNK_HEADER_SIZE = 4096 # The maximum amount of excess data the client sends # using chunk size extensions before we abort the connection. MAX_CHUNK_EXCESS = 16 * 1024 # Content-Length header value validation CONTENT_LENGTH_VALUE_INVALID = /[^\d]/.freeze TE_ERR_MSG = 'Invalid Transfer-Encoding' # See: # https://httpwg.org/specs/rfc9110.html#rfc.section.5.6.1.1 # https://httpwg.org/specs/rfc9112.html#rfc.section.6.1 STRIP_OWS = /\A[ \t]+|[ \t]+\z/ # The object used for a request with no body. All requests with # no body share this one object since it has no state. EmptyBody = NullIO.new include Puma::Const def initialize(io, env=nil) @io = io @to_io = io.to_io @io_buffer = IOBuffer.new @proto_env = env @env = env&.dup @parser = HttpParser.new @parsed_bytes = 0 @read_header = true @read_proxy = false @ready = false @body = nil @body_read_start = nil @buffer = nil @tempfile = nil @timeout_at = nil @requests_served = 0 @hijacked = false @http_content_length_limit = nil @http_content_length_limit_exceeded = false @peerip = nil @peer_family = nil @listener = nil @remote_addr_header = nil @expect_proxy_proto = false @body_remain = 0 @in_last_chunk = false # need unfrozen ASCII-8BIT, +'' is UTF-8 @read_buffer = String.new # rubocop: disable Performance/UnfreezeString end attr_reader :env, :to_io, :body, :io, :timeout_at, :ready, :hijacked, :tempfile, :io_buffer, :http_content_length_limit_exceeded, :requests_served attr_writer :peerip, :http_content_length_limit attr_accessor :remote_addr_header, :listener # Remove in Puma 7? def closed? @to_io.closed? end # Test to see if io meets a bare minimum of functioning, @to_io needs to be # used for MiniSSL::Socket def io_ok? @to_io.is_a?(::BasicSocket) && !closed? end # @!attribute [r] inspect def inspect "#<Puma::Client:0x#{object_id.to_s(16)} @ready=#{@ready.inspect}>" end # For the full hijack protocol, `env['rack.hijack']` is set to # `client.method :full_hijack` def full_hijack @hijacked = true env[HIJACK_IO] ||= @io end # @!attribute [r] in_data_phase def in_data_phase !(@read_header || @read_proxy) end def set_timeout(val) @timeout_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + val end # Number of seconds until the timeout elapses. # @!attribute [r] timeout def timeout [@timeout_at - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max end def reset @parser.reset @io_buffer.reset @read_header = true @read_proxy = !!@expect_proxy_proto @env = @proto_env.dup @parsed_bytes = 0 @ready = false @body_remain = 0 @peerip = nil if @remote_addr_header @in_last_chunk = false @http_content_length_limit_exceeded = false end # only used with back-to-back requests contained in the buffer def process_back_to_back_requests if @buffer return false unless try_to_parse_proxy_protocol @parsed_bytes = parser_execute if @parser.finished? return setup_body elsif @parsed_bytes >= MAX_HEADER raise HttpParserError, "HEADER is longer than allowed, aborting client early." end end end # if a client sends back-to-back requests, the buffer may contain one or more # of them. def has_back_to_back_requests? !(@buffer.nil? || @buffer.empty?) end def close tempfile_close begin @io.close rescue IOError, Errno::EBADF end end def tempfile_close tf_path = @tempfile&.path @tempfile&.close File.unlink(tf_path) if tf_path @tempfile = nil @body = nil rescue Errno::ENOENT, IOError end # If necessary, read the PROXY protocol from the buffer. Returns # false if more data is needed. def try_to_parse_proxy_protocol if @read_proxy if @expect_proxy_proto == :v1 if @buffer.include? "\r\n" if md = PROXY_PROTOCOL_V1_REGEX.match(@buffer) if md[1] @peerip = md[1].split(" ")[0] end @buffer = md.post_match end # if the buffer has a \r\n but doesn't have a PROXY protocol # request, this is just HTTP from a non-PROXY client; move on @read_proxy = false return @buffer.size > 0 else return false end end end true end def try_to_finish if env[CONTENT_LENGTH] && above_http_content_limit(env[CONTENT_LENGTH].to_i) @http_content_length_limit_exceeded = true end if @http_content_length_limit_exceeded @buffer = nil @body = EmptyBody set_ready return true end return read_body if in_data_phase data = nil begin data = @io.read_nonblock(CHUNK_SIZE) rescue IO::WaitReadable return false rescue EOFError # Swallow error, don't log rescue SystemCallError, IOError raise ConnectionError, "Connection error detected during read" end # No data means a closed socket unless data @buffer = nil set_ready raise EOFError end if @buffer @buffer << data else @buffer = data end return false unless try_to_parse_proxy_protocol @parsed_bytes = parser_execute if @parser.finished? && above_http_content_limit(@parser.body.bytesize) @http_content_length_limit_exceeded = true end if @parser.finished? setup_body elsif @parsed_bytes >= MAX_HEADER raise HttpParserError, "HEADER is longer than allowed, aborting client early." else false end end def eagerly_finish return true if @ready while @to_io.wait_readable(0) # rubocop: disable Style/WhileUntilModifier return true if try_to_finish end false end def finish(timeout) return if @ready @to_io.wait_readable(timeout) || timeout! until try_to_finish end # Wraps `@parser.execute` and adds meaningful error messages # @return [Integer] bytes of buffer read by parser # def parser_execute @parser.execute(@env, @buffer, @parsed_bytes) rescue => e @env[HTTP_CONNECTION] = 'close' raise e unless HttpParserError === e && e.message.include?('non-SSL') req, _ = @buffer.split "\r\n\r\n" request_line, headers = req.split "\r\n", 2 # below checks for request issues and changes error message accordingly if !@env.key? REQUEST_METHOD if request_line.count(' ') != 2 # maybe this is an SSL connection ? raise e else method = request_line[/\A[^ ]+/] raise e, "Invalid HTTP format, parsing fails. Bad method #{method}" end elsif !@env.key? REQUEST_PATH path = request_line[/\A[^ ]+ +([^ ?\r\n]+)/, 1] raise e, "Invalid HTTP format, parsing fails. Bad path #{path}" elsif request_line.match?(/\A[^ ]+ +[^ ?\r\n]+\?/) && !@env.key?(QUERY_STRING) query = request_line[/\A[^ ]+ +[^? ]+\?([^ ]+)/, 1] raise e, "Invalid HTTP format, parsing fails. Bad query #{query}" elsif !@env.key? SERVER_PROTOCOL # protocol is bad text = request_line[/[^ ]*\z/] raise HttpParserError, "Invalid HTTP format, parsing fails. Bad protocol #{text}" elsif !headers.empty? # headers are bad hdrs = headers.split("\r\n").map { |h| h.gsub "\n", '\n'}.join "\n" raise HttpParserError, "Invalid HTTP format, parsing fails. Bad headers\n#{hdrs}" end end def timeout! write_error(408) if in_data_phase raise ConnectionError end def write_error(status_code) begin @io << ERROR_RESPONSE[status_code] rescue StandardError end end def peerip return @peerip if @peerip if @remote_addr_header hdr = (@env[@remote_addr_header] || @io.peeraddr.last).split(/[\s,]/).first @peerip = hdr return hdr end @peerip ||= @io.peeraddr.last end def peer_family return @peer_family if @peer_family @peer_family ||= begin @io.local_address.afamily rescue Socket::AF_INET end end # Returns true if the persistent connection can be closed immediately # without waiting for the configured idle/shutdown timeout. # @version 5.0.0 # def can_close? # Allow connection to close if we're not in the middle of parsing a request. @parsed_bytes == 0 end def expect_proxy_proto=(val) if val if @read_header @read_proxy = true end else @read_proxy = false end @expect_proxy_proto = val end private def setup_body @body_read_start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) if @env[HTTP_EXPECT] == CONTINUE # TODO allow a hook here to check the headers before # going forward @io << HTTP_11_100 @io.flush end @read_header = false body = @parser.body te = @env[TRANSFER_ENCODING2] if te te_lwr = te.downcase if te.include? ',' te_ary = te_lwr.split(',').each { |te| te.gsub!(STRIP_OWS, "") } te_count = te_ary.count CHUNKED te_valid = te_ary[0..-2].all? { |e| ALLOWED_TRANSFER_ENCODING.include? e } if te_count > 1 raise HttpParserError , "#{TE_ERR_MSG}, multiple chunked: '#{te}'" elsif te_ary.last != CHUNKED raise HttpParserError , "#{TE_ERR_MSG}, last value must be chunked: '#{te}'" elsif !te_valid raise HttpParserError501, "#{TE_ERR_MSG}, unknown value: '#{te}'" end @env.delete TRANSFER_ENCODING2 return setup_chunked_body body elsif te_lwr == CHUNKED @env.delete TRANSFER_ENCODING2 return setup_chunked_body body elsif ALLOWED_TRANSFER_ENCODING.include? te_lwr raise HttpParserError , "#{TE_ERR_MSG}, single value must be chunked: '#{te}'" else raise HttpParserError501 , "#{TE_ERR_MSG}, unknown value: '#{te}'" end end @chunked_body = false cl = @env[CONTENT_LENGTH] if cl # cannot contain characters that are not \d, or be empty if CONTENT_LENGTH_VALUE_INVALID.match?(cl) || cl.empty? raise HttpParserError, "Invalid Content-Length: #{cl.inspect}" end else @buffer = body.empty? ? nil : body @body = EmptyBody set_ready return true end content_length = cl.to_i remain = content_length - body.bytesize if remain <= 0 # Part of the body is a pipelined request OR garbage. We'll deal with that later. if content_length == 0 @body = EmptyBody if body.empty? @buffer = nil else @buffer = body end elsif remain == 0 @body = StringIO.new body @buffer = nil else @body = StringIO.new(body[0,content_length]) @buffer = body[content_length..-1] end set_ready return true end if remain > MAX_BODY @body = Tempfile.create(Const::PUMA_TMP_BASE) File.unlink @body.path unless IS_WINDOWS @body.binmode @tempfile = @body else # The body[0,0] trick is to get an empty string in the same # encoding as body. @body = StringIO.new body[0,0] end @body.write body @body_remain = remain false end def read_body if @chunked_body return read_chunked_body end # Read an odd sized chunk so we can read even sized ones # after this remain = @body_remain # don't bother with reading zero bytes unless remain.zero? begin chunk = @io.read_nonblock(remain.clamp(0, CHUNK_SIZE), @read_buffer) rescue IO::WaitReadable return false rescue SystemCallError, IOError raise ConnectionError, "Connection error detected during read" end # No chunk means a closed socket unless chunk @body.close @buffer = nil set_ready raise EOFError end remain -= @body.write(chunk) end if remain <= 0 @body.rewind @buffer = nil set_ready true else @body_remain = remain false end end def read_chunked_body while true begin chunk = @io.read_nonblock(CHUNK_SIZE, @read_buffer) rescue IO::WaitReadable return false rescue SystemCallError, IOError raise ConnectionError, "Connection error detected during read" end # No chunk means a closed socket unless chunk @body.close @buffer = nil set_ready raise EOFError end if decode_chunk(chunk) @env[CONTENT_LENGTH] = @chunked_content_length.to_s return true end end end def setup_chunked_body(body) @chunked_body = true @partial_part_left = 0 @prev_chunk = "" @excess_cr = 0 @body = Tempfile.create(Const::PUMA_TMP_BASE) File.unlink @body.path unless IS_WINDOWS @body.binmode @tempfile = @body @chunked_content_length = 0 if decode_chunk(body) @env[CONTENT_LENGTH] = @chunked_content_length.to_s return true end end # @version 5.0.0 def write_chunk(str) @chunked_content_length += @body.write(str) end def decode_chunk(chunk) if @partial_part_left > 0 if @partial_part_left <= chunk.size if @partial_part_left > 2 write_chunk(chunk[0..(@partial_part_left-3)]) # skip the \r\n end chunk = chunk[@partial_part_left..-1] @partial_part_left = 0 else if @partial_part_left > 2 if @partial_part_left == chunk.size + 1 # Don't include the last \r write_chunk(chunk[0..(@partial_part_left-3)]) else # don't include the last \r\n write_chunk(chunk) end end @partial_part_left -= chunk.size return false end end if @prev_chunk.empty? io = StringIO.new(chunk) else io = StringIO.new(@prev_chunk+chunk) @prev_chunk = "" end while !io.eof? line = io.gets if line.end_with?(CHUNK_VALID_ENDING) # Puma doesn't process chunk extensions, but should parse if they're # present, which is the reason for the semicolon regex chunk_hex = line.strip[/\A[^;]+/] if CHUNK_SIZE_INVALID.match? chunk_hex raise HttpParserError, "Invalid chunk size: '#{chunk_hex}'" end len = chunk_hex.to_i(16) if len == 0 @in_last_chunk = true @body.rewind rest = io.read if rest.bytesize < CHUNK_VALID_ENDING_SIZE @buffer = nil @partial_part_left = CHUNK_VALID_ENDING_SIZE - rest.bytesize return false else # if the next character is a CRLF, set buffer to everything after that CRLF start_of_rest = if rest.start_with?(CHUNK_VALID_ENDING) CHUNK_VALID_ENDING_SIZE else # we have started a trailer section, which we do not support. skip it! rest.index(CHUNK_VALID_ENDING*2) + CHUNK_VALID_ENDING_SIZE*2 end @buffer = rest[start_of_rest..-1] @buffer = nil if @buffer.empty? set_ready return true end end # Track the excess as a function of the size of the # header vs the size of the actual data. Excess can # go negative (and is expected to) when the body is # significant. # The additional of chunk_hex.size and 2 compensates # for a client sending 1 byte in a chunked body over # a long period of time, making sure that that client # isn't accidentally eventually punished. @excess_cr += (line.size - len - chunk_hex.size - 2) if @excess_cr >= MAX_CHUNK_EXCESS raise HttpParserError, "Maximum chunk excess detected" end len += 2 part = io.read(len) unless part @partial_part_left = len next end got = part.size case when got == len # proper chunked segment must end with "\r\n" if part.end_with? CHUNK_VALID_ENDING write_chunk(part[0..-3]) # to skip the ending \r\n else raise HttpParserError, "Chunk size mismatch" end when got <= len - 2 write_chunk(part) @partial_part_left = len - part.size when got == len - 1 # edge where we get just \r but not \n write_chunk(part[0..-2]) @partial_part_left = len - part.size end else if @prev_chunk.size + line.size >= MAX_CHUNK_HEADER_SIZE raise HttpParserError, "maximum size of chunk header exceeded" end @prev_chunk = line return false end end if @in_last_chunk set_ready true else false end end def set_ready if @body_read_start @env['puma.request_body_wait'] = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - @body_read_start end @requests_served += 1 @ready = true end def above_http_content_limit(value) @http_content_length_limit&.< value end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/server.rb
lib/puma/server.rb
# frozen_string_literal: true require 'stringio' require_relative 'thread_pool' require_relative 'const' require_relative 'log_writer' require_relative 'events' require_relative 'null_io' require_relative 'reactor' require_relative 'client' require_relative 'binder' require_relative 'util' require_relative 'request' require_relative 'configuration' require_relative 'cluster_accept_loop_delay' require 'socket' require 'io/wait' unless Puma::HAS_NATIVE_IO_WAIT module Puma # The HTTP Server itself. Serves out a single Rack app. # # This class is used by the `Puma::Single` and `Puma::Cluster` classes # to generate one or more `Puma::Server` instances capable of handling requests. # Each Puma process will contain one `Puma::Server` instance. # # The `Puma::Server` instance pulls requests from the socket, adds them to a # `Puma::Reactor` where they get eventually passed to a `Puma::ThreadPool`. # # Each `Puma::Server` will have one reactor and one thread pool. class Server module FiberPerRequest def handle_request(client, requests) Fiber.new do super end.resume end end include Puma::Const include Request attr_reader :options attr_reader :thread attr_reader :log_writer attr_reader :events attr_reader :min_threads, :max_threads # for #stats attr_reader :requests_count # @version 5.0.0 # @todo the following may be deprecated in the future attr_reader :auto_trim_time, :early_hints, :first_data_timeout, :leak_stack_on_error, :persistent_timeout, :reaping_time attr_accessor :app attr_accessor :binder # Create a server for the rack app +app+. # # +log_writer+ is a Puma::LogWriter object used to log info and error messages. # # +events+ is a Puma::Events object used to notify application status events. # # Server#run returns a thread that you can join on to wait for the server # to do its work. # # @note Several instance variables exist so they are available for testing, # and have default values set via +fetch+. Normally the values are set via # `::Puma::Configuration.puma_default_options`. # # @note The `events` parameter is set to nil, and set to `Events.new` in code. # Often `options` needs to be passed, but `events` does not. Using nil allows # calling code to not require events.rb. # def initialize(app, events = nil, options = {}) @app = app @events = events || Events.new @check, @notify = nil @status = :stop @thread = nil @thread_pool = nil @reactor = nil @env_set_http_version = nil @options = if options.is_a?(UserFileDefaultOptions) options else UserFileDefaultOptions.new(options, Configuration::DEFAULTS) end @clustered = (@options.fetch :workers, 0) > 0 @worker_write = @options[:worker_write] @log_writer = @options.fetch :log_writer, LogWriter.stdio @early_hints = @options[:early_hints] @first_data_timeout = @options[:first_data_timeout] @persistent_timeout = @options[:persistent_timeout] @idle_timeout = @options[:idle_timeout] @min_threads = @options[:min_threads] @max_threads = @options[:max_threads] @queue_requests = @options[:queue_requests] @max_keep_alive = @options[:max_keep_alive] @enable_keep_alives = @options[:enable_keep_alives] @enable_keep_alives &&= @queue_requests @io_selector_backend = @options[:io_selector_backend] @http_content_length_limit = @options[:http_content_length_limit] @cluster_accept_loop_delay = ClusterAcceptLoopDelay.new( workers: @options[:workers], max_delay: @options[:wait_for_less_busy_worker] || 0 # Real default is in Configuration::DEFAULTS, this is for unit testing ) if @options[:fiber_per_request] singleton_class.prepend(FiberPerRequest) end # make this a hash, since we prefer `key?` over `include?` @supported_http_methods = if @options[:supported_http_methods] == :any :any else if (ary = @options[:supported_http_methods]) ary else SUPPORTED_HTTP_METHODS end.sort.product([nil]).to_h.freeze end temp = !!(@options[:environment] =~ /\A(development|test)\z/) @leak_stack_on_error = @options[:environment] ? temp : true @binder = Binder.new(log_writer, @options) ENV['RACK_ENV'] ||= "development" @mode = :http @precheck_closing = true @requests_count = 0 @idle_timeout_reached = false end def inherit_binder(bind) @binder = bind end class << self # @!attribute [r] current def current Thread.current.puma_server end # :nodoc: # @version 5.0.0 def tcp_cork_supported? Socket.const_defined?(:TCP_CORK) && Socket.const_defined?(:IPPROTO_TCP) end # :nodoc: # @version 5.0.0 def closed_socket_supported? Socket.const_defined?(:TCP_INFO) && Socket.const_defined?(:IPPROTO_TCP) end private :tcp_cork_supported? private :closed_socket_supported? end # On Linux, use TCP_CORK to better control how the TCP stack # packetizes our stream. This improves both latency and throughput. # socket parameter may be an MiniSSL::Socket, so use to_io # if tcp_cork_supported? # 6 == Socket::IPPROTO_TCP # 3 == TCP_CORK # 1/0 == turn on/off def cork_socket(socket) skt = socket.to_io begin skt.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_CORK, 1) if skt.kind_of? TCPSocket rescue IOError, SystemCallError end end def uncork_socket(socket) skt = socket.to_io begin skt.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_CORK, 0) if skt.kind_of? TCPSocket rescue IOError, SystemCallError end end else def cork_socket(socket) end def uncork_socket(socket) end end if closed_socket_supported? UNPACK_TCP_STATE_FROM_TCP_INFO = "C".freeze def closed_socket?(socket) skt = socket.to_io return false unless skt.kind_of?(TCPSocket) && @precheck_closing begin tcp_info = skt.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_INFO) rescue IOError, SystemCallError @precheck_closing = false false else state = tcp_info.unpack(UNPACK_TCP_STATE_FROM_TCP_INFO)[0] # TIME_WAIT: 6, CLOSE: 7, CLOSE_WAIT: 8, LAST_ACK: 9, CLOSING: 11 (state >= 6 && state <= 9) || state == 11 end end else def closed_socket?(socket) false end end # @!attribute [r] backlog def backlog @thread_pool&.backlog end # @!attribute [r] running def running @thread_pool&.spawned end # This number represents the number of requests that # the server is capable of taking right now. # # For example if the number is 5 then it means # there are 5 threads sitting idle ready to take # a request. If one request comes in, then the # value would be 4 until it finishes processing. # @!attribute [r] pool_capacity def pool_capacity @thread_pool&.pool_capacity end # Runs the server. # # If +background+ is true (the default) then a thread is spun # up in the background to handle requests. Otherwise requests # are handled synchronously. # def run(background=true, thread_name: 'srv') BasicSocket.do_not_reverse_lookup = true @events.fire :state, :booting @status = :run @thread_pool = ThreadPool.new(thread_name, options, server: self) { |client| process_client client } if @queue_requests @reactor = Reactor.new(@io_selector_backend) { |c| # Inversion of control, the reactor is calling a method on the server when it # is done buffering a request or receives a new request from a keepalive connection. self.reactor_wakeup(c) } @reactor.run end @thread_pool.auto_reap! if options[:reaping_time] @thread_pool.auto_trim! if @min_threads != @max_threads && options[:auto_trim_time] @check, @notify = Puma::Util.pipe unless @notify @events.fire :state, :running if background @thread = Thread.new do Puma.set_thread_name thread_name handle_servers end return @thread else handle_servers end end # This method is called from the Reactor thread when a queued Client receives data, # times out, or when the Reactor is shutting down. # # While the code lives in the Server, the logic is executed on the reactor thread, independently # from the server. # # It is responsible for ensuring that a request has been completely received # before it starts to be processed by the ThreadPool. This may be known as read buffering. # If read buffering is not done, and no other read buffering is performed (such as by an application server # such as nginx) then the application would be subject to a slow client attack. # # For a graphical representation of how the request buffer works see [architecture.md](https://github.com/puma/puma/blob/main/docs/architecture.md). # # The method checks to see if it has the full header and body with # the `Puma::Client#try_to_finish` method. If the full request has been sent, # then the request is passed to the ThreadPool (`@thread_pool << client`) # so that a "worker thread" can pick up the request and begin to execute application logic. # The Client is then removed from the reactor (return `true`). # # If a client object times out, a 408 response is written, its connection is closed, # and the object is removed from the reactor (return `true`). # # If the Reactor is shutting down, all Clients are either timed out or passed to the # ThreadPool, depending on their current state (#can_close?). # # Otherwise, if the full request is not ready then the client will remain in the reactor # (return `false`). When the client sends more data to the socket the `Puma::Client` object # will wake up and again be checked to see if it's ready to be passed to the thread pool. def reactor_wakeup(client) shutdown = !@queue_requests if client.try_to_finish || (shutdown && !client.can_close?) @thread_pool << client elsif shutdown || client.timeout == 0 client.timeout! else client.set_timeout(@first_data_timeout) false end rescue StandardError => e client_error(e, client) close_client_safely(client) true end def handle_servers @env_set_http_version = Object.const_defined?(:Rack) && ::Rack.respond_to?(:release) && Gem::Version.new(::Rack.release) < Gem::Version.new('3.1.0') begin check = @check sockets = [check] + @binder.ios pool = @thread_pool queue_requests = @queue_requests drain = options[:drain_on_shutdown] ? 0 : nil addr_send_name, addr_value = case options[:remote_address] when :value [:peerip=, options[:remote_address_value]] when :header [:remote_addr_header=, options[:remote_address_header]] when :proxy_protocol [:expect_proxy_proto=, options[:remote_address_proxy_protocol]] else [nil, nil] end while @status == :run || (drain && shutting_down?) begin ios = IO.select sockets, nil, nil, (shutting_down? ? 0 : @idle_timeout) unless ios unless shutting_down? @idle_timeout_reached = true if @clustered @worker_write << "#{PipeRequest::PIPE_IDLE}#{Process.pid}\n" rescue nil next else @log_writer.log "- Idle timeout reached" @status = :stop end end break end if @idle_timeout_reached && @clustered @idle_timeout_reached = false @worker_write << "#{PipeRequest::PIPE_IDLE}#{Process.pid}\n" rescue nil end ios.first.each do |sock| if sock == check break if handle_check else # if ThreadPool out_of_band code is running, we don't want to add # clients until the code is finished. pool.wait_while_out_of_band_running # A well rested herd (cluster) runs faster if @cluster_accept_loop_delay.on? && (busy_threads_plus_todo = pool.busy_threads) > 0 delay = @cluster_accept_loop_delay.calculate( max_threads: @max_threads, busy_threads_plus_todo: busy_threads_plus_todo ) sleep(delay) end io = begin sock.accept_nonblock rescue IO::WaitReadable next end drain += 1 if shutting_down? client = new_client(io, sock) client.send(addr_send_name, addr_value) if addr_value pool << client end end rescue IOError, Errno::EBADF # In the case that any of the sockets are unexpectedly close. raise rescue StandardError => e @log_writer.unknown_error e, nil, "Listen loop" end end @log_writer.debug "Drained #{drain} additional connections." if drain @events.fire :state, @status if queue_requests @queue_requests = false @reactor.shutdown end graceful_shutdown if @status == :stop || @status == :restart rescue Exception => e @log_writer.unknown_error e, nil, "Exception handling servers" ensure # Errno::EBADF is infrequently raised [@check, @notify].each do |io| begin io.close unless io.closed? rescue Errno::EBADF end end @notify = nil @check = nil end @events.fire :state, :done end # :nodoc: def new_client(io, sock) client = Client.new(io, @binder.env(sock)) client.listener = sock client.http_content_length_limit = @http_content_length_limit client end # :nodoc: def handle_check cmd = @check.read(1) case cmd when STOP_COMMAND @status = :stop return true when HALT_COMMAND @status = :halt return true when RESTART_COMMAND @status = :restart return true end false end # Given a connection on +client+, handle the incoming requests, # or queue the connection in the Reactor if no request is available. # # This method is called from a ThreadPool worker thread. # # This method supports HTTP Keep-Alive so it may, depending on if the client # indicates that it supports keep alive, wait for another request before # returning. # # Return true if one or more requests were processed. def process_client(client) close_socket = true requests = 0 begin if @queue_requests && !client.eagerly_finish client.set_timeout(@first_data_timeout) if @reactor.add client close_socket = false return false end end with_force_shutdown(client) do client.finish(@first_data_timeout) end can_loop = true while can_loop can_loop = false @requests_count += 1 case handle_request(client, requests + 1) when :close when :async close_socket = false when :keep_alive requests += 1 client.reset # This indicates data exists in the client read buffer and there may be # additional requests on it, so process them next_request_ready = if client.has_back_to_back_requests? with_force_shutdown(client) { client.process_back_to_back_requests } else with_force_shutdown(client) { client.eagerly_finish } end if next_request_ready # When Puma has spare threads, allow this one to be monopolized # Perf optimization for https://github.com/puma/puma/issues/3788 if @thread_pool.waiting > 0 can_loop = true else @thread_pool << client close_socket = false end elsif @queue_requests client.set_timeout @persistent_timeout if @reactor.add client close_socket = false end end end end true rescue StandardError => e client_error(e, client, requests) # The ensure tries to close +client+ down requests > 0 ensure client.io_buffer.reset close_client_safely(client) if close_socket end end # :nodoc: def close_client_safely(client) client.close rescue IOError, SystemCallError # Already closed rescue MiniSSL::SSLError => e @log_writer.ssl_error e, client.io rescue StandardError => e @log_writer.unknown_error e, nil, "Client" end # Triggers a client timeout if the thread-pool shuts down # during execution of the provided block. def with_force_shutdown(client, &block) @thread_pool.with_force_shutdown(&block) rescue ThreadPool::ForceShutdown client.timeout! end # :nocov: # Handle various error types thrown by Client I/O operations. def client_error(e, client, requests = 1) # Swallow, do not log return if [ConnectionError, EOFError].include?(e.class) case e when MiniSSL::SSLError lowlevel_error(e, client.env) @log_writer.ssl_error e, client.io when HttpParserError response_to_error(client, requests, e, 400) @log_writer.parse_error e, client when HttpParserError501 response_to_error(client, requests, e, 501) @log_writer.parse_error e, client else response_to_error(client, requests, e, 500) @log_writer.unknown_error e, nil, "Read" end end # A fallback rack response if +@app+ raises as exception. # def lowlevel_error(e, env, status=500) if handler = options[:lowlevel_error_handler] if handler.arity == 1 return handler.call(e) elsif handler.arity == 2 return handler.call(e, env) else return handler.call(e, env, status) end end if @leak_stack_on_error backtrace = e.backtrace.nil? ? '<no backtrace available>' : e.backtrace.join("\n") [status, {}, ["Puma caught this error: #{e.message} (#{e.class})\n#{backtrace}"]] else [status, {}, [""]] end end def response_to_error(client, requests, err, status_code) status, headers, res_body = lowlevel_error(err, client.env, status_code) prepare_response(status, headers, res_body, requests, client) end private :response_to_error # Wait for all outstanding requests to finish. # def graceful_shutdown if options[:shutdown_debug] threads = Thread.list total = threads.size pid = Process.pid $stdout.syswrite "#{pid}: === Begin thread backtrace dump ===\n" threads.each_with_index do |t,i| $stdout.syswrite "#{pid}: Thread #{i+1}/#{total}: #{t.inspect}\n" $stdout.syswrite "#{pid}: #{t.backtrace.join("\n#{pid}: ")}\n\n" end $stdout.syswrite "#{pid}: === End thread backtrace dump ===\n" end if @status != :restart @binder.close end if @thread_pool if timeout = options[:force_shutdown_after] @thread_pool.shutdown timeout.to_f else @thread_pool.shutdown end end end def notify_safely(message) @notify << message rescue IOError, NoMethodError, Errno::EPIPE, Errno::EBADF # The server, in another thread, is shutting down rescue RuntimeError => e # Temporary workaround for https://bugs.ruby-lang.org/issues/13239 if e.message.include?('IOError') # ignore else raise e end end private :notify_safely # Stops the acceptor thread and then causes the worker threads to finish # off the request queue before finally exiting. def stop(sync=false) notify_safely(STOP_COMMAND) @thread.join if @thread && sync end def halt(sync=false) notify_safely(HALT_COMMAND) @thread.join if @thread && sync end def begin_restart(sync=false) notify_safely(RESTART_COMMAND) @thread.join if @thread && sync end def shutting_down? @status == :stop || @status == :restart end # List of methods invoked by #stats. # @version 5.0.0 STAT_METHODS = [ :backlog, :running, :pool_capacity, :busy_threads, :backlog_max, :max_threads, :requests_count, :reactor_max, ].freeze # Returns a hash of stats about the running server for reporting purposes. # @version 5.0.0 # @!attribute [r] stats # @return [Hash] hash containing stat info from `Server` and `ThreadPool` def stats stats = @thread_pool&.stats || {} stats[:max_threads] = @max_threads stats[:requests_count] = @requests_count stats[:reactor_max] = @reactor.reactor_max if @reactor reset_max stats end def reset_max @reactor.reactor_max = 0 if @reactor @thread_pool&.reset_max end # below are 'delegations' to binder # remove in Puma 7? def add_tcp_listener(host, port, optimize_for_latency = true, backlog = 1024) @binder.add_tcp_listener host, port, optimize_for_latency, backlog end def add_ssl_listener(host, port, ctx, optimize_for_latency = true, backlog = 1024) @binder.add_ssl_listener host, port, ctx, optimize_for_latency, backlog end def add_unix_listener(path, umask = nil, mode = nil, backlog = 1024) @binder.add_unix_listener path, umask, mode, backlog end # @!attribute [r] connected_ports def connected_ports @binder.connected_ports end end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false
puma/puma
https://github.com/puma/puma/blob/5937d8953a154d69cab13887cc361eef9d7df2a4/lib/puma/request.rb
lib/puma/request.rb
# frozen_string_literal: true module Puma #β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” DO NOT USE β€” this class is for internal use only β€”β€”β€” # The methods here are included in Server, but are separated into this file. # All the methods here pertain to passing the request to the app, then # writing the response back to the client. # # None of the methods here are called externally, with the exception of # #handle_request, which is called in Server#process_client. # @version 5.0.3 # module Request # :nodoc: # Single element array body: smaller bodies are written to io_buffer first, # then a single write from io_buffer. Larger sizes are written separately. # Also fixes max size of chunked file body read. BODY_LEN_MAX = 1_024 * 256 # File body: smaller bodies are combined with io_buffer, then written to # socket. Larger bodies are written separately using `copy_stream` IO_BODY_MAX = 1_024 * 64 # Array body: elements are collected in io_buffer. When io_buffer's size # exceeds value, they are written to the socket. IO_BUFFER_LEN_MAX = 1_024 * 512 SOCKET_WRITE_ERR_MSG = "Socket timeout writing data" CUSTOM_STAT = 'CUSTOM' include Puma::Const # Takes the request contained in +client+, invokes the Rack application to construct # the response and writes it back to +client.io+. # # It'll return +:close+ when the connection is closed, this doesn't mean # that the response wasn't successful. # # It'll return +:keep_alive+ if the connection is a pipeline or keep-alive connection. # Which may contain additional requests. # # It'll return +:async+ if the connection remains open but will be handled # elsewhere, i.e. the connection has been hijacked by the Rack application. # # Finally, it'll return +true+ on keep-alive connections. # @param client [Puma::Client] # @param requests [Integer] # @return [:close, :keep_alive, :async] def handle_request(client, requests) env = client.env io_buffer = client.io_buffer socket = client.io # io may be a MiniSSL::Socket app_body = nil error = nil return :close if closed_socket?(socket) if client.http_content_length_limit_exceeded return prepare_response(413, {}, ["Payload Too Large"], requests, client) end normalize_env env, client env[PUMA_SOCKET] = socket if env[HTTPS_KEY] && socket.peercert env[PUMA_PEERCERT] = socket.peercert end env[HIJACK_P] = true env[HIJACK] = client.method :full_hijack env[RACK_INPUT] = client.body env[RACK_URL_SCHEME] ||= default_server_port(env) == PORT_443 ? HTTPS : HTTP if @early_hints env[EARLY_HINTS] = lambda { |headers| begin unless (str = str_early_hints headers).empty? fast_write_str socket, "HTTP/1.1 103 Early Hints\r\n#{str}\r\n" end rescue ConnectionError => e @log_writer.debug_error e # noop, if we lost the socket we just won't send the early hints end } end req_env_post_parse env # A rack extension. If the app writes #call'ables to this # array, we will invoke them when the request is done. # env[RACK_AFTER_REPLY] ||= [] env[RACK_RESPONSE_FINISHED] ||= [] begin if @supported_http_methods == :any || @supported_http_methods.key?(env[REQUEST_METHOD]) status, headers, app_body = @thread_pool.with_force_shutdown do @app.call(env) end else @log_writer.log "Unsupported HTTP method used: #{env[REQUEST_METHOD]}" status, headers, app_body = [501, {}, ["#{env[REQUEST_METHOD]} method is not supported"]] end # app_body needs to always be closed, hold value in case lowlevel_error # is called res_body = app_body # full hijack, app called env['rack.hijack'] return :async if client.hijacked status = status.to_i if status == -1 unless headers.empty? and res_body == [] raise "async response must have empty headers and body" end return :async end rescue ThreadPool::ForceShutdown => error @log_writer.unknown_error error, client, "Rack app" @log_writer.log "Detected force shutdown of a thread" status, headers, res_body = lowlevel_error(error, env, 503) rescue Exception => error @log_writer.unknown_error error, client, "Rack app" status, headers, res_body = lowlevel_error(error, env, 500) end prepare_response(status, headers, res_body, requests, client) ensure io_buffer.reset uncork_socket client.io app_body.close if app_body.respond_to? :close client&.tempfile_close if after_reply = env[RACK_AFTER_REPLY] after_reply.each do |o| begin o.call rescue StandardError => e @log_writer.debug_error e end end end if response_finished = env[RACK_RESPONSE_FINISHED] response_finished.reverse_each do |o| begin o.call(env, status, headers, error) rescue StandardError => e @log_writer.debug_error e end end end end # Assembles the headers and prepares the body for actually sending the # response via `#fast_write_response`. # # @param status [Integer] the status returned by the Rack application # @param headers [Hash] the headers returned by the Rack application # @param res_body [Array] the body returned by the Rack application or # a call to `Server#lowlevel_error` # @param requests [Integer] number of inline requests handled # @param client [Puma::Client] # @return [:close, :keep_alive, :async] def prepare_response(status, headers, res_body, requests, client) env = client.env socket = client.io io_buffer = client.io_buffer return :close if closed_socket?(socket) # Close the connection after a reasonable number of inline requests force_keep_alive = @enable_keep_alives && client.requests_served < @max_keep_alive resp_info = str_headers(env, status, headers, res_body, io_buffer, force_keep_alive) close_body = false response_hijack = nil content_length = resp_info[:content_length] keep_alive = resp_info[:keep_alive] if res_body.respond_to?(:each) && !resp_info[:response_hijack] # below converts app_body into body, dependent on app_body's characteristics, and # content_length will be set if it can be determined if !content_length && !resp_info[:transfer_encoding] && status != 204 if res_body.respond_to?(:to_ary) && (array_body = res_body.to_ary) && array_body.is_a?(Array) body = array_body.compact content_length = body.sum(&:bytesize) elsif res_body.is_a?(File) && res_body.respond_to?(:size) body = res_body content_length = body.size elsif res_body.respond_to?(:to_path) && (fn = res_body.to_path) && File.readable?(fn) body = File.open fn, 'rb' content_length = body.size close_body = true else body = res_body end elsif !res_body.is_a?(::File) && res_body.respond_to?(:to_path) && (fn = res_body.to_path) && File.readable?(fn = res_body.to_path) body = File.open fn, 'rb' content_length = body.size close_body = true elsif !res_body.is_a?(::File) && res_body.respond_to?(:filename) && res_body.respond_to?(:bytesize) && File.readable?(fn = res_body.filename) # Sprockets::Asset content_length = res_body.bytesize unless content_length if (body_str = res_body.to_hash[:source]) body = [body_str] else # avoid each and use a File object body = File.open fn, 'rb' close_body = true end else body = res_body end else # partial hijack, from Rack spec: # Servers must ignore the body part of the response tuple when the # rack.hijack response header is present. response_hijack = resp_info[:response_hijack] || res_body end line_ending = LINE_END cork_socket socket if resp_info[:no_body] # 101 (Switching Protocols) doesn't return here or have content_length, # it should be using `response_hijack` unless status == 101 if content_length && status != 204 io_buffer.append CONTENT_LENGTH_S, content_length.to_s, line_ending end io_buffer << LINE_END fast_write_str socket, io_buffer.read_and_reset socket.flush return keep_alive ? :keep_alive : :close end else if content_length io_buffer.append CONTENT_LENGTH_S, content_length.to_s, line_ending chunked = false elsif !response_hijack && resp_info[:allow_chunked] io_buffer << TRANSFER_ENCODING_CHUNKED chunked = true end end io_buffer << line_ending # partial hijack, we write headers, then hand the socket to the app via # response_hijack.call if response_hijack fast_write_str socket, io_buffer.read_and_reset uncork_socket socket response_hijack.call socket return :async end fast_write_response socket, body, io_buffer, chunked, content_length.to_i body.close if close_body # if we're shutting down, close keep_alive connections !shutting_down? && keep_alive ? :keep_alive : :close end HTTP_ON_VALUES = { "on" => true, HTTPS => true } private_constant :HTTP_ON_VALUES # @param env [Hash] see Puma::Client#env, from request # @return [Puma::Const::PORT_443,Puma::Const::PORT_80] # def default_server_port(env) if HTTP_ON_VALUES[env[HTTPS_KEY]] || env[HTTP_X_FORWARDED_PROTO]&.start_with?(HTTPS) || env[HTTP_X_FORWARDED_SCHEME] == HTTPS || env[HTTP_X_FORWARDED_SSL] == "on" PORT_443 else PORT_80 end end # Used to write 'early hints', 'no body' responses, 'hijacked' responses, # and body segments (called by `fast_write_response`). # Writes a string to a socket (normally `Client#io`) using `write_nonblock`. # Large strings may not be written in one pass, especially if `io` is a # `MiniSSL::Socket`. # @param socket [#write_nonblock] the request/response socket # @param str [String] the string written to the io # @raise [ConnectionError] # def fast_write_str(socket, str) n = 0 byte_size = str.bytesize while n < byte_size begin n += socket.write_nonblock(n.zero? ? str : str.byteslice(n..-1)) rescue Errno::EAGAIN, Errno::EWOULDBLOCK unless socket.wait_writable WRITE_TIMEOUT raise ConnectionError, SOCKET_WRITE_ERR_MSG end retry rescue Errno::EPIPE, SystemCallError, IOError raise ConnectionError, SOCKET_WRITE_ERR_MSG end end end # Used to write headers and body. # Writes to a socket (normally `Client#io`) using `#fast_write_str`. # Accumulates `body` items into `io_buffer`, then writes to socket. # @param socket [#write] the response socket # @param body [Enumerable, File] the body object # @param io_buffer [Puma::IOBuffer] contains headers # @param chunked [Boolean] # @paramn content_length [Integer # @raise [ConnectionError] # def fast_write_response(socket, body, io_buffer, chunked, content_length) if body.is_a?(::File) && body.respond_to?(:read) if chunked # would this ever happen? while chunk = body.read(BODY_LEN_MAX) io_buffer.append chunk.bytesize.to_s(16), LINE_END, chunk, LINE_END end fast_write_str socket, CLOSE_CHUNKED else if content_length <= IO_BODY_MAX io_buffer.write body.read(content_length) fast_write_str socket, io_buffer.read_and_reset else fast_write_str socket, io_buffer.read_and_reset IO.copy_stream body, socket end end elsif body.is_a?(::Array) && body.length == 1 body_first = nil # using body_first = body.first causes issues? body.each { |str| body_first ||= str } if body_first.is_a?(::String) && body_first.bytesize < BODY_LEN_MAX # smaller body, write to io_buffer first io_buffer.write body_first fast_write_str socket, io_buffer.read_and_reset else # large body, write both header & body to socket fast_write_str socket, io_buffer.read_and_reset fast_write_str socket, body_first end elsif body.is_a?(::Array) # for array bodies, flush io_buffer to socket when size is greater than # IO_BUFFER_LEN_MAX if chunked body.each do |part| next if (byte_size = part.bytesize).zero? io_buffer.append byte_size.to_s(16), LINE_END, part, LINE_END if io_buffer.length > IO_BUFFER_LEN_MAX fast_write_str socket, io_buffer.read_and_reset end end io_buffer.write CLOSE_CHUNKED else body.each do |part| next if part.bytesize.zero? io_buffer.write part if io_buffer.length > IO_BUFFER_LEN_MAX fast_write_str socket, io_buffer.read_and_reset end end end # may write last body part for non-chunked, also headers if array is empty fast_write_str(socket, io_buffer.read_and_reset) unless io_buffer.length.zero? else # for enum bodies if chunked empty_body = true body.each do |part| next if part.nil? || (byte_size = part.bytesize).zero? empty_body = false io_buffer.append byte_size.to_s(16), LINE_END, part, LINE_END fast_write_str socket, io_buffer.read_and_reset end if empty_body io_buffer << CLOSE_CHUNKED fast_write_str socket, io_buffer.read_and_reset else fast_write_str socket, CLOSE_CHUNKED end else fast_write_str socket, io_buffer.read_and_reset body.each do |part| next if part.bytesize.zero? fast_write_str socket, part end end end socket.flush rescue Errno::EAGAIN, Errno::EWOULDBLOCK raise ConnectionError, SOCKET_WRITE_ERR_MSG rescue Errno::EPIPE, SystemCallError, IOError raise ConnectionError, SOCKET_WRITE_ERR_MSG end private :fast_write_str, :fast_write_response # Given a Hash +env+ for the request read from +client+, add # and fixup keys to comply with Rack's env guidelines. # @param env [Hash] see Puma::Client#env, from request # @param client [Puma::Client] only needed for Client#peerip # def normalize_env(env, client) if host = env[HTTP_HOST] # host can be a hostname, ipv4 or bracketed ipv6. Followed by an optional port. if colon = host.rindex("]:") # IPV6 with port env[SERVER_NAME] = host[0, colon+1] env[SERVER_PORT] = host[colon+2, host.bytesize] elsif !host.start_with?("[") && colon = host.index(":") # not hostname or IPV4 with port env[SERVER_NAME] = host[0, colon] env[SERVER_PORT] = host[colon+1, host.bytesize] else env[SERVER_NAME] = host env[SERVER_PORT] = default_server_port(env) end else env[SERVER_NAME] = LOCALHOST env[SERVER_PORT] = default_server_port(env) end unless env[REQUEST_PATH] # it might be a dumbass full host request header uri = begin URI.parse(env[REQUEST_URI]) rescue URI::InvalidURIError raise Puma::HttpParserError end env[REQUEST_PATH] = uri.path # A nil env value will cause a LintError (and fatal errors elsewhere), # so only set the env value if there actually is a value. env[QUERY_STRING] = uri.query if uri.query end env[PATH_INFO] = env[REQUEST_PATH].to_s # #to_s in case it's nil # From https://www.ietf.org/rfc/rfc3875 : # "Script authors should be aware that the REMOTE_ADDR and # REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9) # may not identify the ultimate source of the request. # They identify the client for the immediate request to the # server; that client may be a proxy, gateway, or other # intermediary acting on behalf of the actual source client." # unless env.key?(REMOTE_ADDR) begin addr = client.peerip rescue Errno::ENOTCONN # Client disconnects can result in an inability to get the # peeraddr from the socket; default to unspec. if client.peer_family == Socket::AF_INET6 addr = UNSPECIFIED_IPV6 else addr = UNSPECIFIED_IPV4 end end # Set unix socket addrs to localhost if addr.empty? if client.peer_family == Socket::AF_INET6 addr = LOCALHOST_IPV6 else addr = LOCALHOST_IPV4 end end env[REMOTE_ADDR] = addr end # The legacy HTTP_VERSION header can be sent as a client header. # Rack v4 may remove using HTTP_VERSION. If so, remove this line. env[HTTP_VERSION] = env[SERVER_PROTOCOL] if @env_set_http_version end private :normalize_env # @param header_key [#to_s] # @return [Boolean] # def illegal_header_key?(header_key) !!(ILLEGAL_HEADER_KEY_REGEX =~ header_key.to_s) end # @param header_value [#to_s] # @return [Boolean] # def illegal_header_value?(header_value) !!(ILLEGAL_HEADER_VALUE_REGEX =~ header_value.to_s) end private :illegal_header_key?, :illegal_header_value? # Fixup any headers with `,` in the name to have `_` now. We emit # headers with `,` in them during the parse phase to avoid ambiguity # with the `-` to `_` conversion for critical headers. But here for # compatibility, we'll convert them back. This code is written to # avoid allocation in the common case (ie there are no headers # with `,` in their names), that's why it has the extra conditionals. # # @note If a normalized version of a `,` header already exists, we ignore # the `,` version. This prevents clobbering headers managed by proxies # but not by clients (Like X-Forwarded-For). # # @param env [Hash] see Puma::Client#env, from request, modifies in place # @version 5.0.3 # def req_env_post_parse(env) to_delete = nil to_add = nil env.each do |k,v| if k.start_with?("HTTP_") && k.include?(",") && !UNMASKABLE_HEADERS.key?(k) if to_delete to_delete << k else to_delete = [k] end new_k = k.tr(",", "_") if env.key?(new_k) next end unless to_add to_add = {} end to_add[new_k] = v end end if to_delete # rubocop:disable Style/SafeNavigation to_delete.each { |k| env.delete(k) } end if to_add env.merge! to_add end end private :req_env_post_parse # Used in the lambda for env[ `Puma::Const::EARLY_HINTS` ] # @param headers [Hash] the headers returned by the Rack application # @return [String] # @version 5.0.3 # def str_early_hints(headers) eh_str = +"" headers.each_pair do |k, vs| next if illegal_header_key?(k) if vs.respond_to?(:to_s) && !vs.to_s.empty? vs.to_s.split(NEWLINE).each do |v| next if illegal_header_value?(v) eh_str << "#{k}: #{v}\r\n" end elsif !(vs.to_s.empty? || !illegal_header_value?(vs)) eh_str << "#{k}: #{vs}\r\n" end end eh_str.freeze end private :str_early_hints # @param status [Integer] status from the app # @return [String] the text description from Puma::HTTP_STATUS_CODES # def fetch_status_code(status) HTTP_STATUS_CODES.fetch(status) { CUSTOM_STAT } end private :fetch_status_code # Processes and write headers to the IOBuffer. # @param env [Hash] see Puma::Client#env, from request # @param status [Integer] the status returned by the Rack application # @param headers [Hash] the headers returned by the Rack application # @param content_length [Integer,nil] content length if it can be determined from the # response body # @param io_buffer [Puma::IOBuffer] modified inn place # @param force_keep_alive [Boolean] 'anded' with keep_alive, based on system # status and `@max_keep_alive` # @return [Hash] resp_info # @version 5.0.3 # def str_headers(env, status, headers, res_body, io_buffer, force_keep_alive) line_ending = LINE_END colon = COLON resp_info = {} resp_info[:no_body] = env[REQUEST_METHOD] == HEAD http_11 = env[SERVER_PROTOCOL] == HTTP_11 if http_11 resp_info[:allow_chunked] = true resp_info[:keep_alive] = env.fetch(HTTP_CONNECTION, "").downcase != CLOSE # An optimization. The most common response is 200, so we can # reply with the proper 200 status without having to compute # the response header. # if status == 200 io_buffer << HTTP_11_200 else io_buffer.append "#{HTTP_11} #{status} ", fetch_status_code(status), line_ending resp_info[:no_body] ||= status < 200 || STATUS_WITH_NO_ENTITY_BODY[status] end else resp_info[:allow_chunked] = false resp_info[:keep_alive] = env.fetch(HTTP_CONNECTION, "").downcase == KEEP_ALIVE # Same optimization as above for HTTP/1.1 # if status == 200 io_buffer << HTTP_10_200 else io_buffer.append "HTTP/1.0 #{status} ", fetch_status_code(status), line_ending resp_info[:no_body] ||= status < 200 || STATUS_WITH_NO_ENTITY_BODY[status] end end # regardless of what the client wants, we always close the connection # if running without request queueing resp_info[:keep_alive] &&= @queue_requests # see prepare_response resp_info[:keep_alive] &&= force_keep_alive resp_info[:response_hijack] = nil headers.each do |k, vs| next if illegal_header_key?(k) case k.downcase when CONTENT_LENGTH2 next if illegal_header_value?(vs) # nil.to_i is 0, nil&.to_i is nil resp_info[:content_length] = vs&.to_i next when TRANSFER_ENCODING resp_info[:allow_chunked] = false resp_info[:content_length] = nil resp_info[:transfer_encoding] = vs when HIJACK resp_info[:response_hijack] = vs next when BANNED_HEADER_KEY next end ary = if vs.is_a?(::Array) && !vs.empty? vs elsif vs.respond_to?(:to_s) && !vs.to_s.empty? vs.to_s.split NEWLINE else nil end if ary ary.each do |v| next if illegal_header_value?(v) io_buffer.append k.downcase, colon, v, line_ending end else io_buffer.append k.downcase, colon, line_ending end end # HTTP/1.1 & 1.0 assume different defaults: # - HTTP 1.0 assumes the connection will be closed if not specified # - HTTP 1.1 assumes the connection will be kept alive if not specified. # Only set the header if we're doing something which is not the default # for this protocol version if http_11 io_buffer << CONNECTION_CLOSE if !resp_info[:keep_alive] else io_buffer << CONNECTION_KEEP_ALIVE if resp_info[:keep_alive] end resp_info end private :str_headers end end
ruby
BSD-3-Clause
5937d8953a154d69cab13887cc361eef9d7df2a4
2026-01-04T15:39:19.886485Z
false