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