Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / ext / call_credentials.cc
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 <nan.h>
20 #include <node.h>
21 #include <uv.h>
22
23 #include <queue>
24
25 #include "call.h"
26 #include "call_credentials.h"
27 #include "grpc/grpc.h"
28 #include "grpc/grpc_security.h"
29 #include "grpc/support/log.h"
30
31 namespace grpc {
32 namespace node {
33
34 using Nan::Callback;
35 using Nan::EscapableHandleScope;
36 using Nan::HandleScope;
37 using Nan::Maybe;
38 using Nan::MaybeLocal;
39 using Nan::ObjectWrap;
40 using Nan::Persistent;
41 using Nan::Utf8String;
42
43 using v8::Exception;
44 using v8::External;
45 using v8::Function;
46 using v8::FunctionTemplate;
47 using v8::Integer;
48 using v8::Local;
49 using v8::Object;
50 using v8::ObjectTemplate;
51 using v8::Value;
52
53 Nan::Callback *CallCredentials::constructor;
54 Persistent<FunctionTemplate> CallCredentials::fun_tpl;
55
56 static Callback *plugin_callback;
57
58 CallCredentials::CallCredentials(grpc_call_credentials *credentials)
59     : wrapped_credentials(credentials) {}
60
61 CallCredentials::~CallCredentials() {
62   grpc_call_credentials_release(wrapped_credentials);
63 }
64
65 void CallCredentials::Init(Local<Object> exports) {
66   HandleScope scope;
67   Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
68   tpl->SetClassName(Nan::New("CallCredentials").ToLocalChecked());
69   tpl->InstanceTemplate()->SetInternalFieldCount(1);
70   Nan::SetPrototypeMethod(tpl, "compose", Compose);
71   fun_tpl.Reset(tpl);
72   Local<Function> ctr = Nan::GetFunction(tpl).ToLocalChecked();
73   Nan::Set(ctr, Nan::New("createFromPlugin").ToLocalChecked(),
74            Nan::GetFunction(Nan::New<FunctionTemplate>(CreateFromPlugin))
75                .ToLocalChecked());
76   Nan::Set(exports, Nan::New("CallCredentials").ToLocalChecked(), ctr);
77   constructor = new Nan::Callback(ctr);
78
79   Local<FunctionTemplate> callback_tpl =
80       Nan::New<FunctionTemplate>(PluginCallback);
81   plugin_callback =
82       new Callback(Nan::GetFunction(callback_tpl).ToLocalChecked());
83 }
84
85 bool CallCredentials::HasInstance(Local<Value> val) {
86   HandleScope scope;
87   return Nan::New(fun_tpl)->HasInstance(val);
88 }
89
90 Local<Value> CallCredentials::WrapStruct(grpc_call_credentials *credentials) {
91   EscapableHandleScope scope;
92   const int argc = 1;
93   if (credentials == NULL) {
94     return scope.Escape(Nan::Null());
95   }
96   Local<Value> argv[argc] = {
97       Nan::New<External>(reinterpret_cast<void *>(credentials))};
98   MaybeLocal<Object> maybe_instance =
99       Nan::NewInstance(constructor->GetFunction(), argc, argv);
100   if (maybe_instance.IsEmpty()) {
101     return scope.Escape(Nan::Null());
102   } else {
103     return scope.Escape(maybe_instance.ToLocalChecked());
104   }
105 }
106
107 grpc_call_credentials *CallCredentials::GetWrappedCredentials() {
108   return wrapped_credentials;
109 }
110
111 NAN_METHOD(CallCredentials::New) {
112   if (info.IsConstructCall()) {
113     if (!info[0]->IsExternal()) {
114       return Nan::ThrowTypeError(
115           "CallCredentials can only be created with the provided functions");
116     }
117     Local<External> ext = info[0].As<External>();
118     grpc_call_credentials *creds_value =
119         reinterpret_cast<grpc_call_credentials *>(ext->Value());
120     CallCredentials *credentials = new CallCredentials(creds_value);
121     credentials->Wrap(info.This());
122     info.GetReturnValue().Set(info.This());
123     return;
124   } else {
125     // This should never be called directly
126     return Nan::ThrowTypeError(
127         "CallCredentials can only be created with the provided functions");
128   }
129 }
130
131 NAN_METHOD(CallCredentials::Compose) {
132   if (!CallCredentials::HasInstance(info.This())) {
133     return Nan::ThrowTypeError(
134         "compose can only be called on CallCredentials objects");
135   }
136   if (!CallCredentials::HasInstance(info[0])) {
137     return Nan::ThrowTypeError(
138         "compose's first argument must be a CallCredentials object");
139   }
140   CallCredentials *self = ObjectWrap::Unwrap<CallCredentials>(info.This());
141   CallCredentials *other = ObjectWrap::Unwrap<CallCredentials>(
142       Nan::To<Object>(info[0]).ToLocalChecked());
143   grpc_call_credentials *creds = grpc_composite_call_credentials_create(
144       self->wrapped_credentials, other->wrapped_credentials, NULL);
145   info.GetReturnValue().Set(WrapStruct(creds));
146 }
147
148 NAN_METHOD(CallCredentials::CreateFromPlugin) {
149   if (!info[0]->IsFunction()) {
150     return Nan::ThrowTypeError(
151         "createFromPlugin's argument must be a function");
152   }
153   grpc_metadata_credentials_plugin plugin;
154   plugin_state *state = new plugin_state;
155   state->callback = new Nan::Callback(info[0].As<Function>());
156   state->pending_callbacks = new std::queue<plugin_callback_data *>();
157   uv_mutex_init(&state->plugin_mutex);
158   uv_async_init(uv_default_loop(), &state->plugin_async, SendPluginCallback);
159   uv_unref((uv_handle_t *)&state->plugin_async);
160
161   state->plugin_async.data = state;
162
163   plugin.get_metadata = plugin_get_metadata;
164   plugin.destroy = plugin_destroy_state;
165   plugin.state = reinterpret_cast<void *>(state);
166   plugin.type = "";
167   grpc_call_credentials *creds =
168       grpc_metadata_credentials_create_from_plugin(plugin, NULL);
169   info.GetReturnValue().Set(WrapStruct(creds));
170 }
171
172 NAN_METHOD(PluginCallback) {
173   // Arguments: status code, error details, metadata
174   if (!info[0]->IsUint32()) {
175     return Nan::ThrowTypeError(
176         "The callback's first argument must be a status code");
177   }
178   if (!info[1]->IsString()) {
179     return Nan::ThrowTypeError(
180         "The callback's second argument must be a string");
181   }
182   if (!info[2]->IsObject()) {
183     return Nan::ThrowTypeError(
184         "The callback's third argument must be an object");
185   }
186   if (!info[3]->IsObject()) {
187     return Nan::ThrowTypeError(
188         "The callback's fourth argument must be an object");
189   }
190   grpc_status_code code =
191       static_cast<grpc_status_code>(Nan::To<uint32_t>(info[0]).FromJust());
192   Utf8String details_utf8_str(info[1]);
193   char *details = *details_utf8_str;
194   grpc_metadata_array array;
195   grpc_metadata_array_init(&array);
196   Local<Object> callback_data = Nan::To<Object>(info[3]).ToLocalChecked();
197   if (!CreateMetadataArray(Nan::To<Object>(info[2]).ToLocalChecked(), &array)) {
198     return Nan::ThrowError("Failed to parse metadata");
199   }
200   grpc_credentials_plugin_metadata_cb cb =
201       reinterpret_cast<grpc_credentials_plugin_metadata_cb>(
202           Nan::Get(callback_data, Nan::New("cb").ToLocalChecked())
203               .ToLocalChecked()
204               .As<External>()
205               ->Value());
206   void *user_data =
207       Nan::Get(callback_data, Nan::New("user_data").ToLocalChecked())
208           .ToLocalChecked()
209           .As<External>()
210           ->Value();
211   cb(user_data, array.metadata, array.count, code, details);
212   DestroyMetadataArray(&array);
213 }
214
215 NAUV_WORK_CB(SendPluginCallback) {
216   Nan::HandleScope scope;
217   plugin_state *state = reinterpret_cast<plugin_state *>(async->data);
218   std::queue<plugin_callback_data *> callbacks;
219   uv_mutex_lock(&state->plugin_mutex);
220   state->pending_callbacks->swap(callbacks);
221   uv_mutex_unlock(&state->plugin_mutex);
222   while (!callbacks.empty()) {
223     plugin_callback_data *data = callbacks.front();
224     callbacks.pop();
225     Local<Object> callback_data = Nan::New<Object>();
226     Nan::Set(callback_data, Nan::New("cb").ToLocalChecked(),
227              Nan::New<v8::External>(reinterpret_cast<void *>(data->cb)));
228     Nan::Set(callback_data, Nan::New("user_data").ToLocalChecked(),
229              Nan::New<v8::External>(data->user_data));
230     const int argc = 3;
231     v8::Local<v8::Value> argv[argc] = {
232         Nan::New(data->service_url).ToLocalChecked(), callback_data,
233         // Get Local<Function> from Nan::Callback*
234         **plugin_callback};
235     Nan::Callback *callback = state->callback;
236     callback->Call(argc, argv, data->async_resource);
237     delete data;
238   }
239 }
240
241 int plugin_get_metadata(
242     void *state, grpc_auth_metadata_context context,
243     grpc_credentials_plugin_metadata_cb cb,
244     void *user_data,
245     grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX],
246     size_t *num_creds_md, grpc_status_code *status,
247     const char **error_details) {
248   HandleScope scope;
249   plugin_state *p_state = reinterpret_cast<plugin_state *>(state);
250   plugin_callback_data *data =
251       new plugin_callback_data(context.service_url, cb, user_data);
252
253   uv_mutex_lock(&p_state->plugin_mutex);
254   p_state->pending_callbacks->push(data);
255   uv_mutex_unlock(&p_state->plugin_mutex);
256
257   uv_async_send(&p_state->plugin_async);
258   return 0;  // Async processing.
259 }
260
261 void plugin_uv_close_cb(uv_handle_t *handle) {
262   uv_async_t *async = reinterpret_cast<uv_async_t *>(handle);
263   plugin_state *state = reinterpret_cast<plugin_state *>(async->data);
264   uv_mutex_destroy(&state->plugin_mutex);
265   delete state->pending_callbacks;
266   delete state->callback;
267   delete state;
268 }
269
270 void plugin_destroy_state(void *ptr) {
271   plugin_state *state = reinterpret_cast<plugin_state *>(ptr);
272   uv_close((uv_handle_t *)&state->plugin_async, plugin_uv_close_cb);
273 }
274
275 }  // namespace node
276 }  // namespace grpc