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