blob: 91239dc2c5ed1014a57f1e4d3f8492c88dafc3bb [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 Tanous3ccb3ad2023-01-13 17:40:03 -08008#include "http_request.hpp"
9#include "http_response.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -080010#include "logging.hpp"
11#include "str_utility.hpp"
James Feist3909dc82020-04-03 10:58:55 -070012#include "webroutes.hpp"
13
Ed Tanousd7857202025-01-28 15:32:26 -080014#include <boost/beast/http/field.hpp>
15#include <boost/beast/http/status.hpp>
Ed Tanous911ac312017-08-15 09:37:42 -070016#include <boost/container/flat_set.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050017
Ed Tanousca89b202024-04-25 23:02:40 -070018#include <algorithm>
19#include <array>
James Feist4418c7f2019-04-15 11:09:15 -070020#include <filesystem>
Ed Tanousd7857202025-01-28 15:32:26 -080021#include <format>
22#include <memory>
Ed Tanous1abe55e2018-09-05 08:30:59 -070023#include <string>
Ed Tanousca89b202024-04-25 23:02:40 -070024#include <string_view>
Ed Tanousd7857202025-01-28 15:32:26 -080025#include <system_error>
26#include <utility>
27#include <vector>
Ed Tanous911ac312017-08-15 09:37:42 -070028
Ed Tanous1abe55e2018-09-05 08:30:59 -070029namespace crow
30{
31namespace webassets
32{
Ed Tanous911ac312017-08-15 09:37:42 -070033
Ed Tanous499b5b42024-04-06 08:39:18 -070034inline std::string getStaticEtag(const std::filesystem::path& webpath)
35{
36 // webpack outputs production chunks in the form:
37 // <filename>.<hash>.<extension>
38 // For example app.63e2c453.css
39 // Try to detect this, so we can use the hash as the ETAG
40 std::vector<std::string> split;
41 bmcweb::split(split, webpath.filename().string(), '.');
Ed Tanous499b5b42024-04-06 08:39:18 -070042 if (split.size() < 3)
43 {
44 return "";
45 }
46
47 // get the second to last element
48 std::string hash = split.rbegin()[1];
49
50 // Webpack hashes are 8 characters long
51 if (hash.size() != 8)
52 {
53 return "";
54 }
55 // Webpack hashes only include hex printable characters
56 if (hash.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos)
57 {
58 return "";
59 }
60 return std::format("\"{}\"", hash);
61}
62
Ed Tanousca89b202024-04-25 23:02:40 -070063static constexpr std::string_view rootpath("/usr/share/www/");
64
65struct StaticFile
Ed Tanous1abe55e2018-09-05 08:30:59 -070066{
Ed Tanousca89b202024-04-25 23:02:40 -070067 std::filesystem::path absolutePath;
68 std::string_view contentType;
69 std::string_view contentEncoding;
70 std::string etag;
71 bool renamed = false;
72};
73
Patrick Williamsbd79bce2024-08-16 15:22:20 -040074inline void handleStaticAsset(
75 const crow::Request& req,
76 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
Ed Tanousca89b202024-04-25 23:02:40 -070077{
78 if (!file.contentType.empty())
79 {
80 asyncResp->res.addHeader(boost::beast::http::field::content_type,
81 file.contentType);
82 }
83
84 if (!file.contentEncoding.empty())
85 {
86 asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
87 file.contentEncoding);
88 }
89
90 if (!file.etag.empty())
91 {
92 asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
93 // Don't cache paths that don't have the etag in them, like
94 // index, which gets transformed to /
95 if (!file.renamed)
96 {
97 // Anything with a hash can be cached forever and is
98 // immutable
99 asyncResp->res.addHeader(boost::beast::http::field::cache_control,
100 "max-age=31556926, immutable");
101 }
102
103 std::string_view cachedEtag =
104 req.getHeaderValue(boost::beast::http::field::if_none_match);
105 if (cachedEtag == file.etag)
106 {
107 asyncResp->res.result(boost::beast::http::status::not_modified);
108 return;
109 }
110 }
111
Myung Baed51c61b2024-09-13 10:35:34 -0500112 if (asyncResp->res.openFile(file.absolutePath) != crow::OpenCode::Success)
Ed Tanousca89b202024-04-25 23:02:40 -0700113 {
114 BMCWEB_LOG_DEBUG("failed to read file");
115 asyncResp->res.result(
116 boost::beast::http::status::internal_server_error);
117 return;
118 }
119}
120
121inline std::string_view getFiletypeForExtension(std::string_view extension)
122{
123 constexpr static std::array<std::pair<std::string_view, std::string_view>,
124 17>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700125 contentTypes{
126 {{".css", "text/css;charset=UTF-8"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700127 {".eot", "application/vnd.ms-fontobject"},
Ed Tanousca89b202024-04-25 23:02:40 -0700128 {".gif", "image/gif"},
129 {".html", "text/html;charset=UTF-8"},
130 {".ico", "image/x-icon"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700131 {".jpeg", "image/jpeg"},
Ed Tanousca89b202024-04-25 23:02:40 -0700132 {".jpg", "image/jpeg"},
133 {".js", "application/javascript;charset=UTF-8"},
134 {".json", "application/json"},
Ed Tanous1abe55e2018-09-05 08:30:59 -0700135 // dev tools don't care about map type, setting to json causes
136 // browser to show as text
137 // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
Ed Tanousca89b202024-04-25 23:02:40 -0700138 {".map", "application/json"},
139 {".png", "image/png;charset=UTF-8"},
140 {".svg", "image/svg+xml"},
141 {".ttf", "application/x-font-ttf"},
142 {".woff", "application/x-font-woff"},
143 {".woff2", "application/x-font-woff2"},
144 {".xml", "application/xml"}}};
Ed Tanousa47f32b2019-10-24 10:08:04 -0700145
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400146 const auto* contentType =
147 std::ranges::find_if(contentTypes, [&extension](const auto& val) {
148 return val.first == extension;
149 });
Ed Tanous153fdcf2021-03-04 16:43:14 -0800150
Ed Tanousca89b202024-04-25 23:02:40 -0700151 if (contentType == contentTypes.end())
152 {
153 BMCWEB_LOG_ERROR(
154 "Cannot determine content-type for file with extension {}",
155 extension);
156 return "";
157 }
158 return contentType->second;
159}
160
161inline void addFile(App& app, const std::filesystem::directory_entry& dir)
162{
163 StaticFile file;
164 file.absolutePath = dir.path();
165 std::filesystem::path relativePath(
166 file.absolutePath.string().substr(rootpath.size() - 1));
167
168 std::string extension = relativePath.extension();
169 std::filesystem::path webpath = relativePath;
170
171 if (extension == ".gz")
172 {
173 webpath = webpath.replace_extension("");
174 // Use the non-gzip version for determining content type
175 extension = webpath.extension().string();
176 file.contentEncoding = "gzip";
177 }
Ed Tanous2b47f942024-03-12 15:43:16 -0700178 else if (extension == ".zstd")
179 {
180 webpath = webpath.replace_extension("");
181 // Use the non-zstd version for determining content type
182 extension = webpath.extension().string();
183 file.contentEncoding = "zstd";
184 }
Ed Tanousca89b202024-04-25 23:02:40 -0700185
186 file.etag = getStaticEtag(webpath);
187
188 if (webpath.filename().string().starts_with("index."))
189 {
190 webpath = webpath.parent_path();
191 if (webpath.string().empty() || webpath.string().back() != '/')
192 {
193 // insert the non-directory version of this path
194 webroutes::routes.insert(webpath);
195 webpath += "/";
196 file.renamed = true;
197 }
198 }
199
200 std::pair<boost::container::flat_set<std::string>::iterator, bool>
201 inserted = webroutes::routes.insert(webpath);
202
203 if (!inserted.second)
204 {
205 // Got a duplicated path. This is expected in certain
206 // situations
207 BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
208 return;
209 }
210 file.contentType = getFiletypeForExtension(extension);
211
212 if (webpath == "/")
213 {
214 forward_unauthorized::hasWebuiRoute = true;
215 }
216
217 app.routeDynamic(webpath)(
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400218 [file = std::move(
219 file)](const crow::Request& req,
220 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
221 handleStaticAsset(req, asyncResp, file);
222 });
Ed Tanousca89b202024-04-25 23:02:40 -0700223}
224
225inline void requestRoutes(App& app)
226{
Ed Tanous153fdcf2021-03-04 16:43:14 -0800227 std::error_code ec;
Ed Tanousca89b202024-04-25 23:02:40 -0700228 std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800229 if (ec)
230 {
Ed Tanous62598e32023-07-17 17:06:25 -0700231 BMCWEB_LOG_ERROR(
Ed Tanousca89b202024-04-25 23:02:40 -0700232 "Unable to find or open {} static file hosting disabled", rootpath);
Ed Tanous153fdcf2021-03-04 16:43:14 -0800233 return;
234 }
235
Ed Tanous1abe55e2018-09-05 08:30:59 -0700236 // In certain cases, we might have both a gzipped version of the file AND a
237 // non-gzipped version. To avoid duplicated routes, we need to make sure we
238 // get the gzipped version first. Because the gzipped path should be longer
Ed Tanous8b156452018-10-12 11:09:26 -0700239 // than the non gzipped path, if we sort in descending order, we should be
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240 // guaranteed to get the gzip version first.
Ed Tanousa47f32b2019-10-24 10:08:04 -0700241 std::vector<std::filesystem::directory_entry> paths(
242 std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 std::sort(paths.rbegin(), paths.rend());
Ed Tanous9dc2c4d2018-03-07 14:51:27 -0800244
Ed Tanousa47f32b2019-10-24 10:08:04 -0700245 for (const std::filesystem::directory_entry& dir : paths)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700246 {
Ed Tanousa47f32b2019-10-24 10:08:04 -0700247 if (std::filesystem::is_directory(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 {
249 // don't recurse into hidden directories or symlinks
Ed Tanous11ba3972022-07-11 09:50:41 -0700250 if (dir.path().filename().string().starts_with(".") ||
Ed Tanousa47f32b2019-10-24 10:08:04 -0700251 std::filesystem::is_symlink(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700252 {
253 dirIter.disable_recursion_pending();
254 }
Ed Tanousba9f9a62017-10-11 16:40:35 -0700255 }
Ed Tanousa47f32b2019-10-24 10:08:04 -0700256 else if (std::filesystem::is_regular_file(dir))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 {
Ed Tanousca89b202024-04-25 23:02:40 -0700258 addFile(app, dir);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 }
Ed Tanous911ac312017-08-15 09:37:42 -0700260 }
Ed Tanous99dc9c72019-10-24 10:09:03 -0700261}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262} // namespace webassets
263} // namespace crow