rack 1.0.1 → 2.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +829 -0
  3. data/CONTRIBUTING.md +136 -0
  4. data/{COPYING → MIT-LICENSE} +4 -2
  5. data/README.rdoc +355 -0
  6. data/Rakefile +64 -98
  7. data/SPEC.rdoc +292 -0
  8. data/bin/rackup +3 -174
  9. data/contrib/rack.png +0 -0
  10. data/contrib/rack.svg +150 -0
  11. data/contrib/rack_logo.svg +164 -111
  12. data/contrib/rdoc.css +412 -0
  13. data/example/lobster.ru +2 -0
  14. data/example/protectedlobster.rb +4 -2
  15. data/example/protectedlobster.ru +3 -1
  16. data/lib/rack/auth/abstract/handler.rb +7 -5
  17. data/lib/rack/auth/abstract/request.rb +12 -2
  18. data/lib/rack/auth/basic.rb +6 -4
  19. data/lib/rack/auth/digest/md5.rb +20 -13
  20. data/lib/rack/auth/digest/nonce.rb +6 -4
  21. data/lib/rack/auth/digest/params.rb +11 -12
  22. data/lib/rack/auth/digest/request.rb +15 -12
  23. data/lib/rack/body_proxy.rb +45 -0
  24. data/lib/rack/builder.rb +213 -19
  25. data/lib/rack/cascade.rb +50 -18
  26. data/lib/rack/chunked.rb +95 -27
  27. data/lib/rack/common_logger.rb +84 -0
  28. data/lib/rack/conditional_get.rb +83 -0
  29. data/lib/rack/config.rb +22 -0
  30. data/lib/rack/content_length.rb +19 -10
  31. data/lib/rack/content_type.rb +12 -5
  32. data/lib/rack/core_ext/regexp.rb +14 -0
  33. data/lib/rack/deflater.rb +90 -42
  34. data/lib/rack/directory.rb +118 -72
  35. data/lib/rack/etag.rb +77 -0
  36. data/lib/rack/events.rb +153 -0
  37. data/lib/rack/file.rb +4 -85
  38. data/lib/rack/files.rb +218 -0
  39. data/lib/rack/handler/cgi.rb +22 -24
  40. data/lib/rack/handler/fastcgi.rb +34 -24
  41. data/lib/rack/handler/lsws.rb +16 -15
  42. data/lib/rack/handler/scgi.rb +38 -29
  43. data/lib/rack/handler/thin.rb +23 -7
  44. data/lib/rack/handler/webrick.rb +95 -37
  45. data/lib/rack/handler.rb +49 -14
  46. data/lib/rack/head.rb +19 -13
  47. data/lib/rack/lint.rb +466 -217
  48. data/lib/rack/lobster.rb +19 -14
  49. data/lib/rack/lock.rb +24 -8
  50. data/lib/rack/logger.rb +20 -0
  51. data/lib/rack/media_type.rb +53 -0
  52. data/lib/rack/method_override.rb +52 -0
  53. data/lib/rack/mime.rb +652 -171
  54. data/lib/rack/mock.rb +203 -64
  55. data/lib/rack/multipart/generator.rb +97 -0
  56. data/lib/rack/multipart/parser.rb +440 -0
  57. data/lib/rack/multipart/uploaded_file.rb +41 -0
  58. data/lib/rack/multipart.rb +64 -0
  59. data/lib/rack/null_logger.rb +39 -0
  60. data/lib/rack/query_parser.rb +266 -0
  61. data/lib/rack/recursive.rb +18 -11
  62. data/lib/rack/reloader.rb +13 -5
  63. data/lib/rack/request.rb +607 -191
  64. data/lib/rack/response.rb +245 -110
  65. data/lib/rack/rewindable_input.rb +15 -21
  66. data/lib/rack/runtime.rb +34 -0
  67. data/lib/rack/sendfile.rb +192 -0
  68. data/lib/rack/server.rb +466 -0
  69. data/lib/rack/session/abstract/id.rb +449 -68
  70. data/lib/rack/session/cookie.rb +159 -47
  71. data/lib/rack/session/memcache.rb +4 -103
  72. data/lib/rack/session/pool.rb +39 -49
  73. data/lib/rack/show_exceptions.rb +390 -0
  74. data/lib/rack/{showstatus.rb → show_status.rb} +21 -14
  75. data/lib/rack/static.rb +164 -14
  76. data/lib/rack/tempfile_reaper.rb +22 -0
  77. data/lib/rack/urlmap.rb +60 -18
  78. data/lib/rack/utils.rb +508 -277
  79. data/lib/rack/version.rb +29 -0
  80. data/lib/rack.rb +85 -34
  81. data/rack.gemspec +43 -51
  82. metadata +119 -207
  83. data/KNOWN-ISSUES +0 -18
  84. data/RDOX +0 -428
  85. data/README +0 -364
  86. data/SPEC +0 -164
  87. data/lib/rack/adapter/camping.rb +0 -22
  88. data/lib/rack/auth/openid.rb +0 -480
  89. data/lib/rack/commonlogger.rb +0 -61
  90. data/lib/rack/conditionalget.rb +0 -47
  91. data/lib/rack/handler/evented_mongrel.rb +0 -8
  92. data/lib/rack/handler/mongrel.rb +0 -87
  93. data/lib/rack/handler/swiftiplied_mongrel.rb +0 -8
  94. data/lib/rack/methodoverride.rb +0 -27
  95. data/lib/rack/showexceptions.rb +0 -349
  96. data/test/cgi/lighttpd.conf +0 -20
  97. data/test/cgi/test +0 -9
  98. data/test/cgi/test.fcgi +0 -8
  99. data/test/cgi/test.ru +0 -7
  100. data/test/multipart/binary +0 -0
  101. data/test/multipart/empty +0 -10
  102. data/test/multipart/ie +0 -6
  103. data/test/multipart/nested +0 -10
  104. data/test/multipart/none +0 -9
  105. data/test/multipart/semicolon +0 -6
  106. data/test/multipart/text +0 -10
  107. data/test/spec_rack_auth_basic.rb +0 -73
  108. data/test/spec_rack_auth_digest.rb +0 -226
  109. data/test/spec_rack_auth_openid.rb +0 -84
  110. data/test/spec_rack_builder.rb +0 -84
  111. data/test/spec_rack_camping.rb +0 -51
  112. data/test/spec_rack_cascade.rb +0 -50
  113. data/test/spec_rack_cgi.rb +0 -89
  114. data/test/spec_rack_chunked.rb +0 -62
  115. data/test/spec_rack_commonlogger.rb +0 -32
  116. data/test/spec_rack_conditionalget.rb +0 -41
  117. data/test/spec_rack_content_length.rb +0 -43
  118. data/test/spec_rack_content_type.rb +0 -30
  119. data/test/spec_rack_deflater.rb +0 -127
  120. data/test/spec_rack_directory.rb +0 -61
  121. data/test/spec_rack_fastcgi.rb +0 -89
  122. data/test/spec_rack_file.rb +0 -75
  123. data/test/spec_rack_handler.rb +0 -43
  124. data/test/spec_rack_head.rb +0 -30
  125. data/test/spec_rack_lint.rb +0 -521
  126. data/test/spec_rack_lobster.rb +0 -45
  127. data/test/spec_rack_lock.rb +0 -38
  128. data/test/spec_rack_methodoverride.rb +0 -60
  129. data/test/spec_rack_mock.rb +0 -157
  130. data/test/spec_rack_mongrel.rb +0 -189
  131. data/test/spec_rack_recursive.rb +0 -77
  132. data/test/spec_rack_request.rb +0 -504
  133. data/test/spec_rack_response.rb +0 -218
  134. data/test/spec_rack_rewindable_input.rb +0 -118
  135. data/test/spec_rack_session_cookie.rb +0 -82
  136. data/test/spec_rack_session_memcache.rb +0 -240
  137. data/test/spec_rack_session_pool.rb +0 -172
  138. data/test/spec_rack_showexceptions.rb +0 -21
  139. data/test/spec_rack_showstatus.rb +0 -72
  140. data/test/spec_rack_static.rb +0 -37
  141. data/test/spec_rack_thin.rb +0 -91
  142. data/test/spec_rack_urlmap.rb +0 -185
  143. data/test/spec_rack_utils.rb +0 -387
  144. data/test/spec_rack_webrick.rb +0 -130
  145. data/test/testrequest.rb +0 -57
  146. data/test/unregistered_handler/rack/handler/unregistered.rb +0 -7
  147. data/test/unregistered_handler/rack/handler/unregistered_long_one.rb +0 -7
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+
5
+ # = Sendfile
6
+ #
7
+ # The Sendfile middleware intercepts responses whose body is being
8
+ # served from a file and replaces it with a server specific X-Sendfile
9
+ # header. The web server is then responsible for writing the file contents
10
+ # to the client. This can dramatically reduce the amount of work required
11
+ # by the Ruby backend and takes advantage of the web server's optimized file
12
+ # delivery code.
13
+ #
14
+ # In order to take advantage of this middleware, the response body must
15
+ # respond to +to_path+ and the request must include an X-Sendfile-Type
16
+ # header. Rack::Files and other components implement +to_path+ so there's
17
+ # rarely anything you need to do in your application. The X-Sendfile-Type
18
+ # header is typically set in your web servers configuration. The following
19
+ # sections attempt to document
20
+ #
21
+ # === Nginx
22
+ #
23
+ # Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile
24
+ # but requires parts of the filesystem to be mapped into a private URL
25
+ # hierarchy.
26
+ #
27
+ # The following example shows the Nginx configuration required to create
28
+ # a private "/files/" area, enable X-Accel-Redirect, and pass the special
29
+ # X-Sendfile-Type and X-Accel-Mapping headers to the backend:
30
+ #
31
+ # location ~ /files/(.*) {
32
+ # internal;
33
+ # alias /var/www/$1;
34
+ # }
35
+ #
36
+ # location / {
37
+ # proxy_redirect off;
38
+ #
39
+ # proxy_set_header Host $host;
40
+ # proxy_set_header X-Real-IP $remote_addr;
41
+ # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
42
+ #
43
+ # proxy_set_header X-Accel-Mapping /var/www/=/files/;
44
+ #
45
+ # proxy_pass http://127.0.0.1:8080/;
46
+ # }
47
+ #
48
+ # The X-Accel-Mapping header should specify the location on the file system,
49
+ # followed by an equals sign (=), followed name of the private URL pattern
50
+ # that it maps to. The middleware performs a simple substitution on the
51
+ # resulting path.
52
+ #
53
+ # To enable X-Accel-Redirect, you must configure the middleware explicitly:
54
+ #
55
+ # use Rack::Sendfile, "X-Accel-Redirect"
56
+ #
57
+ # For security reasons, the X-Sendfile-Type header from requests is ignored.
58
+ # The sendfile variation must be set via the middleware constructor.
59
+ #
60
+ # See Also: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile
61
+ #
62
+ # === lighttpd
63
+ #
64
+ # Lighttpd has supported some variation of the X-Sendfile header for some
65
+ # time, although only recent version support X-Sendfile in a reverse proxy
66
+ # configuration.
67
+ #
68
+ # $HTTP["host"] == "example.com" {
69
+ # proxy-core.protocol = "http"
70
+ # proxy-core.balancer = "round-robin"
71
+ # proxy-core.backends = (
72
+ # "127.0.0.1:8000",
73
+ # "127.0.0.1:8001",
74
+ # ...
75
+ # )
76
+ #
77
+ # proxy-core.allow-x-sendfile = "enable"
78
+ # proxy-core.rewrite-request = (
79
+ # "X-Sendfile-Type" => (".*" => "X-Sendfile")
80
+ # )
81
+ # }
82
+ #
83
+ # See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore
84
+ #
85
+ # === Apache
86
+ #
87
+ # X-Sendfile is supported under Apache 2.x using a separate module:
88
+ #
89
+ # https://tn123.org/mod_xsendfile/
90
+ #
91
+ # Once the module is compiled and installed, you can enable it using
92
+ # XSendFile config directive:
93
+ #
94
+ # RequestHeader Set X-Sendfile-Type X-Sendfile
95
+ # ProxyPassReverse / http://localhost:8001/
96
+ # XSendFile on
97
+ #
98
+ # === Mapping parameter
99
+ #
100
+ # The third parameter allows for an overriding extension of the
101
+ # X-Accel-Mapping header. Mappings should be provided in tuples of internal to
102
+ # external. The internal values may contain regular expression syntax, they
103
+ # will be matched with case indifference.
104
+ #
105
+ # When X-Accel-Redirect is explicitly enabled via the variation parameter,
106
+ # and no application-level mappings are provided, the middleware will read
107
+ # the X-Accel-Mapping header from the proxy. This allows nginx to control
108
+ # the path mapping without requiring application-level configuration.
109
+ #
110
+ # === Security
111
+ #
112
+ # For security reasons, the X-Sendfile-Type header from HTTP requests is
113
+ # ignored. The sendfile variation must be explicitly configured via the
114
+ # middleware constructor to prevent information disclosure vulnerabilities
115
+ # where attackers could bypass proxy restrictions.
116
+
117
+ class Sendfile
118
+ def initialize(app, variation = nil, mappings = [])
119
+ @app = app
120
+ @variation = variation
121
+ @mappings = mappings.map do |internal, external|
122
+ [/\A#{internal}/i, external]
123
+ end
124
+ end
125
+
126
+ def call(env)
127
+ status, headers, body = @app.call(env)
128
+ if body.respond_to?(:to_path)
129
+ case type = variation(env)
130
+ when 'X-Accel-Redirect'
131
+ path = ::File.expand_path(body.to_path)
132
+ if url = map_accel_path(env, path)
133
+ headers[CONTENT_LENGTH] = '0'
134
+ # '?' must be percent-encoded because it is not query string but a part of path
135
+ headers[type] = ::Rack::Utils.escape_path(url).gsub('?', '%3F')
136
+ obody = body
137
+ body = Rack::BodyProxy.new([]) do
138
+ obody.close if obody.respond_to?(:close)
139
+ end
140
+ else
141
+ env[RACK_ERRORS].puts "X-Accel-Mapping header missing"
142
+ end
143
+ when 'X-Sendfile', 'X-Lighttpd-Send-File'
144
+ path = ::File.expand_path(body.to_path)
145
+ headers[CONTENT_LENGTH] = '0'
146
+ headers[type] = path
147
+ obody = body
148
+ body = Rack::BodyProxy.new([]) do
149
+ obody.close if obody.respond_to?(:close)
150
+ end
151
+ when '', nil
152
+ else
153
+ env[RACK_ERRORS].puts "Unknown x-sendfile variation: #{type.inspect}"
154
+ end
155
+ end
156
+ [status, headers, body]
157
+ end
158
+
159
+ private
160
+
161
+ def variation(env)
162
+ # Note: HTTP_X_SENDFILE_TYPE is intentionally NOT read for security reasons.
163
+ # Attackers could use this header to enable x-accel-redirect and bypass proxy restrictions.
164
+ @variation || env['sendfile.type']
165
+ end
166
+
167
+ def x_accel_mapping(env)
168
+ # Only allow header when:
169
+ # 1. X-Accel-Redirect is explicitly enabled via constructor.
170
+ # 2. No application-level mappings are configured.
171
+ return nil unless @variation =~ /x-accel-redirect/i
172
+ return nil if @mappings.any?
173
+
174
+ env['HTTP_X_ACCEL_MAPPING']
175
+ end
176
+
177
+ def map_accel_path(env, path)
178
+ if mapping = @mappings.find { |internal, _| internal =~ path }
179
+ return path.sub(*mapping)
180
+ elsif mapping = x_accel_mapping(env)
181
+ # Safe to use header: explicit config + no app mappings:
182
+ mapping.split(',').map(&:strip).each do |m|
183
+ internal, external = m.split('=', 2).map(&:strip)
184
+ new_path = path.sub(/\A#{internal}/i, external)
185
+ return new_path unless path == new_path
186
+ end
187
+
188
+ return path
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,466 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+ require 'fileutils'
5
+
6
+ module Rack
7
+
8
+ class Server
9
+ (require_relative 'core_ext/regexp'; using ::Rack::RegexpExtensions) if RUBY_VERSION < '2.4'
10
+
11
+ class Options
12
+ def parse!(args)
13
+ options = {}
14
+ opt_parser = OptionParser.new("", 24, ' ') do |opts|
15
+ opts.banner = "Usage: rackup [ruby options] [rack options] [rackup config]"
16
+
17
+ opts.separator ""
18
+ opts.separator "Ruby options:"
19
+
20
+ lineno = 1
21
+ opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line|
22
+ eval line, TOPLEVEL_BINDING, "-e", lineno
23
+ lineno += 1
24
+ }
25
+
26
+ opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") {
27
+ options[:debug] = true
28
+ }
29
+ opts.on("-w", "--warn", "turn warnings on for your script") {
30
+ options[:warn] = true
31
+ }
32
+ opts.on("-q", "--quiet", "turn off logging") {
33
+ options[:quiet] = true
34
+ }
35
+
36
+ opts.on("-I", "--include PATH",
37
+ "specify $LOAD_PATH (may be used more than once)") { |path|
38
+ (options[:include] ||= []).concat(path.split(":"))
39
+ }
40
+
41
+ opts.on("-r", "--require LIBRARY",
42
+ "require the library, before executing your script") { |library|
43
+ (options[:require] ||= []) << library
44
+ }
45
+
46
+ opts.separator ""
47
+ opts.separator "Rack options:"
48
+ opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line|
49
+ options[:builder] = line
50
+ }
51
+
52
+ opts.on("-s", "--server SERVER", "serve using SERVER (thin/puma/webrick)") { |s|
53
+ options[:server] = s
54
+ }
55
+
56
+ opts.on("-o", "--host HOST", "listen on HOST (default: localhost)") { |host|
57
+ options[:Host] = host
58
+ }
59
+
60
+ opts.on("-p", "--port PORT", "use PORT (default: 9292)") { |port|
61
+ options[:Port] = port
62
+ }
63
+
64
+ opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name|
65
+ name, value = name.split('=', 2)
66
+ value = true if value.nil?
67
+ options[name.to_sym] = value
68
+ }
69
+
70
+ opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e|
71
+ options[:environment] = e
72
+ }
73
+
74
+ opts.on("-D", "--daemonize", "run daemonized in the background") { |d|
75
+ options[:daemonize] = d ? true : false
76
+ }
77
+
78
+ opts.on("-P", "--pid FILE", "file to store PID") { |f|
79
+ options[:pid] = ::File.expand_path(f)
80
+ }
81
+
82
+ opts.separator ""
83
+ opts.separator "Profiling options:"
84
+
85
+ opts.on("--heap HEAPFILE", "Build the application, then dump the heap to HEAPFILE") do |e|
86
+ options[:heapfile] = e
87
+ end
88
+
89
+ opts.on("--profile PROFILE", "Dump CPU or Memory profile to PROFILE (defaults to a tempfile)") do |e|
90
+ options[:profile_file] = e
91
+ end
92
+
93
+ opts.on("--profile-mode MODE", "Profile mode (cpu|wall|object)") do |e|
94
+ { cpu: true, wall: true, object: true }.fetch(e.to_sym) do
95
+ raise OptionParser::InvalidOption, "unknown profile mode: #{e}"
96
+ end
97
+ options[:profile_mode] = e.to_sym
98
+ end
99
+
100
+ opts.separator ""
101
+ opts.separator "Common options:"
102
+
103
+ opts.on_tail("-h", "-?", "--help", "Show this message") do
104
+ puts opts
105
+ puts handler_opts(options)
106
+
107
+ exit
108
+ end
109
+
110
+ opts.on_tail("--version", "Show version") do
111
+ puts "Rack #{Rack.version} (Release: #{Rack.release})"
112
+ exit
113
+ end
114
+ end
115
+
116
+ begin
117
+ opt_parser.parse! args
118
+ rescue OptionParser::InvalidOption => e
119
+ warn e.message
120
+ abort opt_parser.to_s
121
+ end
122
+
123
+ options[:config] = args.last if args.last && !args.last.empty?
124
+ options
125
+ end
126
+
127
+ def handler_opts(options)
128
+ begin
129
+ info = []
130
+ server = Rack::Handler.get(options[:server]) || Rack::Handler.default
131
+ if server && server.respond_to?(:valid_options)
132
+ info << ""
133
+ info << "Server-specific options for #{server.name}:"
134
+
135
+ has_options = false
136
+ server.valid_options.each do |name, description|
137
+ next if /^(Host|Port)[^a-zA-Z]/.match?(name.to_s) # ignore handler's host and port options, we do our own.
138
+ info << " -O %-21s %s" % [name, description]
139
+ has_options = true
140
+ end
141
+ return "" if !has_options
142
+ end
143
+ info.join("\n")
144
+ rescue NameError, LoadError
145
+ return "Warning: Could not find handler specified (#{options[:server] || 'default'}) to determine handler-specific options"
146
+ end
147
+ end
148
+ end
149
+
150
+ # Start a new rack server (like running rackup). This will parse ARGV and
151
+ # provide standard ARGV rackup options, defaulting to load 'config.ru'.
152
+ #
153
+ # Providing an options hash will prevent ARGV parsing and will not include
154
+ # any default options.
155
+ #
156
+ # This method can be used to very easily launch a CGI application, for
157
+ # example:
158
+ #
159
+ # Rack::Server.start(
160
+ # :app => lambda do |e|
161
+ # [200, {'Content-Type' => 'text/html'}, ['hello world']]
162
+ # end,
163
+ # :server => 'cgi'
164
+ # )
165
+ #
166
+ # Further options available here are documented on Rack::Server#initialize
167
+ def self.start(options = nil)
168
+ new(options).start
169
+ end
170
+
171
+ attr_writer :options
172
+
173
+ # Options may include:
174
+ # * :app
175
+ # a rack application to run (overrides :config and :builder)
176
+ # * :builder
177
+ # a string to evaluate a Rack::Builder from
178
+ # * :config
179
+ # a rackup configuration file path to load (.ru)
180
+ # * :environment
181
+ # this selects the middleware that will be wrapped around
182
+ # your application. Default options available are:
183
+ # - development: CommonLogger, ShowExceptions, and Lint
184
+ # - deployment: CommonLogger
185
+ # - none: no extra middleware
186
+ # note: when the server is a cgi server, CommonLogger is not included.
187
+ # * :server
188
+ # choose a specific Rack::Handler, e.g. cgi, fcgi, webrick
189
+ # * :daemonize
190
+ # if true, the server will daemonize itself (fork, detach, etc)
191
+ # * :pid
192
+ # path to write a pid file after daemonize
193
+ # * :Host
194
+ # the host address to bind to (used by supporting Rack::Handler)
195
+ # * :Port
196
+ # the port to bind to (used by supporting Rack::Handler)
197
+ # * :AccessLog
198
+ # webrick access log options (or supporting Rack::Handler)
199
+ # * :debug
200
+ # turn on debug output ($DEBUG = true)
201
+ # * :warn
202
+ # turn on warnings ($-w = true)
203
+ # * :include
204
+ # add given paths to $LOAD_PATH
205
+ # * :require
206
+ # require the given libraries
207
+ #
208
+ # Additional options for profiling app initialization include:
209
+ # * :heapfile
210
+ # location for ObjectSpace.dump_all to write the output to
211
+ # * :profile_file
212
+ # location for CPU/Memory (StackProf) profile output (defaults to a tempfile)
213
+ # * :profile_mode
214
+ # StackProf profile mode (cpu|wall|object)
215
+ def initialize(options = nil)
216
+ @ignore_options = []
217
+
218
+ if options
219
+ @use_default_options = false
220
+ @options = options
221
+ @app = options[:app] if options[:app]
222
+ else
223
+ argv = defined?(SPEC_ARGV) ? SPEC_ARGV : ARGV
224
+ @use_default_options = true
225
+ @options = parse_options(argv)
226
+ end
227
+ end
228
+
229
+ def options
230
+ merged_options = @use_default_options ? default_options.merge(@options) : @options
231
+ merged_options.reject { |k, v| @ignore_options.include?(k) }
232
+ end
233
+
234
+ def default_options
235
+ environment = ENV['RACK_ENV'] || 'development'
236
+ default_host = environment == 'development' ? 'localhost' : '0.0.0.0'
237
+
238
+ {
239
+ environment: environment,
240
+ pid: nil,
241
+ Port: 9292,
242
+ Host: default_host,
243
+ AccessLog: [],
244
+ config: "config.ru"
245
+ }
246
+ end
247
+
248
+ def app
249
+ @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config
250
+ end
251
+
252
+ class << self
253
+ def logging_middleware
254
+ lambda { |server|
255
+ /CGI/.match?(server.server.name) || server.options[:quiet] ? nil : [Rack::CommonLogger, $stderr]
256
+ }
257
+ end
258
+
259
+ def default_middleware_by_environment
260
+ m = Hash.new {|h, k| h[k] = []}
261
+ m["deployment"] = [
262
+ [Rack::ContentLength],
263
+ logging_middleware,
264
+ [Rack::TempfileReaper]
265
+ ]
266
+ m["development"] = [
267
+ [Rack::ContentLength],
268
+ logging_middleware,
269
+ [Rack::ShowExceptions],
270
+ [Rack::Lint],
271
+ [Rack::TempfileReaper]
272
+ ]
273
+
274
+ m
275
+ end
276
+
277
+ def middleware
278
+ default_middleware_by_environment
279
+ end
280
+ end
281
+
282
+ def middleware
283
+ self.class.middleware
284
+ end
285
+
286
+ def start(&block)
287
+ if options[:warn]
288
+ $-w = true
289
+ end
290
+
291
+ if includes = options[:include]
292
+ $LOAD_PATH.unshift(*includes)
293
+ end
294
+
295
+ Array(options[:require]).each do |library|
296
+ require library
297
+ end
298
+
299
+ if options[:debug]
300
+ $DEBUG = true
301
+ require 'pp'
302
+ p options[:server]
303
+ pp wrapped_app
304
+ pp app
305
+ end
306
+
307
+ check_pid! if options[:pid]
308
+
309
+ # Touch the wrapped app, so that the config.ru is loaded before
310
+ # daemonization (i.e. before chdir, etc).
311
+ handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do
312
+ wrapped_app
313
+ end
314
+
315
+ daemonize_app if options[:daemonize]
316
+
317
+ write_pid if options[:pid]
318
+
319
+ trap(:INT) do
320
+ if server.respond_to?(:shutdown)
321
+ server.shutdown
322
+ else
323
+ exit
324
+ end
325
+ end
326
+
327
+ server.run(wrapped_app, **options, &block)
328
+ end
329
+
330
+ def server
331
+ @_server ||= Rack::Handler.get(options[:server])
332
+
333
+ unless @_server
334
+ @_server = Rack::Handler.default
335
+
336
+ # We already speak FastCGI
337
+ @ignore_options = [:File, :Port] if @_server.to_s == 'Rack::Handler::FastCGI'
338
+ end
339
+
340
+ @_server
341
+ end
342
+
343
+ private
344
+ def build_app_and_options_from_config
345
+ if !::File.exist? options[:config]
346
+ abort "configuration #{options[:config]} not found"
347
+ end
348
+
349
+ app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
350
+ @options.merge!(options) { |key, old, new| old }
351
+ app
352
+ end
353
+
354
+ def handle_profiling(heapfile, profile_mode, filename)
355
+ if heapfile
356
+ require "objspace"
357
+ ObjectSpace.trace_object_allocations_start
358
+ yield
359
+ GC.start
360
+ ::File.open(heapfile, "w") { |f| ObjectSpace.dump_all(output: f) }
361
+ exit
362
+ end
363
+
364
+ if profile_mode
365
+ require "stackprof"
366
+ require "tempfile"
367
+
368
+ make_profile_name(filename) do |filename|
369
+ ::File.open(filename, "w") do |f|
370
+ StackProf.run(mode: profile_mode, out: f) do
371
+ yield
372
+ end
373
+ puts "Profile written to: #{filename}"
374
+ end
375
+ end
376
+ exit
377
+ end
378
+
379
+ yield
380
+ end
381
+
382
+ def make_profile_name(filename)
383
+ if filename
384
+ yield filename
385
+ else
386
+ ::Dir::Tmpname.create("profile.dump") do |tmpname, _, _|
387
+ yield tmpname
388
+ end
389
+ end
390
+ end
391
+
392
+ def build_app_from_string
393
+ Rack::Builder.new_from_string(self.options[:builder])
394
+ end
395
+
396
+ def parse_options(args)
397
+ # Don't evaluate CGI ISINDEX parameters.
398
+ # http://www.meb.uni-bonn.de/docs/cgi/cl.html
399
+ args.clear if ENV.include?(REQUEST_METHOD)
400
+
401
+ @options = opt_parser.parse!(args)
402
+ @options[:config] = ::File.expand_path(options[:config])
403
+ ENV["RACK_ENV"] = options[:environment]
404
+ @options
405
+ end
406
+
407
+ def opt_parser
408
+ Options.new
409
+ end
410
+
411
+ def build_app(app)
412
+ middleware[options[:environment]].reverse_each do |middleware|
413
+ middleware = middleware.call(self) if middleware.respond_to?(:call)
414
+ next unless middleware
415
+ klass, *args = middleware
416
+ app = klass.new(app, *args)
417
+ end
418
+ app
419
+ end
420
+
421
+ def wrapped_app
422
+ @wrapped_app ||= build_app app
423
+ end
424
+
425
+ def daemonize_app
426
+ # Cannot be covered as it forks
427
+ # :nocov:
428
+ Process.daemon
429
+ # :nocov:
430
+ end
431
+
432
+ def write_pid
433
+ ::File.open(options[:pid], ::File::CREAT | ::File::EXCL | ::File::WRONLY ){ |f| f.write("#{Process.pid}") }
434
+ at_exit { ::FileUtils.rm_f(options[:pid]) }
435
+ rescue Errno::EEXIST
436
+ check_pid!
437
+ retry
438
+ end
439
+
440
+ def check_pid!
441
+ case pidfile_process_status
442
+ when :running, :not_owned
443
+ $stderr.puts "A server is already running. Check #{options[:pid]}."
444
+ exit(1)
445
+ when :dead
446
+ ::File.delete(options[:pid])
447
+ end
448
+ end
449
+
450
+ def pidfile_process_status
451
+ return :exited unless ::File.exist?(options[:pid])
452
+
453
+ pid = ::File.read(options[:pid]).to_i
454
+ return :dead if pid == 0
455
+
456
+ Process.kill(0, pid)
457
+ :running
458
+ rescue Errno::ESRCH
459
+ :dead
460
+ rescue Errno::EPERM
461
+ :not_owned
462
+ end
463
+
464
+ end
465
+
466
+ end