3552b2d1b7d7dbbf257d3eceaaade69b9af3b5c2
[nit.git] / lib / nitcorn / file_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Provides the `FileServer` action, which is a standard and minimal file server
19 module file_server
20
21 import reactor
22 import sessions
23 import media_types
24 import http_errors
25
26 redef class String
27 # Returns a `String` copy of `self` without any of the prefixed '/'s
28 #
29 # Examples:
30 #
31 # assert "/home/".strip_start_slashes == "home/"
32 # assert "////home/".strip_start_slashes == "home/"
33 # assert "../home/".strip_start_slashes == "../home/"
34 fun strip_start_slashes: String
35 do
36 for i in chars.length.times do if chars[i] != '/' then return substring_from(i)
37 return ""
38 end
39 end
40
41 # A simple file server
42 class FileServer
43 super Action
44
45 # Root folder of `self` file system
46 var root: String
47
48 init
49 do
50 var root = self.root
51
52 # Simplify the root path as each file requested will also be simplified
53 root = root.simplify_path
54
55 # Make sure the root ends with '/', this makes a difference in the security
56 # check on each file access.
57 root = root + "/"
58
59 self.root = root
60 end
61
62 # Error page template for a given `code`
63 fun error_page(code: Int): Streamable do return new ErrorTemplate(code)
64
65 # Header of each directory page
66 var header: nullable Streamable = null is writable
67
68 redef fun answer(request, turi)
69 do
70 var response
71
72 var local_file = root.join_path(turi.strip_start_slashes)
73 local_file = local_file.simplify_path
74
75 # Is it reachable?
76 #
77 # This make sure that the requested file is within the root folder.
78 if (local_file + "/").has_prefix(root) then
79 # Does it exists?
80 if local_file.file_exists then
81 if local_file.file_stat.is_dir then
82 # If we target a directory without an ending `/`,
83 # redirect to the directory ending with `/`.
84 if not request.uri.is_empty and
85 request.uri.chars.last != '/' then
86 response = new HttpResponse(303)
87 response.header["Location"] = request.uri + "/"
88 return response
89 end
90
91 # Show index file instead of the directory listing
92 # only if `index.html` or `index.htm` is available
93 var index_file = local_file.join_path("index.html")
94 if index_file.file_exists then
95 local_file = index_file
96 else
97 index_file = local_file.join_path("index.htm")
98 if index_file.file_exists then local_file = index_file
99 end
100 end
101
102 response = new HttpResponse(200)
103 if local_file.file_stat.is_dir then
104 # Show the directory listing
105 var title = turi
106 var files = local_file.files
107
108 var links = new Array[String]
109 if turi.length > 1 then
110 var path = (request.uri + "/..").simplify_path
111 links.add "<a href=\"{path}/\">..</a>"
112 end
113 for file in files do
114 var local_path = local_file.join_path(file).simplify_path
115 var web_path = file.simplify_path
116 if local_path.file_stat.is_dir then web_path = web_path + "/"
117 links.add "<a href=\"{web_path}\">{file}</a>"
118 end
119
120 var header = self.header
121 var header_code
122 if header != null then
123 header_code = header.write_to_string
124 else header_code = ""
125
126 response.body = """
127 <!DOCTYPE html>
128 <head>
129 <meta charset="utf-8">
130 <meta http-equiv="X-UA-Compatible" content="IE=edge">
131 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
132 <title>{{{title}}}</title>
133 </head>
134 <body>
135 {{{header_code}}}
136 <div class="container">
137 <h1>{{{title}}}</h1>
138 <ul>
139 <li>{{{links.join("</li>\n\t\t\t<li>")}}}</li>
140 </ul>
141 </div>
142 </body>
143 </html>"""
144
145 response.header["Content-Type"] = media_types["html"].as(not null)
146 else
147 # It's a single file
148 var file = new IFStream.open(local_file)
149 response.body = file.read_all
150
151 var ext = local_file.file_extension
152 if ext != null then
153 var media_type = media_types[ext]
154 if media_type != null then
155 response.header["Content-Type"] = media_type
156 else response.header["Content-Type"] = "application/octet-stream"
157 end
158
159 file.close
160 end
161
162 else response = new HttpResponse(404)
163 else response = new HttpResponse(403)
164
165 if response.status_code != 200 then
166 var tmpl = error_page(response.status_code)
167 if header != null and tmpl isa ErrorTemplate then tmpl.header = header
168 response.body = tmpl.to_s
169 end
170
171 return response
172 end
173 end