xref: /openbmc/bmcweb/include/webassets.hpp (revision ca89b200)
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 
getStaticEtag(const std::filesystem::path & webpath)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(const crow::Request & req,const std::shared_ptr<bmcweb::AsyncResp> & asyncResp,const StaticFile & file)66     handleStaticAsset(const crow::Request& req,
67                       const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
68                       const StaticFile& file)
69 {
70     if (!file.contentType.empty())
71     {
72         asyncResp->res.addHeader(boost::beast::http::field::content_type,
73                                  file.contentType);
74     }
75 
76     if (!file.contentEncoding.empty())
77     {
78         asyncResp->res.addHeader(boost::beast::http::field::content_encoding,
79                                  file.contentEncoding);
80     }
81 
82     if (!file.etag.empty())
83     {
84         asyncResp->res.addHeader(boost::beast::http::field::etag, file.etag);
85         // Don't cache paths that don't have the etag in them, like
86         // index, which gets transformed to /
87         if (!file.renamed)
88         {
89             // Anything with a hash can be cached forever and is
90             // immutable
91             asyncResp->res.addHeader(boost::beast::http::field::cache_control,
92                                      "max-age=31556926, immutable");
93         }
94 
95         std::string_view cachedEtag =
96             req.getHeaderValue(boost::beast::http::field::if_none_match);
97         if (cachedEtag == file.etag)
98         {
99             asyncResp->res.result(boost::beast::http::status::not_modified);
100             return;
101         }
102     }
103 
104     if (!asyncResp->res.openFile(file.absolutePath))
105     {
106         BMCWEB_LOG_DEBUG("failed to read file");
107         asyncResp->res.result(
108             boost::beast::http::status::internal_server_error);
109         return;
110     }
111 }
112 
getFiletypeForExtension(std::string_view extension)113 inline std::string_view getFiletypeForExtension(std::string_view extension)
114 {
115     constexpr static std::array<std::pair<std::string_view, std::string_view>,
116                                 17>
117         contentTypes{
118             {{".css", "text/css;charset=UTF-8"},
119              {".eot", "application/vnd.ms-fontobject"},
120              {".gif", "image/gif"},
121              {".html", "text/html;charset=UTF-8"},
122              {".ico", "image/x-icon"},
123              {".jpeg", "image/jpeg"},
124              {".jpg", "image/jpeg"},
125              {".js", "application/javascript;charset=UTF-8"},
126              {".json", "application/json"},
127              // dev tools don't care about map type, setting to json causes
128              // browser to show as text
129              // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
130              {".map", "application/json"},
131              {".png", "image/png;charset=UTF-8"},
132              {".svg", "image/svg+xml"},
133              {".ttf", "application/x-font-ttf"},
134              {".woff", "application/x-font-woff"},
135              {".woff2", "application/x-font-woff2"},
136              {".xml", "application/xml"}}};
137 
138     const auto* contentType = std::ranges::find_if(
139         contentTypes,
140         [&extension](const auto& val) { return val.first == extension; });
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 
addFile(App & app,const std::filesystem::directory_entry & dir)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 
170     file.etag = getStaticEtag(webpath);
171 
172     if (webpath.filename().string().starts_with("index."))
173     {
174         webpath = webpath.parent_path();
175         if (webpath.string().empty() || webpath.string().back() != '/')
176         {
177             // insert the non-directory version of this path
178             webroutes::routes.insert(webpath);
179             webpath += "/";
180             file.renamed = true;
181         }
182     }
183 
184     std::pair<boost::container::flat_set<std::string>::iterator, bool>
185         inserted = webroutes::routes.insert(webpath);
186 
187     if (!inserted.second)
188     {
189         // Got a duplicated path.  This is expected in certain
190         // situations
191         BMCWEB_LOG_DEBUG("Got duplicated path {}", webpath.string());
192         return;
193     }
194     file.contentType = getFiletypeForExtension(extension);
195 
196     if (webpath == "/")
197     {
198         forward_unauthorized::hasWebuiRoute = true;
199     }
200 
201     app.routeDynamic(webpath)(
202         [file = std::move(file)](
203             const crow::Request& req,
204             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
205         handleStaticAsset(req, asyncResp, file);
206     });
207 }
208 
requestRoutes(App & app)209 inline void requestRoutes(App& app)
210 {
211     std::error_code ec;
212     std::filesystem::recursive_directory_iterator dirIter({rootpath}, ec);
213     if (ec)
214     {
215         BMCWEB_LOG_ERROR(
216             "Unable to find or open {} static file hosting disabled", rootpath);
217         return;
218     }
219 
220     // In certain cases, we might have both a gzipped version of the file AND a
221     // non-gzipped version.  To avoid duplicated routes, we need to make sure we
222     // get the gzipped version first.  Because the gzipped path should be longer
223     // than the non gzipped path, if we sort in descending order, we should be
224     // guaranteed to get the gzip version first.
225     std::vector<std::filesystem::directory_entry> paths(
226         std::filesystem::begin(dirIter), std::filesystem::end(dirIter));
227     std::sort(paths.rbegin(), paths.rend());
228 
229     for (const std::filesystem::directory_entry& dir : paths)
230     {
231         if (std::filesystem::is_directory(dir))
232         {
233             // don't recurse into hidden directories or symlinks
234             if (dir.path().filename().string().starts_with(".") ||
235                 std::filesystem::is_symlink(dir))
236             {
237                 dirIter.disable_recursion_pending();
238             }
239         }
240         else if (std::filesystem::is_regular_file(dir))
241         {
242             addFile(app, dir);
243         }
244     }
245 }
246 } // namespace webassets
247 } // namespace crow
248