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