nitcorn/file_server: fix warnings on file_stat calls
[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): Writable do return new ErrorTemplate(code)
64
65 # Header of each directory page
66 var header: nullable Writable = null is writable
67
68 # Custom JavaScript code added within a `<script>` block to each page
69 var javascript_header: nullable Writable = null is writable
70
71 # Caching attributes of served files, used as the `cache-control` field in response headers
72 var cache_control = "public, max-age=360" is writable
73
74 # Show directory listing?
75 var show_directory_listing = true is writable
76
77 redef fun answer(request, turi)
78 do
79 var response
80
81 var local_file = root.join_path(turi.strip_start_slashes)
82 local_file = local_file.simplify_path
83
84 # Is it reachable?
85 #
86 # This make sure that the requested file is within the root folder.
87 if (local_file + "/").has_prefix(root) then
88 # Does it exists?
89 var file_stat = local_file.file_stat
90 if file_stat != null then
91 if file_stat.is_dir then
92 # If we target a directory without an ending `/`,
93 # redirect to the directory ending with `/`.
94 var uri = request.uri
95 if not uri.is_empty and uri.chars.last != '/' then
96 return answer_redirection(request.uri + "/")
97 end
98
99 # Show index file instead of the directory listing
100 # only if `index.html` or `index.htm` is available
101 var index_file = local_file.join_path("index.html")
102 if index_file.file_exists then
103 local_file = index_file
104 else
105 index_file = local_file.join_path("index.htm")
106 if index_file.file_exists then local_file = index_file
107 end
108 end
109
110 file_stat = local_file.file_stat
111 if show_directory_listing and file_stat != null and file_stat.is_dir then
112 response = answer_directory_listing(request, turi, local_file)
113 else if file_stat != null and not file_stat.is_dir then # It's a single file
114 response = answer_file(local_file)
115 else response = new HttpResponse(404)
116 else response = new HttpResponse(404)
117 else response = new HttpResponse(403)
118
119 if response.status_code != 200 then
120 var tmpl = error_page(response.status_code)
121 if header != null and tmpl isa ErrorTemplate then tmpl.header = header
122 response.body = tmpl.to_s
123 end
124
125 return response
126 end
127
128 # Answer a 303 redirection to `location`.
129 fun answer_redirection(location: String): HttpResponse do
130 var response = new HttpResponse(303)
131 response.header["Location"] = location
132 return response
133 end
134
135 # Build a reponse containing a single `local_file`.
136 #
137 # Returns a 404 error if local_file does not exists.
138 fun answer_file(local_file: String): HttpResponse do
139 if not local_file.file_exists then return new HttpResponse(404)
140
141 var response = new HttpResponse(200)
142 response.files.add local_file
143
144 # Set Content-Type depending on the file extension
145 var ext = local_file.file_extension
146 if ext != null then
147 var media_type = media_types[ext]
148 if media_type != null then
149 response.header["Content-Type"] = media_type
150 else response.header["Content-Type"] = "application/octet-stream"
151 end
152
153 # Cache control
154 response.header["cache-control"] = cache_control
155 return response
156 end
157
158 # Answer with a directory listing for files within `local_files`.
159 fun answer_directory_listing(request: HttpRequest, turi, local_file: String): HttpResponse do
160 # Show the directory listing
161 var title = turi
162 var files = local_file.files
163
164 alpha_comparator.sort files
165
166 var links = new Array[String]
167 if turi.length > 1 then
168 var path = (request.uri + "/..").simplify_path
169 links.add "<a href=\"{path}/\">..</a>"
170 end
171 for file in files do
172 var local_path = local_file.join_path(file).simplify_path
173 var web_path = file.simplify_path
174 var file_stat = local_path.file_stat
175 if file_stat != null and file_stat.is_dir then web_path = web_path + "/"
176 links.add "<a href=\"{web_path}\">{file}</a>"
177 end
178
179 var header = self.header
180 var header_code
181 if header != null then
182 header_code = header.write_to_string
183 else header_code = ""
184
185 var response = new HttpResponse(200)
186 response.body = """
187 <!DOCTYPE html>
188 <head>
189 <meta charset="utf-8">
190 <meta http-equiv="X-UA-Compatible" content="IE=edge">
191 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
192 <script>
193 {{{javascript_header or else ""}}}
194 </script>
195 <title>{{{title}}}</title>
196 </head>
197 <body>
198 {{{header_code}}}
199 <div class="container">
200 <h1>{{{title}}}</h1>
201 <ul>
202 <li>{{{links.join("</li>\n\t\t\t<li>")}}}</li>
203 </ul>
204 </div>
205 </body>
206 </html>"""
207
208 response.header["Content-Type"] = media_types["html"].as(not null)
209 return response
210 end
211 end