xref: /openbmc/bmcweb/include/webassets.hpp (revision d45d2d0f)
1 #pragma once
2 
3 #include "filesystem.hpp"
4 
5 #include <crow/app.h>
6 #include <crow/http_request.h>
7 #include <crow/http_response.h>
8 #include <crow/routing.h>
9 
10 #include <boost/algorithm/string/replace.hpp>
11 #include <boost/container/flat_set.hpp>
12 #include <fstream>
13 #include <string>
14 
15 namespace crow
16 {
17 namespace webassets
18 {
19 
20 namespace filesystem = std::filesystem;
21 
22 struct CmpStr
23 {
24     bool operator()(const char* a, const char* b) const
25     {
26         return std::strcmp(a, b) < 0;
27     }
28 };
29 
30 static boost::container::flat_set<std::string> routes;
31 
32 template <typename... Middlewares> void requestRoutes(Crow<Middlewares...>& app)
33 {
34     const static boost::container::flat_map<const char*, const char*, CmpStr>
35         contentTypes{
36             {{".css", "text/css;charset=UTF-8"},
37              {".html", "text/html;charset=UTF-8"},
38              {".js", "application/javascript;charset=UTF-8"},
39              {".png", "image/png;charset=UTF-8"},
40              {".woff", "application/x-font-woff"},
41              {".woff2", "application/x-font-woff2"},
42              {".gif", "image/gif"},
43              {".ico", "image/x-icon"},
44              {".ttf", "application/x-font-ttf"},
45              {".svg", "image/svg+xml"},
46              {".eot", "application/vnd.ms-fontobject"},
47              {".xml", "application/xml"},
48              {".json", "application/json"},
49              {".jpg", "image/jpeg"},
50              {".jpeg", "image/jpeg"},
51              {".json", "application/json"},
52              // dev tools don't care about map type, setting to json causes
53              // browser to show as text
54              // https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
55              {".map", "application/json"}}};
56     filesystem::path rootpath{"/usr/share/www/"};
57     filesystem::recursive_directory_iterator dirIter(rootpath);
58     // In certain cases, we might have both a gzipped version of the file AND a
59     // non-gzipped version.  To avoid duplicated routes, we need to make sure we
60     // get the gzipped version first.  Because the gzipped path should be longer
61     // than the non gzipped path, if we sort in descending order, we should be
62     // guaranteed to get the gzip version first.
63     std::vector<filesystem::directory_entry> paths(filesystem::begin(dirIter),
64                                                    filesystem::end(dirIter));
65     std::sort(paths.rbegin(), paths.rend());
66 
67     for (const filesystem::directory_entry& dir : paths)
68     {
69         filesystem::path absolutePath = dir.path();
70         filesystem::path relativePath{
71             absolutePath.string().substr(rootpath.string().size() - 1)};
72         if (filesystem::is_directory(dir))
73         {
74             // don't recurse into hidden directories or symlinks
75             if (boost::starts_with(dir.path().filename().string(), ".") ||
76                 filesystem::is_symlink(dir))
77             {
78                 dirIter.disable_recursion_pending();
79             }
80         }
81         else if (filesystem::is_regular_file(dir))
82         {
83             std::string extension = relativePath.extension();
84             filesystem::path webpath = relativePath;
85             const char* contentEncoding = nullptr;
86 
87             if (extension == ".gz")
88             {
89                 webpath = webpath.replace_extension("");
90                 // Use the non-gzip version for determining content type
91                 extension = webpath.extension().string();
92                 contentEncoding = "gzip";
93             }
94 
95             if (boost::starts_with(webpath.filename().string(), "index."))
96             {
97                 webpath = webpath.parent_path();
98                 if (webpath.string().size() == 0 ||
99                     webpath.string().back() != '/')
100                 {
101                     // insert the non-directory version of this path
102                     routes.insert(webpath);
103                     webpath += "/";
104                 }
105             }
106 
107             std::pair<boost::container::flat_set<std::string>::iterator, bool>
108                 inserted = routes.insert(webpath);
109 
110             if (!inserted.second)
111             {
112                 // Got a duplicated path.  This is expected in certain
113                 // situations
114                 BMCWEB_LOG_DEBUG << "Got duplicated path " << webpath;
115                 continue;
116             }
117             const char* contentType = nullptr;
118 
119             auto contentTypeIt = contentTypes.find(extension.c_str());
120             if (contentTypeIt == contentTypes.end())
121             {
122                 BMCWEB_LOG_ERROR << "Cannot determine content-type for "
123                                  << absolutePath << " with extension "
124                                  << extension;
125             }
126             else
127             {
128                 contentType = contentTypeIt->second;
129             }
130 
131             app.routeDynamic(webpath)(
132                 [absolutePath, contentType, contentEncoding](
133                     const crow::Request& req, crow::Response& res) {
134                     if (contentType != nullptr)
135                     {
136                         res.addHeader("Content-Type", contentType);
137                     }
138 
139                     if (contentEncoding != nullptr)
140                     {
141                         res.addHeader("Content-Encoding", contentEncoding);
142                     }
143 
144                     // res.set_header("Cache-Control", "public, max-age=86400");
145                     std::ifstream inf(absolutePath);
146                     if (!inf)
147                     {
148                         BMCWEB_LOG_DEBUG << "failed to read file";
149                         res.result(
150                             boost::beast::http::status::internal_server_error);
151                         res.end();
152                         return;
153                     }
154 
155                     res.body() = {std::istreambuf_iterator<char>(inf),
156                                   std::istreambuf_iterator<char>()};
157                     res.end();
158                 });
159         }
160     }
161 } // namespace webassets
162 } // namespace webassets
163 } // namespace crow
164