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/lib/surface/init.h"
22 
23 #include <limits.h>
24 
25 #include "absl/base/thread_annotations.h"
26 
27 #include <grpc/fork.h>
28 #include <grpc/grpc.h>
29 #include <grpc/grpc_security.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/sync.h>
32 #include <grpc/support/time.h>
33 
34 #include "src/core/ext/filters/client_channel/backup_poller.h"
35 #include "src/core/lib/channel/channel_args.h"
36 #include "src/core/lib/channel/channel_stack_builder.h"
37 #include "src/core/lib/config/core_configuration.h"
38 #include "src/core/lib/debug/trace.h"
39 #include "src/core/lib/event_engine/forkable.h"
40 #include "src/core/lib/event_engine/posix_engine/timer_manager.h"
41 #include "src/core/lib/experiments/config.h"
42 #include "src/core/lib/gprpp/fork.h"
43 #include "src/core/lib/gprpp/sync.h"
44 #include "src/core/lib/gprpp/thd.h"
45 #include "src/core/lib/iomgr/exec_ctx.h"
46 #include "src/core/lib/iomgr/iomgr.h"
47 #include "src/core/lib/iomgr/timer_manager.h"
48 #include "src/core/lib/security/authorization/grpc_server_authz_filter.h"
49 #include "src/core/lib/security/credentials/credentials.h"
50 #include "src/core/lib/security/security_connector/security_connector.h"
51 #include "src/core/lib/security/transport/auth_filters.h"
52 #include "src/core/lib/surface/api_trace.h"
53 #include "src/core/lib/surface/channel_stack_type.h"
54 #include "src/core/lib/surface/init_internally.h"
55 
56 // Remnants of the old plugin system
57 void grpc_resolver_dns_ares_init(void);
58 void grpc_resolver_dns_ares_shutdown(void);
59 
60 #define MAX_PLUGINS 128
61 
62 static gpr_once g_basic_init = GPR_ONCE_INIT;
63 static grpc_core::Mutex* g_init_mu;
__anon6e83c3c80102() 64 static int g_initializations ABSL_GUARDED_BY(g_init_mu) = []() {
65   grpc_core::CoreConfiguration::SetDefaultBuilder(
66       grpc_core::BuildCoreConfiguration);
67   return 0;
68 }();
69 static grpc_core::CondVar* g_shutting_down_cv;
70 static bool g_shutting_down ABSL_GUARDED_BY(g_init_mu) = false;
71 
maybe_prepend_client_auth_filter(grpc_core::ChannelStackBuilder * builder)72 static bool maybe_prepend_client_auth_filter(
73     grpc_core::ChannelStackBuilder* builder) {
74   if (builder->channel_args().Contains(GRPC_ARG_SECURITY_CONNECTOR)) {
75     builder->PrependFilter(&grpc_core::ClientAuthFilter::kFilter);
76   }
77   return true;
78 }
79 
maybe_prepend_server_auth_filter(grpc_core::ChannelStackBuilder * builder)80 static bool maybe_prepend_server_auth_filter(
81     grpc_core::ChannelStackBuilder* builder) {
82   if (builder->channel_args().Contains(GRPC_SERVER_CREDENTIALS_ARG)) {
83     builder->PrependFilter(&grpc_core::ServerAuthFilter::kFilter);
84   }
85   return true;
86 }
87 
maybe_prepend_grpc_server_authz_filter(grpc_core::ChannelStackBuilder * builder)88 static bool maybe_prepend_grpc_server_authz_filter(
89     grpc_core::ChannelStackBuilder* builder) {
90   if (builder->channel_args().GetPointer<grpc_authorization_policy_provider>(
91           GRPC_ARG_AUTHORIZATION_POLICY_PROVIDER) != nullptr) {
92     builder->PrependFilter(&grpc_core::GrpcServerAuthzFilter::kFilterVtable);
93   }
94   return true;
95 }
96 
97 namespace grpc_core {
RegisterSecurityFilters(CoreConfiguration::Builder * builder)98 void RegisterSecurityFilters(CoreConfiguration::Builder* builder) {
99   // Register the auth client with a priority < INT_MAX to allow the authority
100   // filter -on which the auth filter depends- to be higher on the channel
101   // stack.
102   builder->channel_init()->RegisterStage(GRPC_CLIENT_SUBCHANNEL, INT_MAX - 1,
103                                          maybe_prepend_client_auth_filter);
104   builder->channel_init()->RegisterStage(GRPC_CLIENT_DIRECT_CHANNEL,
105                                          INT_MAX - 1,
106                                          maybe_prepend_client_auth_filter);
107   builder->channel_init()->RegisterStage(GRPC_SERVER_CHANNEL, INT_MAX - 1,
108                                          maybe_prepend_server_auth_filter);
109   // Register the GrpcServerAuthzFilter with a priority less than
110   // server_auth_filter to allow server_auth_filter on which the grpc filter
111   // depends on to be higher on the channel stack.
112   builder->channel_init()->RegisterStage(
113       GRPC_SERVER_CHANNEL, INT_MAX - 2, maybe_prepend_grpc_server_authz_filter);
114 }
115 }  // namespace grpc_core
116 
do_basic_init(void)117 static void do_basic_init(void) {
118   grpc_core::InitInternally = grpc_init;
119   grpc_core::ShutdownInternally = grpc_shutdown;
120   grpc_core::IsInitializedInternally = []() {
121     return grpc_is_initialized() != 0;
122   };
123   gpr_log_verbosity_init();
124   g_init_mu = new grpc_core::Mutex();
125   g_shutting_down_cv = new grpc_core::CondVar();
126   gpr_time_init();
127   grpc_core::PrintExperimentsList();
128   grpc_core::Fork::GlobalInit();
129   grpc_event_engine::experimental::RegisterForkHandlers();
130   grpc_fork_handlers_auto_register();
131   grpc_tracer_init();
132   grpc_client_channel_global_init_backup_polling();
133 }
134 
grpc_init(void)135 void grpc_init(void) {
136   gpr_once_init(&g_basic_init, do_basic_init);
137 
138   grpc_core::MutexLock lock(g_init_mu);
139   if (++g_initializations == 1) {
140     if (g_shutting_down) {
141       g_shutting_down = false;
142       g_shutting_down_cv->SignalAll();
143     }
144     grpc_iomgr_init();
145     grpc_resolver_dns_ares_init();
146     grpc_iomgr_start();
147   }
148 
149   GRPC_API_TRACE("grpc_init(void)", 0, ());
150 }
151 
grpc_shutdown_internal_locked(void)152 void grpc_shutdown_internal_locked(void)
153     ABSL_EXCLUSIVE_LOCKS_REQUIRED(g_init_mu) {
154   {
155     grpc_core::ExecCtx exec_ctx(0);
156     grpc_iomgr_shutdown_background_closure();
157     grpc_timer_manager_set_threading(false);  // shutdown timer_manager thread
158     grpc_resolver_dns_ares_shutdown();
159     grpc_iomgr_shutdown();
160   }
161   g_shutting_down = false;
162   g_shutting_down_cv->SignalAll();
163 }
164 
grpc_shutdown_internal(void *)165 void grpc_shutdown_internal(void* /*ignored*/) {
166   GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
167   grpc_core::MutexLock lock(g_init_mu);
168   // We have released lock from the shutdown thread and it is possible that
169   // another grpc_init has been called, and do nothing if that is the case.
170   if (--g_initializations != 0) {
171     return;
172   }
173   grpc_shutdown_internal_locked();
174 }
175 
grpc_shutdown(void)176 void grpc_shutdown(void) {
177   GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
178   grpc_core::MutexLock lock(g_init_mu);
179 
180   if (--g_initializations == 0) {
181     grpc_core::ApplicationCallbackExecCtx* acec =
182         grpc_core::ApplicationCallbackExecCtx::Get();
183     if (!grpc_iomgr_is_any_background_poller_thread() &&
184         !grpc_event_engine::experimental::TimerManager::
185             IsTimerManagerThread() &&
186         (acec == nullptr ||
187          (acec->Flags() & GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD) ==
188              0) &&
189         grpc_core::ExecCtx::Get() == nullptr) {
190       // just run clean-up when this is called on non-executor thread.
191       gpr_log(GPR_DEBUG, "grpc_shutdown starts clean-up now");
192       g_shutting_down = true;
193       grpc_shutdown_internal_locked();
194     } else {
195       // spawn a detached thread to do the actual clean up in case we are
196       // currently in an executor thread.
197       gpr_log(GPR_DEBUG, "grpc_shutdown spawns clean-up thread");
198       g_initializations++;
199       g_shutting_down = true;
200       grpc_core::Thread cleanup_thread(
201           "grpc_shutdown", grpc_shutdown_internal, nullptr, nullptr,
202           grpc_core::Thread::Options().set_joinable(false).set_tracked(false));
203       cleanup_thread.Start();
204     }
205   }
206 }
207 
grpc_shutdown_blocking(void)208 void grpc_shutdown_blocking(void) {
209   GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
210   grpc_core::MutexLock lock(g_init_mu);
211   if (--g_initializations == 0) {
212     g_shutting_down = true;
213     grpc_shutdown_internal_locked();
214   }
215 }
216 
grpc_is_initialized(void)217 int grpc_is_initialized(void) {
218   int r;
219   gpr_once_init(&g_basic_init, do_basic_init);
220   grpc_core::MutexLock lock(g_init_mu);
221   r = g_initializations > 0;
222   return r;
223 }
224 
grpc_maybe_wait_for_async_shutdown(void)225 void grpc_maybe_wait_for_async_shutdown(void) {
226   gpr_once_init(&g_basic_init, do_basic_init);
227   grpc_core::MutexLock lock(g_init_mu);
228   while (g_shutting_down) {
229     g_shutting_down_cv->Wait(g_init_mu);
230   }
231 }
232