• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
create_error_html(BlockAllocator & balloc,unsigned int http_status)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::span{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, R"(<!DOCTYPE html><html lang="en"><title>)"_sr, status_string,
53       " "_sr, reason_phrase, "</title><body><h1>"_sr, status_string, " "_sr,
54       reason_phrase, "</h1><footer>"_sr, httpconf.server_name,
55       "</footer></body></html>"_sr);
56 }
57 
create_forwarded(BlockAllocator & balloc,int params,const StringRef & node_by,const StringRef & node_for,const StringRef & host,const StringRef & proto)58 StringRef create_forwarded(BlockAllocator &balloc, int params,
59                            const StringRef &node_by, const StringRef &node_for,
60                            const StringRef &host, const StringRef &proto) {
61   size_t len = 0;
62   if ((params & FORWARDED_BY) && !node_by.empty()) {
63     len += str_size("by=\"") + node_by.size() + str_size("\";");
64   }
65   if ((params & FORWARDED_FOR) && !node_for.empty()) {
66     len += str_size("for=\"") + node_for.size() + str_size("\";");
67   }
68   if ((params & FORWARDED_HOST) && !host.empty()) {
69     len += str_size("host=\"") + host.size() + str_size("\";");
70   }
71   if ((params & FORWARDED_PROTO) && !proto.empty()) {
72     len += str_size("proto=") + proto.size() + str_size(";");
73   }
74 
75   auto iov = make_byte_ref(balloc, len + 1);
76   auto p = std::begin(iov);
77 
78   if ((params & FORWARDED_BY) && !node_by.empty()) {
79     // This must be quoted-string unless it is obfuscated version
80     // (which starts with "_") or some special value (e.g.,
81     // "localhost" for UNIX domain socket), since ':' is not allowed
82     // in token.  ':' is used to separate host and port.
83     if (node_by[0] == '_' || node_by[0] == 'l') {
84       p = util::copy_lit(p, "by=");
85       p = std::copy(std::begin(node_by), std::end(node_by), p);
86       p = util::copy_lit(p, ";");
87     } else {
88       p = util::copy_lit(p, "by=\"");
89       p = std::copy(std::begin(node_by), std::end(node_by), p);
90       p = util::copy_lit(p, "\";");
91     }
92   }
93   if ((params & FORWARDED_FOR) && !node_for.empty()) {
94     // We only quote IPv6 literal address only, which starts with '['.
95     if (node_for[0] == '[') {
96       p = util::copy_lit(p, "for=\"");
97       p = std::copy(std::begin(node_for), std::end(node_for), p);
98       p = util::copy_lit(p, "\";");
99     } else {
100       p = util::copy_lit(p, "for=");
101       p = std::copy(std::begin(node_for), std::end(node_for), p);
102       p = util::copy_lit(p, ";");
103     }
104   }
105   if ((params & FORWARDED_HOST) && !host.empty()) {
106     // Just be quoted to skip checking characters.
107     p = util::copy_lit(p, "host=\"");
108     p = std::copy(std::begin(host), std::end(host), p);
109     p = util::copy_lit(p, "\";");
110   }
111   if ((params & FORWARDED_PROTO) && !proto.empty()) {
112     // Scheme production rule only allow characters which are all in
113     // token.
114     p = util::copy_lit(p, "proto=");
115     p = std::copy(std::begin(proto), std::end(proto), p);
116     *p++ = ';';
117   }
118 
119   if (std::begin(iov) == p) {
120     return StringRef{};
121   }
122 
123   --p;
124   *p = '\0';
125 
126   return StringRef{std::span{std::begin(iov), p}};
127 }
128 
colorizeHeaders(const char * hdrs)129 std::string colorizeHeaders(const char *hdrs) {
130   std::string nhdrs;
131   const char *p = strchr(hdrs, '\n');
132   if (!p) {
133     // Not valid HTTP header
134     return hdrs;
135   }
136   nhdrs.append(hdrs, p + 1);
137   ++p;
138   while (1) {
139     const char *np = strchr(p, ':');
140     if (!np) {
141       nhdrs.append(p);
142       break;
143     }
144     nhdrs += TTY_HTTP_HD;
145     nhdrs.append(p, np);
146     nhdrs += TTY_RST;
147     auto redact = util::strieq("authorization"_sr, StringRef{p, np});
148     p = np;
149     np = strchr(p, '\n');
150     if (!np) {
151       if (redact) {
152         nhdrs.append(": <redacted>");
153       } else {
154         nhdrs.append(p);
155       }
156       break;
157     }
158     if (redact) {
159       nhdrs.append(": <redacted>\n");
160     } else {
161       nhdrs.append(p, np + 1);
162     }
163     p = np + 1;
164   }
165   return nhdrs;
166 }
167 
select_padding_callback(nghttp2_session * session,const nghttp2_frame * frame,size_t max_payload,void * user_data)168 nghttp2_ssize select_padding_callback(nghttp2_session *session,
169                                       const nghttp2_frame *frame,
170                                       size_t max_payload, void *user_data) {
171   return std::min(max_payload, frame->hd.length + get_config()->padding);
172 }
173 
create_affinity_cookie(BlockAllocator & balloc,const StringRef & name,uint32_t affinity_cookie,const StringRef & path,bool secure)174 StringRef create_affinity_cookie(BlockAllocator &balloc, const StringRef &name,
175                                  uint32_t affinity_cookie,
176                                  const StringRef &path, bool secure) {
177   static constexpr auto PATH_PREFIX = "; Path="_sr;
178   static constexpr auto SECURE = "; Secure"_sr;
179   // <name>=<value>[; Path=<path>][; Secure]
180   size_t len = name.size() + 1 + 8;
181 
182   if (!path.empty()) {
183     len += PATH_PREFIX.size() + path.size();
184   }
185   if (secure) {
186     len += SECURE.size();
187   }
188 
189   auto iov = make_byte_ref(balloc, len + 1);
190   auto p = std::copy(std::begin(name), std::end(name), std::begin(iov));
191   *p++ = '=';
192   affinity_cookie = htonl(affinity_cookie);
193   p = util::format_hex(p, std::span{&affinity_cookie, 1});
194   if (!path.empty()) {
195     p = std::copy(std::begin(PATH_PREFIX), std::end(PATH_PREFIX), p);
196     p = std::copy(std::begin(path), std::end(path), p);
197   }
198   if (secure) {
199     p = std::copy(std::begin(SECURE), std::end(SECURE), p);
200   }
201   *p = '\0';
202   return StringRef{std::span{std::begin(iov), p}};
203 }
204 
require_cookie_secure_attribute(SessionAffinityCookieSecure secure,const StringRef & scheme)205 bool require_cookie_secure_attribute(SessionAffinityCookieSecure secure,
206                                      const StringRef &scheme) {
207   switch (secure) {
208   case SessionAffinityCookieSecure::AUTO:
209     return scheme == "https"_sr;
210   case SessionAffinityCookieSecure::YES:
211     return true;
212   default:
213     return false;
214   }
215 }
216 
create_altsvc_header_value(BlockAllocator & balloc,const std::vector<AltSvc> & altsvcs)217 StringRef create_altsvc_header_value(BlockAllocator &balloc,
218                                      const std::vector<AltSvc> &altsvcs) {
219   // <PROTOID>="<HOST>:<SERVICE>"; <PARAMS>
220   size_t len = 0;
221 
222   if (altsvcs.empty()) {
223     return StringRef{};
224   }
225 
226   for (auto &altsvc : altsvcs) {
227     len += util::percent_encode_tokenlen(altsvc.protocol_id);
228     len += str_size("=\"");
229     len += util::quote_stringlen(altsvc.host);
230     len += str_size(":");
231     len += altsvc.service.size();
232     len += str_size("\"");
233     if (!altsvc.params.empty()) {
234       len += str_size("; ");
235       len += altsvc.params.size();
236     }
237   }
238 
239   // ", " between items.
240   len += (altsvcs.size() - 1) * 2;
241 
242   // We will write additional ", " at the end, and cut it later.
243   auto iov = make_byte_ref(balloc, len + 2);
244   auto p = std::begin(iov);
245 
246   for (auto &altsvc : altsvcs) {
247     p = util::percent_encode_token(p, altsvc.protocol_id);
248     p = util::copy_lit(p, "=\"");
249     p = util::quote_string(p, altsvc.host);
250     *p++ = ':';
251     p = std::copy(std::begin(altsvc.service), std::end(altsvc.service), p);
252     *p++ = '"';
253     if (!altsvc.params.empty()) {
254       p = util::copy_lit(p, "; ");
255       p = std::copy(std::begin(altsvc.params), std::end(altsvc.params), p);
256     }
257     p = util::copy_lit(p, ", ");
258   }
259 
260   p -= 2;
261   *p = '\0';
262 
263   assert(static_cast<size_t>(p - std::begin(iov)) == len);
264 
265   return StringRef{std::span{std::begin(iov), p}};
266 }
267 
check_http_scheme(const StringRef & scheme,bool encrypted)268 bool check_http_scheme(const StringRef &scheme, bool encrypted) {
269   return encrypted ? scheme == "https"_sr : scheme == "http"_sr;
270 }
271 
272 } // namespace http
273 
274 } // namespace shrpx
275