blob: baa16c4ee82e373c8257601cf21b77e5af91491c [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous911ac312017-08-15 09:37:42 -07003#pragma once
4
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08005#include "app.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -08006#include "async_resp.hpp"
7#include "forward_unauthorized.hpp"
Ed Tanousb2539062024-03-12 16:58:35 -07008#include "http_body.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08009#include "http_request.hpp"
10#include "http_response.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -080011#include "logging.hpp"
12#include "str_utility.hpp"
James Feist3909dc82020-04-03 10:58:55 -070013#include "webroutes.hpp"
14
Ed Tanousd7857202025-01-28 15:32:26 -080015#include <boost/beast/http/field.hpp>
16#include <boost/beast/http/status.hpp>
Ed Tanous911ac312017-08-15 09:37:42 -070017#include <boost/container/flat_set.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018
Ed Tanousca89b202024-04-25 23:02:40 -070019#include <algorithm>
20#include <array>
James Feist4418c7f2019-04-15 11:09:15 -070021#include <filesystem>
Ed Tanousd7857202025-01-28 15:32:26 -080022#include <format>
23#include <memory>
Ed Tanous1abe55e2018-09-05 08:30:59 -070024#include <string>
Ed Tanousca89b202024-04-25 23:02:40 -070025#include <string_view>
Ed Tanousd7857202025-01-28 15:32:26 -080026#include <system_error>
27#include <utility>
28#include <vector>
Ed Tanous911ac312017-08-15 09:37:42 -070029
Ed Tanous1abe55e2018-09-05 08:30:59 -070030namespace crow
31{
32namespace webassets
33{
Ed Tanous911ac312017-08-15 09:37:42 -070034
Ed Tanous499b5b42024-04-06 08:39:18 -070035inline std::string getStaticEtag(const std::filesystem::path& webpath)
36{
37 // webpack outputs production chunks in the form:
38 // <filename>.<hash>.<extension>
39 // For example app.63e2c453.css
40 // Try to detect this, so we can use the hash as the ETAG
41 std::vector<std::string> split;
42 bmcweb::split(split, webpath.filename().string(), '.');
Ed Tanous499b5b42024-04-06 08:39:18 -070043 if (split.size() < 3)
44 {
45 return "";
46 }
47
48 // get the second to last element
49 std::string hash = split.rbegin()[1];
50
51 // Webpack hashes are 8 characters long
52 if (hash.size() != 8)
53 {
54 return "";
55 }
56 // Webpack hashes only include hex printable characters
57 if (hash.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos)
58 {
59 return "";
60 }
61 return std::format("\"{}\"", hash);
62}
63
Ed Tanousca89b202024-04-25 23:02:40 -070064static constexpr std::string_view rootpath("/usr/share/www/");
65
66struct StaticFile
Ed Tanous1abe55e2018-09-05 08:30:59 -070067{
Ed Tanousca89b202024-04-25 23:02:40 -070068 std::filesystem::path absolutePath;
69 std::string_view contentType;
70 std::string_view contentEncoding;
71 std::string etag;
Ed Tanousb2539062024-03-12 16:58:35 -070072 bmcweb::CompressionType onDiskComp = bmcweb::CompressionType::Raw;
Ed Tanousca89b202024-04-25 23:02:40 -070073 bool renamed = false;
74};
75
Patrick Williamsbd79bce2024-08-16 15:22:20 -040076inline void handleStaticAsset(
77 const crow::Request& req,
78 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
Ed Tanousca89b202024-04-25 23:02:40 -070079{
80 if (!file.contentType.empty())
81 {
82 asyncResp->res.addHeader(boost::beast::http::field::content_type,
83 file.contentType);
84 }
85
86 if (!file.contentEncoding.empty())
87 {
88 asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
89 file.contentEncoding);
90 }
91
92 if (!file.etag.empty())
93 {
94 asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
95 // Don't cache paths that don't have the etag in them, like
96 // index, which gets transformed to /
97 if (!file.renamed)
98 {
99 // Anything with a hash can be cached forever and is
100 // immutable
101 asyncResp->res.addHeader(boost::beast::http::field::cache_control,
102 "max-age=31556926, immutable");
103 }
104
105 std::string_view cachedEtag =
106 req.getHeaderValue(boost::beast::http::field::if_none_match);
107 if (cachedEtag == file.etag)
108 {
109 asyncResp->res.result(boost::beast::http::status::not_modified);
110 return;
111 }
112 }
113
Ed Tanousb2539062024-03-12 16:58:35 -0700114 if (asyncResp->res.openFile(file.absolutePath, bmcweb::EncodingType::Raw,
115 file.onDiskComp) != crow::OpenCode::Success)
Ed Tanousca89b202024-04-25 23:02:40 -0700116 {
117 BMCWEB_LOG_DEBUG("failed to read file");
118 asyncResp->res.result(
119 boost::beast::http::status::internal_server_error);
120 return;
121 }
122}
123
124inline std::string_view getFiletypeForExtension(std::string_view extension)
125{
126 constexpr static std::array<std::pair<std::string_view, std::string_view>,
127 17>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700128 contentTypes{
129 {{".css", "text/css;charset=UTF-8"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700130 {".eot", "application/vnd.ms-fontobject"},
Ed Tanousca89b202024-04-25 23:02:40 -0700131 {".gif", "image/gif"},
132 {".html", "text/html;charset=UTF-8"},
133 {".ico", "image/x-icon"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700134 {".jpeg", "image/jpeg"},
Ed Tanousca89b202024-04-25 23:02:40 -0700135 {".jpg", "image/jpeg"},
136 {".js", "application/javascript;charset=UTF-8"},
137 {".json", "application/json"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700138 // dev tools don't care about map type, setting to json causes
139 // browser to show as text
140 // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
Ed Tanousca89b202024-04-25 23:02:40 -0700141 {".map", "application/json"},
142 {".png", "image/png;charset=UTF-8"},
143 {".svg", "image/svg+xml"},
144 {".ttf", "application/x-font-ttf"},
145 {".woff", "application/x-font-woff"},
146 {".woff2", "application/x-font-woff2"},
147 {".xml", "application/xml"}}};
Ed Tanousa47f32b2019-10-24 10:08:04 -0700148
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400149 const auto* contentType =
150 std::ranges::find_if(contentTypes, [&extension](const auto& val) {
151 return val.first == extension;
152 });
Ed Tanous153fdcf2021-03-04 16:43:14 -0800153
Ed Tanousca89b202024-04-25 23:02:40 -0700154 if (contentType == contentTypes.end())
155 {
156 BMCWEB_LOG_ERROR(
157 "Cannot determine content-type for file with extension {}",
158 extension);
159 return "";
160 }
161 return contentType->second;
162}
163
164inline void addFile(App& app, const std::filesystem::directory_entry& dir)
165{
166 StaticFile file;
167 file.absolutePath = dir.path();
168 std::filesystem::path relativePath(
169 file.absolutePath.string().substr(rootpath.size() - 1));
170
171 std::string extension = relativePath.extension();
172 std::filesystem::path webpath = relativePath;
173
174 if (extension == ".gz")
175 {
176 webpath = webpath.replace_extension("");
177 // Use the non-gzip version for determining content type
178 extension = webpath.extension().string();
179 file.contentEncoding = "gzip";
Ed Tanousb2539062024-03-12 16:58:35 -0700180 file.onDiskComp = bmcweb::CompressionType::Gzip;
Ed Tanousca89b202024-04-25 23:02:40 -0700181 }
Ed Tanous2b47f942024-03-12 15:43:16 -0700182 else if (extension == ".zstd")
183 {
184 webpath = webpath.replace_extension("");
185 // Use the non-zstd version for determining content type
186 extension = webpath.extension().string();
187 file.contentEncoding = "zstd";
Ed Tanousb2539062024-03-12 16:58:35 -0700188 file.onDiskComp = bmcweb::CompressionType::Zstd;
Ed Tanous2b47f942024-03-12 15:43:16 -0700189 }
Ed Tanousca89b202024-04-25 23:02:40 -0700190
191 file.etag = getStaticEtag(webpath);
192
193 if (webpath.filename().string().starts_with("index."))
194 {
195 webpath = webpath.parent_path();
196 if (webpath.string().empty() || webpath.string().back() != '/')
197 {
198 // insert the non-directory version of this path
199 webroutes::routes.insert(webpath);
200 webpath += "/";
201 file.renamed = true;
202 }
203 }
204
205 std::pair<boost::container::flat_set<std::string>::iterator, bool>
206 inserted = webroutes::routes.insert(webpath);
207
208 if (!inserted.second)
209 {
210 // Got a duplicated path. This is expected in certain
211 // situations
212 BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
213 return;
214 }
215 file.contentType = getFiletypeForExtension(extension);
216
217 if (webpath == "/")
218 {
Myung Bae834d99b2025-08-03 11:33:43 -0500219 forward_unauthorized::hasWebuiRoute() = true;
Ed Tanousca89b202024-04-25 23:02:40 -0700220 }
221
222 app.routeDynamic(webpath)(
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400223 [file = std::move(
224 file)](const crow::Request& req,
225 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
226 handleStaticAsset(req, asyncResp, file);
227 });
Ed Tanousca89b202024-04-25 23:02:40 -0700228}
229
230inline void requestRoutes(App& app)
231{
Ed Tanous153fdcf2021-03-04 16:43:14 -0800232 std::error_code ec;
Ed Tanousca89b202024-04-25 23:02:40 -0700233 std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800234 if (ec)
235 {
Ed Tanous62598e32023-07-17 17:06:25 -0700236 BMCWEB_LOG_ERROR(
Ed Tanousca89b202024-04-25 23:02:40 -0700237 "Unable to find or open {} static file hosting disabled", rootpath);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800238 return;
239 }
240
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 // In certain cases, we might have both a gzipped version of the file AND a
242 // non-gzipped version. To avoid duplicated routes, we need to make sure we
243 // get the gzipped version first. Because the gzipped path should be longer
Ed Tanous8b156452018-10-12 11:09:26 -0700244 // than the non gzipped path, if we sort in descending order, we should be
Ed Tanous1abe55e2018-09-05 08:30:59 -0700245 // guaranteed to get the gzip version first.
Ed Tanousa47f32b2019-10-24 10:08:04 -0700246 std::vector<std::filesystem::directory_entry> paths(
247 std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 std::sort(paths.rbegin(), paths.rend());
Ed Tanous9dc2c4d2018-03-07 14:51:27 -0800249
Ed Tanousa47f32b2019-10-24 10:08:04 -0700250 for (const std::filesystem::directory_entry& dir : paths)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700251 {
Ed Tanousa47f32b2019-10-24 10:08:04 -0700252 if (std::filesystem::is_directory(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700253 {
254 // don't recurse into hidden directories or symlinks
Ed Tanous11ba3972022-07-11 09:50:41 -0700255 if (dir.path().filename().string().starts_with(".") ||
Ed Tanousa47f32b2019-10-24 10:08:04 -0700256 std::filesystem::is_symlink(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 {
258 dirIter.disable_recursion_pending();
259 }
Ed Tanousba9f9a62017-10-11 16:40:35 -0700260 }
Ed Tanousa47f32b2019-10-24 10:08:04 -0700261 else if (std::filesystem::is_regular_file(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 {
Ed Tanousca89b202024-04-25 23:02:40 -0700263 addFile(app, dir);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700264 }
Ed Tanous911ac312017-08-15 09:37:42 -0700265 }
Ed Tanous99dc9c72019-10-24 10:09:03 -0700266}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700267} // namespace webassets
268} // namespace crow