blob: 9ac2abd106d5bf1590cb8635d08aaef6af38a633 [file] [log] [blame]
Ed Tanous911ac312017-08-15 09:37:42 -07001#pragma once
2
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08003#include "app.hpp"
4#include "http_request.hpp"
5#include "http_response.hpp"
6#include "routing.hpp"
James Feist3909dc82020-04-03 10:58:55 -07007#include "webroutes.hpp"
8
Ed Tanous911ac312017-08-15 09:37:42 -07009#include <boost/container/flat_set.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050010
Ed Tanousca89b202024-04-25 23:02:40 -070011#include <algorithm>
12#include <array>
James Feist4418c7f2019-04-15 11:09:15 -070013#include <filesystem>
Ed Tanous1abe55e2018-09-05 08:30:59 -070014#include <fstream>
15#include <string>
Ed Tanousca89b202024-04-25 23:02:40 -070016#include <string_view>
Ed Tanous911ac312017-08-15 09:37:42 -070017
Ed Tanous1abe55e2018-09-05 08:30:59 -070018namespace crow
19{
20namespace webassets
21{
Ed Tanous911ac312017-08-15 09:37:42 -070022
Ed Tanous499b5b42024-04-06 08:39:18 -070023inline std::string getStaticEtag(const std::filesystem::path& webpath)
24{
25 // webpack outputs production chunks in the form:
26 // <filename>.<hash>.<extension>
27 // For example app.63e2c453.css
28 // Try to detect this, so we can use the hash as the ETAG
29 std::vector<std::string> split;
30 bmcweb::split(split, webpath.filename().string(), '.');
31 BMCWEB_LOG_DEBUG("Checking {} split.size() {}", webpath.filename().string(),
32 split.size());
33 if (split.size() < 3)
34 {
35 return "";
36 }
37
38 // get the second to last element
39 std::string hash = split.rbegin()[1];
40
41 // Webpack hashes are 8 characters long
42 if (hash.size() != 8)
43 {
44 return "";
45 }
46 // Webpack hashes only include hex printable characters
47 if (hash.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos)
48 {
49 return "";
50 }
51 return std::format("\"{}\"", hash);
52}
53
Ed Tanousca89b202024-04-25 23:02:40 -070054static constexpr std::string_view rootpath("/usr/share/www/");
55
56struct StaticFile
Ed Tanous1abe55e2018-09-05 08:30:59 -070057{
Ed Tanousca89b202024-04-25 23:02:40 -070058 std::filesystem::path absolutePath;
59 std::string_view contentType;
60 std::string_view contentEncoding;
61 std::string etag;
62 bool renamed = false;
63};
64
65inline void
66 handleStaticAsset(const crow::Request& req,
67 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
68 const StaticFile& file)
69{
70 if (!file.contentType.empty())
71 {
72 asyncResp->res.addHeader(boost::beast::http::field::content_type,
73 file.contentType);
74 }
75
76 if (!file.contentEncoding.empty())
77 {
78 asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
79 file.contentEncoding);
80 }
81
82 if (!file.etag.empty())
83 {
84 asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
85 // Don't cache paths that don't have the etag in them, like
86 // index, which gets transformed to /
87 if (!file.renamed)
88 {
89 // Anything with a hash can be cached forever and is
90 // immutable
91 asyncResp->res.addHeader(boost::beast::http::field::cache_control,
92 "max-age=31556926, immutable");
93 }
94
95 std::string_view cachedEtag =
96 req.getHeaderValue(boost::beast::http::field::if_none_match);
97 if (cachedEtag == file.etag)
98 {
99 asyncResp->res.result(boost::beast::http::status::not_modified);
100 return;
101 }
102 }
103
104 if (!asyncResp->res.openFile(file.absolutePath))
105 {
106 BMCWEB_LOG_DEBUG("failed to read file");
107 asyncResp->res.result(
108 boost::beast::http::status::internal_server_error);
109 return;
110 }
111}
112
113inline std::string_view getFiletypeForExtension(std::string_view extension)
114{
115 constexpr static std::array<std::pair<std::string_view, std::string_view>,
116 17>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700117 contentTypes{
118 {{".css", "text/css;charset=UTF-8"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700119 {".eot", "application/vnd.ms-fontobject"},
Ed Tanousca89b202024-04-25 23:02:40 -0700120 {".gif", "image/gif"},
121 {".html", "text/html;charset=UTF-8"},
122 {".ico", "image/x-icon"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700123 {".jpeg", "image/jpeg"},
Ed Tanousca89b202024-04-25 23:02:40 -0700124 {".jpg", "image/jpeg"},
125 {".js", "application/javascript;charset=UTF-8"},
126 {".json", "application/json"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700127 // dev tools don't care about map type, setting to json causes
128 // browser to show as text
129 // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
Ed Tanousca89b202024-04-25 23:02:40 -0700130 {".map", "application/json"},
131 {".png", "image/png;charset=UTF-8"},
132 {".svg", "image/svg+xml"},
133 {".ttf", "application/x-font-ttf"},
134 {".woff", "application/x-font-woff"},
135 {".woff2", "application/x-font-woff2"},
136 {".xml", "application/xml"}}};
Ed Tanousa47f32b2019-10-24 10:08:04 -0700137
Ed Tanousca89b202024-04-25 23:02:40 -0700138 const auto* contentType = std::ranges::find_if(
139 contentTypes,
140 [&extension](const auto& val) { return val.first == extension; });
Ed Tanous153fdcf2021-03-04 16:43:14 -0800141
Ed Tanousca89b202024-04-25 23:02:40 -0700142 if (contentType == contentTypes.end())
143 {
144 BMCWEB_LOG_ERROR(
145 "Cannot determine content-type for file with extension {}",
146 extension);
147 return "";
148 }
149 return contentType->second;
150}
151
152inline void addFile(App& app, const std::filesystem::directory_entry& dir)
153{
154 StaticFile file;
155 file.absolutePath = dir.path();
156 std::filesystem::path relativePath(
157 file.absolutePath.string().substr(rootpath.size() - 1));
158
159 std::string extension = relativePath.extension();
160 std::filesystem::path webpath = relativePath;
161
162 if (extension == ".gz")
163 {
164 webpath = webpath.replace_extension("");
165 // Use the non-gzip version for determining content type
166 extension = webpath.extension().string();
167 file.contentEncoding = "gzip";
168 }
169
170 file.etag = getStaticEtag(webpath);
171
172 if (webpath.filename().string().starts_with("index."))
173 {
174 webpath = webpath.parent_path();
175 if (webpath.string().empty() || webpath.string().back() != '/')
176 {
177 // insert the non-directory version of this path
178 webroutes::routes.insert(webpath);
179 webpath += "/";
180 file.renamed = true;
181 }
182 }
183
184 std::pair<boost::container::flat_set<std::string>::iterator, bool>
185 inserted = webroutes::routes.insert(webpath);
186
187 if (!inserted.second)
188 {
189 // Got a duplicated path. This is expected in certain
190 // situations
191 BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
192 return;
193 }
194 file.contentType = getFiletypeForExtension(extension);
195
196 if (webpath == "/")
197 {
198 forward_unauthorized::hasWebuiRoute = true;
199 }
200
201 app.routeDynamic(webpath)(
202 [file = std::move(file)](
203 const crow::Request& req,
204 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
205 handleStaticAsset(req, asyncResp, file);
206 });
207}
208
209inline void requestRoutes(App& app)
210{
Ed Tanous153fdcf2021-03-04 16:43:14 -0800211 std::error_code ec;
Ed Tanousca89b202024-04-25 23:02:40 -0700212 std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800213 if (ec)
214 {
Ed Tanous62598e32023-07-17 17:06:25 -0700215 BMCWEB_LOG_ERROR(
Ed Tanousca89b202024-04-25 23:02:40 -0700216 "Unable to find or open {} static file hosting disabled", rootpath);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800217 return;
218 }
219
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220 // In certain cases, we might have both a gzipped version of the file AND a
221 // non-gzipped version. To avoid duplicated routes, we need to make sure we
222 // get the gzipped version first. Because the gzipped path should be longer
Ed Tanous8b156452018-10-12 11:09:26 -0700223 // than the non gzipped path, if we sort in descending order, we should be
Ed Tanous1abe55e2018-09-05 08:30:59 -0700224 // guaranteed to get the gzip version first.
Ed Tanousa47f32b2019-10-24 10:08:04 -0700225 std::vector<std::filesystem::directory_entry> paths(
226 std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700227 std::sort(paths.rbegin(), paths.rend());
Ed Tanous9dc2c4d2018-03-07 14:51:27 -0800228
Ed Tanousa47f32b2019-10-24 10:08:04 -0700229 for (const std::filesystem::directory_entry& dir : paths)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700230 {
Ed Tanousa47f32b2019-10-24 10:08:04 -0700231 if (std::filesystem::is_directory(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700232 {
233 // don't recurse into hidden directories or symlinks
Ed Tanous11ba3972022-07-11 09:50:41 -0700234 if (dir.path().filename().string().starts_with(".") ||
Ed Tanousa47f32b2019-10-24 10:08:04 -0700235 std::filesystem::is_symlink(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700236 {
237 dirIter.disable_recursion_pending();
238 }
Ed Tanousba9f9a62017-10-11 16:40:35 -0700239 }
Ed Tanousa47f32b2019-10-24 10:08:04 -0700240 else if (std::filesystem::is_regular_file(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 {
Ed Tanousca89b202024-04-25 23:02:40 -0700242 addFile(app, dir);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 }
Ed Tanous911ac312017-08-15 09:37:42 -0700244 }
Ed Tanous99dc9c72019-10-24 10:09:03 -0700245}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700246} // namespace webassets
247} // namespace crow