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 <stdlib.h>
20 
21 #include <initializer_list>
22 #include <map>
23 #include <memory>
24 #include <string>
25 #include <utility>
26 #include <vector>
27 
28 #include "absl/strings/str_format.h"
29 
30 #include <grpc/compression.h>
31 #include <grpc/grpc.h>
32 #include <grpc/impl/compression_types.h>
33 #include <grpc/status.h>
34 #include <grpc/support/alloc.h>
35 #include <grpc/support/log.h>
36 #include <grpc/support/time.h>
37 #include <grpcpp/channel.h>
38 #include <grpcpp/client_context.h>
39 #include <grpcpp/impl/interceptor_common.h>
40 #include <grpcpp/impl/sync.h>
41 #include <grpcpp/security/credentials.h>
42 #include <grpcpp/server_context.h>
43 #include <grpcpp/support/client_interceptor.h>
44 
45 #include "src/core/lib/gprpp/crash.h"
46 
47 namespace grpc {
48 
49 class Channel;
50 
51 class DefaultGlobalClientCallbacks final
52     : public ClientContext::GlobalCallbacks {
53  public:
~DefaultGlobalClientCallbacks()54   ~DefaultGlobalClientCallbacks() override {}
DefaultConstructor(ClientContext *)55   void DefaultConstructor(ClientContext* /*context*/) override {}
Destructor(ClientContext *)56   void Destructor(ClientContext* /*context*/) override {}
57 };
58 
59 static DefaultGlobalClientCallbacks* g_default_client_callbacks =
60     new DefaultGlobalClientCallbacks();
61 static ClientContext::GlobalCallbacks* g_client_callbacks =
62     g_default_client_callbacks;
63 
ClientContext()64 ClientContext::ClientContext()
65     : initial_metadata_received_(false),
66       wait_for_ready_(false),
67       wait_for_ready_explicitly_set_(false),
68       call_(nullptr),
69       call_canceled_(false),
70       deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)),
71       census_context_(nullptr),
72       propagate_from_call_(nullptr),
73       compression_algorithm_(GRPC_COMPRESS_NONE),
74       initial_metadata_corked_(false) {
75   g_client_callbacks->DefaultConstructor(this);
76 }
77 
~ClientContext()78 ClientContext::~ClientContext() {
79   if (call_) {
80     grpc_call_unref(call_);
81     call_ = nullptr;
82   }
83   g_client_callbacks->Destructor(this);
84 }
85 
set_credentials(const std::shared_ptr<CallCredentials> & creds)86 void ClientContext::set_credentials(
87     const std::shared_ptr<CallCredentials>& creds) {
88   creds_ = creds;
89   // If call_ is set, we have already created the call, and set the call
90   // credentials. This should only be done before we have started the batch
91   // for sending initial metadata.
92   if (creds_ != nullptr && call_ != nullptr) {
93     if (!creds_->ApplyToCall(call_)) {
94       SendCancelToInterceptors();
95       grpc_call_cancel_with_status(call_, GRPC_STATUS_CANCELLED,
96                                    "Failed to set credentials to rpc.",
97                                    nullptr);
98     }
99   }
100 }
101 
FromInternalServerContext(const grpc::ServerContextBase & context,PropagationOptions options)102 std::unique_ptr<ClientContext> ClientContext::FromInternalServerContext(
103     const grpc::ServerContextBase& context, PropagationOptions options) {
104   std::unique_ptr<ClientContext> ctx(new ClientContext);
105   ctx->propagate_from_call_ = context.call_.call;
106   ctx->propagation_options_ = options;
107   return ctx;
108 }
109 
FromServerContext(const grpc::ServerContextBase & server_context,PropagationOptions options)110 std::unique_ptr<ClientContext> ClientContext::FromServerContext(
111     const grpc::ServerContextBase& server_context, PropagationOptions options) {
112   return FromInternalServerContext(server_context, options);
113 }
114 
FromCallbackServerContext(const grpc::CallbackServerContext & server_context,PropagationOptions options)115 std::unique_ptr<ClientContext> ClientContext::FromCallbackServerContext(
116     const grpc::CallbackServerContext& server_context,
117     PropagationOptions options) {
118   return FromInternalServerContext(server_context, options);
119 }
120 
AddMetadata(const std::string & meta_key,const std::string & meta_value)121 void ClientContext::AddMetadata(const std::string& meta_key,
122                                 const std::string& meta_value) {
123   send_initial_metadata_.insert(std::make_pair(meta_key, meta_value));
124 }
125 
set_call(grpc_call * call,const std::shared_ptr<Channel> & channel)126 void ClientContext::set_call(grpc_call* call,
127                              const std::shared_ptr<Channel>& channel) {
128   internal::MutexLock lock(&mu_);
129   GPR_ASSERT(call_ == nullptr);
130   call_ = call;
131   channel_ = channel;
132   if (creds_ && !creds_->ApplyToCall(call_)) {
133     // TODO(yashykt): should interceptors also see this status?
134     SendCancelToInterceptors();
135     grpc_call_cancel_with_status(call, GRPC_STATUS_CANCELLED,
136                                  "Failed to set credentials to rpc.", nullptr);
137   }
138   if (call_canceled_) {
139     SendCancelToInterceptors();
140     grpc_call_cancel(call_, nullptr);
141   }
142 }
143 
set_compression_algorithm(grpc_compression_algorithm algorithm)144 void ClientContext::set_compression_algorithm(
145     grpc_compression_algorithm algorithm) {
146   compression_algorithm_ = algorithm;
147   const char* algorithm_name = nullptr;
148   if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) {
149     grpc_core::Crash(absl::StrFormat(
150         "Name for compression algorithm '%d' unknown.", algorithm));
151   }
152   GPR_ASSERT(algorithm_name != nullptr);
153   AddMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name);
154 }
155 
TryCancel()156 void ClientContext::TryCancel() {
157   internal::MutexLock lock(&mu_);
158   if (call_) {
159     SendCancelToInterceptors();
160     grpc_call_cancel(call_, nullptr);
161   } else {
162     call_canceled_ = true;
163   }
164 }
165 
SendCancelToInterceptors()166 void ClientContext::SendCancelToInterceptors() {
167   internal::CancelInterceptorBatchMethods cancel_methods;
168   for (size_t i = 0; i < rpc_info_.interceptors_.size(); i++) {
169     rpc_info_.RunInterceptor(&cancel_methods, i);
170   }
171 }
172 
peer() const173 std::string ClientContext::peer() const {
174   std::string peer;
175   if (call_) {
176     char* c_peer = grpc_call_get_peer(call_);
177     peer = c_peer;
178     gpr_free(c_peer);
179   }
180   return peer;
181 }
182 
SetGlobalCallbacks(GlobalCallbacks * client_callbacks)183 void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) {
184   GPR_ASSERT(g_client_callbacks == g_default_client_callbacks);
185   GPR_ASSERT(client_callbacks != nullptr);
186   GPR_ASSERT(client_callbacks != g_default_client_callbacks);
187   g_client_callbacks = client_callbacks;
188 }
189 
190 }  // namespace grpc
191