Module: TinyRubyServer

Defined in:
lib/tiny_ruby_server.rb,
lib/tiny_ruby_server/version.rb

Constant Summary collapse

WEB_ROOT =

File will be served from below directory

'./public'
CONTENT_TYPE_MAPPING =

Map extensions to their content type

{
  'html' => 'text/html',
  'txt' => 'text/plain', 
  'png' => 'image/png',
  'jpg' => 'image/jpeg',
  'gif' => 'image/gif'
}
DEFAULT_CONTENT_TYPE =

Treat as binary data if content type can not be found

'application/octet-stream'
VERSION =
"0.1"

Class Method Summary collapse

Class Method Details

.content_type(path) ⇒ Object

Helper function to parse extension of requested file, then looks up its content type:



25
26
27
28
# File 'lib/tiny_ruby_server.rb', line 25

def self.content_type(path)
  ext = File.extname(path).split(".").last
  CONTENT_TYPE_MAPPING.fetch(ext, DEFAULT_CONTENT_TYPE)
end

.requested_file(request_line) ⇒ Object

The below is lifted from Rack::File The reason for this is that it is extremely easy to introduce a security vulnerablility where any file in file system can be accessed. In fact, the below was added in 2013 specifically to deal with such a security vulnerablility



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tiny_ruby_server.rb', line 39

def self.requested_file(request_line)
  request_uri  = request_line.split(" ")[1]
  path         = URI.unescape(URI(request_uri).path)

  clean = []

  # Split the path into components
  parts = path.split("/")

  parts.each do |part|
    # skip any empty or current directory (".") path components
    next if part.empty? || part == '.'
    # If the path component goes up one directory level (".."),
    # remove the last clean component.
    # Otherwise, add the component to the Array of clean components
    part == '..' ? clean.pop : clean << part
  end
  # return the web root joined to the clean path
  path = File.join(WEB_ROOT, *clean)
  
end