1 /*
2 * Copyright (c) 2021-2022 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 "common_context.h"
17
18 #include "context_key.h"
19 #include "socket_constant.h"
20 #include "event_manager.h"
21 #include "napi_utils.h"
22
23 namespace OHOS::NetStack {
CommonContext(napi_env env,EventManager * manager)24 CommonContext::CommonContext(napi_env env, EventManager *manager) : BaseContext(env, manager) {}
25
ParseParams(napi_value * params,size_t paramsCount)26 void CommonContext::ParseParams(napi_value *params, size_t paramsCount)
27 {
28 bool valid = CheckParamsType(params, paramsCount);
29 if (!valid) {
30 if (paramsCount == PARAM_JUST_CALLBACK) {
31 if (NapiUtils::GetValueType(GetEnv(), params[0]) == napi_function) {
32 SetCallback(params[0]);
33 }
34 return;
35 }
36 return;
37 }
38
39 if (paramsCount != PARAM_NONE) {
40 SetParseOK(SetCallback(params[0]) == napi_ok);
41 return;
42 }
43 SetParseOK(true);
44 }
45
GetSocketFd() const46 int CommonContext::GetSocketFd() const
47 {
48 return (int)(uint64_t)manager_->GetData();
49 }
50
CheckParamsType(napi_value * params,size_t paramsCount)51 bool CommonContext::CheckParamsType(napi_value *params, size_t paramsCount)
52 {
53 if (paramsCount == PARAM_NONE) {
54 return true;
55 }
56
57 if (paramsCount == PARAM_JUST_CALLBACK) {
58 return NapiUtils::GetValueType(GetEnv(), params[0]) == napi_function;
59 }
60 return false;
61 }
62
CloseContext(napi_env env,EventManager * manager)63 CloseContext::CloseContext(napi_env env, EventManager *manager) : CommonContext(env, manager) {}
64
SetSocketFd(int sock)65 void CloseContext::SetSocketFd(int sock)
66 {
67 manager_->SetData(reinterpret_cast<void *>(sock));
68 }
69
GetErrorCode() const70 int32_t CommonContext::GetErrorCode() const
71 {
72 if (BaseContext::IsPermissionDenied()) {
73 return PERMISSION_DENIED_CODE;
74 }
75
76 auto err = BaseContext::GetErrorCode();
77 if (err == PARSE_ERROR_CODE) {
78 return PARSE_ERROR_CODE;
79 }
80 return err + SOCKET_ERROR_CODE_BASE;
81 }
82
GetErrorMessage() const83 std::string CommonContext::GetErrorMessage() const
84 {
85 if (BaseContext::IsPermissionDenied()) {
86 return PERMISSION_DENIED_MSG;
87 }
88
89 auto errCode = BaseContext::GetErrorCode();
90 if (errCode == PARSE_ERROR_CODE) {
91 return PARSE_ERROR_MSG;
92 }
93 char err[MAX_ERR_NUM] = {0};
94 (void)strerror_r(errCode, err, MAX_ERR_NUM);
95 return err;
96 }
97 } // namespace OHOS::NetStack
98