1 /*
2 * Copyright (c) 2023 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 "tls_server_napi_context.h"
17
18 #include <cstdint>
19 #include <string_view>
20
21 #include "constant.h"
22 #include "napi_utils.h"
23 #include "netstack_log.h"
24
25 namespace OHOS {
26 namespace NetStack {
27 namespace TlsSocketServer {
28 static constexpr std::string_view PARSE_ERROR = "data is not int";
29
TLSServerNapiContext(napi_env env,const std::shared_ptr<EventManager> & manager)30 TLSServerNapiContext::TLSServerNapiContext(napi_env env, const std::shared_ptr<EventManager> &manager)
31 : BaseContext(env, manager)
32 {
33 remoteCert_.encodingFormat = TlsSocket::EncodingFormat::DER;
34 }
35
ParseParams(napi_value * params,size_t paramsCount)36 void TLSServerNapiContext::ParseParams(napi_value *params, size_t paramsCount)
37 {
38 if (!CheckParamsType(params, paramsCount)) {
39 return;
40 }
41 if (paramsCount == TlsSocket::PARAM_JUST_CALLBACK) {
42 SetParseOK(SetCallback(params[TlsSocket::ARG_INDEX_0]) == napi_ok);
43 return;
44 }
45 SetParseOK(true);
46
47 return;
48 }
49
CheckParamsType(napi_value * params,size_t paramsCount)50 bool TLSServerNapiContext::CheckParamsType(napi_value *params, size_t paramsCount)
51 {
52 if (paramsCount == TlsSocket::PARAM_NONE) {
53 NETSTACK_LOGD("param is none");
54 return true;
55 }
56
57 if (paramsCount == TlsSocket::PARAM_JUST_CALLBACK) {
58 if (NapiUtils::GetValueType(GetEnv(), params[TlsSocket::ARG_INDEX_0]) != napi_function) {
59 NETSTACK_LOGE("first param is not string");
60 SetNeedThrowException(true);
61 SetError(PARSE_ERROR_CODE, PARSE_ERROR.data());
62 return false;
63 }
64 return true;
65 }
66
67 if (paramsCount == TlsSocket::PARAM_OPTIONS_AND_CALLBACK) {
68 if (NapiUtils::GetValueType(GetEnv(), params[TlsSocket::ARG_INDEX_0]) != napi_number) {
69 NETSTACK_LOGE("first param is not int");
70 SetNeedThrowException(true);
71 SetError(PARSE_ERROR_CODE, PARSE_ERROR.data());
72 return false;
73 }
74 if (NapiUtils::GetValueType(GetEnv(), params[TlsSocket::ARG_INDEX_1]) != napi_function) {
75 NETSTACK_LOGE("second param is not function");
76 return false;
77 }
78 return true;
79 }
80 return false;
81 }
82 } // namespace TlsSocketServer
83 } // namespace NetStack
84 } // namespace OHOS
85