Debian Codegraph @

src/core/ext/transport/chttp2/server/chttp2_server.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/ext/transport/chttp2/server/chttp2_server.h"
22
23 #include <inttypes.h>
24 #include <string.h>
25
26 #include <algorithm>
27 #include <map>
28 #include <memory>
29 #include <string>
30 #include <utility>
31 #include <vector>
32
33 #include "absl/base/thread_annotations.h"
34 #include "absl/status/status.h"
35 #include "absl/status/statusor.h"
36 #include "absl/strings/str_cat.h"
37 #include "absl/strings/str_format.h"
38 #include "absl/strings/string_view.h"
39 #include "absl/strings/strip.h"
40 #include "absl/types/optional.h"
41
42 #include <grpc/grpc.h>
43 #include <grpc/grpc_posix.h>
44 #include <grpc/impl/codegen/grpc_types.h>
45 #include <grpc/slice_buffer.h>
46 #include <grpc/support/alloc.h>
47 #include <grpc/support/log.h>
48
49 #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
50 #include "src/core/ext/transport/chttp2/transport/frame.h"
51 #include "src/core/ext/transport/chttp2/transport/internal.h"
52 #include "src/core/lib/address_utils/sockaddr_utils.h"
53 #include "src/core/lib/channel/channel_args.h"
54 #include "src/core/lib/channel/channelz.h"
55 #include "src/core/lib/config/core_configuration.h"
56 #include "src/core/lib/debug/trace.h"
57 #include "src/core/lib/event_engine/channel_args_endpoint_config.h"
58 #include "src/core/lib/gprpp/debug_location.h"
59 #include "src/core/lib/gprpp/orphanable.h"
60 #include "src/core/lib/gprpp/ref_counted_ptr.h"
61 #include "src/core/lib/gprpp/status_helper.h"
62 #include "src/core/lib/gprpp/sync.h"
63 #include "src/core/lib/gprpp/time.h"
64 #include "src/core/lib/gprpp/unique_type_name.h"
65 #include "src/core/lib/iomgr/closure.h"
66 #include "src/core/lib/iomgr/endpoint.h"
67 #include "src/core/lib/iomgr/iomgr_fwd.h"
68 #include "src/core/lib/iomgr/pollset_set.h"
69 #include "src/core/lib/iomgr/resolve_address.h"
70 #include "src/core/lib/iomgr/resolved_address.h"
71 #include "src/core/lib/iomgr/tcp_server.h"
72 #include "src/core/lib/iomgr/timer.h"
73 #include "src/core/lib/iomgr/unix_sockets_posix.h"
74 #include "src/core/lib/resource_quota/memory_quota.h"
75 #include "src/core/lib/resource_quota/resource_quota.h"
76 #include "src/core/lib/security/credentials/credentials.h"
77 #include "src/core/lib/security/credentials/insecure/insecure_credentials.h"
78 #include "src/core/lib/security/security_connector/security_connector.h"
79 #include "src/core/lib/surface/api_trace.h"
80 #include "src/core/lib/surface/server.h"
81 #include "src/core/lib/transport/error_utils.h"
82 #include "src/core/lib/transport/handshaker.h"
83 #include "src/core/lib/transport/handshaker_registry.h"
84 #include "src/core/lib/transport/transport.h"
85 #include "src/core/lib/transport/transport_fwd.h"
86 #include "src/core/lib/uri/uri_parser.h"
87
88 #ifdef GPR_SUPPORT_CHANNELS_FROM_FD
89 #include "src/core/lib/iomgr/ev_posix.h"
90 #include "src/core/lib/iomgr/exec_ctx.h"
91 #include "src/core/lib/iomgr/tcp_client_posix.h"
92 #endif // GPR_SUPPORT_CHANNELS_FROM_FD
93
94 namespace grpc_core {
95 namespace {
96
97 const char kUnixUriPrefix[] = "unix:";
98 const char kUnixAbstractUriPrefix[] = "unix-abstract:";
99
100 class Chttp2ServerListener : public Server::ListenerInterface {
101 public:
102 static grpc_error_handle Create(Server* server, grpc_resolved_address* addr,
103 const ChannelArgs& args,
104 Chttp2ServerArgsModifier args_modifier,
105 int* port_num);
106
107 static grpc_error_handle CreateWithAcceptor(
108 Server* server, const char* name, const ChannelArgs& args,
109 Chttp2ServerArgsModifier args_modifier);
110
111 // Do not instantiate directly. Use one of the factory methods above.
112 Chttp2ServerListener(Server* server, const ChannelArgs& args,
113 Chttp2ServerArgsModifier args_modifier);
114 ~Chttp2ServerListener() override;
115
116 void Start(Server* server,
117 const std::vector<grpc_pollset*>* pollsets) override;
118
119 channelz::ListenSocketNode* channelz_listen_socket_node() const override {
120 return channelz_listen_socket_.get();
121 }
122
123 void SetOnDestroyDone(grpc_closure* on_destroy_done) override;
124
125 void Orphan() override;
126
127 private:
128 class ConfigFetcherWatcher
129 : public grpc_server_config_fetcher::WatcherInterface {
130 public:
131 explicit ConfigFetcherWatcher(RefCountedPtr<Chttp2ServerListener> listener)
132 : listener_(std::move(listener)) {}
133
134 void UpdateConnectionManager(
135 RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
136 connection_manager) override;
137
138 void StopServing() override;
139
140 private:
141 RefCountedPtr<Chttp2ServerListener> listener_;
142 };
143
144 class ActiveConnection : public InternallyRefCounted<ActiveConnection> {
145 public:
146 class HandshakingState : public InternallyRefCounted<HandshakingState> {
147 public:
148 HandshakingState(RefCountedPtr<ActiveConnection> connection_ref,
149 grpc_pollset* accepting_pollset,
150 grpc_tcp_server_acceptor* acceptor,
151 const ChannelArgs& args);
152
153 ~HandshakingState() override;
154
155 void Orphan() override;
156
157 void Start(grpc_endpoint* endpoint, const ChannelArgs& args);
158
159 // Needed to be able to grab an external ref in
160 // ActiveConnection::Start()
161 using InternallyRefCounted<HandshakingState>::Ref;
162
163 private:
164 static void OnTimeout(void* arg, grpc_error_handle error);
165 static void OnReceiveSettings(void* arg, grpc_error_handle /* error */);
166 static void OnHandshakeDone(void* arg, grpc_error_handle error);
167 RefCountedPtr<ActiveConnection> const connection_;
168 grpc_pollset* const accepting_pollset_;
169 grpc_tcp_server_acceptor* acceptor_;
170 RefCountedPtr<HandshakeManager> handshake_mgr_
171 ABSL_GUARDED_BY(&connection_->mu_);
172 // State for enforcing handshake timeout on receiving HTTP/2 settings.
173 Timestamp const deadline_;
174 grpc_timer timer_ ABSL_GUARDED_BY(&connection_->mu_);
175 grpc_closure on_timeout_ ABSL_GUARDED_BY(&connection_->mu_);
176 grpc_closure on_receive_settings_ ABSL_GUARDED_BY(&connection_->mu_);
177 grpc_pollset_set* const interested_parties_;
178 };
179
180 ActiveConnection(grpc_pollset* accepting_pollset,
181 grpc_tcp_server_acceptor* acceptor,
182 const ChannelArgs& args, MemoryOwner memory_owner);
183 ~ActiveConnection() override;
184
185 void Orphan() override;
186
187 void SendGoAway();
188
189 void Start(RefCountedPtr<Chttp2ServerListener> listener,
190 grpc_endpoint* endpoint, const ChannelArgs& args);
191
192 // Needed to be able to grab an external ref in
193 // Chttp2ServerListener::OnAccept()
194 using InternallyRefCounted<ActiveConnection>::Ref;
195
196 private:
197 static void OnClose(void* arg, grpc_error_handle error);
198 static void OnDrainGraceTimeExpiry(void* arg, grpc_error_handle error);
199
200 RefCountedPtr<Chttp2ServerListener> listener_;
201 Mutex mu_ ABSL_ACQUIRED_AFTER(&listener_->mu_);
202 // Set by HandshakingState before the handshaking begins and reset when
203 // handshaking is done.
204 OrphanablePtr<HandshakingState> handshaking_state_ ABSL_GUARDED_BY(&mu_);
205 // Set by HandshakingState when handshaking is done and a valid transport
206 // is created.
207 grpc_chttp2_transport* transport_ ABSL_GUARDED_BY(&mu_) = nullptr;
208 grpc_closure on_close_;
209 grpc_timer drain_grace_timer_;
210 grpc_closure on_drain_grace_time_expiry_;
211 bool drain_grace_timer_expiry_callback_pending_ ABSL_GUARDED_BY(&mu_) =
212 false;
213 bool shutdown_ ABSL_GUARDED_BY(&mu_) = false;
214 };
215
216 // To allow access to RefCounted<> like interface.
217 friend class RefCountedPtr<Chttp2ServerListener>;
218
219 // Should only be called once so as to start the TCP server.
220 void StartListening();
221
222 static void OnAccept(void* arg, grpc_endpoint* tcp,
223 grpc_pollset* accepting_pollset,
224 grpc_tcp_server_acceptor* acceptor);
225
226 static void TcpServerShutdownComplete(void* arg, grpc_error_handle error);
227
228 static void DestroyListener(Server* /*server*/, void* arg,
229 grpc_closure* destroy_done);
230
231 // The interface required by RefCountedPtr<> has been manually implemented
232 // here to take a ref on tcp_server_ instead. Note that, the handshaker
233 // needs tcp_server_ to exist for the lifetime of the handshake since it's
234 // needed by acceptor. Sharing refs between the listener and tcp_server_ is
235 // just an optimization to avoid taking additional refs on the listener,
236 // since TcpServerShutdownComplete already holds a ref to the listener.
237 void IncrementRefCount() { grpc_tcp_server_ref(tcp_server_); }
238 void IncrementRefCount(const DebugLocation& /* location */,
239 const char* /* reason */) {
240 IncrementRefCount();
241 }
242
243 RefCountedPtr<Chttp2ServerListener> Ref() GRPC_MUST_USE_RESULT {
244 IncrementRefCount();
245 return RefCountedPtr<Chttp2ServerListener>(this);
246 }
247 RefCountedPtr<Chttp2ServerListener> Ref(const DebugLocation& /* location */,
248 const char* /* reason */)
249 GRPC_MUST_USE_RESULT {
250 return Ref();
251 }
252
253 void Unref() { grpc_tcp_server_unref(tcp_server_); }
254 void Unref(const DebugLocation& /* location */, const char* /* reason */) {
255 Unref();
256 }
257
258 Server* const server_;
259 grpc_tcp_server* tcp_server_;
260 grpc_resolved_address resolved_address_;
261 Chttp2ServerArgsModifier const args_modifier_;
262 ConfigFetcherWatcher* config_fetcher_watcher_ = nullptr;
263 ChannelArgs args_;
264 Mutex mu_;
265 RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
266 connection_manager_ ABSL_GUARDED_BY(mu_);
267 // Signals whether grpc_tcp_server_start() has been called.
268 bool started_ ABSL_GUARDED_BY(mu_) = false;
269 // Signals whether grpc_tcp_server_start() has completed.
270 CondVar started_cv_ ABSL_GUARDED_BY(mu_);
271 // Signals whether new requests/connections are to be accepted.
272 bool is_serving_ ABSL_GUARDED_BY(mu_) = false;
273 // Signals whether the application has triggered shutdown.
274 bool shutdown_ ABSL_GUARDED_BY(mu_) = false;
275 std::map<ActiveConnection*, OrphanablePtr<ActiveConnection>> connections_
276 ABSL_GUARDED_BY(mu_);
277 grpc_closure tcp_server_shutdown_complete_ ABSL_GUARDED_BY(mu_);
278 grpc_closure* on_destroy_done_ ABSL_GUARDED_BY(mu_) = nullptr;
279 RefCountedPtr<channelz::ListenSocketNode> channelz_listen_socket_;
280 MemoryQuotaRefPtr memory_quota_;
281 };
282
283 //
284 // Chttp2ServerListener::ConfigFetcherWatcher
285 //
286
287 void Chttp2ServerListener::ConfigFetcherWatcher::UpdateConnectionManager(
288 RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
289 connection_manager) {
290 RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
291 connection_manager_to_destroy;
292 class GracefulShutdownExistingConnections {
293 public:
294 ~GracefulShutdownExistingConnections() {
295 // Send GOAWAYs on the transports so that they get disconnected when
296 // existing RPCs finish, and so that no new RPC is started on them.
297 for (auto& connection : connections_) {
298 connection.first->SendGoAway();
299 }
300 }
301
302 void set_connections(
303 std::map<ActiveConnection*, OrphanablePtr<ActiveConnection>>
304 connections) {
305 GPR_ASSERT(connections_.empty());
306 connections_ = std::move(connections);
307 }
308
309 private:
310 std::map<ActiveConnection*, OrphanablePtr<ActiveConnection>> connections_;
311 } connections_to_shutdown;
312 {
313 MutexLock lock(&listener_->mu_);
314 connection_manager_to_destroy = listener_->connection_manager_;
315 listener_->connection_manager_ = std::move(connection_manager);
316 connections_to_shutdown.set_connections(std::move(listener_->connections_));
317 if (listener_->shutdown_) {
318 return;
319 }
320 listener_->is_serving_ = true;
321 if (listener_->started_) return;
322 }
323 int port_temp;
324 grpc_error_handle error = grpc_tcp_server_add_port(
325 listener_->tcp_server_, &listener_->resolved_address_, &port_temp);
326 if (!error.ok()) {
327 gpr_log(GPR_ERROR, "Error adding port to server: %s",
328 StatusToString(error).c_str());
329 // TODO(yashykt): We wouldn't need to assert here if we bound to the
330 // port earlier during AddPort.
331 GPR_ASSERT(0);
332 }
333 listener_->StartListening();
334 {
335 MutexLock lock(&listener_->mu_);
336 listener_->started_ = true;
337 listener_->started_cv_.SignalAll();
338 }
339 }
340
341 void Chttp2ServerListener::ConfigFetcherWatcher::StopServing() {
342 std::map<ActiveConnection*, OrphanablePtr<ActiveConnection>> connections;
343 {
344 MutexLock lock(&listener_->mu_);
345 listener_->is_serving_ = false;
346 connections = std::move(listener_->connections_);
347 }
348 // Send GOAWAYs on the transports so that they disconnected when existing
349 // RPCs finish.
350 for (auto& connection : connections) {
351 connection.first->SendGoAway();
352 }
353 }
354
355 //
356 // Chttp2ServerListener::ActiveConnection::HandshakingState
357 //
358
359 Timestamp GetConnectionDeadline(const ChannelArgs& args) {
360 return Timestamp::Now() +
361 std::max(
362 Duration::Milliseconds(1),
363 args.GetDurationFromIntMillis(GRPC_ARG_SERVER_HANDSHAKE_TIMEOUT_MS)
364 .value_or(Duration::Seconds(120)));
365 }
366
367 Chttp2ServerListener::ActiveConnection::HandshakingState::HandshakingState(
368 RefCountedPtr<ActiveConnection> connection_ref,
369 grpc_pollset* accepting_pollset, grpc_tcp_server_acceptor* acceptor,
370 const ChannelArgs& args)
371 : connection_(std::move(connection_ref)),
372 accepting_pollset_(accepting_pollset),
373 acceptor_(acceptor),
374 handshake_mgr_(MakeRefCounted<HandshakeManager>()),
375 deadline_(GetConnectionDeadline(args)),
376 interested_parties_(grpc_pollset_set_create()) {
377 grpc_pollset_set_add_pollset(interested_parties_, accepting_pollset_);
378 CoreConfiguration::Get().handshaker_registry().AddHandshakers(
379 HANDSHAKER_SERVER, args, interested_parties_, handshake_mgr_.get());
380 }
381
382 Chttp2ServerListener::ActiveConnection::HandshakingState::~HandshakingState() {
383 grpc_pollset_set_del_pollset(interested_parties_, accepting_pollset_);
384 grpc_pollset_set_destroy(interested_parties_);
385 gpr_free(acceptor_);
386 }
387
388 void Chttp2ServerListener::ActiveConnection::HandshakingState::Orphan() {
389 {
390 MutexLock lock(&connection_->mu_);
391 if (handshake_mgr_ != nullptr) {
392 handshake_mgr_->Shutdown(GRPC_ERROR_CREATE("Listener stopped serving."));
393 }
394 }
395 Unref();
396 }
397
398 void Chttp2ServerListener::ActiveConnection::HandshakingState::Start(
399 grpc_endpoint* endpoint, const ChannelArgs& channel_args) {
400 Ref().release(); // Held by OnHandshakeDone
401 RefCountedPtr<HandshakeManager> handshake_mgr;
402 {
403 MutexLock lock(&connection_->mu_);
404 if (handshake_mgr_ == nullptr) return;
405 handshake_mgr = handshake_mgr_;
406 }
407 handshake_mgr->DoHandshake(endpoint, channel_args, deadline_, acceptor_,
408 OnHandshakeDone, this);
409 }
410
411 void Chttp2ServerListener::ActiveConnection::HandshakingState::OnTimeout(
412 void* arg, grpc_error_handle error) {
413 HandshakingState* self = static_cast<HandshakingState*>(arg);
414 // Note that we may be called with absl::OkStatus() when the timer fires
415 // or with an error indicating that the timer system is being shut down.
416 if (error != absl::CancelledError()) {
417 grpc_transport_op* op = grpc_make_transport_op(nullptr);
418 op->disconnect_with_error = GRPC_ERROR_CREATE(
419 "Did not receive HTTP/2 settings before handshake timeout");
420 grpc_chttp2_transport* transport = nullptr;
421 {
422 MutexLock lock(&self->connection_->mu_);
423 transport = self->connection_->transport_;
424 }
425 grpc_transport_perform_op(&transport->base, op);
426 }
427 self->Unref();
428 }
429
430 void Chttp2ServerListener::ActiveConnection::HandshakingState::
431 OnReceiveSettings(void* arg, grpc_error_handle /* error */) {
432 HandshakingState* self = static_cast<HandshakingState*>(arg);
433 grpc_timer_cancel(&self->timer_);
434 self->Unref();
435 }
436
437 void Chttp2ServerListener::ActiveConnection::HandshakingState::OnHandshakeDone(
438 void* arg, grpc_error_handle error) {
439 auto* args = static_cast<HandshakerArgs*>(arg);
440 HandshakingState* self = static_cast<HandshakingState*>(args->user_data);
441 OrphanablePtr<HandshakingState> handshaking_state_ref;
442 RefCountedPtr<HandshakeManager> handshake_mgr;
443 bool cleanup_connection = false;
444 {
445 MutexLock connection_lock(&self->connection_->mu_);
446 if (!error.ok() || self->connection_->shutdown_) {
447 std::string error_str = StatusToString(error);
448 gpr_log(GPR_DEBUG, "Handshaking failed: %s", error_str.c_str());
449 cleanup_connection = true;
450 if (error.ok() && args->endpoint != nullptr) {
451 // We were shut down or stopped serving after handshaking completed
452 // successfully, so destroy the endpoint here.
453 // TODO(ctiller): It is currently necessary to shutdown endpoints
454 // before destroying them, even if we know that there are no
455 // pending read/write callbacks. This should be fixed, at which
456 // point this can be removed.
457 grpc_endpoint_shutdown(args->endpoint, absl::OkStatus());
458 grpc_endpoint_destroy(args->endpoint);
459 grpc_slice_buffer_destroy(args->read_buffer);
460 gpr_free(args->read_buffer);
461 }
462 } else {
463 // If the handshaking succeeded but there is no endpoint, then the
464 // handshaker may have handed off the connection to some external
465 // code, so we can just clean up here without creating a transport.
466 if (args->endpoint != nullptr) {
467 grpc_transport* transport =
468 grpc_create_chttp2_transport(args->args, args->endpoint, false);
469 grpc_error_handle channel_init_err =
470 self->connection_->listener_->server_->SetupTransport(
471 transport, self->accepting_pollset_, args->args,
472 grpc_chttp2_transport_get_socket_node(transport));
473 if (channel_init_err.ok()) {
474 // Use notify_on_receive_settings callback to enforce the
475 // handshake deadline.
476 // Note: The reinterpret_cast<>s here are safe, because
477 // grpc_chttp2_transport is a C-style extension of
478 // grpc_transport, so this is morally equivalent of a
479 // static_cast<> to a derived class.
480 // TODO(roth): Change to static_cast<> when we C++-ify the
481 // transport API.
482 self->connection_->transport_ =
483 reinterpret_cast<grpc_chttp2_transport*>(transport);
484 GRPC_CHTTP2_REF_TRANSPORT(self->connection_->transport_,
485 "ActiveConnection"); // Held by connection_
486 self->Ref().release(); // Held by OnReceiveSettings().
487 GRPC_CLOSURE_INIT(&self->on_receive_settings_, OnReceiveSettings,
488 self, grpc_schedule_on_exec_ctx);
489 // If the listener has been configured with a config fetcher, we
490 // need to watch on the transport being closed so that we can an
491 // updated list of active connections.
492 grpc_closure* on_close = nullptr;
493 if (self->connection_->listener_->config_fetcher_watcher_ !=
494 nullptr) {
495 // Refs helds by OnClose()
496 self->connection_->Ref().release();
497 on_close = &self->connection_->on_close_;
498 } else {
499 // Remove the connection from the connections_ map since OnClose()
500 // will not be invoked when a config fetcher is set.
501 cleanup_connection = true;
502 }
503 grpc_chttp2_transport_start_reading(transport, args->read_buffer,
504 &self->on_receive_settings_,
505 on_close);
506 self->Ref().release(); // Held by OnTimeout().
507 GRPC_CLOSURE_INIT(&self->on_timeout_, OnTimeout, self,
508 grpc_schedule_on_exec_ctx);
509 grpc_timer_init(&self->timer_, self->deadline_, &self->on_timeout_);
510 } else {
511 // Failed to create channel from transport. Clean up.
512 gpr_log(GPR_ERROR, "Failed to create channel: %s",
513 StatusToString(channel_init_err).c_str());
514 grpc_transport_destroy(transport);
515 grpc_slice_buffer_destroy(args->read_buffer);
516 gpr_free(args->read_buffer);
517 cleanup_connection = true;
518 }
519 } else {
520 cleanup_connection = true;
521 }
522 }
523 // Since the handshake manager is done, the connection no longer needs to
524 // shutdown the handshake when the listener needs to stop serving.
525 // Avoid calling the destructor of HandshakeManager and HandshakingState
526 // from within the critical region.
527 handshake_mgr = std::move(self->handshake_mgr_);
528 handshaking_state_ref = std::move(self->connection_->handshaking_state_);
529 }
530 gpr_free(self->acceptor_);
531 self->acceptor_ = nullptr;
532 OrphanablePtr<ActiveConnection> connection;
533 if (cleanup_connection) {
534 MutexLock listener_lock(&self->connection_->listener_->mu_);
535 auto it = self->connection_->listener_->connections_.find(
536 self->connection_.get());
537 if (it != self->connection_->listener_->connections_.end()) {
538 connection = std::move(it->second);
539 self->connection_->listener_->connections_.erase(it);
540 }
541 }
542 self->Unref();
543 }
544
545 //
546 // Chttp2ServerListener::ActiveConnection
547 //
548
549 Chttp2ServerListener::ActiveConnection::ActiveConnection(
550 grpc_pollset* accepting_pollset, grpc_tcp_server_acceptor* acceptor,
551 const ChannelArgs& args, MemoryOwner memory_owner)
552 : handshaking_state_(memory_owner.MakeOrphanable<HandshakingState>(
553 Ref(), accepting_pollset, acceptor, args)) {
554 GRPC_CLOSURE_INIT(&on_close_, ActiveConnection::OnClose, this,
555 grpc_schedule_on_exec_ctx);
556 }
557
558 Chttp2ServerListener::ActiveConnection::~ActiveConnection() {
559 if (transport_ != nullptr) {
560 GRPC_CHTTP2_UNREF_TRANSPORT(transport_, "ActiveConnection");
561 }
562 }
563
564 void Chttp2ServerListener::ActiveConnection::Orphan() {
565 OrphanablePtr<HandshakingState> handshaking_state;
566 {
567 MutexLock lock(&mu_);
568 shutdown_ = true;
569 // Reset handshaking_state_ since we have been orphaned by the listener
570 // signaling that the listener has stopped serving.
571 handshaking_state = std::move(handshaking_state_);
572 }
573 Unref();
574 }
575
576 void Chttp2ServerListener::ActiveConnection::SendGoAway() {
577 grpc_chttp2_transport* transport = nullptr;
578 {
579 MutexLock lock(&mu_);
580 if (transport_ != nullptr && !shutdown_) {
581 transport = transport_;
582 Ref().release(); // Ref held by OnDrainGraceTimeExpiry
583 GRPC_CLOSURE_INIT(&on_drain_grace_time_expiry_, OnDrainGraceTimeExpiry,
584 this, nullptr);
585 grpc_timer_init(
586 &drain_grace_timer_,
587 Timestamp::Now() +
588 std::max(
589 Duration::Zero(),
590 listener_->args_
591 .GetDurationFromIntMillis(
592 GRPC_ARG_SERVER_CONFIG_CHANGE_DRAIN_GRACE_TIME_MS)
593 .value_or(Duration::Minutes(10))),
594 &on_drain_grace_time_expiry_);
595 drain_grace_timer_expiry_callback_pending_ = true;
596 shutdown_ = true;
597 }
598 }
599 if (transport != nullptr) {
600 grpc_transport_op* op = grpc_make_transport_op(nullptr);
601 op->goaway_error =
602 GRPC_ERROR_CREATE("Server is stopping to serve requests.");
603 grpc_transport_perform_op(&transport->base, op);
604 }
605 }
606
607 void Chttp2ServerListener::ActiveConnection::Start(
608 RefCountedPtr<Chttp2ServerListener> listener, grpc_endpoint* endpoint,
609 const ChannelArgs& args) {
610 RefCountedPtr<HandshakingState> handshaking_state_ref;
611 listener_ = std::move(listener);
612 {
613 MutexLock lock(&mu_);
614 if (shutdown_) return;
615 // Hold a ref to HandshakingState to allow starting the handshake outside
616 // the critical region.
617 handshaking_state_ref = handshaking_state_->Ref();
618 }
619 handshaking_state_ref->Start(endpoint, args);
620 }
621
622 void Chttp2ServerListener::ActiveConnection::OnClose(
623 void* arg, grpc_error_handle /* error */) {
624 ActiveConnection* self = static_cast<ActiveConnection*>(arg);
625 OrphanablePtr<ActiveConnection> connection;
626 {
627 MutexLock listener_lock(&self->listener_->mu_);
628 MutexLock connection_lock(&self->mu_);
629 // The node was already deleted from the connections_ list if the
630 // connection is shutdown.
631 if (!self->shutdown_) {
632 auto it = self->listener_->connections_.find(self);
633 if (it != self->listener_->connections_.end()) {
634 connection = std::move(it->second);
635 self->listener_->connections_.erase(it);
636 }
637 self->shutdown_ = true;
638 }
639 // Cancel the drain_grace_timer_ if needed.
640 if (self->drain_grace_timer_expiry_callback_pending_) {
641 grpc_timer_cancel(&self->drain_grace_timer_);
642 }
643 }
644 self->Unref();
645 }
646
647 void Chttp2ServerListener::ActiveConnection::OnDrainGraceTimeExpiry(
648 void* arg, grpc_error_handle error) {
649 ActiveConnection* self = static_cast<ActiveConnection*>(arg);
650 // If the drain_grace_timer_ was not cancelled, disconnect the transport
651 // immediately.
652 if (error.ok()) {
653 grpc_chttp2_transport* transport = nullptr;
654 {
655 MutexLock lock(&self->mu_);
656 transport = self->transport_;
657 }
658 grpc_transport_op* op = grpc_make_transport_op(nullptr);
659 op->disconnect_with_error = GRPC_ERROR_CREATE(
660 "Drain grace time expired. Closing connection immediately.");
661 grpc_transport_perform_op(&transport->base, op);
662 }
663 self->Unref();
664 }
665
666 //
667 // Chttp2ServerListener
668 //
669
670 grpc_error_handle Chttp2ServerListener::Create(
671 Server* server, grpc_resolved_address* addr, const ChannelArgs& args,
672 Chttp2ServerArgsModifier args_modifier, int* port_num) {
673 Chttp2ServerListener* listener = nullptr;
674 // The bulk of this method is inside of a lambda to make cleanup
675 // easier without using goto.
676 grpc_error_handle error = [&]() {
677 grpc_error_handle error;
678 // Create Chttp2ServerListener.
679 listener = new Chttp2ServerListener(server, args, args_modifier);
680 error = grpc_tcp_server_create(
681 &listener->tcp_server_shutdown_complete_,
682 grpc_event_engine::experimental::ChannelArgsEndpointConfig(args),
683 &listener->tcp_server_);
684 if (!error.ok()) return error;
685 if (server->config_fetcher() != nullptr) {
686 listener->resolved_address_ = *addr;
687 // TODO(yashykt): Consider binding so as to be able to return the port
688 // number.
689 } else {
690 error = grpc_tcp_server_add_port(listener->tcp_server_, addr, port_num);
691 if (!error.ok()) return error;
692 }
693 // Create channelz node.
694 if (args.GetBool(GRPC_ARG_ENABLE_CHANNELZ)
695 .value_or(GRPC_ENABLE_CHANNELZ_DEFAULT)) {
696 auto string_address = grpc_sockaddr_to_uri(addr);
697 if (!string_address.ok()) {
698 return GRPC_ERROR_CREATE(string_address.status().ToString());
699 }
700 listener->channelz_listen_socket_ =
701 MakeRefCounted<channelz::ListenSocketNode>(
702 *string_address,
703 absl::StrCat("chttp2 listener ", *string_address));
704 }
705 // Register with the server only upon success
706 server->AddListener(OrphanablePtr<Server::ListenerInterface>(listener));
707 return absl::OkStatus();
708 }();
709 if (!error.ok()) {
710 if (listener != nullptr) {
711 if (listener->tcp_server_ != nullptr) {
712 // listener is deleted when tcp_server_ is shutdown.
713 grpc_tcp_server_unref(listener->tcp_server_);
714 } else {
715 delete listener;
716 }
717 }
718 }
719 return error;
720 }
721
722 grpc_error_handle Chttp2ServerListener::CreateWithAcceptor(
723 Server* server, const char* name, const ChannelArgs& args,
724 Chttp2ServerArgsModifier args_modifier) {
725 Chttp2ServerListener* listener =
726 new Chttp2ServerListener(server, args, args_modifier);
727 grpc_error_handle error = grpc_tcp_server_create(
728 &listener->tcp_server_shutdown_complete_,
729 grpc_event_engine::experimental::ChannelArgsEndpointConfig(args),
730 &listener->tcp_server_);
731 if (!error.ok()) {
732 delete listener;
733 return error;
734 }
735 // TODO(yangg) channelz
736 TcpServerFdHandler** arg_val = args.GetPointer<TcpServerFdHandler*>(name);
737 *arg_val = grpc_tcp_server_create_fd_handler(listener->tcp_server_);
738 server->AddListener(OrphanablePtr<Server::ListenerInterface>(listener));
739 return absl::OkStatus();
740 }
741
742 Chttp2ServerListener::Chttp2ServerListener(
743 Server* server, const ChannelArgs& args,
744 Chttp2ServerArgsModifier args_modifier)
745 : server_(server),
746 args_modifier_(args_modifier),
747 args_(args),
748 memory_quota_(args.GetObject<ResourceQuota>()->memory_quota()) {
749 GRPC_CLOSURE_INIT(&tcp_server_shutdown_complete_, TcpServerShutdownComplete,
750 this, grpc_schedule_on_exec_ctx);
751 }
752
753 Chttp2ServerListener::~Chttp2ServerListener() {
754 // Flush queued work before destroying handshaker factory, since that
755 // may do a synchronous unref.
756 ExecCtx::Get()->Flush();
757 if (on_destroy_done_ != nullptr) {
758 ExecCtx::Run(DEBUG_LOCATION, on_destroy_done_, absl::OkStatus());
759 ExecCtx::Get()->Flush();
760 }
761 }
762
763 /* Server callback: start listening on our ports */
764 void Chttp2ServerListener::Start(
765 Server* /*server*/, const std::vector<grpc_pollset*>* /* pollsets */) {
766 if (server_->config_fetcher() != nullptr) {
767 auto watcher = std::make_unique<ConfigFetcherWatcher>(Ref());
768 config_fetcher_watcher_ = watcher.get();
769 server_->config_fetcher()->StartWatch(
770 grpc_sockaddr_to_string(&resolved_address_, false).value(),
771 std::move(watcher));
772 } else {
773 {
774 MutexLock lock(&mu_);
775 started_ = true;
776 is_serving_ = true;
777 }
778 StartListening();
779 }
780 }
781
782 void Chttp2ServerListener::StartListening() {
783 grpc_tcp_server_start(tcp_server_, &server_->pollsets(), OnAccept, this);
784 }
785
786 void Chttp2ServerListener::SetOnDestroyDone(grpc_closure* on_destroy_done) {
787 MutexLock lock(&mu_);
788 on_destroy_done_ = on_destroy_done;
789 }
790
791 void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp,
792 grpc_pollset* accepting_pollset,
793 grpc_tcp_server_acceptor* acceptor) {
794 Chttp2ServerListener* self = static_cast<Chttp2ServerListener*>(arg);
795 ChannelArgs args = self->args_;
796 RefCountedPtr<grpc_server_config_fetcher::ConnectionManager>
797 connection_manager;
798 {
799 MutexLock lock(&self->mu_);
800 connection_manager = self->connection_manager_;
801 }
802 auto endpoint_cleanup = [&](grpc_error_handle error) {
803 grpc_endpoint_shutdown(tcp, error);
804 grpc_endpoint_destroy(tcp);
805 gpr_free(acceptor);
806 };
807 if (self->server_->config_fetcher() != nullptr) {
808 if (connection_manager == nullptr) {
809 grpc_error_handle error = GRPC_ERROR_CREATE(
810 "No ConnectionManager configured. Closing connection.");
811 endpoint_cleanup(error);
812 return;
813 }
814 absl::StatusOr<ChannelArgs> args_result =
815 connection_manager->UpdateChannelArgsForConnection(args, tcp);
816 if (!args_result.ok()) {
817 gpr_log(GPR_DEBUG, "Closing connection: %s",
818 args_result.status().ToString().c_str());
819 endpoint_cleanup(GRPC_ERROR_CREATE(args_result.status().ToString()));
820 return;
821 }
822 grpc_error_handle error;
823 args = self->args_modifier_(*args_result, &error);
824 if (!error.ok()) {
825 gpr_log(GPR_DEBUG, "Closing connection: %s",
826 StatusToString(error).c_str());
827 endpoint_cleanup(error);
828 return;
829 }
830 }
831 auto memory_owner = self->memory_quota_->CreateMemoryOwner(
832 absl::StrCat(grpc_endpoint_get_peer(tcp), ":server_channel"));
833 auto connection = memory_owner.MakeOrphanable<ActiveConnection>(
834 accepting_pollset, acceptor, args, std::move(memory_owner));
835 // We no longer own acceptor
836 acceptor = nullptr;
837 // Hold a ref to connection to allow starting handshake outside the
838 // critical region
839 RefCountedPtr<ActiveConnection> connection_ref = connection->Ref();
840 RefCountedPtr<Chttp2ServerListener> listener_ref;
841 {
842 MutexLock lock(&self->mu_);
843 // Shutdown the the connection if listener's stopped serving or if the
844 // connection manager has changed.
845 if (!self->shutdown_ && self->is_serving_ &&
846 connection_manager == self->connection_manager_) {
847 // This ref needs to be taken in the critical region after having made
848 // sure that the listener has not been Orphaned, so as to avoid
849 // heap-use-after-free issues where `Ref()` is invoked when the ref of
850 // tcp_server_ has already reached 0. (Ref() implementation of
851 // Chttp2ServerListener is grpc_tcp_server_ref().)
852 listener_ref = self->Ref();
853 self->connections_.emplace(connection.get(), std::move(connection));
854 }
855 }
856 if (connection != nullptr) {
857 endpoint_cleanup(absl::OkStatus());
858 } else {
859 connection_ref->Start(std::move(listener_ref), tcp, args);
860 }
861 }
862
863 void Chttp2ServerListener::TcpServerShutdownComplete(
864 void* arg, grpc_error_handle /*error*/) {
865 Chttp2ServerListener* self = static_cast<Chttp2ServerListener*>(arg);
866 self->channelz_listen_socket_.reset();
867 delete self;
868 }
869
870 /* Server callback: destroy the tcp listener (so we don't generate further
871 callbacks) */
872 void Chttp2ServerListener::Orphan() {
873 // Cancel the watch before shutting down so as to avoid holding a ref to the
874 // listener in the watcher.
875 if (config_fetcher_watcher_ != nullptr) {
876 server_->config_fetcher()->CancelWatch(config_fetcher_watcher_);
877 }
878 std::map<ActiveConnection*, OrphanablePtr<ActiveConnection>> connections;
879 grpc_tcp_server* tcp_server;
880 {
881 MutexLock lock(&mu_);
882 shutdown_ = true;
883 is_serving_ = false;
884 // Orphan the connections so that they can start cleaning up.
885 connections = std::move(connections_);
886 // If the listener is currently set to be serving but has not been started
887 // yet, it means that `grpc_tcp_server_start` is in progress. Wait for the
888 // operation to finish to avoid causing races.
889 while (is_serving_ && !started_) {
890 started_cv_.Wait(&mu_);
891 }
892 tcp_server = tcp_server_;
893 }
894 grpc_tcp_server_shutdown_listeners(tcp_server);
895 grpc_tcp_server_unref(tcp_server);
896 }
897
898 } // namespace
899
900 //
901 // Chttp2ServerAddPort()
902 //
903
904 grpc_error_handle Chttp2ServerAddPort(Server* server, const char* addr,
905 const ChannelArgs& args,
906 Chttp2ServerArgsModifier args_modifier,
907 int* port_num) {
908 if (addr == nullptr) {
909 return GRPC_ERROR_CREATE("Invalid address: addr cannot be a nullptr.");
910 }
911 if (strncmp(addr, "external:", 9) == 0) {
912 return Chttp2ServerListener::CreateWithAcceptor(server, addr, args,
913 args_modifier);
914 }
915 *port_num = -1;
916 absl::StatusOr<std::vector<grpc_resolved_address>> resolved_or;
917 std::vector<grpc_error_handle> error_list;
918 std::string parsed_addr = URI::PercentDecode(addr);
919 absl::string_view parsed_addr_unprefixed{parsed_addr};
920 // Using lambda to avoid use of goto.
921 grpc_error_handle error = [&]() {
922 grpc_error_handle error;
923 if (absl::ConsumePrefix(&parsed_addr_unprefixed, kUnixUriPrefix)) {
924 resolved_or = grpc_resolve_unix_domain_address(parsed_addr_unprefixed);
925 } else if (absl::ConsumePrefix(&parsed_addr_unprefixed,
926 kUnixAbstractUriPrefix)) {
927 resolved_or =
928 grpc_resolve_unix_abstract_domain_address(parsed_addr_unprefixed);
929 } else {
930 resolved_or =
931 GetDNSResolver()->LookupHostnameBlocking(parsed_addr, "https");
932 }
933 if (!resolved_or.ok()) {
934 return absl_status_to_grpc_error(resolved_or.status());
935 }
936 // Create a listener for each resolved address.
937 for (auto& addr : *resolved_or) {
938 // If address has a wildcard port (0), use the same port as a previous
939 // listener.
940 if (*port_num != -1 && grpc_sockaddr_get_port(&addr) == 0) {
941 grpc_sockaddr_set_port(&addr, *port_num);
942 }
943 int port_temp = -1;
944 error = Chttp2ServerListener::Create(server, &addr, args, args_modifier,
945 &port_temp);
946 if (!error.ok()) {
947 error_list.push_back(error);
948 } else {
949 if (*port_num == -1) {
950 *port_num = port_temp;
951 } else {
952 GPR_ASSERT(*port_num == port_temp);
953 }
954 }
955 }
956 if (error_list.size() == resolved_or->size()) {
957 std::string msg = absl::StrFormat(
958 "No address added out of total %" PRIuPTR " resolved for '%s'",
959 resolved_or->size(), addr);
960 return GRPC_ERROR_CREATE_REFERENCING(msg.c_str(), error_list.data(),
961 error_list.size());
962 } else if (!error_list.empty()) {
963 std::string msg = absl::StrFormat(
964 "Only %" PRIuPTR " addresses added out of total %" PRIuPTR
965 " resolved",
966 resolved_or->size() - error_list.size(), resolved_or->size());
967 error = GRPC_ERROR_CREATE_REFERENCING(msg.c_str(), error_list.data(),
968 error_list.size());
969 gpr_log(GPR_INFO, "WARNING: %s", StatusToString(error).c_str());
970 // we managed to bind some addresses: continue without error
971 }
972 return absl::OkStatus();
973 }(); // lambda end
974 if (!error.ok()) *port_num = 0;
975 return error;
976 }
977
978 namespace {
979
980 ChannelArgs ModifyArgsForConnection(const ChannelArgs& args,
981 grpc_error_handle* error) {
982 auto* server_credentials = args.GetObject<grpc_server_credentials>();
983 if (server_credentials == nullptr) {
984 *error = GRPC_ERROR_CREATE("Could not find server credentials");
985 return args;
986 }
987 auto security_connector = server_credentials->create_security_connector(args);
988 if (security_connector == nullptr) {
989 *error = GRPC_ERROR_CREATE(
990 absl::StrCat("Unable to create secure server with credentials of type ",
991 server_credentials->type().name()));
992 return args;
993 }
994 return args.SetObject(security_connector);
995 }
996
997 } // namespace
998 } // namespace grpc_core
999
1000 int grpc_server_add_http2_port(grpc_server* server, const char* addr,
1001 grpc_server_credentials* creds) {
1002 grpc_core::ExecCtx exec_ctx;
1003 grpc_error_handle err;
1004 grpc_core::RefCountedPtr<grpc_server_security_connector> sc;
1005 int port_num = 0;
1006 grpc_core::Server* core_server = grpc_core::Server::FromC(server);
1007 grpc_core::ChannelArgs args = core_server->channel_args();
1008 GRPC_API_TRACE("grpc_server_add_http2_port(server=%p, addr=%s, creds=%p)", 3,
1009 (server, addr, creds));
1010 // Create security context.
1011 if (creds == nullptr) {
1012 err = GRPC_ERROR_CREATE(
1013 "No credentials specified for secure server port (creds==NULL)");
1014 goto done;
1015 }
1016 // TODO(yashykt): Ideally, we would not want to have different behavior here
1017 // based on whether a config fetcher is configured or not. Currently, we have
1018 // a feature for SSL credentials reloading with an application callback that
1019 // assumes that there is a single security connector. If we delay the creation
1020 // of the security connector to after the creation of the listener(s), we
1021 // would have potentially multiple security connectors which breaks the
1022 // assumption for SSL creds reloading. When the API for SSL creds reloading is
1023 // rewritten, we would be able to make this workaround go away by removing
1024 // that assumption. As an immediate drawback of this workaround, config
1025 // fetchers need to be registered before adding ports to the server.
1026 if (core_server->config_fetcher() != nullptr) {
1027 // Create channel args.
1028 args = args.SetObject(creds->Ref());
1029 } else {
1030 sc = creds->create_security_connector(grpc_core::ChannelArgs());
1031 if (sc == nullptr) {
1032 err = GRPC_ERROR_CREATE(absl::StrCat(
1033 "Unable to create secure server with credentials of type ",
1034 creds->type().name()));
1035 goto done;
1036 }
1037 args = args.SetObject(creds->Ref()).SetObject(sc);
1038 }
1039 // Add server port.
1040 err = grpc_core::Chttp2ServerAddPort(
1041 core_server, addr, args, grpc_core::ModifyArgsForConnection, &port_num);
1042 done:
1043 sc.reset(DEBUG_LOCATION, "server");
1044 if (!err.ok()) {
1045 gpr_log(GPR_ERROR, "%s", grpc_core::StatusToString(err).c_str());
1046 }
1047 return port_num;
1048 }
1049
1050 #ifdef GPR_SUPPORT_CHANNELS_FROM_FD
1051 void grpc_server_add_channel_from_fd(grpc_server* server, int fd,
1052 grpc_server_credentials* creds) {
1053 // For now, we only support insecure server credentials
1054 if (creds == nullptr ||
1055 creds->type() != grpc_core::InsecureServerCredentials::Type()) {
1056 gpr_log(GPR_ERROR, "Failed to create channel due to invalid creds");
1057 return;
1058 }
1059 grpc_core::ExecCtx exec_ctx;
1060 grpc_core::Server* core_server = grpc_core::Server::FromC(server);
1061
1062 grpc_core::ChannelArgs server_args = core_server->channel_args();
1063 std::string name = absl::StrCat("fd:", fd);
1064 auto memory_quota =
1065 server_args.GetObject<grpc_core::ResourceQuota>()->memory_quota();
1066 grpc_endpoint* server_endpoint = grpc_tcp_create_from_fd(
1067 grpc_fd_create(fd, name.c_str(), true),
1068 grpc_event_engine::experimental::ChannelArgsEndpointConfig(server_args),
1069 name);
1070 grpc_transport* transport = grpc_create_chttp2_transport(
1071 server_args, server_endpoint, false /* is_client */
1072 );
1073 grpc_error_handle error =
1074 core_server->SetupTransport(transport, nullptr, server_args, nullptr);
1075 if (error.ok()) {
1076 for (grpc_pollset* pollset : core_server->pollsets()) {
1077 grpc_endpoint_add_to_pollset(server_endpoint, pollset);
1078 }
1079 grpc_chttp2_transport_start_reading(transport, nullptr, nullptr, nullptr);
1080 } else {
1081 gpr_log(GPR_ERROR, "Failed to create channel: %s",
1082 grpc_core::StatusToString(error).c_str());
1083 grpc_transport_destroy(transport);
1084 }
1085 }
1086
1087 #else // !GPR_SUPPORT_CHANNELS_FROM_FD
1088
1089 void grpc_server_add_channel_from_fd(grpc_server* /* server */, int /* fd */,
1090 grpc_server_credentials* /* creds */) {
1091 GPR_ASSERT(0);
1092 }
1093
1094 #endif // GPR_SUPPORT_CHANNELS_FROM_FD