xref: /openbmc/bmcweb/include/http_utility.hpp (revision 4cee35e7)
1 #pragma once
2 #include "http_request.hpp"
3 
4 #include <boost/algorithm/string.hpp>
5 
6 namespace http_helpers
7 {
8 inline std::vector<std::string> parseAccept(std::string_view header)
9 {
10     std::vector<std::string> encodings;
11     // chrome currently sends 6 accepts headers, firefox sends 4.
12     encodings.reserve(6);
13     boost::split(encodings, header, boost::is_any_of(", "),
14                  boost::token_compress_on);
15 
16     return encodings;
17 }
18 
19 inline bool requestPrefersHtml(std::string_view header)
20 {
21     for (const std::string& encoding : parseAccept(header))
22     {
23         if (encoding == "text/html")
24         {
25             return true;
26         }
27         if (encoding == "application/json")
28         {
29             return false;
30         }
31     }
32     return false;
33 }
34 
35 inline bool isOctetAccepted(std::string_view header)
36 {
37     for (const std::string& encoding : parseAccept(header))
38     {
39         if (encoding == "*/*" || encoding == "application/octet-stream")
40         {
41             return true;
42         }
43     }
44     return false;
45 }
46 
47 inline std::string urlEncode(const std::string_view value)
48 {
49     std::ostringstream escaped;
50     escaped.fill('0');
51     escaped << std::hex;
52 
53     for (const char c : value)
54     {
55         // Keep alphanumeric and other accepted characters intact
56         if ((isalnum(c) != 0) || c == '-' || c == '_' || c == '.' || c == '~')
57         {
58             escaped << c;
59             continue;
60         }
61 
62         // Any other characters are percent-encoded
63         escaped << std::uppercase;
64         escaped << '%' << std::setw(2)
65                 << static_cast<int>(static_cast<unsigned char>(c));
66         escaped << std::nouppercase;
67     }
68 
69     return escaped.str();
70 }
71 } // namespace http_helpers
72