1 /*
2  * Copyright (c) 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 "js_application.h"
17 
18 #include "ability_runtime_error_util.h"
19 #include "accesstoken_kit.h"
20 #include "context_impl.h"
21 #include "hilog_tag_wrapper.h"
22 #include "js_application_context_utils.h"
23 #include "js_error_utils.h"
24 #include "js_runtime_utils.h"
25 #include "js_context_utils.h"
26 #include "napi_base_context.h"
27 
28 namespace OHOS {
29 namespace AbilityRuntime {
30 namespace {
31     constexpr size_t ARGC_ZERO = 0;
32     constexpr size_t ARGC_ONE = 1;
33     constexpr size_t ARGC_TWO = 2;
34     constexpr const char* PERMISSION_GET_BUNDLE_INFO = "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED";
35 }
Finalizer(napi_env env,void * data,void * hint)36 void JsApplication::Finalizer(napi_env env, void *data, void *hint)
37 {
38     TAG_LOGD(AAFwkTag::APPKIT, "Called.");
39     std::unique_ptr<JsApplication>(static_cast<JsApplication *>(data));
40 }
41 
GetApplicationContext(napi_env env,napi_callback_info info)42 napi_value JsApplication::GetApplicationContext(napi_env env, napi_callback_info info)
43 {
44     GET_NAPI_INFO_AND_CALL(env, info, JsApplication, OnGetApplicationContext);
45 }
46 
OnGetApplicationContext(napi_env env,NapiCallbackInfo & info)47 napi_value JsApplication::OnGetApplicationContext(napi_env env, NapiCallbackInfo &info)
48 {
49     TAG_LOGD(AAFwkTag::APPKIT, "Called.");
50     napi_value value = JsApplicationContextUtils::CreateJsApplicationContext(env);
51     auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.ApplicationContext", &value, 1);
52     if (systemModule == nullptr) {
53         TAG_LOGE(AAFwkTag::APPKIT, "Invalid systemModule.");
54         AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INTERNAL_ERROR);
55         return CreateJsUndefined(env);
56     }
57     napi_value object = systemModule->GetNapiValue();
58     if (!CheckTypeForNapiValue(env, object, napi_object)) {
59         TAG_LOGE(AAFwkTag::APPKIT, "Failed to get context native object.");
60         AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INTERNAL_ERROR);
61         return CreateJsUndefined(env);
62     }
63     return object;
64 }
65 
CreateModuleContext(napi_env env,napi_callback_info info)66 napi_value JsApplication::CreateModuleContext(napi_env env, napi_callback_info info)
67 {
68     GET_NAPI_INFO_AND_CALL(env, info, JsApplication, OnCreateModuleContext);
69 }
70 
CreateBundleContext(napi_env env,napi_callback_info info)71 napi_value JsApplication::CreateBundleContext(napi_env env, napi_callback_info info)
72 {
73     GET_NAPI_INFO_AND_CALL(env, info, JsApplication, OnCreateBundleContext);
74 }
75 
OnCreateModuleContext(napi_env env,NapiCallbackInfo & info)76 napi_value JsApplication::OnCreateModuleContext(napi_env env, NapiCallbackInfo &info)
77 {
78     TAG_LOGD(AAFwkTag::APPKIT, "Called");
79     if (info.argc < ARGC_TWO) {
80         TAG_LOGE(AAFwkTag::APPKIT, "invalid argc");
81         ThrowTooFewParametersError(env);
82         return CreateJsUndefined(env);
83     }
84 
85     bool stageMode = false;
86     napi_status status = OHOS::AbilityRuntime::IsStageContext(env, info.argv[ARGC_ZERO], stageMode);
87     if (status != napi_ok || !stageMode) {
88         TAG_LOGE(AAFwkTag::APPKIT, "not stageMode");
89         ThrowInvalidParamError(env, "Parse param context failed, must be a context of stageMode.");
90         return CreateJsUndefined(env);
91     }
92 
93     auto context = OHOS::AbilityRuntime::GetStageModeContext(env, info.argv[ARGC_ZERO]);
94     if (context == nullptr) {
95         TAG_LOGE(AAFwkTag::APPKIT, "null context");
96         ThrowInvalidParamError(env, "Parse param context failed, must not be nullptr.");
97         return CreateJsUndefined(env);
98     }
99 
100     auto inputContextPtr = Context::ConvertTo<Context>(context);
101     if (inputContextPtr == nullptr) {
102         TAG_LOGE(AAFwkTag::APPKIT, "Convert to context failed");
103         ThrowInvalidParamError(env, "Parse param context failed, must be a context.");
104         return CreateJsUndefined(env);
105     }
106 
107     std::shared_ptr<std::shared_ptr<Context>> moduleContext = std::make_shared<std::shared_ptr<Context>>();
108     std::shared_ptr<ContextImpl> contextImpl = std::make_shared<ContextImpl>();
109     if (contextImpl == nullptr) {
110         TAG_LOGE(AAFwkTag::APPKIT, "null contextImpl");
111         ThrowInvalidParamError(env, "create context failed.");
112         return CreateJsUndefined(env);
113     }
114     std::string moduleName = "";
115     std::string bundleName = "";
116     if (info.argc == ARGC_TWO) {
117         TAG_LOGD(AAFwkTag::APPKIT, "Called");
118         if (!ConvertFromJsValue(env, info.argv[ARGC_ONE], moduleName)) {
119             TAG_LOGE(AAFwkTag::APPKIT, "Parse failed");
120             ThrowInvalidParamError(env, "Parse param moduleName failed, moduleName must be string.");
121             return CreateJsUndefined(env);
122         }
123     } else {
124         TAG_LOGD(AAFwkTag::APPKIT, "Called");
125         if (!CheckCallerIsSystemApp()) {
126             TAG_LOGE(AAFwkTag::APPKIT, "no system app");
127             ThrowNotSystemAppError(env);
128             return CreateJsUndefined(env);
129         }
130 
131         if (!CheckCallerPermission(PERMISSION_GET_BUNDLE_INFO)) {
132             TAG_LOGE(AAFwkTag::APPKIT, "no permission");
133             ThrowNoPermissionError(env, PERMISSION_GET_BUNDLE_INFO);
134             return CreateJsUndefined(env);
135         }
136 
137         if (!ConvertFromJsValue(env, info.argv[ARGC_TWO], moduleName)
138             || !ConvertFromJsValue(env, info.argv[ARGC_ONE], bundleName)) {
139             TAG_LOGE(AAFwkTag::APPKIT, "Parse failed");
140             ThrowInvalidParamError(env, "Parse param failed, moduleName and bundleName must be string.");
141             return CreateJsUndefined(env);
142         }
143     }
144     TAG_LOGD(AAFwkTag::APPKIT, "moduleName: %{public}s, bundlename: %{public}s",
145         moduleName.c_str(), bundleName.c_str());
146     NapiAsyncTask::ExecuteCallback execute = [moduleName, bundleName, contextImpl,
147         moduleContext, inputContextPtr]() {
148         if (bundleName.empty()) {
149             *moduleContext = contextImpl->CreateModuleContext(moduleName, inputContextPtr);
150         } else {
151             *moduleContext = contextImpl->CreateModuleContext(bundleName, moduleName, inputContextPtr);
152         }
153     };
154 
155     NapiAsyncTask::CompleteCallback complete;
156     SetCreateCompleteCallback(moduleContext, complete);
157 
158     napi_value result = nullptr;
159     NapiAsyncTask::ScheduleHighQos("JsApplication::OnCreateModuleContext",
160         env, CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result));
161 
162     return result;
163 }
164 
CheckCallerIsSystemApp()165 bool JsApplication::CheckCallerIsSystemApp()
166 {
167     auto selfToken = IPCSkeleton::GetSelfTokenID();
168     if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken)) {
169         return false;
170     }
171     return true;
172 }
173 
CheckCallerPermission(const std::string & permission)174 bool JsApplication::CheckCallerPermission(const std::string &permission)
175 {
176     auto selfToken = IPCSkeleton::GetSelfTokenID();
177     int ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(selfToken, permission);
178     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
179         return false;
180     }
181     return true;
182 }
183 
184 
OnCreateBundleContext(napi_env env,NapiCallbackInfo & info)185 napi_value JsApplication::OnCreateBundleContext(napi_env env, NapiCallbackInfo &info)
186 {
187     TAG_LOGD(AAFwkTag::APPKIT, "Called");
188     if (!CheckCallerIsSystemApp()) {
189         TAG_LOGE(AAFwkTag::APPKIT, "no system app");
190         ThrowNotSystemAppError(env);
191         return CreateJsUndefined(env);
192     }
193 
194     if (info.argc < ARGC_TWO) {
195         TAG_LOGE(AAFwkTag::APPKIT, "invalid argc");
196         ThrowTooFewParametersError(env);
197         return CreateJsUndefined(env);
198     }
199 
200     if (!CheckCallerPermission(PERMISSION_GET_BUNDLE_INFO)) {
201         TAG_LOGE(AAFwkTag::APPKIT, "no permission");
202         ThrowNoPermissionError(env, PERMISSION_GET_BUNDLE_INFO);
203         return CreateJsUndefined(env);
204     }
205 
206     bool stageMode = false;
207     napi_status status = OHOS::AbilityRuntime::IsStageContext(env, info.argv[ARGC_ZERO], stageMode);
208     if (status != napi_ok || !stageMode) {
209         TAG_LOGE(AAFwkTag::APPKIT, "not stageMode");
210         ThrowInvalidParamError(env, "Parse param context failed, must be a context of stageMode.");
211         return CreateJsUndefined(env);
212     }
213 
214     auto context = OHOS::AbilityRuntime::GetStageModeContext(env, info.argv[ARGC_ZERO]);
215     if (context == nullptr) {
216         TAG_LOGE(AAFwkTag::APPKIT, "null context");
217         ThrowInvalidParamError(env, "Parse param context failed, must not be nullptr.");
218         return CreateJsUndefined(env);
219     }
220 
221     auto inputContextPtr = Context::ConvertTo<Context>(context);
222     if (inputContextPtr == nullptr) {
223         TAG_LOGE(AAFwkTag::APPKIT, "Convert to context failed");
224         ThrowInvalidParamError(env, "Parse param context failed, must be a context.");
225         return CreateJsUndefined(env);
226     }
227 
228     std::string bundleName;
229     if (!ConvertFromJsValue(env, info.argv[ARGC_ONE], bundleName)) {
230         TAG_LOGE(AAFwkTag::APPKIT, "Parse bundleName failed");
231         ThrowInvalidParamError(env, "Parse param bundleName failed, bundleName must be string.");
232         return CreateJsUndefined(env);
233     }
234 
235     auto bundleContext = std::make_shared<std::shared_ptr<Context>>();
236     std::shared_ptr<ContextImpl> contextImpl = std::make_shared<ContextImpl>();
237 
238     NapiAsyncTask::ExecuteCallback execute = [bundleName, contextImpl,
239         bundleContext, inputContextPtr]() {
240         contextImpl->CreateBundleContext(*bundleContext, bundleName, inputContextPtr);
241     };
242 
243     NapiAsyncTask::CompleteCallback complete;
244     SetCreateCompleteCallback(bundleContext, complete);
245 
246     napi_value result = nullptr;
247     NapiAsyncTask::ScheduleHighQos("JsApplication::OnCreateBundleContext",
248         env, CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result));
249 
250     return result;
251 }
252 
SetCreateCompleteCallback(std::shared_ptr<std::shared_ptr<Context>> contextPtr,NapiAsyncTask::CompleteCallback & complete)253 void JsApplication::SetCreateCompleteCallback(std::shared_ptr<std::shared_ptr<Context>> contextPtr,
254     NapiAsyncTask::CompleteCallback &complete)
255 {
256     TAG_LOGD(AAFwkTag::APPKIT, "Called");
257     complete = [contextPtr](napi_env env, NapiAsyncTask &task, int32_t status) {
258         auto context = *contextPtr;
259         if (!context) {
260             TAG_LOGE(AAFwkTag::APPKIT, "failed to create context");
261             task.Reject(env, CreateJsError(env,
262                 static_cast<int32_t>(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), "invalid param."));
263             return;
264         }
265         napi_value value = CreateJsBaseContext(env, context, true);
266         auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1);
267         if (systemModule == nullptr) {
268             TAG_LOGW(AAFwkTag::APPKIT, "invalid systemModule");
269             task.Reject(env, CreateJsError(env,
270                 static_cast<int32_t>(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), "invalid param."));
271             return;
272         }
273 
274         napi_value object = systemModule->GetNapiValue();
275         if (!CheckTypeForNapiValue(env, object, napi_object)) {
276             TAG_LOGE(AAFwkTag::APPKIT, "Failed to get object");
277             task.Reject(env, CreateJsError(env,
278                 static_cast<int32_t>(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), "invalid param."));
279             return;
280         }
281 
282         auto workContext = new (std::nothrow) std::weak_ptr<Context>(context);
283         napi_coerce_to_native_binding_object(env, object, DetachCallbackFunc, AttachBaseContext, workContext, nullptr);
284         napi_status ret = napi_wrap(env, object, workContext,
285             [](napi_env, void *data, void *) {
286                 TAG_LOGD(AAFwkTag::APPKIT, "Finalizer for weak_ptr module context is called");
287                 delete static_cast<std::weak_ptr<Context> *>(data);
288             },
289             nullptr, nullptr);
290         if (ret != napi_ok && workContext != nullptr) {
291             TAG_LOGE(AAFwkTag::APPKIT, "napi_wrap Failed: %{public}d", ret);
292             delete workContext;
293             return;
294         }
295         task.ResolveWithNoError(env, object);
296     };
297 }
298 
CreateJsContext(napi_env env,const std::shared_ptr<Context> & context)299 napi_value JsApplication::CreateJsContext(napi_env env, const std::shared_ptr<Context> &context)
300 {
301     napi_value value = CreateJsBaseContext(env, context, true);
302     auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1);
303     if (systemModule == nullptr) {
304         TAG_LOGW(AAFwkTag::APPKIT, "invalid systemModule");
305         ThrowInvalidParamError(env, "invalid param.");
306         return CreateJsUndefined(env);
307     }
308     napi_value object = systemModule->GetNapiValue();
309     if (!CheckTypeForNapiValue(env, object, napi_object)) {
310         TAG_LOGE(AAFwkTag::APPKIT, "Failed to get object");
311         ThrowInvalidParamError(env, "invalid param.");
312         return CreateJsUndefined(env);
313     }
314 
315     auto workContext = new (std::nothrow) std::weak_ptr<Context>(context);
316     napi_coerce_to_native_binding_object(env, object, DetachCallbackFunc, AttachBaseContext, workContext, nullptr);
317     napi_status status = napi_wrap(env, object, workContext,
318         [](napi_env, void *data, void *) {
319             TAG_LOGD(AAFwkTag::APPKIT, "Finalizer for weak_ptr module context is called");
320             delete static_cast<std::weak_ptr<Context> *>(data);
321         },
322         nullptr, nullptr);
323     if (status != napi_ok && workContext != nullptr) {
324         TAG_LOGE(AAFwkTag::APPKIT, "napi_wrap Failed: %{public}d", status);
325         delete workContext;
326         ThrowInvalidParamError(env, "invalid param.");
327         return CreateJsUndefined(env);
328     }
329 
330     return object;
331 }
332 
ApplicationInit(napi_env env,napi_value exportObj)333 napi_value ApplicationInit(napi_env env, napi_value exportObj)
334 {
335     TAG_LOGD(AAFwkTag::APPKIT, "Called");
336     if (env == nullptr || exportObj == nullptr) {
337         TAG_LOGE(AAFwkTag::APPKIT, "Env or exportObj is nullptr.");
338         return nullptr;
339     }
340 
341     auto jsApplication = std::make_unique<JsApplication>();
342     napi_wrap(env, exportObj, jsApplication.release(), JsApplication::Finalizer, nullptr, nullptr);
343 
344     const char *moduleName = "application";
345     BindNativeFunction(env, exportObj, "getApplicationContext", moduleName,
346         JsApplication::GetApplicationContext);
347 
348     BindNativeFunction(env, exportObj, "createModuleContext", moduleName,
349         JsApplication::CreateModuleContext);
350 
351     BindNativeFunction(env, exportObj, "createBundleContext", moduleName,
352         JsApplication::CreateBundleContext);
353     return CreateJsUndefined(env);
354 }
355 } // namespace AbilityRuntime
356 } // namespace OHOS