blob: 689c7d357e3e08773ce9466050cb546e00b1909c [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
Patrick Williamsbd79bce2024-08-16 15:22:20 -040065inline void handleStaticAsset(
66 const crow::Request& req,
67 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
Ed Tanousca89b202024-04-25 23:02:40 -070068{
69 if (!file.contentType.empty())
70 {
71 asyncResp->res.addHeader(boost::beast::http::field::content_type,
72 file.contentType);
73 }
74
75 if (!file.contentEncoding.empty())
76 {
77 asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
78 file.contentEncoding);
79 }
80
81 if (!file.etag.empty())
82 {
83 asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
84 // Don't cache paths that don't have the etag in them, like
85 // index, which gets transformed to /
86 if (!file.renamed)
87 {
88 // Anything with a hash can be cached forever and is
89 // immutable
90 asyncResp->res.addHeader(boost::beast::http::field::cache_control,
91 "max-age=31556926, immutable");
92 }
93
94 std::string_view cachedEtag =
95 req.getHeaderValue(boost::beast::http::field::if_none_match);
96 if (cachedEtag == file.etag)
97 {
98 asyncResp->res.result(boost::beast::http::status::not_modified);
99 return;
100 }
101 }
102
103 if (!asyncResp->res.openFile(file.absolutePath))
104 {
105 BMCWEB_LOG_DEBUG("failed to read file");
106 asyncResp->res.result(
107 boost::beast::http::status::internal_server_error);
108 return;
109 }
110}
111
112inline std::string_view getFiletypeForExtension(std::string_view extension)
113{
114 constexpr static std::array<std::pair<std::string_view, std::string_view>,
115 17>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700116 contentTypes{
117 {{".css", "text/css;charset=UTF-8"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700118 {".eot", "application/vnd.ms-fontobject"},
Ed Tanousca89b202024-04-25 23:02:40 -0700119 {".gif", "image/gif"},
120 {".html", "text/html;charset=UTF-8"},
121 {".ico", "image/x-icon"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700122 {".jpeg", "image/jpeg"},
Ed Tanousca89b202024-04-25 23:02:40 -0700123 {".jpg", "image/jpeg"},
124 {".js", "application/javascript;charset=UTF-8"},
125 {".json", "application/json"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700126 // dev tools don't care about map type, setting to json causes
127 // browser to show as text
128 // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
Ed Tanousca89b202024-04-25 23:02:40 -0700129 {".map", "application/json"},
130 {".png", "image/png;charset=UTF-8"},
131 {".svg", "image/svg+xml"},
132 {".ttf", "application/x-font-ttf"},
133 {".woff", "application/x-font-woff"},
134 {".woff2", "application/x-font-woff2"},
135 {".xml", "application/xml"}}};
Ed Tanousa47f32b2019-10-24 10:08:04 -0700136
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400137 const auto* contentType =
138 std::ranges::find_if(contentTypes, [&extension](const auto& val) {
139 return val.first == extension;
140 });
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 }
Ed Tanous2b47f942024-03-12 15:43:16 -0700169 else if (extension == ".zstd")
170 {
171 webpath = webpath.replace_extension("");
172 // Use the non-zstd version for determining content type
173 extension = webpath.extension().string();
174 file.contentEncoding = "zstd";
175 }
Ed Tanousca89b202024-04-25 23:02:40 -0700176
177 file.etag = getStaticEtag(webpath);
178
179 if (webpath.filename().string().starts_with("index."))
180 {
181 webpath = webpath.parent_path();
182 if (webpath.string().empty() || webpath.string().back() != '/')
183 {
184 // insert the non-directory version of this path
185 webroutes::routes.insert(webpath);
186 webpath += "/";
187 file.renamed = true;
188 }
189 }
190
191 std::pair<boost::container::flat_set<std::string>::iterator, bool>
192 inserted = webroutes::routes.insert(webpath);
193
194 if (!inserted.second)
195 {
196 // Got a duplicated path. This is expected in certain
197 // situations
198 BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
199 return;
200 }
201 file.contentType = getFiletypeForExtension(extension);
202
203 if (webpath == "/")
204 {
205 forward_unauthorized::hasWebuiRoute = true;
206 }
207
208 app.routeDynamic(webpath)(
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400209 [file = std::move(
210 file)](const crow::Request& req,
211 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
212 handleStaticAsset(req, asyncResp, file);
213 });
Ed Tanousca89b202024-04-25 23:02:40 -0700214}
215
216inline void requestRoutes(App& app)
217{
Ed Tanous153fdcf2021-03-04 16:43:14 -0800218 std::error_code ec;
Ed Tanousca89b202024-04-25 23:02:40 -0700219 std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800220 if (ec)
221 {
Ed Tanous62598e32023-07-17 17:06:25 -0700222 BMCWEB_LOG_ERROR(
Ed Tanousca89b202024-04-25 23:02:40 -0700223 "Unable to find or open {} static file hosting disabled", rootpath);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800224 return;
225 }
226
Ed Tanous1abe55e2018-09-05 08:30:59 -0700227 // In certain cases, we might have both a gzipped version of the file AND a
228 // non-gzipped version. To avoid duplicated routes, we need to make sure we
229 // get the gzipped version first. Because the gzipped path should be longer
Ed Tanous8b156452018-10-12 11:09:26 -0700230 // than the non gzipped path, if we sort in descending order, we should be
Ed Tanous1abe55e2018-09-05 08:30:59 -0700231 // guaranteed to get the gzip version first.
Ed Tanousa47f32b2019-10-24 10:08:04 -0700232 std::vector<std::filesystem::directory_entry> paths(
233 std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700234 std::sort(paths.rbegin(), paths.rend());
Ed Tanous9dc2c4d2018-03-07 14:51:27 -0800235
Ed Tanousa47f32b2019-10-24 10:08:04 -0700236 for (const std::filesystem::directory_entry& dir : paths)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700237 {
Ed Tanousa47f32b2019-10-24 10:08:04 -0700238 if (std::filesystem::is_directory(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700239 {
240 // don't recurse into hidden directories or symlinks
Ed Tanous11ba3972022-07-11 09:50:41 -0700241 if (dir.path().filename().string().starts_with(".") ||
Ed Tanousa47f32b2019-10-24 10:08:04 -0700242 std::filesystem::is_symlink(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 {
244 dirIter.disable_recursion_pending();
245 }
Ed Tanousba9f9a62017-10-11 16:40:35 -0700246 }
Ed Tanousa47f32b2019-10-24 10:08:04 -0700247 else if (std::filesystem::is_regular_file(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 {
Ed Tanousca89b202024-04-25 23:02:40 -0700249 addFile(app, dir);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700250 }
Ed Tanous911ac312017-08-15 09:37:42 -0700251 }
Ed Tanous99dc9c72019-10-24 10:09:03 -0700252}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700253} // namespace webassets
254} // namespace crow