1 /*
2  * Copyright (C) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "napi_rand.h"
17 
18 #include "securec.h"
19 #include "log.h"
20 #include "memory.h"
21 
22 #include "napi_utils.h"
23 #include "napi_crypto_framework_defines.h"
24 
25 namespace OHOS {
26 namespace CryptoFramework {
27 thread_local napi_ref NapiRand::classRef_ = nullptr;
28 
29 struct RandCtx {
30     napi_env env = nullptr;
31 
32     AsyncType asyncType = ASYNC_CALLBACK;
33     napi_ref callback = nullptr;
34     napi_deferred deferred = nullptr;
35     napi_value promise = nullptr;
36     napi_async_work asyncWork = nullptr;
37     napi_ref randomRef = nullptr;
38 
39     int32_t numBytes = 0;
40     HcfBlob *seedBlob = nullptr;
41 
42     HcfResult errCode = HCF_SUCCESS;
43     const char *errMsg = nullptr;
44     HcfBlob *randBlob = nullptr;
45     HcfRand *rand = nullptr;
46 };
47 
FreeCryptoFwkCtx(napi_env env,RandCtx * context)48 static void FreeCryptoFwkCtx(napi_env env, RandCtx *context)
49 {
50     if (context == nullptr) {
51         return;
52     }
53     if (context->asyncWork != nullptr) {
54         napi_delete_async_work(env, context->asyncWork);
55         context->asyncWork = nullptr;
56     }
57 
58     if (context->callback != nullptr) {
59         napi_delete_reference(env, context->callback);
60         context->callback = nullptr;
61     }
62     if (context->randomRef != nullptr) {
63         napi_delete_reference(env, context->randomRef);
64         context->randomRef = nullptr;
65     }
66     if (context->seedBlob != nullptr) {
67         HcfFree(context->seedBlob->data);
68         context->seedBlob->data = nullptr;
69         context->seedBlob->len = 0;
70         HcfFree(context->seedBlob);
71         context->seedBlob = nullptr;
72     }
73     if (context->randBlob != nullptr) {
74         HcfFree(context->randBlob->data);
75         context->randBlob->data = nullptr;
76         context->randBlob->len = 0;
77         HcfFree(context->randBlob);
78         context->randBlob = nullptr;
79     }
80     context->errMsg = nullptr;
81     context->rand = nullptr;
82     HcfFree(context);
83 }
84 
ReturnCallbackResult(napi_env env,RandCtx * context,napi_value result)85 static void ReturnCallbackResult(napi_env env, RandCtx *context, napi_value result)
86 {
87     napi_value businessError = nullptr;
88     if (context->errCode != HCF_SUCCESS) {
89         businessError = GenerateBusinessError(env, context->errCode, context->errMsg);
90     }
91     napi_value params[ARGS_SIZE_TWO] = { businessError, result };
92 
93     napi_value func = nullptr;
94     napi_get_reference_value(env, context->callback, &func);
95 
96     napi_value recv = nullptr;
97     napi_value callFuncRet = nullptr;
98     napi_get_undefined(env, &recv);
99     napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet);
100 }
101 
ReturnPromiseResult(napi_env env,RandCtx * context,napi_value result)102 static void ReturnPromiseResult(napi_env env, RandCtx *context, napi_value result)
103 {
104     if (context->errCode == HCF_SUCCESS) {
105         napi_resolve_deferred(env, context->deferred, result);
106     } else {
107         napi_reject_deferred(env, context->deferred,
108             GenerateBusinessError(env, context->errCode, context->errMsg));
109     }
110 }
111 
GenerateRandomExecute(napi_env env,void * data)112 static void GenerateRandomExecute(napi_env env, void *data)
113 {
114     RandCtx *context = static_cast<RandCtx *>(data);
115     HcfRand *randObj = context->rand;
116     HcfBlob *randBlob = reinterpret_cast<HcfBlob *>(HcfMalloc(sizeof(HcfBlob), 0));
117     if (randBlob == nullptr) {
118         LOGE("randBlob is null!");
119         context->errCode = HCF_ERR_MALLOC;
120         context->errMsg = "malloc data blob failed";
121         return;
122     }
123     int32_t numBytes = context->numBytes;
124     context->errCode = randObj->generateRandom(randObj, numBytes, randBlob);
125     if (context->errCode != HCF_SUCCESS) {
126         LOGD("[error] generateRandom failed!");
127         context->errMsg = "generateRandom failed";
128         HcfFree(randBlob);
129         return;
130     }
131     context->randBlob = randBlob;
132 }
133 
GenerateRandomComplete(napi_env env,napi_status status,void * data)134 static void GenerateRandomComplete(napi_env env, napi_status status, void *data)
135 {
136     RandCtx *context = static_cast<RandCtx *>(data);
137     napi_value returnRandBlob = ConvertBlobToNapiValue(env, context->randBlob);
138     if (returnRandBlob == nullptr) {
139         LOGE("returnOutBlob is nullptr!");
140         returnRandBlob = NapiGetNull(env);
141     }
142     if (context->asyncType == ASYNC_CALLBACK) {
143         ReturnCallbackResult(env, context, returnRandBlob);
144     } else {
145         ReturnPromiseResult(env, context, returnRandBlob);
146     }
147     FreeCryptoFwkCtx(env, context);
148 }
149 
BuildGenerateRandomCtx(napi_env env,napi_callback_info info,RandCtx * context)150 static bool BuildGenerateRandomCtx(napi_env env, napi_callback_info info, RandCtx *context)
151 {
152     napi_value thisVar = nullptr;
153     size_t expectedArgsCount = ARGS_SIZE_TWO;
154     size_t argc = expectedArgsCount;
155     napi_value argv[ARGS_SIZE_TWO] = { nullptr };
156     napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
157     if ((argc != expectedArgsCount) && (argc != expectedArgsCount - CALLBACK_SIZE)) {
158         LOGE("The arguments count is not expected!");
159         return false;
160     }
161 
162     if (!GetInt32FromJSParams(env, argv[PARAM0], context->numBytes)) {
163         LOGE("get numBytes failed!");
164         return false;
165     }
166     context->asyncType = isCallback(env, argv[expectedArgsCount - 1], argc, expectedArgsCount) ?
167         ASYNC_CALLBACK : ASYNC_PROMISE;
168 
169     NapiRand *napiRand = nullptr;
170     napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&napiRand));
171     if (status != napi_ok || napiRand == nullptr) {
172         LOGE("failed to unwrap NapiRand obj!");
173         return false;
174     }
175 
176     context->rand = napiRand->GetRand();
177 
178     if (napi_create_reference(env, thisVar, 1, &context->randomRef) != napi_ok) {
179         LOGE("create random ref failed when generate random!");
180         return false;
181     }
182 
183     if (context->asyncType == ASYNC_PROMISE) {
184         napi_create_promise(env, &context->deferred, &context->promise);
185         return true;
186     } else {
187         return GetCallbackFromJSParams(env, argv[PARAM1], &context->callback);
188     }
189 }
190 
NewRandJsGenerateAsyncWork(napi_env env,RandCtx * context)191 static napi_value NewRandJsGenerateAsyncWork(napi_env env, RandCtx *context)
192 {
193     napi_create_async_work(
194         env, nullptr, GetResourceName(env, "GenerateRandom"),
195         [](napi_env env, void *data) {
196             GenerateRandomExecute(env, data);
197             return;
198         },
199         [](napi_env env, napi_status status, void *data) {
200             GenerateRandomComplete(env, status, data);
201             return;
202         },
203         static_cast<void *>(context),
204         &context->asyncWork);
205 
206     napi_queue_async_work(env, context->asyncWork);
207     if (context->asyncType == ASYNC_PROMISE) {
208         return context->promise;
209     } else {
210         return NapiGetNull(env);
211     }
212 }
213 
NapiRand(HcfRand * randObj)214 NapiRand::NapiRand(HcfRand *randObj)
215 {
216     this->randObj_ = randObj;
217 }
218 
~NapiRand()219 NapiRand::~NapiRand()
220 {
221     HcfObjDestroy(this->randObj_);
222 }
223 
GetRand()224 HcfRand *NapiRand::GetRand()
225 {
226     return this->randObj_;
227 }
228 
JsGenerateRandom(napi_env env,napi_callback_info info)229 napi_value NapiRand::JsGenerateRandom(napi_env env, napi_callback_info info)
230 {
231     RandCtx *context = static_cast<RandCtx *>(HcfMalloc(sizeof(RandCtx), 0));
232     if (context == nullptr) {
233         napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed"));
234         LOGE("malloc context failed!");
235         return nullptr;
236     }
237 
238     if (!BuildGenerateRandomCtx(env, info, context)) {
239         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail."));
240         LOGE("build context fail.");
241         FreeCryptoFwkCtx(env, context);
242         return nullptr;
243     }
244 
245     return NewRandJsGenerateAsyncWork(env, context);
246 }
247 
JsGenerateRandomSync(napi_env env,napi_callback_info info)248 napi_value NapiRand::JsGenerateRandomSync(napi_env env, napi_callback_info info)
249 {
250     napi_value thisVar = nullptr;
251     NapiRand *napiRand = nullptr;
252     size_t expectedArgsCount = ARGS_SIZE_ONE;
253     size_t argc = expectedArgsCount;
254     napi_value argv[ARGS_SIZE_ONE] = { nullptr };
255 
256     napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
257     if (argc != expectedArgsCount) {
258         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count"));
259         LOGE("The arguments count is not expected!");
260         return nullptr;
261     }
262 
263     int32_t numBytes = 0;
264     if (!GetInt32FromJSParams(env, argv[PARAM0], numBytes)) {
265         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get numBytes failed!"));
266         LOGE("get numBytes failed!");
267         return nullptr;
268     }
269     napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&napiRand));
270     if (status != napi_ok || napiRand == nullptr) {
271         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to unwrap NapiRand obj!"));
272         LOGE("failed to unwrap NapiRand obj!");
273         return nullptr;
274     }
275     HcfRand *rand = napiRand->GetRand();
276     if (rand == nullptr) {
277         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!"));
278         LOGE("fail to get rand obj!");
279         return nullptr;
280     }
281 
282     HcfBlob randBlob = { .data = nullptr, .len = 0};
283     HcfResult res = rand->generateRandom(rand, numBytes, &randBlob);
284     if (res != HCF_SUCCESS) {
285         napi_throw(env, GenerateBusinessError(env, res, "generateRandom failed!"));
286         LOGD("[error] generateRandom failed!");
287         return nullptr;
288     }
289 
290     napi_value instance = ConvertBlobToNapiValue(env, &randBlob);
291     HcfBlobDataClearAndFree(&randBlob);
292     return instance;
293 }
294 
JsSetSeed(napi_env env,napi_callback_info info)295 napi_value NapiRand::JsSetSeed(napi_env env, napi_callback_info info)
296 {
297     napi_value thisVar = nullptr;
298     NapiRand *napiRand = nullptr;
299     size_t expectedArgsCount = ARGS_SIZE_ONE;
300     size_t argc = expectedArgsCount;
301     napi_value argv[ARGS_SIZE_ONE] = { nullptr };
302 
303     napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
304     if (argc != expectedArgsCount) {
305         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count"));
306         LOGE("The arguments count is not expected!");
307         return nullptr;
308     }
309     HcfBlob *seedBlob = GetBlobFromNapiDataBlob(env, argv[PARAM0]);
310     if (seedBlob == nullptr) {
311         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to get seedBlob!"));
312         LOGE("failed to get seedBlob!");
313         return nullptr;
314     }
315     napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&napiRand));
316     if (status != napi_ok || napiRand == nullptr) {
317         HcfBlobDataClearAndFree(seedBlob);
318         HcfFree(seedBlob);
319         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to unwrap NapiRand obj!"));
320         LOGE("failed to unwrap NapiRand obj!");
321         return nullptr;
322     }
323     HcfRand *rand = napiRand->GetRand();
324     if (rand == nullptr) {
325         HcfBlobDataClearAndFree(seedBlob);
326         HcfFree(seedBlob);
327         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!"));
328         LOGE("fail to get rand obj!");
329         return nullptr;
330     }
331     HcfResult res = rand->setSeed(rand, seedBlob);
332     if (res != HCF_SUCCESS) {
333         HcfBlobDataClearAndFree(seedBlob);
334         HcfFree(seedBlob);
335         napi_throw(env, GenerateBusinessError(env, res, "set seed failed."));
336         LOGD("[error] set seed failed.");
337         return nullptr;
338     }
339     HcfBlobDataClearAndFree(seedBlob);
340     HcfFree(seedBlob);
341     return thisVar;
342 }
343 
JsGetAlgorithm(napi_env env,napi_callback_info info)344 napi_value NapiRand::JsGetAlgorithm(napi_env env, napi_callback_info info)
345 {
346     napi_value thisVar = nullptr;
347     NapiRand *napiRand = nullptr;
348 
349     napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
350     napi_status status = napi_unwrap(env, thisVar, reinterpret_cast<void **>(&napiRand));
351     if (status != napi_ok || napiRand == nullptr) {
352         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to unwrap NapiRand obj!"));
353         LOGE("failed to unwrap NapiRand obj!");
354         return nullptr;
355     }
356 
357     HcfRand *rand = napiRand->GetRand();
358     if (rand == nullptr) {
359         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!"));
360         LOGE("fail to get rand obj!");
361         return nullptr;
362     }
363 
364     const char *algoName = rand->getAlgoName(rand);
365     napi_value instance = nullptr;
366     napi_create_string_utf8(env, algoName, NAPI_AUTO_LENGTH, &instance);
367     return instance;
368 }
369 
RandConstructor(napi_env env,napi_callback_info info)370 napi_value NapiRand::RandConstructor(napi_env env, napi_callback_info info)
371 {
372     napi_value thisVar = nullptr;
373     napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
374     return thisVar;
375 }
376 
CreateRand(napi_env env,napi_callback_info info)377 napi_value NapiRand::CreateRand(napi_env env, napi_callback_info info)
378 {
379     HcfRand *randObj = nullptr;
380     HcfResult res = HcfRandCreate(&randObj);
381     if (res != HCF_SUCCESS) {
382         napi_throw(env, GenerateBusinessError(env, res, "create C obj failed."));
383         LOGE("create c randObj failed.");
384         return nullptr;
385     }
386     napi_value instance = nullptr;
387     napi_value constructor = nullptr;
388     napi_get_reference_value(env, classRef_, &constructor);
389     napi_new_instance(env, constructor, 0, nullptr, &instance);
390     NapiRand *randNapiObj = new (std::nothrow) NapiRand(randObj);
391     if (randNapiObj == nullptr) {
392         napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "new rand napi obj failed."));
393         HcfObjDestroy(randObj);
394         LOGE("create rand napi obj failed");
395         return nullptr;
396     }
397     napi_status status = napi_wrap(
398         env, instance, randNapiObj,
399         [](napi_env env, void *data, void *hint) {
400             NapiRand *rand = static_cast<NapiRand *>(data);
401             delete rand;
402             return;
403         }, nullptr, nullptr);
404     if (status != napi_ok) {
405         napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiRand obj!"));
406         delete randNapiObj;
407         LOGE("failed to wrap NapiRand obj!");
408         return nullptr;
409     }
410     return instance;
411 }
412 
DefineRandJSClass(napi_env env,napi_value exports)413 void NapiRand::DefineRandJSClass(napi_env env, napi_value exports)
414 {
415     napi_property_descriptor desc[] = {
416         DECLARE_NAPI_FUNCTION("createRandom", NapiRand::CreateRand),
417     };
418     napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
419     napi_property_descriptor classDesc[] = {
420         DECLARE_NAPI_FUNCTION("generateRandom", NapiRand::JsGenerateRandom),
421         DECLARE_NAPI_FUNCTION("generateRandomSync", NapiRand::JsGenerateRandomSync),
422         DECLARE_NAPI_FUNCTION("setSeed", NapiRand::JsSetSeed),
423         {.utf8name = "algName", .getter = NapiRand::JsGetAlgorithm},
424     };
425     napi_value constructor = nullptr;
426     napi_define_class(env, "Random", NAPI_AUTO_LENGTH, RandConstructor, nullptr,
427         sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor);
428     napi_create_reference(env, constructor, 1, &classRef_);
429 }
430 } // CryptoFramework
431 } // OHOS
432