xref: /openbmc/bmcweb/include/webassets.hpp (revision 36b5cba2d032908f7e2d5355c512c7541fad4861)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 
5 #include "app.hpp"
6 #include "async_resp.hpp"
7 #include "forward_unauthorized.hpp"
8 #include "http_body.hpp"
9 #include "http_request.hpp"
10 #include "http_response.hpp"
11 #include "logging.hpp"
12 #include "str_utility.hpp"
13 #include "webroutes.hpp"
14 
15 #include <boost/beast/http/field.hpp>
16 #include <boost/beast/http/status.hpp>
17 #include <boost/container/flat_set.hpp>
18 
19 #include <algorithm>
20 #include <array>
21 #include <filesystem>
22 #include <format>
23 #include <memory>
24 #include <ranges>
25 #include <string>
26 #include <string_view>
27 #include <system_error>
28 #include <utility>
29 #include <vector>
30 
31 namespace crow
32 {
33 namespace webassets
34 {
35 
getStaticEtag(const std::filesystem::path & webpath)36 inline std::string getStaticEtag(const std::filesystem::path& webpath)
37 {
38     // Build tools output production chunks in the form:
39     // <filename>.<hash>.<extension>
40     // Webpack example: app.63e2c453.css (8 hex chars)
41     // Vite example: app.DhhjLIym.js (8 alphanumeric chars)
42     // Try to detect this, so we can use the hash as the ETAG
43     std::vector<std::string> split;
44     bmcweb::split(split, webpath.filename().string(), '.');
45     if (split.size() < 3)
46     {
47         return "";
48     }
49 
50     // get the second to last element
51     std::string hash = split.rbegin()[1];
52 
53     // Build tool hashes are 8 characters long
54     if (hash.size() != 8)
55     {
56         return "";
57     }
58     // Build tool hashes only include alphanumeric characters
59     if (hash.find_first_not_of(
60             "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") !=
61         std::string::npos)
62     {
63         return "";
64     }
65     return std::format("\"{}\"", hash);
66 }
67 
68 static constexpr std::string_view rootpath("/usr/share/www/");
69 
70 struct StaticFile
71 {
72     std::filesystem::path absolutePath;
73     std::string_view contentType;
74     std::string_view contentEncoding;
75     std::string etag;
76     bmcweb::CompressionType onDiskComp = bmcweb::CompressionType::Raw;
77     bool renamed = false;
78 };
79 
handleStaticAsset(const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const StaticFile & file)80 inline void handleStaticAsset(
81     const crow::Request& req,
82     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
83 {
84     if (!file.contentType.empty())
85     {
86         asyncResp->res.addHeader(boost::beast::http::field::content_type,
87                                  file.contentType);
88     }
89 
90     if (!file.contentEncoding.empty())
91     {
92         asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
93                                  file.contentEncoding);
94     }
95 
96     if (!file.etag.empty())
97     {
98         asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
99         // Don't cache paths that don't have the etag in them, like
100         // index, which gets transformed to /
101         if (!file.renamed)
102         {
103             // Anything with a hash can be cached forever and is
104             // immutable
105             asyncResp->res.addHeader(boost::beast::http::field::cache_control,
106                                      "max-age=31556926, immutable");
107         }
108 
109         std::string_view cachedEtag =
110             req.getHeaderValue(boost::beast::http::field::if_none_match);
111         if (cachedEtag == file.etag)
112         {
113             asyncResp->res.result(boost::beast::http::status::not_modified);
114             return;
115         }
116     }
117 
118     if (asyncResp->res.openFile(file.absolutePath, bmcweb::EncodingType::Raw,
119                                 file.onDiskComp) != crow::OpenCode::Success)
120     {
121         BMCWEB_LOG_DEBUG("failed to read file");
122         asyncResp->res.result(
123             boost::beast::http::status::internal_server_error);
124         return;
125     }
126 }
127 
getFiletypeForExtension(std::string_view extension)128 inline std::string_view getFiletypeForExtension(std::string_view extension)
129 {
130     constexpr static std::array<std::pair<std::string_view, std::string_view>,
131                                 17>
132         contentTypes{
133             {{".css", "text/css;charset=UTF-8"},
134              {".eot", "application/vnd.ms-fontobject"},
135              {".gif", "image/gif"},
136              {".html", "text/html;charset=UTF-8"},
137              {".ico", "image/x-icon"},
138              {".jpeg", "image/jpeg"},
139              {".jpg", "image/jpeg"},
140              {".js", "application/javascript;charset=UTF-8"},
141              {".json", "application/json"},
142              // dev tools don't care about map type, setting to json causes
143              // browser to show as text
144              // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
145              {".map", "application/json"},
146              {".png", "image/png;charset=UTF-8"},
147              {".svg", "image/svg+xml"},
148              {".ttf", "application/x-font-ttf"},
149              {".woff", "application/x-font-woff"},
150              {".woff2", "application/x-font-woff2"},
151              {".xml", "application/xml"}}};
152 
153     const auto* contentType =
154         std::ranges::find_if(contentTypes, [&extension](const auto& val) {
155             return val.first == extension;
156         });
157 
158     if (contentType == contentTypes.end())
159     {
160         BMCWEB_LOG_ERROR(
161             "Cannot determine content-type for file with extension {}",
162             extension);
163         return "";
164     }
165     return contentType->second;
166 }
167 
addFile(App & app,const std::filesystem::directory_entry & dir)168 inline void addFile(App& app, const std::filesystem::directory_entry& dir)
169 {
170     StaticFile file;
171     file.absolutePath = dir.path();
172     std::filesystem::path relativePath(
173         file.absolutePath.string().substr(rootpath.size() - 1));
174 
175     std::string extension = relativePath.extension();
176     std::filesystem::path webpath = relativePath;
177 
178     if (extension == ".gz")
179     {
180         webpath = webpath.replace_extension("");
181         // Use the non-gzip version for determining content type
182         extension = webpath.extension().string();
183         file.contentEncoding = "gzip";
184         file.onDiskComp = bmcweb::CompressionType::Gzip;
185     }
186     else if (extension == ".zstd")
187     {
188         webpath = webpath.replace_extension("");
189         // Use the non-zstd version for determining content type
190         extension = webpath.extension().string();
191         file.contentEncoding = "zstd";
192         file.onDiskComp = bmcweb::CompressionType::Zstd;
193     }
194 
195     file.etag = getStaticEtag(webpath);
196 
197     if (webpath.filename().string().starts_with("index.") &&
198         webpath.extension() == ".html")
199     {
200         webpath = webpath.parent_path();
201         if (webpath.string().empty() || webpath.string().back() != '/')
202         {
203             // insert the non-directory version of this path
204             webroutes::routes.insert(webpath);
205             webpath += "/";
206             file.renamed = true;
207         }
208     }
209 
210     std::pair<boost::container::flat_set<std::string>::iterator, bool>
211         inserted = webroutes::routes.insert(webpath);
212 
213     if (!inserted.second)
214     {
215         // Got a duplicated path.  This is expected in certain
216         // situations
217         BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
218         return;
219     }
220     file.contentType = getFiletypeForExtension(extension);
221 
222     if (webpath == "/")
223     {
224         forward_unauthorized::hasWebuiRoute() = true;
225     }
226 
227     app.routeDynamic(webpath)(
228         [file = std::move(
229              file)](const crow::Request& req,
230                     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
231             handleStaticAsset(req, asyncResp, file);
232         });
233 }
234 
requestRoutes(App & app)235 inline void requestRoutes(App& app)
236 {
237     std::error_code ec;
238     std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
239     if (ec)
240     {
241         BMCWEB_LOG_ERROR(
242             "Unable to find or open {} static file hosting disabled", rootpath);
243         return;
244     }
245 
246     // In certain cases, we might have both a gzipped version of the file AND a
247     // non-gzipped version.  To avoid duplicated routes, we need to make sure we
248     // get the gzipped version first.  Because the gzipped path should be longer
249     // than the non gzipped path, if we sort in descending order, we should be
250     // guaranteed to get the gzip version first.
251     std::vector<std::filesystem::directory_entry> paths(
252         std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
253     std::ranges::sort(std::ranges::reverse_view(paths));
254 
255     for (const std::filesystem::directory_entry& dir : paths)
256     {
257         if (std::filesystem::is_directory(dir))
258         {
259             // don't recurse into hidden directories or symlinks
260             if (dir.path().filename().string().starts_with(".") ||
261                 std::filesystem::is_symlink(dir))
262             {
263                 dirIter.disable_recursion_pending();
264             }
265         }
266         else if (std::filesystem::is_regular_file(dir))
267         {
268             addFile(app, dir);
269         }
270     }
271 }
272 } // namespace webassets
273 } // namespace crow
274