2016-09-15 20:45:54 +00:00
|
|
|
{% if !flag?(:without_zlib) %}
|
|
|
|
require "zlib"
|
|
|
|
{% end %}
|
|
|
|
|
2016-07-17 11:43:13 +00:00
|
|
|
module Kemal
|
|
|
|
class StaticFileHandler < HTTP::StaticFileHandler
|
2019-08-30 11:32:23 +00:00
|
|
|
# ameba:disable Metrics/CyclomaticComplexity
|
2017-08-25 13:41:02 +00:00
|
|
|
def call(context : HTTP::Server::Context)
|
2016-07-17 11:43:13 +00:00
|
|
|
return call_next(context) if context.request.path.not_nil! == "/"
|
2016-09-15 20:45:54 +00:00
|
|
|
|
2018-11-01 11:29:05 +00:00
|
|
|
case context.request.method
|
|
|
|
when "GET", "HEAD"
|
|
|
|
else
|
2016-09-15 20:45:54 +00:00
|
|
|
if @fallthrough
|
|
|
|
call_next(context)
|
|
|
|
else
|
|
|
|
context.response.status_code = 405
|
|
|
|
context.response.headers.add("Allow", "GET, HEAD")
|
|
|
|
end
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
config = Kemal.config.serve_static
|
|
|
|
original_path = context.request.path.not_nil!
|
2019-08-03 16:35:40 +00:00
|
|
|
request_path = URI.decode(original_path)
|
2016-09-15 20:45:54 +00:00
|
|
|
|
|
|
|
# File path cannot contains '\0' (NUL) because all filesystem I know
|
|
|
|
# don't accept '\0' character as file name.
|
|
|
|
if request_path.includes? '\0'
|
|
|
|
context.response.status_code = 400
|
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
expanded_path = File.expand_path(request_path, "/")
|
2018-11-01 11:29:05 +00:00
|
|
|
is_dir_path = if original_path.ends_with?('/') && !expanded_path.ends_with? '/'
|
|
|
|
expanded_path = expanded_path + '/'
|
|
|
|
true
|
|
|
|
else
|
|
|
|
expanded_path.ends_with? '/'
|
|
|
|
end
|
2016-09-15 20:45:54 +00:00
|
|
|
|
|
|
|
file_path = File.join(@public_dir, expanded_path)
|
|
|
|
is_dir = Dir.exists? file_path
|
|
|
|
|
2018-11-01 11:29:05 +00:00
|
|
|
if request_path != expanded_path
|
|
|
|
redirect_to context, expanded_path
|
|
|
|
elsif is_dir && !is_dir_path
|
|
|
|
redirect_to context, expanded_path + '/'
|
2016-09-15 20:45:54 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
if Dir.exists?(file_path)
|
|
|
|
if config.is_a?(Hash) && config["dir_listing"] == true
|
|
|
|
context.response.content_type = "text/html"
|
|
|
|
directory_listing(context.response, request_path, file_path)
|
|
|
|
else
|
2019-06-13 11:31:45 +00:00
|
|
|
call_next(context)
|
2016-09-15 20:45:54 +00:00
|
|
|
end
|
|
|
|
elsif File.exists?(file_path)
|
2018-07-16 02:54:36 +00:00
|
|
|
last_modified = modification_time(file_path)
|
|
|
|
add_cache_headers(context.response.headers, last_modified)
|
|
|
|
|
|
|
|
if cache_request?(context, last_modified)
|
|
|
|
context.response.status_code = 304
|
|
|
|
return
|
|
|
|
end
|
2017-03-12 12:38:47 +00:00
|
|
|
send_file(context, file_path)
|
2016-09-15 20:45:54 +00:00
|
|
|
else
|
|
|
|
call_next(context)
|
|
|
|
end
|
|
|
|
end
|
2015-12-10 19:15:28 +00:00
|
|
|
end
|
|
|
|
end
|