xref: /openbmc/bmcweb/include/webassets.hpp (revision 834d99ba6b7b06b73378ea62f56f0b25cf80e1ec)
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 <string>
25 #include <string_view>
26 #include <system_error>
27 #include <utility>
28 #include <vector>
29 
30 namespace crow
31 {
32 namespace webassets
33 {
34 
getStaticEtag(const std::filesystem::path & webpath)35 inline 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(), '.');
43     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 
64 static constexpr std::string_view rootpath("/usr/share/www/");
65 
66 struct StaticFile
67 {
68     std::filesystem::path absolutePath;
69     std::string_view contentType;
70     std::string_view contentEncoding;
71     std::string etag;
72     bmcweb::CompressionType onDiskComp = bmcweb::CompressionType::Raw;
73     bool renamed = false;
74 };
75 
handleStaticAsset(const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const StaticFile & file)76 inline void handleStaticAsset(
77     const crow::Request& req,
78     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
79 {
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 
114     if (asyncResp->res.openFile(file.absolutePath, bmcweb::EncodingType::Raw,
115                                 file.onDiskComp) != crow::OpenCode::Success)
116     {
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 
getFiletypeForExtension(std::string_view extension)124 inline std::string_view getFiletypeForExtension(std::string_view extension)
125 {
126     constexpr static std::array<std::pair<std::string_view, std::string_view>,
127                                 17>
128         contentTypes{
129             {{".css", "text/css;charset=UTF-8"},
130              {".eot", "application/vnd.ms-fontobject"},
131              {".gif", "image/gif"},
132              {".html", "text/html;charset=UTF-8"},
133              {".ico", "image/x-icon"},
134              {".jpeg", "image/jpeg"},
135              {".jpg", "image/jpeg"},
136              {".js", "application/javascript;charset=UTF-8"},
137              {".json", "application/json"},
138              // 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
141              {".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"}}};
148 
149     const auto* contentType =
150         std::ranges::find_if(contentTypes, [&extension](const auto& val) {
151             return val.first == extension;
152         });
153 
154     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 
addFile(App & app,const std::filesystem::directory_entry & dir)164 inline 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";
180         file.onDiskComp = bmcweb::CompressionType::Gzip;
181     }
182     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";
188         file.onDiskComp = bmcweb::CompressionType::Zstd;
189     }
190 
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     {
219         forward_unauthorized::hasWebuiRoute() = true;
220     }
221 
222     app.routeDynamic(webpath)(
223         [file = std::move(
224              file)](const crow::Request& req,
225                     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
226             handleStaticAsset(req, asyncResp, file);
227         });
228 }
229 
requestRoutes(App & app)230 inline void requestRoutes(App& app)
231 {
232     std::error_code ec;
233     std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
234     if (ec)
235     {
236         BMCWEB_LOG_ERROR(
237             "Unable to find or open {} static file hosting disabled", rootpath);
238         return;
239     }
240 
241     // 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
244     // than the non gzipped path, if we sort in descending order, we should be
245     // guaranteed to get the gzip version first.
246     std::vector<std::filesystem::directory_entry> paths(
247         std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
248     std::sort(paths.rbegin(), paths.rend());
249 
250     for (const std::filesystem::directory_entry& dir : paths)
251     {
252         if (std::filesystem::is_directory(dir))
253         {
254             // don't recurse into hidden directories or symlinks
255             if (dir.path().filename().string().starts_with(".") ||
256                 std::filesystem::is_symlink(dir))
257             {
258                 dirIter.disable_recursion_pending();
259             }
260         }
261         else if (std::filesystem::is_regular_file(dir))
262         {
263             addFile(app, dir);
264         }
265     }
266 }
267 } // namespace webassets
268 } // namespace crow
269