Imported Upstream version 1.46.0
[platform/upstream/nghttp2.git] / src / shrpx_http.cc
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2012 Tatsuhiro Tsujikawa
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 #include "shrpx_http.h"
26
27 #include "shrpx_config.h"
28 #include "shrpx_log.h"
29 #include "http2.h"
30 #include "util.h"
31
32 using namespace nghttp2;
33
34 namespace shrpx {
35
36 namespace http {
37
38 StringRef create_error_html(BlockAllocator &balloc, unsigned int http_status) {
39   auto &httpconf = get_config()->http;
40
41   const auto &error_pages = httpconf.error_pages;
42   for (const auto &page : error_pages) {
43     if (page.http_status == 0 || page.http_status == http_status) {
44       return StringRef{std::begin(page.content), std::end(page.content)};
45     }
46   }
47
48   auto status_string = http2::stringify_status(balloc, http_status);
49   auto reason_phrase = http2::get_reason_phrase(http_status);
50
51   return concat_string_ref(
52       balloc, StringRef::from_lit(R"(<!DOCTYPE html><html lang="en"><title>)"),
53       status_string, StringRef::from_lit(" "), reason_phrase,
54       StringRef::from_lit("</title><body><h1>"), status_string,
55       StringRef::from_lit(" "), reason_phrase,
56       StringRef::from_lit("</h1><footer>"), httpconf.server_name,
57       StringRef::from_lit("</footer></body></html>"));
58 }
59
60 StringRef create_forwarded(BlockAllocator &balloc, int params,
61                            const StringRef &node_by, const StringRef &node_for,
62                            const StringRef &host, const StringRef &proto) {
63   size_t len = 0;
64   if ((params & FORWARDED_BY) && !node_by.empty()) {
65     len += str_size("by=\"") + node_by.size() + str_size("\";");
66   }
67   if ((params & FORWARDED_FOR) && !node_for.empty()) {
68     len += str_size("for=\"") + node_for.size() + str_size("\";");
69   }
70   if ((params & FORWARDED_HOST) && !host.empty()) {
71     len += str_size("host=\"") + host.size() + str_size("\";");
72   }
73   if ((params & FORWARDED_PROTO) && !proto.empty()) {
74     len += str_size("proto=") + proto.size() + str_size(";");
75   }
76
77   auto iov = make_byte_ref(balloc, len + 1);
78   auto p = iov.base;
79
80   if ((params & FORWARDED_BY) && !node_by.empty()) {
81     // This must be quoted-string unless it is obfuscated version
82     // (which starts with "_") or some special value (e.g.,
83     // "localhost" for UNIX domain socket), since ':' is not allowed
84     // in token.  ':' is used to separate host and port.
85     if (node_by[0] == '_' || node_by[0] == 'l') {
86       p = util::copy_lit(p, "by=");
87       p = std::copy(std::begin(node_by), std::end(node_by), p);
88       p = util::copy_lit(p, ";");
89     } else {
90       p = util::copy_lit(p, "by=\"");
91       p = std::copy(std::begin(node_by), std::end(node_by), p);
92       p = util::copy_lit(p, "\";");
93     }
94   }
95   if ((params & FORWARDED_FOR) && !node_for.empty()) {
96     // We only quote IPv6 literal address only, which starts with '['.
97     if (node_for[0] == '[') {
98       p = util::copy_lit(p, "for=\"");
99       p = std::copy(std::begin(node_for), std::end(node_for), p);
100       p = util::copy_lit(p, "\";");
101     } else {
102       p = util::copy_lit(p, "for=");
103       p = std::copy(std::begin(node_for), std::end(node_for), p);
104       p = util::copy_lit(p, ";");
105     }
106   }
107   if ((params & FORWARDED_HOST) && !host.empty()) {
108     // Just be quoted to skip checking characters.
109     p = util::copy_lit(p, "host=\"");
110     p = std::copy(std::begin(host), std::end(host), p);
111     p = util::copy_lit(p, "\";");
112   }
113   if ((params & FORWARDED_PROTO) && !proto.empty()) {
114     // Scheme production rule only allow characters which are all in
115     // token.
116     p = util::copy_lit(p, "proto=");
117     p = std::copy(std::begin(proto), std::end(proto), p);
118     *p++ = ';';
119   }
120
121   if (iov.base == p) {
122     return StringRef{};
123   }
124
125   --p;
126   *p = '\0';
127
128   return StringRef{iov.base, p};
129 }
130
131 std::string colorizeHeaders(const char *hdrs) {
132   std::string nhdrs;
133   const char *p = strchr(hdrs, '\n');
134   if (!p) {
135     // Not valid HTTP header
136     return hdrs;
137   }
138   nhdrs.append(hdrs, p + 1);
139   ++p;
140   while (1) {
141     const char *np = strchr(p, ':');
142     if (!np) {
143       nhdrs.append(p);
144       break;
145     }
146     nhdrs += TTY_HTTP_HD;
147     nhdrs.append(p, np);
148     nhdrs += TTY_RST;
149     auto redact = util::strieq_l("authorization", StringRef{p, np});
150     p = np;
151     np = strchr(p, '\n');
152     if (!np) {
153       if (redact) {
154         nhdrs.append(": <redacted>");
155       } else {
156         nhdrs.append(p);
157       }
158       break;
159     }
160     if (redact) {
161       nhdrs.append(": <redacted>\n");
162     } else {
163       nhdrs.append(p, np + 1);
164     }
165     p = np + 1;
166   }
167   return nhdrs;
168 }
169
170 ssize_t select_padding_callback(nghttp2_session *session,
171                                 const nghttp2_frame *frame, size_t max_payload,
172                                 void *user_data) {
173   return std::min(max_payload, frame->hd.length + get_config()->padding);
174 }
175
176 StringRef create_affinity_cookie(BlockAllocator &balloc, const StringRef &name,
177                                  uint32_t affinity_cookie,
178                                  const StringRef &path, bool secure) {
179   static constexpr auto PATH_PREFIX = StringRef::from_lit("; Path=");
180   static constexpr auto SECURE = StringRef::from_lit("; Secure");
181   // <name>=<value>[; Path=<path>][; Secure]
182   size_t len = name.size() + 1 + 8;
183
184   if (!path.empty()) {
185     len += PATH_PREFIX.size() + path.size();
186   }
187   if (secure) {
188     len += SECURE.size();
189   }
190
191   auto iov = make_byte_ref(balloc, len + 1);
192   auto p = iov.base;
193   p = std::copy(std::begin(name), std::end(name), p);
194   *p++ = '=';
195   affinity_cookie = htonl(affinity_cookie);
196   p = util::format_hex(p,
197                        StringRef{reinterpret_cast<uint8_t *>(&affinity_cookie),
198                                  reinterpret_cast<uint8_t *>(&affinity_cookie) +
199                                      sizeof(affinity_cookie)});
200   if (!path.empty()) {
201     p = std::copy(std::begin(PATH_PREFIX), std::end(PATH_PREFIX), p);
202     p = std::copy(std::begin(path), std::end(path), p);
203   }
204   if (secure) {
205     p = std::copy(std::begin(SECURE), std::end(SECURE), p);
206   }
207   *p = '\0';
208   return StringRef{iov.base, p};
209 }
210
211 bool require_cookie_secure_attribute(SessionAffinityCookieSecure secure,
212                                      const StringRef &scheme) {
213   switch (secure) {
214   case SessionAffinityCookieSecure::AUTO:
215     return scheme == "https";
216   case SessionAffinityCookieSecure::YES:
217     return true;
218   default:
219     return false;
220   }
221 }
222
223 StringRef create_altsvc_header_value(BlockAllocator &balloc,
224                                      const std::vector<AltSvc> &altsvcs) {
225   // <PROTOID>="<HOST>:<SERVICE>"; <PARAMS>
226   size_t len = 0;
227
228   if (altsvcs.empty()) {
229     return StringRef{};
230   }
231
232   for (auto &altsvc : altsvcs) {
233     len += util::percent_encode_tokenlen(altsvc.protocol_id);
234     len += str_size("=\"");
235     len += util::quote_stringlen(altsvc.host);
236     len += str_size(":");
237     len += altsvc.service.size();
238     len += str_size("\"");
239     if (!altsvc.params.empty()) {
240       len += str_size("; ");
241       len += altsvc.params.size();
242     }
243   }
244
245   // ", " between items.
246   len += (altsvcs.size() - 1) * 2;
247
248   // We will write additional ", " at the end, and cut it later.
249   auto iov = make_byte_ref(balloc, len + 2);
250   auto p = iov.base;
251
252   for (auto &altsvc : altsvcs) {
253     p = util::percent_encode_token(p, altsvc.protocol_id);
254     p = util::copy_lit(p, "=\"");
255     p = util::quote_string(p, altsvc.host);
256     *p++ = ':';
257     p = std::copy(std::begin(altsvc.service), std::end(altsvc.service), p);
258     *p++ = '"';
259     if (!altsvc.params.empty()) {
260       p = util::copy_lit(p, "; ");
261       p = std::copy(std::begin(altsvc.params), std::end(altsvc.params), p);
262     }
263     p = util::copy_lit(p, ", ");
264   }
265
266   p -= 2;
267   *p = '\0';
268
269   assert(static_cast<size_t>(p - iov.base) == len);
270
271   return StringRef{iov.base, p};
272 }
273
274 } // namespace http
275
276 } // namespace shrpx