1 /*
2   Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
3 
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2.0,
6   as published by the Free Software Foundation.
7 
8   This program is also distributed with certain software (including
9   but not limited to OpenSSL) that is licensed under separate terms,
10   as designated in a particular file or component or in included license
11   documentation.  The authors of MySQL hereby grant you an additional
12   permission to link the program and your derivative works with the
13   separately licensed software that they have included with MySQL.
14 
15   This program is distributed in the hope that it will be useful,
16   but WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18   GNU General Public License for more details.
19 
20   You should have received a copy of the GNU General Public License
21   along with this program; if not, write to the Free Software
22   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23 */
24 
25 #include "static_files.h"
26 
27 #include <memory>
28 #include <string>
29 
30 #ifdef _WIN32
31 #include <io.h>  // close
32 #else
33 #include <unistd.h>  // close
34 #endif
35 #include <fcntl.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 
39 #include <event2/http.h>  // evhttp_uridecode
40 
41 #include "mysql/harness/stdx/io/file_handle.h"
42 #include "mysqlrouter/http_auth_realm_component.h"
43 #include "mysqlrouter/http_server_component.h"
44 
45 #include "content_type.h"
46 
handle_request(HttpRequest & req)47 void HttpStaticFolderHandler::handle_request(HttpRequest &req) {
48   HttpUri parsed_uri{req.get_uri()};
49 
50   // failed to parse the URI
51   if (!parsed_uri) {
52     req.send_error(HttpStatusCode::BadRequest);
53     return;
54   }
55 
56   if (req.get_method() != HttpMethod::Get &&
57       req.get_method() != HttpMethod::Head) {
58     req.send_error(HttpStatusCode::MethodNotAllowed);
59 
60     return;
61   }
62 
63   if (!require_realm_.empty()) {
64     if (auto realm =
65             HttpAuthRealmComponent::get_instance().get(require_realm_)) {
66       if (HttpAuth::require_auth(req, realm)) {
67         // request is already handled, nothing to do
68         return;
69       }
70 
71       // access granted, fall through
72     }
73   }
74 
75   // guess mime-type
76 
77   std::string file_path{static_basedir_};
78 
79   file_path += "/";
80   std::unique_ptr<char, decltype(&free)> unescaped{
81       evhttp_uridecode(parsed_uri.get_path().c_str(), 1, nullptr), &free};
82   file_path += http_uri_path_canonicalize(unescaped.get());
83 
84   auto out_hdrs = req.get_output_headers();
85 
86   struct stat st;
87   if (-1 == stat(file_path.c_str(), &st)) {
88     if (errno == ENOENT) {
89       // file doesn't exist
90       req.send_error(HttpStatusCode::NotFound);
91 
92       return;
93     } else {
94       req.send_error(HttpStatusCode::InternalError);
95 
96       return;
97     }
98   }
99 
100   // if we have a directory, check if it contains a index.html file
101   if ((st.st_mode & S_IFMT) == S_IFDIR) {
102     file_path += "/index.html";
103 
104     if (-1 == stat(file_path.c_str(), &st)) {
105       if (errno == ENOENT) {
106         // it was a directory, but there is no index-file
107         req.send_error(HttpStatusCode::Forbidden);
108 
109         return;
110       } else {
111         req.send_error(HttpStatusCode::InternalError);
112 
113         return;
114       }
115     }
116   }
117 
118   auto res = stdx::io::file_handle::file({}, file_path);
119   if (!res) {
120     if (res.error() ==
121         make_error_condition(std::errc::no_such_file_or_directory)) {
122       // stat() succeeded, but open() failed.
123       //
124       // either a race or apparmor
125       req.send_error(HttpStatusCode::NotFound);
126 
127       return;
128     } else {
129       // if it was a directory
130       req.send_error(HttpStatusCode::InternalError);
131 
132       return;
133     }
134   } else {
135     auto fh = std::move(res.value());
136     if (!req.is_modified_since(st.st_mtime)) {
137       req.send_error(HttpStatusCode::NotModified);
138       return;
139     }
140 
141     req.add_last_modified(st.st_mtime);
142 
143     auto chunk = req.get_output_buffer();
144     // if the file-size is 0, there is nothing to send ... and it triggers a
145     // mmap() error
146     if (st.st_size > 0) {
147       // only use sendfile if packet is large enough as it will be sent in sep
148       // TCP packet/syscall
149       //
150       // using TCP_CORK would help here
151       // if (st.st_size > 64 * 1024) {
152       //    evbuffer_set_flags(chunk, EVBUFFER_FLAG_DRAINS_TO_FD);
153       // }
154       chunk.add_file(fh.release(), 0, st.st_size);
155       // file_fd is owned by evbuffer_add_file(), don't close it
156     } else {
157       fh.close();
158     }
159 
160     // file exists
161     auto n = file_path.rfind('.');
162     if (n != std::string::npos) {
163       out_hdrs.add("Content-Type",
164                    ContentType::from_extension(file_path.substr(n + 1)));
165     }
166 
167     req.send_reply(HttpStatusCode::Ok,
168                    HttpStatusCode::get_default_status_text(HttpStatusCode::Ok),
169                    chunk);
170 
171     return;
172   }
173 }
174