xref: /openbmc/bmcweb/include/webassets.hpp (revision d78572018fc2022091ff8b8eb5a7fef2172ba3d6)
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_request.hpp"
9 #include "http_response.hpp"
10 #include "logging.hpp"
11 #include "str_utility.hpp"
12 #include "webroutes.hpp"
13 
14 #include <boost/beast/http/field.hpp>
15 #include <boost/beast/http/status.hpp>
16 #include <boost/container/flat_set.hpp>
17 
18 #include <algorithm>
19 #include <array>
20 #include <filesystem>
21 #include <format>
22 #include <memory>
23 #include <string>
24 #include <string_view>
25 #include <system_error>
26 #include <utility>
27 #include <vector>
28 
29 namespace crow
30 {
31 namespace webassets
32 {
33 
getStaticEtag(const std::filesystem::path & webpath)34 inline 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(), '.');
42     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 
63 static constexpr std::string_view rootpath("/usr/share/www/");
64 
65 struct StaticFile
66 {
67     std::filesystem::path absolutePath;
68     std::string_view contentType;
69     std::string_view contentEncoding;
70     std::string etag;
71     bool renamed = false;
72 };
73 
handleStaticAsset(const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const StaticFile & file)74 inline void handleStaticAsset(
75     const crow::Request& req,
76     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const StaticFile& file)
77 {
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 
112     if (asyncResp->res.openFile(file.absolutePath) != crow::OpenCode::Success)
113     {
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 
getFiletypeForExtension(std::string_view extension)121 inline std::string_view getFiletypeForExtension(std::string_view extension)
122 {
123     constexpr static std::array<std::pair<std::string_view, std::string_view>,
124                                 17>
125         contentTypes{
126             {{".css", "text/css;charset=UTF-8"},
127              {".eot", "application/vnd.ms-fontobject"},
128              {".gif", "image/gif"},
129              {".html", "text/html;charset=UTF-8"},
130              {".ico", "image/x-icon"},
131              {".jpeg", "image/jpeg"},
132              {".jpg", "image/jpeg"},
133              {".js", "application/javascript;charset=UTF-8"},
134              {".json", "application/json"},
135              // 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
138              {".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"}}};
145 
146     const auto* contentType =
147         std::ranges::find_if(contentTypes, [&extension](const auto& val) {
148             return val.first == extension;
149         });
150 
151     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 
addFile(App & app,const std::filesystem::directory_entry & dir)161 inline 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     }
178     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     }
185 
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)(
218         [file = std::move(
219              file)](const crow::Request& req,
220                     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
221             handleStaticAsset(req, asyncResp, file);
222         });
223 }
224 
requestRoutes(App & app)225 inline void requestRoutes(App& app)
226 {
227     std::error_code ec;
228     std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
229     if (ec)
230     {
231         BMCWEB_LOG_ERROR(
232             "Unable to find or open {} static file hosting disabled", rootpath);
233         return;
234     }
235 
236     // 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
239     // than the non gzipped path, if we sort in descending order, we should be
240     // guaranteed to get the gzip version first.
241     std::vector<std::filesystem::directory_entry> paths(
242         std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
243     std::sort(paths.rbegin(), paths.rend());
244 
245     for (const std::filesystem::directory_entry& dir : paths)
246     {
247         if (std::filesystem::is_directory(dir))
248         {
249             // don't recurse into hidden directories or symlinks
250             if (dir.path().filename().string().starts_with(".") ||
251                 std::filesystem::is_symlink(dir))
252             {
253                 dirIter.disable_recursion_pending();
254             }
255         }
256         else if (std::filesystem::is_regular_file(dir))
257         {
258             addFile(app, dir);
259         }
260     }
261 }
262 } // namespace webassets
263 } // namespace crow
264