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_http2_downstream_connection.h"
26
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif // HAVE_UNISTD_H
30
31 #include "llhttp.h"
32
33 #include "shrpx_client_handler.h"
34 #include "shrpx_upstream.h"
35 #include "shrpx_downstream.h"
36 #include "shrpx_config.h"
37 #include "shrpx_error.h"
38 #include "shrpx_http.h"
39 #include "shrpx_http2_session.h"
40 #include "shrpx_worker.h"
41 #include "shrpx_log.h"
42 #include "http2.h"
43 #include "util.h"
44 #include "ssl_compat.h"
45
46 using namespace nghttp2;
47
48 namespace shrpx {
49
Http2DownstreamConnection(Http2Session * http2session)50 Http2DownstreamConnection::Http2DownstreamConnection(Http2Session *http2session)
51 : dlnext(nullptr),
52 dlprev(nullptr),
53 http2session_(http2session),
54 sd_(nullptr) {}
55
~Http2DownstreamConnection()56 Http2DownstreamConnection::~Http2DownstreamConnection() {
57 if (LOG_ENABLED(INFO)) {
58 DCLOG(INFO, this) << "Deleting";
59 }
60 if (downstream_) {
61 downstream_->disable_downstream_rtimer();
62 downstream_->disable_downstream_wtimer();
63
64 uint32_t error_code;
65 if (downstream_->get_request_state() == DownstreamState::STREAM_CLOSED &&
66 downstream_->get_upgraded()) {
67 // For upgraded connection, send NO_ERROR. Should we consider
68 // request states other than DownstreamState::STREAM_CLOSED ?
69 error_code = NGHTTP2_NO_ERROR;
70 } else {
71 error_code = NGHTTP2_INTERNAL_ERROR;
72 }
73
74 if (http2session_->get_state() == Http2SessionState::CONNECTED &&
75 downstream_->get_downstream_stream_id() != -1) {
76 submit_rst_stream(downstream_, error_code);
77
78 auto &resp = downstream_->response();
79
80 http2session_->consume(downstream_->get_downstream_stream_id(),
81 resp.unconsumed_body_length);
82
83 resp.unconsumed_body_length = 0;
84
85 http2session_->signal_write();
86 }
87 }
88 http2session_->remove_downstream_connection(this);
89
90 if (LOG_ENABLED(INFO)) {
91 DCLOG(INFO, this) << "Deleted";
92 }
93 }
94
attach_downstream(Downstream * downstream)95 int Http2DownstreamConnection::attach_downstream(Downstream *downstream) {
96 if (LOG_ENABLED(INFO)) {
97 DCLOG(INFO, this) << "Attaching to DOWNSTREAM:" << downstream;
98 }
99 http2session_->add_downstream_connection(this);
100 http2session_->signal_write();
101
102 downstream_ = downstream;
103 downstream_->reset_downstream_rtimer();
104
105 auto &req = downstream_->request();
106
107 // HTTP/2 disables HTTP Upgrade.
108 if (req.method != HTTP_CONNECT && req.connect_proto == ConnectProto::NONE) {
109 req.upgrade_request = false;
110 }
111
112 return 0;
113 }
114
detach_downstream(Downstream * downstream)115 void Http2DownstreamConnection::detach_downstream(Downstream *downstream) {
116 if (LOG_ENABLED(INFO)) {
117 DCLOG(INFO, this) << "Detaching from DOWNSTREAM:" << downstream;
118 }
119
120 auto &resp = downstream_->response();
121
122 if (downstream_->get_downstream_stream_id() != -1) {
123 if (submit_rst_stream(downstream) == 0) {
124 http2session_->signal_write();
125 }
126
127 http2session_->consume(downstream_->get_downstream_stream_id(),
128 resp.unconsumed_body_length);
129
130 resp.unconsumed_body_length = 0;
131
132 http2session_->signal_write();
133 }
134
135 downstream->disable_downstream_rtimer();
136 downstream->disable_downstream_wtimer();
137 downstream_ = nullptr;
138 }
139
submit_rst_stream(Downstream * downstream,uint32_t error_code)140 int Http2DownstreamConnection::submit_rst_stream(Downstream *downstream,
141 uint32_t error_code) {
142 int rv = -1;
143 if (http2session_->get_state() == Http2SessionState::CONNECTED &&
144 downstream->get_downstream_stream_id() != -1) {
145 switch (downstream->get_response_state()) {
146 case DownstreamState::MSG_RESET:
147 case DownstreamState::MSG_BAD_HEADER:
148 case DownstreamState::MSG_COMPLETE:
149 break;
150 default:
151 if (LOG_ENABLED(INFO)) {
152 DCLOG(INFO, this) << "Submit RST_STREAM for DOWNSTREAM:" << downstream
153 << ", stream_id="
154 << downstream->get_downstream_stream_id()
155 << ", error_code=" << error_code;
156 }
157 rv = http2session_->submit_rst_stream(
158 downstream->get_downstream_stream_id(), error_code);
159 }
160 }
161 return rv;
162 }
163
164 namespace {
http2_data_read_callback(nghttp2_session * session,int32_t stream_id,uint8_t * buf,size_t length,uint32_t * data_flags,nghttp2_data_source * source,void * user_data)165 nghttp2_ssize http2_data_read_callback(nghttp2_session *session,
166 int32_t stream_id, uint8_t *buf,
167 size_t length, uint32_t *data_flags,
168 nghttp2_data_source *source,
169 void *user_data) {
170 int rv;
171 auto sd = static_cast<StreamData *>(
172 nghttp2_session_get_stream_user_data(session, stream_id));
173 if (!sd || !sd->dconn) {
174 return NGHTTP2_ERR_DEFERRED;
175 }
176 auto dconn = sd->dconn;
177 auto downstream = dconn->get_downstream();
178 if (!downstream) {
179 // In this case, RST_STREAM should have been issued. But depending
180 // on the priority, DATA frame may come first.
181 return NGHTTP2_ERR_DEFERRED;
182 }
183 const auto &req = downstream->request();
184 auto input = downstream->get_request_buf();
185
186 auto nread = std::min(input->rleft(), length);
187 auto input_empty = input->rleft() == nread;
188
189 *data_flags |= NGHTTP2_DATA_FLAG_NO_COPY;
190
191 if (input_empty &&
192 downstream->get_request_state() == DownstreamState::MSG_COMPLETE &&
193 // If connection is upgraded, don't set EOF flag, since HTTP/1
194 // will set MSG_COMPLETE to request state after upgrade response
195 // header is seen.
196 (!req.upgrade_request ||
197 (downstream->get_response_state() == DownstreamState::HEADER_COMPLETE &&
198 !downstream->get_upgraded()))) {
199
200 *data_flags |= NGHTTP2_DATA_FLAG_EOF;
201
202 const auto &trailers = req.fs.trailers();
203 if (!trailers.empty()) {
204 std::vector<nghttp2_nv> nva;
205 nva.reserve(trailers.size());
206 http2::copy_headers_to_nva_nocopy(nva, trailers, http2::HDOP_STRIP_ALL);
207 if (!nva.empty()) {
208 rv = nghttp2_submit_trailer(session, stream_id, nva.data(), nva.size());
209 if (rv != 0) {
210 if (nghttp2_is_fatal(rv)) {
211 return NGHTTP2_ERR_CALLBACK_FAILURE;
212 }
213 } else {
214 *data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
215 }
216 }
217 }
218 }
219
220 if (nread == 0 && (*data_flags & NGHTTP2_DATA_FLAG_EOF) == 0) {
221 downstream->disable_downstream_wtimer();
222
223 return NGHTTP2_ERR_DEFERRED;
224 }
225
226 return nread;
227 }
228 } // namespace
229
push_request_headers()230 int Http2DownstreamConnection::push_request_headers() {
231 int rv;
232 if (!downstream_) {
233 return 0;
234 }
235 if (!http2session_->can_push_request(downstream_)) {
236 // The HTTP2 session to the backend has not been established or
237 // connection is now being checked. This function will be called
238 // again just after it is established.
239 downstream_->set_request_pending(true);
240 http2session_->start_checking_connection();
241 return 0;
242 }
243
244 downstream_->set_request_pending(false);
245
246 const auto &req = downstream_->request();
247
248 if (req.connect_proto != ConnectProto::NONE &&
249 !http2session_->get_allow_connect_proto()) {
250 return -1;
251 }
252
253 auto &balloc = downstream_->get_block_allocator();
254
255 auto config = get_config();
256 auto &httpconf = config->http;
257 auto &http2conf = config->http2;
258
259 auto no_host_rewrite = httpconf.no_host_rewrite || config->http2_proxy ||
260 req.regular_connect_method();
261
262 // http2session_ has already in CONNECTED state, so we can get
263 // addr_idx here.
264 const auto &downstream_hostport = http2session_->get_addr()->hostport;
265
266 // For HTTP/1.0 request, there is no authority in request. In that
267 // case, we use backend server's host nonetheless.
268 auto authority = StringRef(downstream_hostport);
269
270 if (no_host_rewrite && !req.authority.empty()) {
271 authority = req.authority;
272 }
273
274 downstream_->set_request_downstream_host(authority);
275
276 size_t num_cookies = 0;
277 if (!http2conf.no_cookie_crumbling) {
278 num_cookies = downstream_->count_crumble_request_cookie();
279 }
280
281 // 11 means:
282 // 1. :method
283 // 2. :scheme
284 // 3. :path
285 // 4. :authority (or host)
286 // 5. :protocol (optional)
287 // 6. via (optional)
288 // 7. x-forwarded-for (optional)
289 // 8. x-forwarded-proto (optional)
290 // 9. te (optional)
291 // 10. forwarded (optional)
292 // 11. early-data (optional)
293 auto nva = std::vector<nghttp2_nv>();
294 nva.reserve(req.fs.headers().size() + 11 + num_cookies +
295 httpconf.add_request_headers.size());
296
297 if (req.connect_proto == ConnectProto::WEBSOCKET) {
298 nva.push_back(http2::make_field(":method"_sr, "CONNECT"_sr));
299 nva.push_back(http2::make_field(":protocol"_sr, "websocket"_sr));
300 } else {
301 nva.push_back(
302 http2::make_field(":method"_sr, http2::to_method_string(req.method)));
303 }
304
305 if (!req.regular_connect_method()) {
306 assert(!req.scheme.empty());
307
308 auto addr = http2session_->get_addr();
309 assert(addr);
310 // We will handle more protocol scheme upgrade in the future.
311 if (addr->tls && addr->upgrade_scheme && req.scheme == "http"_sr) {
312 nva.push_back(http2::make_field(":scheme"_sr, "https"_sr));
313 } else {
314 nva.push_back(http2::make_field(":scheme"_sr, req.scheme));
315 }
316
317 if (req.method == HTTP_OPTIONS && req.path.empty()) {
318 nva.push_back(http2::make_field(":path"_sr, "*"_sr));
319 } else {
320 nva.push_back(http2::make_field(":path"_sr, req.path));
321 }
322
323 if (!req.no_authority || req.connect_proto != ConnectProto::NONE) {
324 nva.push_back(http2::make_field(":authority"_sr, authority));
325 } else {
326 nva.push_back(http2::make_field("host"_sr, authority));
327 }
328 } else {
329 nva.push_back(http2::make_field(":authority"_sr, authority));
330 }
331
332 auto &fwdconf = httpconf.forwarded;
333 auto &xffconf = httpconf.xff;
334 auto &xfpconf = httpconf.xfp;
335 auto &earlydataconf = httpconf.early_data;
336
337 uint32_t build_flags =
338 (fwdconf.strip_incoming ? http2::HDOP_STRIP_FORWARDED : 0) |
339 (xffconf.strip_incoming ? http2::HDOP_STRIP_X_FORWARDED_FOR : 0) |
340 (xfpconf.strip_incoming ? http2::HDOP_STRIP_X_FORWARDED_PROTO : 0) |
341 (earlydataconf.strip_incoming ? http2::HDOP_STRIP_EARLY_DATA : 0) |
342 http2::HDOP_STRIP_SEC_WEBSOCKET_KEY;
343
344 http2::copy_headers_to_nva_nocopy(nva, req.fs.headers(), build_flags);
345
346 if (!http2conf.no_cookie_crumbling) {
347 downstream_->crumble_request_cookie(nva);
348 }
349
350 auto upstream = downstream_->get_upstream();
351 auto handler = upstream->get_client_handler();
352
353 #if defined(NGHTTP2_GENUINE_OPENSSL) || defined(NGHTTP2_OPENSSL_IS_BORINGSSL)
354 auto conn = handler->get_connection();
355
356 if (conn->tls.ssl && !SSL_is_init_finished(conn->tls.ssl)) {
357 nva.push_back(http2::make_field("early-data"_sr, "1"_sr));
358 }
359 #endif // NGHTTP2_GENUINE_OPENSSL || NGHTTP2_OPENSSL_IS_BORINGSSL
360
361 auto fwd =
362 fwdconf.strip_incoming ? nullptr : req.fs.header(http2::HD_FORWARDED);
363
364 if (fwdconf.params) {
365 auto params = fwdconf.params;
366
367 if (config->http2_proxy || req.regular_connect_method()) {
368 params &= ~FORWARDED_PROTO;
369 }
370
371 auto value = http::create_forwarded(
372 balloc, params, handler->get_forwarded_by(),
373 handler->get_forwarded_for(), req.authority, req.scheme);
374
375 if (fwd || !value.empty()) {
376 if (fwd) {
377 if (value.empty()) {
378 value = fwd->value;
379 } else {
380 value = concat_string_ref(balloc, fwd->value, ", "_sr, value);
381 }
382 }
383
384 nva.push_back(http2::make_field("forwarded"_sr, value));
385 }
386 } else if (fwd) {
387 nva.push_back(http2::make_field("forwarded"_sr, fwd->value));
388 }
389
390 auto xff = xffconf.strip_incoming ? nullptr
391 : req.fs.header(http2::HD_X_FORWARDED_FOR);
392
393 if (xffconf.add) {
394 StringRef xff_value;
395 const auto &addr = upstream->get_client_handler()->get_ipaddr();
396 if (xff) {
397 xff_value = concat_string_ref(balloc, xff->value, ", "_sr, addr);
398 } else {
399 xff_value = addr;
400 }
401 nva.push_back(http2::make_field("x-forwarded-for"_sr, xff_value));
402 } else if (xff) {
403 nva.push_back(http2::make_field("x-forwarded-for"_sr, xff->value));
404 }
405
406 if (!config->http2_proxy && !req.regular_connect_method()) {
407 auto xfp = xfpconf.strip_incoming
408 ? nullptr
409 : req.fs.header(http2::HD_X_FORWARDED_PROTO);
410
411 if (xfpconf.add) {
412 StringRef xfp_value;
413 // We use same protocol with :scheme header field
414 if (xfp) {
415 xfp_value = concat_string_ref(balloc, xfp->value, ", "_sr, req.scheme);
416 } else {
417 xfp_value = req.scheme;
418 }
419 nva.push_back(http2::make_field("x-forwarded-proto"_sr, xfp_value));
420 } else if (xfp) {
421 nva.push_back(http2::make_field("x-forwarded-proto"_sr, xfp->value));
422 }
423 }
424
425 auto via = req.fs.header(http2::HD_VIA);
426 if (httpconf.no_via) {
427 if (via) {
428 nva.push_back(http2::make_field("via"_sr, (*via).value));
429 }
430 } else {
431 size_t vialen = 16;
432 if (via) {
433 vialen += via->value.size() + 2;
434 }
435
436 auto iov = make_byte_ref(balloc, vialen + 1);
437 auto p = std::begin(iov);
438
439 if (via) {
440 p = std::copy(std::begin(via->value), std::end(via->value), p);
441 p = util::copy_lit(p, ", ");
442 }
443 p = http::create_via_header_value(p, req.http_major, req.http_minor);
444 *p = '\0';
445
446 nva.push_back(
447 http2::make_field("via"_sr, StringRef{std::span{std::begin(iov), p}}));
448 }
449
450 auto te = req.fs.header(http2::HD_TE);
451 // HTTP/1 upstream request can contain keyword other than
452 // "trailers". We just forward "trailers".
453 // TODO more strict handling required here.
454 if (te && http2::contains_trailers(te->value)) {
455 nva.push_back(http2::make_field("te"_sr, "trailers"_sr));
456 }
457
458 for (auto &p : httpconf.add_request_headers) {
459 nva.push_back(http2::make_field(p.name, p.value));
460 }
461
462 if (LOG_ENABLED(INFO)) {
463 std::stringstream ss;
464 for (auto &nv : nva) {
465 auto name = StringRef{nv.name, nv.namelen};
466
467 if ("authorization"_sr == name) {
468 ss << TTY_HTTP_HD << name << TTY_RST << ": <redacted>\n";
469 continue;
470 }
471 ss << TTY_HTTP_HD << name << TTY_RST << ": "
472 << StringRef{nv.value, nv.valuelen} << "\n";
473 }
474 DCLOG(INFO, this) << "HTTP request headers\n" << ss.str();
475 }
476
477 auto transfer_encoding = req.fs.header(http2::HD_TRANSFER_ENCODING);
478
479 nghttp2_data_provider2 *data_prdptr = nullptr;
480 nghttp2_data_provider2 data_prd;
481
482 // Add body as long as transfer-encoding is given even if
483 // req.fs.content_length == 0 to forward trailer fields.
484 if (req.method == HTTP_CONNECT || req.connect_proto != ConnectProto::NONE ||
485 transfer_encoding || req.fs.content_length > 0 || req.http2_expect_body) {
486 // Request-body is expected.
487 data_prd = {{}, http2_data_read_callback};
488 data_prdptr = &data_prd;
489 }
490
491 rv = http2session_->submit_request(this, nva.data(), nva.size(), data_prdptr);
492 if (rv != 0) {
493 DCLOG(FATAL, this) << "nghttp2_submit_request() failed";
494 return -1;
495 }
496
497 if (data_prdptr) {
498 downstream_->reset_downstream_wtimer();
499 }
500
501 http2session_->signal_write();
502 return 0;
503 }
504
push_upload_data_chunk(const uint8_t * data,size_t datalen)505 int Http2DownstreamConnection::push_upload_data_chunk(const uint8_t *data,
506 size_t datalen) {
507 if (!downstream_->get_request_header_sent()) {
508 auto output = downstream_->get_blocked_request_buf();
509 auto &req = downstream_->request();
510 output->append(data, datalen);
511 req.unconsumed_body_length += datalen;
512 return 0;
513 }
514
515 int rv;
516 auto output = downstream_->get_request_buf();
517 output->append(data, datalen);
518 if (downstream_->get_downstream_stream_id() != -1) {
519 rv = http2session_->resume_data(this);
520 if (rv != 0) {
521 return -1;
522 }
523
524 downstream_->ensure_downstream_wtimer();
525
526 http2session_->signal_write();
527 }
528 return 0;
529 }
530
end_upload_data()531 int Http2DownstreamConnection::end_upload_data() {
532 if (!downstream_->get_request_header_sent()) {
533 downstream_->set_blocked_request_data_eof(true);
534 return 0;
535 }
536
537 int rv;
538 if (downstream_->get_downstream_stream_id() != -1) {
539 rv = http2session_->resume_data(this);
540 if (rv != 0) {
541 return -1;
542 }
543
544 downstream_->ensure_downstream_wtimer();
545
546 http2session_->signal_write();
547 }
548 return 0;
549 }
550
resume_read(IOCtrlReason reason,size_t consumed)551 int Http2DownstreamConnection::resume_read(IOCtrlReason reason,
552 size_t consumed) {
553 int rv;
554
555 if (http2session_->get_state() != Http2SessionState::CONNECTED) {
556 return 0;
557 }
558
559 if (!downstream_ || downstream_->get_downstream_stream_id() == -1) {
560 return 0;
561 }
562
563 if (consumed > 0) {
564 rv = http2session_->consume(downstream_->get_downstream_stream_id(),
565 consumed);
566
567 if (rv != 0) {
568 return -1;
569 }
570
571 auto &resp = downstream_->response();
572
573 resp.unconsumed_body_length -= consumed;
574
575 http2session_->signal_write();
576 }
577
578 return 0;
579 }
580
on_read()581 int Http2DownstreamConnection::on_read() { return 0; }
582
on_write()583 int Http2DownstreamConnection::on_write() { return 0; }
584
attach_stream_data(StreamData * sd)585 void Http2DownstreamConnection::attach_stream_data(StreamData *sd) {
586 // It is possible sd->dconn is not NULL. sd is detached when
587 // on_stream_close_callback. Before that, after MSG_COMPLETE is set
588 // to Downstream::set_response_state(), upstream's readcb is called
589 // and execution path eventually could reach here. Since the
590 // response was already handled, we just detach sd.
591 detach_stream_data();
592 sd_ = sd;
593 sd_->dconn = this;
594 }
595
detach_stream_data()596 StreamData *Http2DownstreamConnection::detach_stream_data() {
597 if (sd_) {
598 auto sd = sd_;
599 sd_ = nullptr;
600 sd->dconn = nullptr;
601 return sd;
602 }
603 return nullptr;
604 }
605
on_timeout()606 int Http2DownstreamConnection::on_timeout() {
607 if (!downstream_) {
608 return 0;
609 }
610
611 return submit_rst_stream(downstream_, NGHTTP2_NO_ERROR);
612 }
613
614 const std::shared_ptr<DownstreamAddrGroup> &
get_downstream_addr_group() const615 Http2DownstreamConnection::get_downstream_addr_group() const {
616 return http2session_->get_downstream_addr_group();
617 }
618
get_addr() const619 DownstreamAddr *Http2DownstreamConnection::get_addr() const { return nullptr; }
620
621 } // namespace shrpx
622