1 /*
2 * Copyright (c) 2021-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 "usb_right_manager.h"
17
18 #include <algorithm>
19 #include <semaphore.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 #include <regex>
23
24 #include "ability_manager_client.h"
25 #include "accesstoken_kit.h"
26 #include "bundle_mgr_interface.h"
27 #include "common_event_manager.h"
28 #include "common_event_support.h"
29 #include "ipc_skeleton.h"
30 #include "iservice_registry.h"
31 #include "os_account_manager.h"
32 #include "string_ex.h"
33 #include "system_ability_definition.h"
34 #include "tokenid_kit.h"
35 #include "usb_errors.h"
36 #include "usb_right_db_helper.h"
37 #include "usb_napi_errors.h"
38 #include "usb_srv_support.h"
39 #include "usb_service.h"
40 #include "parameters.h"
41
42 using namespace OHOS::AppExecFwk;
43 using namespace OHOS::EventFwk;
44 using namespace OHOS::Security::AccessToken;
45
46 namespace OHOS {
47 namespace USB {
48
49 constexpr int32_t PARAM_BUF_LEN = 128;
50 constexpr int32_t USB_RIGHT_USERID_INVALID = -1;
51 constexpr int32_t USB_RIGHT_USERID_DEFAULT = 100;
52 constexpr int32_t USB_RIGHT_USERID_CONSOLE = 0;
53 constexpr int32_t DECIMAL_BASE = 10;
54 constexpr int32_t MAX_RETRY_TIMES = 30;
55 constexpr int32_t RETRY_INTERVAL_SECONDS = 1;
56 constexpr int32_t MESSAGE_PARCEL_KEY_SIZE = 3;
57 const std::string USB_MANAGE_ACCESS_USB_DEVICE = "ohos.permission.MANAGE_USB_CONFIG";
58 const std::string DEVELOPERMODE_STATE = "const.security.developermode.state";
59 const std::string DEFAULT_SERIAL_BUNDLE_NAME = "com.example.serial";
60 const std::string DEFAULT_SERIAL_DEVICE_NAME = "1-1";
61 enum UsbRightTightUpChoose : uint32_t {
62 TIGHT_UP_USB_RIGHT_RECORD_NONE = 0,
63 TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED = 1 << 0,
64 TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED = 1 << 1,
65 TIGHT_UP_USB_RIGHT_RECORD_EXPIRED = 1 << 2,
66 TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED = 1 << 3,
67 };
68
69 constexpr uint32_t TIGHT_UP_USB_RIGHT_RECORD_ALL =
70 (TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED | TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED |
71 TIGHT_UP_USB_RIGHT_RECORD_EXPIRED | TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED);
72
73 sem_t UsbRightManager::waitDialogDisappear_ {0};
74 std::mutex UsbRightManager::usbDialogParamsMutex_;
75 std::map<std::string, std::string> UsbRightManager::usbDialogParams_ = {};
76
77 class RightSubscriber : public CommonEventSubscriber {
78 public:
RightSubscriber(const CommonEventSubscribeInfo & sp)79 explicit RightSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}
80
OnReceiveEvent(const CommonEventData & data)81 void OnReceiveEvent(const CommonEventData &data) override
82 {
83 auto &want = data.GetWant();
84 std::string wantAction = want.GetAction();
85
86 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s wantAction %{public}s", __func__, wantAction.c_str());
87 if (wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
88 wantAction == CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED ||
89 wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) {
90 int32_t uid = want.GetParams().GetIntParam("userId", USB_RIGHT_USERID_DEFAULT);
91 std::string bundleName = want.GetBundle();
92 int32_t ret = UsbRightManager::CleanUpRightAppUninstalled(uid, bundleName);
93 USB_HILOGD(MODULE_USB_SERVICE,
94 "recv event uninstall: event=%{public}s bunndleName=%{public}s uid=%{public}d, delete_ret=%{public}d",
95 wantAction.c_str(), bundleName.c_str(), uid, ret);
96 } else if (wantAction == CommonEventSupport::COMMON_EVENT_UID_REMOVED ||
97 wantAction == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
98 int32_t totalUsers = 0;
99 int32_t deleteUsers = 0;
100 int32_t ret = UsbRightManager::CleanUpRightUserDeleted(totalUsers, deleteUsers);
101 USB_HILOGD(MODULE_USB_SERVICE,
102 "recv event user delete: event=%{public}s, delete detail[%{public}d/%{public}d]: %{public}d",
103 wantAction.c_str(), deleteUsers, totalUsers, ret);
104 } else if (wantAction == CommonEventSupport::COMMON_EVENT_USER_STOPPED) {
105 int32_t uid = data.GetCode();
106 int32_t ret = UsbRightManager::CleanUpRightUserStopped(uid);
107 USB_HILOGD(MODULE_USB_SERVICE, "on user %{public}d stopped, ret=%{public}d", uid, ret);
108 #ifdef USB_MANAGER_FEATURE_DEVICE
109 } else if (wantAction == CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) {
110 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: COMMON_EVENT_DATA_SHARE_READY action is start!", __func__);
111 auto usbService = UsbService::GetGlobalInstance();
112 if (!usbService->InitSettingsDataHdcStatus()) {
113 USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: function is get failed!", __func__);
114 }
115 #endif // USB_MANAGER_FEATURE_DEVICE
116 } else if (wantAction == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
117 #ifdef USB_MANAGER_FEATURE_DEVICE
118 USB_HILOGI(MODULE_USB_SERVICE, "recv user switched.");
119 auto usbService = UsbService::GetGlobalInstance();
120 if (usbService != nullptr) {
121 usbService->UserChangeProcess();
122 }
123 #endif // USB_MANAGER_FEATURE_DEVICE
124 }
125 }
126 };
127
Init()128 int32_t UsbRightManager::Init()
129 {
130 USB_HILOGI(MODULE_USB_SERVICE, "subscriber app/bundle remove event and uid/user remove event");
131 MatchingSkills matchingSkills;
132 /* subscribe app/bundle remove event, need permission: ohos.permission.LISTEN_BUNDLE_CHANGE */
133 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
134 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
135 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
136 /* subscribe uid/user remove event */
137 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_UID_REMOVED);
138 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
139 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED);
140
141 #ifdef USB_MANAGER_FEATURE_DEVICE
142 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY);
143 #endif // USB_MANAGER_FEATURE_DEVICE
144 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
145 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
146 std::shared_ptr<RightSubscriber> subscriber = std::make_shared<RightSubscriber>(subscriberInfo);
147 int32_t retryTimes = 0;
148 while (retryTimes < MAX_RETRY_TIMES) {
149 retryTimes++;
150 bool ret = CommonEventManager::SubscribeCommonEvent(subscriber);
151 if (!ret) {
152 USB_HILOGW(MODULE_USB_SERVICE, "subscriber event for right manager failed: %{public}d", ret);
153 sleep(RETRY_INTERVAL_SECONDS);
154 continue;
155 }
156 return UEC_OK;
157 }
158 return UEC_SERVICE_INNER_ERR;
159 }
160
HasRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)161 bool UsbRightManager::HasRight(const std::string &deviceName, const std::string &bundleName,
162 const std::string &tokenId, const int32_t &userId)
163 {
164 USB_HILOGI(MODULE_USB_SERVICE, "HasRight: uid=%{public}d app=%{public}s",
165 userId, bundleName.c_str());
166 if (userId == USB_RIGHT_USERID_CONSOLE) {
167 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
168 return true;
169 }
170 uint64_t nowTime = GetCurrentTimestamp();
171 (void)TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_EXPIRED);
172 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
173 // no record or expired record: expired true, has right false, add right next time
174 // valid record: expired false, has right true, no need add right
175 if (helper == nullptr) {
176 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
177 return false;
178 }
179 return !helper->IsRecordExpired(userId, deviceName, bundleName, tokenId, nowTime);
180 }
181
ConnectAbility()182 int32_t UsbRightManager::ConnectAbility()
183 {
184 if (usbAbilityConn_ == nullptr) {
185 USB_HILOGI(MODULE_SERVICE, "new UsbAbilityConn");
186 usbAbilityConn_ = sptr<UsbAbilityConn>(new (std::nothrow) UsbAbilityConn());
187 }
188
189 auto abmc = AAFwk::AbilityManagerClient::GetInstance();
190 if (abmc == nullptr) {
191 USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed");
192 return USB_RIGHT_FAILURE;
193 }
194
195 AAFwk::Want want;
196 want.SetElementName("com.ohos.sceneboard", "com.ohos.sceneboard.systemdialog");
197 int32_t ret = abmc->ConnectAbility(want, usbAbilityConn_, -1);
198 if (ret != ERR_OK) {
199 want.SetElementName("com.ohos.systemui", "com.ohos.systemui.dialog");
200 int32_t ret = abmc->ConnectAbility(want, usbAbilityConn_, -1);
201 if (ret != ERR_OK) {
202 USB_HILOGE(MODULE_USB_SERVICE, "ConnectServiceExtensionAbility systemui failed, ret: %{public}d", ret);
203 usbAbilityConn_ = nullptr;
204 return ret;
205 }
206 }
207 return USB_RIGHT_OK;
208 }
209
210 #ifdef USB_MANAGER_FEATURE_HOST
RequestRight(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)211 int32_t UsbRightManager::RequestRight(const std::string &busDev, const std::string &deviceName,
212 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
213 {
214 USB_HILOGD(MODULE_USB_SERVICE, "RequestRight: busdev=%{private}s app=%{public}s", busDev.c_str(),
215 bundleName.c_str());
216 if (HasRight(deviceName, bundleName, tokenId, userId)) {
217 USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
218 return UEC_OK;
219 }
220 if (!GetUserAgreementByDiag(busDev, deviceName, bundleName, tokenId, userId)) {
221 USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
222 return UEC_SERVICE_PERMISSION_DENIED;
223 }
224 return UEC_OK;
225 }
226
GetUserAgreementByDiag(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)227 bool UsbRightManager::GetUserAgreementByDiag(const std::string &busDev, const std::string &deviceName,
228 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
229 {
230 #ifdef USB_RIGHT_TEST
231 return true;
232 #endif
233 /* There can only be one dialog at a time */
234 std::lock_guard<std::mutex> guard(dialogRunning_);
235 if (!ShowUsbDialog(busDev, deviceName, bundleName, tokenId)) {
236 USB_HILOGE(MODULE_USB_SERVICE, "ShowUsbDialog failed");
237 return false;
238 }
239
240 return HasRight(deviceName, bundleName, tokenId, userId);
241 }
242
ShowUsbDialog(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId)243 bool UsbRightManager::ShowUsbDialog(
244 const std::string &busDev, const std::string &deviceName, const std::string &bundleName, const std::string &tokenId)
245 {
246 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s deviceName %{public}s bundleName %{public}s tokenId %{public}s",
247 __func__, deviceName.c_str(), bundleName.c_str(), tokenId.c_str());
248
249 std::string appName;
250 if (!GetAppName(bundleName, appName)) {
251 appName = bundleName;
252 }
253
254 std::string productName;
255 if (!GetProductName(busDev, productName)) {
256 productName = busDev;
257 }
258
259 {
260 std::lock_guard<std::mutex> lock(usbDialogParamsMutex_);
261 usbDialogParams_.clear();
262 usbDialogParams_["bundleName"] = bundleName;
263 usbDialogParams_["deviceName"] = busDev;
264 usbDialogParams_["tokenId"] = tokenId;
265 usbDialogParams_["appName"] = appName;
266 usbDialogParams_["productName"] = productName;
267 }
268
269 sem_init(&waitDialogDisappear_, 1, 0);
270 int32_t ret = ConnectAbility();
271 if (ret != UEC_OK) {
272 USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
273 return false;
274 }
275 /* Waiting for the user to click */
276 sem_wait(&waitDialogDisappear_);
277 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s success", __func__);
278 return true;
279 }
280
GetProductName(const std::string & devName,std::string & productName)281 bool UsbRightManager::GetProductName(const std::string &devName, std::string &productName)
282 {
283 auto usbService = UsbService::GetGlobalInstance();
284 if (usbService == nullptr) {
285 return false;
286 }
287 return usbService->GetDeviceProductName(devName, productName);
288 }
289 #endif // USB_MANAGER_FEATURE_HOST
290
RequestRight(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId,const int32_t & userId,bool & result)291 int32_t UsbRightManager::RequestRight(const USBAccessory &access, const std::string &seriaValue,
292 const std::string &bundleName, const std::string &tokenId, const int32_t &userId, bool &result)
293 {
294 USB_HILOGD(MODULE_USB_SERVICE, "RequestAccessoryRight: seriaValue=%{public}s app=%{public}s",
295 seriaValue.c_str(), bundleName.c_str());
296 if (HasRight(seriaValue, bundleName, tokenId, userId)) {
297 USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
298 result = true;
299 return UEC_OK;
300 }
301 if (!GetUserAgreementByDiag(access, seriaValue, bundleName, tokenId, userId)) {
302 USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
303 result = false;
304 return UEC_OK;
305 }
306 result = true;
307 return UEC_OK;
308 }
309
IsWithinUint64Range(const std::string & numberStr)310 bool IsWithinUint64Range(const std::string &numberStr)
311 {
312 if (numberStr.empty()) {
313 USB_HILOGE(MODULE_USB_SERVICE, "numberStr is empty");
314 return false;
315 }
316 errno = 0;
317 uint64_t number = 0;
318 number = std::strtoull(numberStr.c_str(), nullptr, DECIMAL_BASE);
319 if (errno == ERANGE) {
320 USB_HILOGE(MODULE_USB_SERVICE, "number is out of uint64_t range");
321 return false;
322 }
323 return true;
324 }
325
RequestRight(const int32_t portId,const SerialDeviceIdentity & serialDeviceIdentity,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)326 int32_t UsbRightManager::RequestRight(const int32_t portId, const SerialDeviceIdentity &serialDeviceIdentity,
327 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
328 {
329 USB_HILOGI(MODULE_USB_SERVICE, "RequestSerialRight: serialValue=%{public}s app=%{public}s",
330 serialDeviceIdentity.deviceName.c_str(), bundleName.c_str());
331 if (HasRight(serialDeviceIdentity.deviceName, bundleName, tokenId, userId)) {
332 USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
333 return UEC_OK;
334 }
335 if (!GetUserAgreementByDiag(portId, serialDeviceIdentity, bundleName, tokenId, userId)) {
336 USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
337 return UEC_SERVICE_PERMISSION_DENIED;
338 }
339 return UEC_OK;
340 }
341
AddDeviceRight(const std::string & deviceName,const std::string & tokenIdStr)342 bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &tokenIdStr)
343 {
344 if (!IsAllDigits(tokenIdStr)) {
345 USB_HILOGE(MODULE_USB_SERVICE, "tokenIdStr invalid");
346 return false;
347 }
348 /* already checked system app/hap when call */
349 if (!IsWithinUint64Range(tokenIdStr)) {
350 USB_HILOGE(MODULE_USB_SERVICE, "tokenIdStr is out of uint64_t range");
351 return false;
352 }
353 HapTokenInfo hapTokenInfoRes;
354 int32_t ret = AccessTokenKit::GetHapTokenInfo((AccessTokenID) std::stoul(tokenIdStr), hapTokenInfoRes);
355 if (ret != UEC_OK) {
356 USB_HILOGE(MODULE_USB_SERVICE, "GetHapTokenInfo failed:ret:%{public}d", ret);
357 return false;
358 }
359 int32_t uid = hapTokenInfoRes.userID;
360 if (uid == USB_RIGHT_USERID_CONSOLE) {
361 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
362 return true;
363 }
364 uint64_t installTime = GetCurrentTimestamp();
365 uint64_t updateTime = GetCurrentTimestamp();
366 if (!GetBundleInstallAndUpdateTime(uid, hapTokenInfoRes.bundleName, installTime, updateTime)) {
367 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}d", uid);
368 }
369 struct UsbRightAppInfo info;
370 info.uid = uid;
371 info.installTime = installTime;
372 info.updateTime = updateTime;
373 info.requestTime = GetCurrentTimestamp();
374 info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
375
376 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
377 if (helper == nullptr) {
378 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
379 return false;
380 }
381 ret = helper->AddOrUpdateRightRecord(uid, deviceName, hapTokenInfoRes.bundleName, tokenIdStr, info);
382 if (ret < 0) {
383 USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}d, ret=%{public}d",
384 deviceName.c_str(), uid, ret);
385 return false;
386 }
387 return true;
388 }
389
AddDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)390 bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &bundleName,
391 const std::string &tokenId, const int32_t &userId)
392 {
393 /* already checked system app/hap when call */
394 if (userId == USB_RIGHT_USERID_CONSOLE) {
395 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
396 return true;
397 }
398 uint64_t installTime = GetCurrentTimestamp();
399 uint64_t updateTime = GetCurrentTimestamp();
400 if (!GetBundleInstallAndUpdateTime(userId, bundleName, installTime, updateTime)) {
401 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}s/%{public}d",
402 bundleName.c_str(), userId);
403 }
404 struct UsbRightAppInfo info;
405 info.uid = userId;
406 info.installTime = installTime;
407 info.updateTime = updateTime;
408 info.requestTime = GetCurrentTimestamp();
409 info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
410
411 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
412 if (helper == nullptr) {
413 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
414 return false;
415 }
416 int32_t ret = helper->AddOrUpdateRightRecord(userId, deviceName, bundleName, tokenId, info);
417 if (ret < 0) {
418 USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}s/%{public}d, ret=%{public}d",
419 deviceName.c_str(), bundleName.c_str(), userId, ret);
420 return false;
421 }
422 return true;
423 }
424
RemoveDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)425 bool UsbRightManager::RemoveDeviceRight(const std::string &deviceName, const std::string &bundleName,
426 const std::string &tokenId, const int32_t &userId)
427 {
428 if (userId == USB_RIGHT_USERID_CONSOLE) {
429 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
430 return true;
431 }
432 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
433 if (helper == nullptr) {
434 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
435 return false;
436 }
437 int32_t ret = helper->DeleteRightRecord(userId, deviceName, bundleName, tokenId);
438 if (ret < 0) {
439 USB_HILOGE(MODULE_USB_SERVICE, "delete failed: %{public}s/%{public}s/%{public}d", deviceName.c_str(),
440 bundleName.c_str(), userId);
441 return false;
442 }
443 return true;
444 }
445
CancelDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)446 int32_t UsbRightManager::CancelDeviceRight(const std::string &deviceName, const std::string &bundleName,
447 const std::string &tokenId, const int32_t &userId)
448 {
449 if (userId == USB_RIGHT_USERID_CONSOLE) {
450 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
451 return UEC_SERVICE_INVALID_VALUE;
452 }
453 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
454 if (helper == nullptr) {
455 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
456 return UEC_SERVICE_INNER_ERR;
457 }
458 int32_t ret = helper->DeleteRightRecord(userId, deviceName, bundleName, tokenId);
459 if (ret < 0) {
460 USB_HILOGW(MODULE_USB_SERVICE, "delete failed: %{public}s/%{public}s/%{public}d", deviceName.c_str(),
461 bundleName.c_str(), userId);
462 return UEC_OK;
463 }
464 return UEC_OK;
465 }
466
RemoveDeviceAllRight(const std::string & deviceName)467 bool UsbRightManager::RemoveDeviceAllRight(const std::string &deviceName)
468 {
469 USB_HILOGD(MODULE_USB_SERVICE, "device %{private}s detached, process right", deviceName.c_str());
470 CleanUpRightTemporaryExpired(deviceName);
471 TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_ALL);
472 UnShowUsbDialog();
473 return true;
474 }
475
GetAccessoryName(const USBAccessory & access,std::string & accessName)476 bool UsbRightManager::GetAccessoryName(const USBAccessory &access, std::string &accessName)
477 {
478 accessName = access.GetProduct();
479 return true;
480 }
481
ShowUsbDialog(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId)482 bool UsbRightManager::ShowUsbDialog(const USBAccessory &access, const std::string &seriaValue,
483 const std::string &bundleName, const std::string &tokenId)
484 {
485 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s seriaValue %{public}s bundleName %{public}s tokenId %{public}s",
486 __func__, seriaValue.c_str(), bundleName.c_str(), tokenId.c_str());
487
488 std::string appName;
489 if (!GetAppName(bundleName, appName)) {
490 appName = bundleName;
491 }
492
493 std::string accessoryName;
494 if (!GetAccessoryName(access, accessoryName)) {
495 accessoryName = seriaValue;
496 }
497
498 {
499 std::lock_guard <std::mutex> lock(usbDialogParamsMutex_);
500 usbDialogParams_.clear();
501 usbDialogParams_["bundleName"] = bundleName;
502 usbDialogParams_["deviceName"] = seriaValue;
503 usbDialogParams_["tokenId"] = tokenId;
504 usbDialogParams_["appName"] = appName;
505 usbDialogParams_["productName"] = accessoryName;
506 usbDialogParams_["accessory"] = access.GetJsonString();
507 }
508
509 sem_init(&waitDialogDisappear_, 1, 0);
510 int32_t ret = ConnectAbility();
511 if (ret != UEC_OK) {
512 USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
513 return false;
514 }
515 /* Waiting for the user to click */
516 sem_wait(&waitDialogDisappear_);
517 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s success", __func__);
518 return true;
519 }
520
ShowSerialDialog(const int32_t portId,const uint32_t tokenId,const std::string & bundleName,const std::string & busDev)521 bool UsbRightManager::ShowSerialDialog(const int32_t portId, const uint32_t tokenId, const std::string &bundleName,
522 const std::string &busDev)
523 {
524 USB_HILOGI(MODULE_USB_SERVICE,
525 "%{public}s portId %{public}d tokenId %{public}d bundleName %{public}s busDev %{public}s",
526 __func__, portId, tokenId, bundleName.c_str(), busDev.c_str());
527
528 std::string appName;
529 if (!GetAppName(bundleName, appName)) {
530 appName = bundleName;
531 }
532
533 int32_t castId = static_cast<int32_t>(tokenId);
534 if (castId < 0) {
535 USB_HILOGE(MODULE_SERVICE, "tokenId cast failed %{public}d", castId);
536 return false;
537 }
538
539 {
540 std::lock_guard <std::mutex> lock(usbDialogParamsMutex_);
541 usbDialogParams_.clear();
542 usbDialogParams_["portId"] = std::to_string(portId);
543 usbDialogParams_["tokenId"] = std::to_string(castId);
544 usbDialogParams_["bundleName"] = DEFAULT_SERIAL_BUNDLE_NAME;
545 usbDialogParams_["deviceName"] = DEFAULT_SERIAL_DEVICE_NAME;
546 usbDialogParams_["appName"] = appName;
547 usbDialogParams_["productName"] = "COM" + std::to_string(portId);
548 }
549
550 sem_init(&waitDialogDisappear_, 1, 0);
551 int32_t ret = ConnectAbility();
552 if (ret != UEC_OK) {
553 USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
554 return false;
555 }
556 /* Waiting for the user to click */
557 sem_wait(&waitDialogDisappear_);
558 USB_HILOGI(MODULE_USB_SERVICE, "sem_wait done");
559 return true;
560 }
561
GetUserAgreementByDiag(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)562 bool UsbRightManager::GetUserAgreementByDiag(const USBAccessory &access, const std::string &seriaValue,
563 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
564 {
565 /* There can only be one dialog at a time */
566 std::lock_guard<std::mutex> guard(dialogRunning_);
567 if (!ShowUsbDialog(access, seriaValue, bundleName, tokenId)) {
568 USB_HILOGE(MODULE_USB_SERVICE, "ShowUsbDialog failed");
569 return false;
570 }
571
572 return HasRight(seriaValue, bundleName, tokenId, userId);
573 }
574
GetUserAgreementByDiag(const int32_t portId,const SerialDeviceIdentity & serialDeviceIdentity,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)575 bool UsbRightManager::GetUserAgreementByDiag(const int32_t portId, const SerialDeviceIdentity &serialDeviceIdentity,
576 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
577 {
578 USB_HILOGI(MODULE_USB_SERVICE, "GetUserAgreementByDiag start");
579 /* There can only be one dialog at a time */
580 std::lock_guard<std::mutex> guard(dialogRunning_);
581 if (!std::regex_match(tokenId, std::regex("^[0-9]+$"))) {
582 USB_HILOGE(MODULE_USB_SERVICE, "Invalid tokenId");
583 return false;
584 }
585 uint32_t mTokenId = static_cast<uint32_t>(std::stoul(tokenId));
586 if (!ShowSerialDialog(portId, mTokenId, bundleName, serialDeviceIdentity.busDev)) {
587 USB_HILOGE(MODULE_USB_SERVICE, "ShowSerialDialog failed");
588 return false;
589 }
590
591 return HasRight(serialDeviceIdentity.deviceName, bundleName, tokenId, userId);
592 }
593
GetBundleMgr()594 sptr<IBundleMgr> UsbRightManager::GetBundleMgr()
595 {
596 auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
597 if (sam == nullptr) {
598 USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbilityManager return nullptr");
599 return nullptr;
600 }
601 auto bundleMgrSa = sam->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
602 if (bundleMgrSa == nullptr) {
603 USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbility return nullptr");
604 return nullptr;
605 }
606 auto bundleMgr = iface_cast<IBundleMgr>(bundleMgrSa);
607 if (bundleMgr == nullptr) {
608 USB_HILOGW(MODULE_USB_SERVICE, "iface_cast return nullptr");
609 }
610 return bundleMgr;
611 }
612
GetBundleResMgr()613 sptr<IBundleResource> UsbRightManager::GetBundleResMgr()
614 {
615 auto bundleMgr = GetBundleMgr();
616 if (bundleMgr == nullptr) {
617 return nullptr;
618 }
619 return bundleMgr->GetBundleResourceProxy();
620 }
621
GetAppName(const std::string & bundleName,std::string & appName)622 bool UsbRightManager::GetAppName(const std::string &bundleName, std::string &appName)
623 {
624 auto resMgr = GetBundleResMgr();
625 if (resMgr == nullptr) {
626 USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res mgr failed");
627 return false;
628 }
629
630 BundleResourceInfo info;
631 int32_t ret = resMgr->GetBundleResourceInfo(bundleName, (uint32_t)ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL, info);
632 if (ret != ERR_OK) {
633 USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res info failed: %{public}d", ret);
634 return false;
635 }
636 appName = info.label;
637 return true;
638 }
639
IsSystemAppOrSa()640 bool UsbRightManager::IsSystemAppOrSa()
641 {
642 uint64_t tokenid = IPCSkeleton::GetCallingFullTokenID();
643 bool isSystemApp = TokenIdKit::IsSystemAppByFullTokenID(tokenid);
644 if (isSystemApp) {
645 return true;
646 }
647
648 AccessTokenID accessTokenId = IPCSkeleton::GetCallingTokenID();
649 ATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(accessTokenId);
650 if (tokenType == TOKEN_NATIVE) {
651 return true;
652 }
653
654 USB_HILOGW(MODULE_USB_SERVICE, "neither system app nor sa");
655 return false;
656 }
657
VerifyPermission()658 bool UsbRightManager::VerifyPermission()
659 {
660 AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
661 int32_t ret = AccessTokenKit::VerifyAccessToken(tokenId, USB_MANAGE_ACCESS_USB_DEVICE);
662 if (ret == PermissionState::PERMISSION_DENIED) {
663 USB_HILOGW(MODULE_USB_SERVICE, "no permission");
664 return false;
665 }
666 return true;
667 }
668
IsAppInstalled(int32_t uid,const std::string & bundleName)669 bool UsbRightManager::IsAppInstalled(int32_t uid, const std::string &bundleName)
670 {
671 auto bundleMgr = GetBundleMgr();
672 if (bundleMgr == nullptr) {
673 USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
674 return false;
675 }
676 ApplicationInfo appInfo;
677 if (!bundleMgr->GetApplicationInfo(bundleName, GET_BASIC_APPLICATION_INFO, uid, appInfo)) {
678 USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr GetApplicationInfo failed");
679 return false;
680 }
681 return true;
682 }
683
GetBundleInstallAndUpdateTime(int32_t uid,const std::string & bundleName,uint64_t & installTime,uint64_t & updateTime)684 bool UsbRightManager::GetBundleInstallAndUpdateTime(
685 int32_t uid, const std::string &bundleName, uint64_t &installTime, uint64_t &updateTime)
686 {
687 BundleInfo bundleInfo;
688 auto bundleMgr = GetBundleMgr();
689 if (bundleMgr == nullptr) {
690 USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
691 return false;
692 }
693 if (!bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, uid)) {
694 USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr GetBundleInfo(uid) failed");
695 return false;
696 }
697 installTime = static_cast<uint64_t>(bundleInfo.installTime);
698 updateTime = static_cast<uint64_t>(bundleInfo.updateTime);
699 return true;
700 }
701
GetCurrentTimestamp()702 uint64_t UsbRightManager::GetCurrentTimestamp()
703 {
704 int64_t time =
705 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
706 return static_cast<uint64_t>(time);
707 }
708
GetCurrentUserId(int32_t & uid)709 void UsbRightManager::GetCurrentUserId(int32_t &uid)
710 {
711 int32_t ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), uid);
712 if (ret != UEC_OK) {
713 USB_HILOGE(MODULE_USB_SERVICE, "GetOsAccountLocalIdFromUid failed: %{public}d, set to defult", ret);
714 uid = USB_RIGHT_USERID_DEFAULT; /* default user id */
715 }
716 USB_HILOGD(MODULE_USB_SERVICE, "usb get userid success: %{public}d, uid: %{public}d", ret, uid);
717 }
718
IsOsAccountExists(int32_t id,bool & isAccountExists)719 int32_t UsbRightManager::IsOsAccountExists(int32_t id, bool &isAccountExists)
720 {
721 int32_t ret = AccountSA::OsAccountManager::IsOsAccountExists(id, isAccountExists);
722 if (ret != UEC_OK) {
723 USB_HILOGE(MODULE_USB_SERVICE, " api IsOsAccountExists failed: ret=%{public}d id=%{public}d", ret, id);
724 return USB_RIGHT_FAILURE;
725 }
726 return USB_RIGHT_OK;
727 }
728
HasSetFuncRight(int32_t functions)729 int32_t UsbRightManager::HasSetFuncRight(int32_t functions)
730 {
731 if (!(static_cast<uint32_t>(functions) & UsbSrvSupport::FUNCTION_HDC)) {
732 return UEC_OK;
733 }
734 USB_HILOGI(MODULE_USB_SERVICE, "Set up function permission validation");
735 char paramValue[PARAM_BUF_LEN] = { 0 };
736 int32_t ret = GetParameter("persist.hdc.control", "true", paramValue, sizeof(paramValue));
737 if (ret < 0) {
738 USB_HILOGW(MODULE_USB_SERVICE, "GetParameter fail");
739 }
740 ret = strcmp(paramValue, "true");
741 if (ret != 0) {
742 USB_HILOGE(MODULE_USB_SERVICE, "HDC setup failed");
743 return UEC_SERVICE_PERMISSION_CHECK_HDC;
744 }
745 if (!OHOS::system::GetBoolParameter(DEVELOPERMODE_STATE, false)) {
746 USB_HILOGE(MODULE_USB_SERVICE, "Developer mode unabled, FUNCTION_HDC cannot be set");
747 return UEC_SERVICE_PERMISSION_CHECK_HDC;
748 }
749 return UEC_OK;
750 }
751
CleanUpRightExpired(std::vector<std::string> & devices)752 int32_t UsbRightManager::CleanUpRightExpired(std::vector<std::string> &devices)
753 {
754 USB_HILOGD(MODULE_USB_SERVICE, "clean up expired right: size=%{public}zu", devices.size());
755 size_t len = devices.size();
756 int32_t ret = USB_RIGHT_OK;
757 for (size_t i = 0; i < len; i++) {
758 std::string dev = devices.at(i);
759 ret = CleanUpRightTemporaryExpired(dev);
760 if (ret != USB_RIGHT_OK) {
761 USB_HILOGE(MODULE_USB_SERVICE,
762 "failed(%{public}zu/%{public}zu): delete temporary expiried record, dev=%{private}s", i, len,
763 dev.c_str());
764 continue;
765 }
766 }
767 int32_t uid = USB_RIGHT_USERID_INVALID;
768 GetCurrentUserId(uid);
769 ret = CleanUpRightNormalExpired(uid);
770 if (ret != USB_RIGHT_OK) {
771 USB_HILOGE(MODULE_USB_SERVICE, "delete expired record with uid(%{public}d) failed: %{public}d", uid, ret);
772 }
773 return ret;
774 }
775
CleanUpRightAppUninstalled(int32_t uid,int32_t & totalApps,int32_t & deleteApps)776 int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, int32_t &totalApps, int32_t &deleteApps)
777 {
778 std::vector<std::string> apps;
779 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
780 if (helper == nullptr) {
781 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
782 return false;
783 }
784 int32_t ret = helper->QueryRightRecordApps(uid, apps);
785 if (ret <= 0) {
786 /* error or empty record */
787 return USB_RIGHT_NOP;
788 }
789 totalApps = static_cast<int32_t>(apps.size());
790 deleteApps = 0;
791 for (int32_t i = 0; i < totalApps; i++) {
792 std::string app = apps.at(i);
793 if (!IsAppInstalled(uid, app)) {
794 ret = helper->DeleteAppRightRecord(uid, app);
795 if (ret != USB_RIGHT_OK) {
796 USB_HILOGW(MODULE_USB_SERVICE, "clean failed: app=%{public}s, ret=%{public}d", app.c_str(), ret);
797 continue;
798 }
799 deleteApps++;
800 }
801 }
802 USB_HILOGD(MODULE_USB_SERVICE, "clean uninstall app record[%{public}d/%{public}d]: uid=%{public}d", deleteApps,
803 totalApps, uid);
804 return ret;
805 }
806
CleanUpRightAppUninstalled(int32_t uid,const std::string & bundleName)807 int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, const std::string &bundleName)
808 {
809 std::vector<std::string> apps;
810 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
811 if (helper == nullptr) {
812 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
813 return false;
814 }
815 int32_t ret = helper->QueryRightRecordApps(uid, apps);
816 if (ret <= 0) {
817 /* error or empty record */
818 return USB_RIGHT_NOP;
819 }
820 int32_t index = 0;
821 if (!StringVectorFound(apps, bundleName, index)) {
822 /* app not in record, ignore */
823 return USB_RIGHT_NOP;
824 }
825 ret = helper->DeleteAppRightRecord(uid, apps.at(index));
826 USB_HILOGD(MODULE_USB_SERVICE, "clean[%{public}d/%{public}zu]: uid=%{public}d, app=%{public}s, ret=%{public}d",
827 index, apps.size(), uid, bundleName.c_str(), ret);
828 return ret;
829 }
830
StringVectorSortAndUniq(std::vector<std::string> & strings)831 void UsbRightManager::StringVectorSortAndUniq(std::vector<std::string> &strings)
832 {
833 sort(strings.begin(), strings.end());
834 auto last = unique(strings.begin(), strings.end());
835 strings.erase(last, strings.end());
836 }
837
StringVectorFound(const std::vector<std::string> & strings,const std::string & value,int32_t & index)838 bool UsbRightManager::StringVectorFound(
839 const std::vector<std::string> &strings, const std::string &value, int32_t &index)
840 {
841 size_t len = strings.size();
842 for (size_t i = 0; i < len; i++) {
843 if (value == strings.at(i)) {
844 index = static_cast<int32_t>(i);
845 return true;
846 }
847 }
848 return false;
849 }
850
CleanUpRightAppReinstalled(int32_t uid,uint32_t & totalApps,uint32_t & deleteApps)851 int32_t UsbRightManager::CleanUpRightAppReinstalled(int32_t uid, uint32_t &totalApps, uint32_t &deleteApps)
852 {
853 std::vector<std::string> apps;
854 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
855 if (helper == nullptr) {
856 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
857 return false;
858 }
859 int32_t ret = helper->QueryRightRecordApps(uid, apps);
860 if (ret <= 0) {
861 USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
862 return USB_RIGHT_NOP;
863 }
864 StringVectorSortAndUniq(apps);
865 deleteApps = 0;
866 totalApps = apps.size();
867 std::vector<std::string> deleteBundleNames;
868 for (size_t i = 0; i < apps.size(); i++) {
869 std::string bundleName = apps.at(i);
870 std::vector<struct UsbRightAppInfo> infos;
871 ret = helper->QueryAppRightRecord(uid, bundleName, infos);
872 if (ret < 0) {
873 USB_HILOGE(MODULE_USB_SERVICE, "query app info %{public}s failed: %{public}d", bundleName.c_str(), ret);
874 return USB_RIGHT_FAILURE;
875 }
876 uint64_t installTime = 0;
877 uint64_t updateTime = 0;
878 if (!GetBundleInstallAndUpdateTime(uid, bundleName, installTime, updateTime)) {
879 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: app=%{public}s uid=%{public}d",
880 bundleName.c_str(), uid);
881 return USB_RIGHT_FAILURE;
882 }
883 for (size_t j = 0; j < infos.size(); j++) {
884 struct UsbRightAppInfo info = infos.at(j);
885 if (info.installTime != installTime) {
886 deleteBundleNames.push_back(bundleName);
887 break;
888 }
889 }
890 }
891 StringVectorSortAndUniq(deleteBundleNames);
892 ret = helper->DeleteAppsRightRecord(uid, deleteBundleNames);
893 if (ret != USB_RIGHT_OK) {
894 USB_HILOGE(MODULE_USB_SERVICE, "delete apps failed: %{public}d", ret);
895 } else {
896 deleteApps = deleteBundleNames.size();
897 }
898 return ret;
899 }
900
CleanUpRightUserDeleted(int32_t & totalUsers,int32_t & deleteUsers)901 int32_t UsbRightManager::CleanUpRightUserDeleted(int32_t &totalUsers, int32_t &deleteUsers)
902 {
903 std::vector<std::string> rightRecordUids;
904 bool isAccountExists = false;
905 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
906 if (helper == nullptr) {
907 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
908 return false;
909 }
910 int32_t ret = helper->QueryRightRecordUids(rightRecordUids);
911 if (ret <= 0) {
912 USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
913 return USB_RIGHT_NOP;
914 }
915 size_t len = rightRecordUids.size();
916 deleteUsers = 0;
917 for (size_t i = 0; i < len; i++) {
918 int32_t uid = 0;
919 if (!StrToInt(rightRecordUids.at(i), uid)) {
920 USB_HILOGE(MODULE_USB_SERVICE, "convert failed: %{public}s", rightRecordUids.at(i).c_str());
921 continue;
922 }
923 ret = IsOsAccountExists(uid, isAccountExists);
924 if (ret != USB_RIGHT_OK) {
925 USB_HILOGE(MODULE_USB_SERVICE, "call IsOsAccountExists failed: %{public}d", ret);
926 continue;
927 }
928 if (!isAccountExists) {
929 ret = helper->DeleteUidRightRecord(uid);
930 USB_HILOGE(MODULE_USB_SERVICE, "detecte delete uid=%{public}d: %{public}d", uid, ret);
931 deleteUsers++;
932 }
933 USB_HILOGD(MODULE_USB_SERVICE, "uid exist, ignore: %{public}d", uid);
934 }
935 totalUsers = static_cast<int32_t>(rightRecordUids.size());
936 return USB_RIGHT_OK;
937 }
938
CleanUpRightUserStopped(int32_t uid)939 int32_t UsbRightManager::CleanUpRightUserStopped(int32_t uid)
940 {
941 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
942 if (helper == nullptr) {
943 USB_HILOGE(MODULE_USB_SERVICE, "CleanUpRightUserStopped %{public}d: helper is null", uid);
944 return false;
945 }
946
947 return helper->DeleteUidRightRecord(uid);
948 }
949
CleanUpRightTemporaryExpired(const std::string & deviceName)950 int32_t UsbRightManager::CleanUpRightTemporaryExpired(const std::string &deviceName)
951 {
952 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
953 if (helper == nullptr) {
954 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
955 return false;
956 }
957 int32_t ret = helper->DeleteValidPeriodRightRecord(USB_RIGHT_VALID_PERIOD_MIN, deviceName);
958 if (ret != USB_RIGHT_OK) {
959 USB_HILOGE(MODULE_USB_SERVICE, "failed: delete temporary expiried record: dev=%{private}s", deviceName.c_str());
960 }
961 return ret;
962 }
963
CleanUpRightNormalExpired(int32_t uid)964 int32_t UsbRightManager::CleanUpRightNormalExpired(int32_t uid)
965 {
966 uint64_t nowTime = GetCurrentTimestamp();
967 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
968 int32_t ret = helper->DeleteNormalExpiredRightRecord(uid, nowTime);
969 if (ret != USB_RIGHT_OK) {
970 USB_HILOGD(MODULE_USB_SERVICE, "failed: clean up expired record at %{public}" PRIu64 "", nowTime);
971 }
972 return ret;
973 }
974
TidyUpRight(uint32_t choose)975 int32_t UsbRightManager::TidyUpRight(uint32_t choose)
976 {
977 if (choose == TIGHT_UP_USB_RIGHT_RECORD_NONE) {
978 /* ignore */
979 return USB_RIGHT_NOP;
980 }
981 if ((choose | TIGHT_UP_USB_RIGHT_RECORD_ALL) != TIGHT_UP_USB_RIGHT_RECORD_ALL) {
982 USB_HILOGE(MODULE_USB_SERVICE, "choose invalid");
983 return UEC_SERVICE_INVALID_VALUE;
984 }
985 int32_t uid = USB_RIGHT_USERID_INVALID;
986 GetCurrentUserId(uid);
987 if (uid == USB_RIGHT_USERID_CONSOLE) {
988 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
989 return true;
990 }
991 int32_t ret = 0;
992 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED) != 0) {
993 int32_t totalUninstalledApps = 0;
994 int32_t deleteUninstalledApps = 0;
995 ret = CleanUpRightAppUninstalled(uid, totalUninstalledApps, deleteUninstalledApps);
996 USB_HILOGD(MODULE_USB_SERVICE, "delete app uninstalled record[%{public}d/%{public}d]: %{public}d",
997 deleteUninstalledApps, totalUninstalledApps, ret);
998 }
999 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED) != 0) {
1000 int32_t totalUsers = 0;
1001 int32_t deleteUsers = 0;
1002 ret = CleanUpRightUserDeleted(totalUsers, deleteUsers);
1003 USB_HILOGD(MODULE_USB_SERVICE, "delete user deleted record[%{public}d/%{public}d]: %{public}d", deleteUsers,
1004 totalUsers, ret);
1005 }
1006 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_EXPIRED) != 0) {
1007 ret = CleanUpRightNormalExpired(uid);
1008 USB_HILOGD(MODULE_USB_SERVICE, "delete expired record: %{public}d", ret);
1009 }
1010 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED) != 0) {
1011 uint32_t totalReinstalledApps = 0;
1012 uint32_t deleteReinstalledApps = 0;
1013 ret = CleanUpRightAppReinstalled(uid, totalReinstalledApps, deleteReinstalledApps);
1014 USB_HILOGD(MODULE_USB_SERVICE, "delete app reinstalled record[%{public}u/%{public}u]: %{public}d",
1015 deleteReinstalledApps, totalReinstalledApps, ret);
1016 }
1017 return ret;
1018 }
1019
IsAllDigits(const std::string & bundleName)1020 bool UsbRightManager::IsAllDigits(const std::string &bundleName)
1021 {
1022 size_t len = bundleName.length();
1023 for (size_t i = 0; i < len; i++) {
1024 if (!isdigit(bundleName[i])) {
1025 return false;
1026 }
1027 }
1028 return true;
1029 }
1030
UnShowUsbDialog()1031 bool UsbRightManager::UnShowUsbDialog()
1032 {
1033 if (usbAbilityConn_ == nullptr) {
1034 return true;
1035 }
1036
1037 auto abmc = AAFwk::AbilityManagerClient::GetInstance();
1038 if (abmc == nullptr) {
1039 USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed");
1040 return false;
1041 }
1042 USB_HILOGI(MODULE_USB_SERVICE, "unshow usb dialog window");
1043 usbAbilityConn_->CloseDialog();
1044
1045 int32_t ret = abmc->DisconnectAbility(usbAbilityConn_);
1046 if (ret != UEC_OK) {
1047 USB_HILOGE(MODULE_SERVICE, "DisconnectAbility failed %{public}d", ret);
1048 return false;
1049 }
1050 USB_HILOGD(MODULE_USB_SERVICE, "unshow usb dialog window success");
1051 return true;
1052 }
1053
OnAbilityConnectDone(const AppExecFwk::ElementName & element,const sptr<IRemoteObject> & remoteObject,int32_t resultCode)1054 void UsbRightManager::UsbAbilityConn::OnAbilityConnectDone(const AppExecFwk::ElementName &element,
1055 const sptr<IRemoteObject> &remoteObject, int32_t resultCode)
1056 {
1057 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s UsbAbilityConn", __func__);
1058 if (remoteObject == nullptr) {
1059 USB_HILOGE(MODULE_USB_SERVICE, "remoteObject is nullptr");
1060 return;
1061 }
1062
1063 MessageParcel data;
1064 MessageParcel reply;
1065 MessageOption option;
1066 data.WriteInt32(MESSAGE_PARCEL_KEY_SIZE);
1067 data.WriteString16(u"bundleName");
1068 data.WriteString16(u"com.usb.right");
1069 data.WriteString16(u"abilityName");
1070 data.WriteString16(u"UsbServiceExtAbility");
1071 data.WriteString16(u"parameters");
1072 cJSON* paramJson = cJSON_CreateObject();
1073
1074 {
1075 std::lock_guard <std::mutex> lock(usbDialogParamsMutex_);
1076 for (auto it : usbDialogParams_) {
1077 cJSON_AddStringToObject(paramJson, it.first.c_str(), it.second.c_str());
1078 }
1079 }
1080
1081 std::string uiExtensionTypeStr = "sysDialog/common";
1082 cJSON_AddStringToObject(paramJson, "ability.want.params.uiExtensionType", uiExtensionTypeStr.c_str());
1083
1084 char *pParamJson = cJSON_PrintUnformatted(paramJson);
1085 cJSON_Delete(paramJson);
1086 paramJson = nullptr;
1087 if (!pParamJson) {
1088 USB_HILOGE(MODULE_USB_SERVICE, "Print paramJson error");
1089 return;
1090 }
1091 std::string paramStr(pParamJson);
1092 data.WriteString16(Str8ToStr16(paramStr));
1093 cJSON_free(pParamJson);
1094 pParamJson = NULL;
1095
1096 const uint32_t cmdCode = 1;
1097 int32_t ret = remoteObject->SendRequest(cmdCode, data, reply, option);
1098 USB_HILOGI(MODULE_USB_SERVICE, "%{public}s ret %{public}d", __func__, ret);
1099 if (ret != ERR_OK) {
1100 USB_HILOGE(MODULE_USB_SERVICE, "send request failed: %{public}d", ret);
1101 return;
1102 }
1103 if (!reply.ReadInt32(ret) || ret != ERR_OK) {
1104 USB_HILOGE(MODULE_USB_SERVICE, "show dialog failed: %{public}d", ret);
1105 return;
1106 }
1107 remoteObject_ = remoteObject;
1108 }
1109
OnAbilityDisconnectDone(const AppExecFwk::ElementName & element,int32_t resultCode)1110 void UsbRightManager::UsbAbilityConn::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element,
1111 int32_t resultCode)
1112 {
1113 USB_HILOGI(MODULE_USB_SERVICE, "disconnect done");
1114 sem_post(&waitDialogDisappear_);
1115 remoteObject_ = nullptr;
1116 }
1117
CloseDialog()1118 void UsbRightManager::UsbAbilityConn::CloseDialog()
1119 {
1120 if (remoteObject_ == nullptr) {
1121 USB_HILOGW(MODULE_USB_SERVICE, "CloseDialog: disconnected");
1122 return;
1123 }
1124
1125 MessageParcel data;
1126 MessageParcel reply;
1127 MessageOption option;
1128 const uint32_t cmdCode = 3;
1129 int32_t ret = remoteObject_->SendRequest(cmdCode, data, reply, option);
1130 int32_t replyCode = -1;
1131 bool success = false;
1132 if (ret == ERR_OK) {
1133 success = reply.ReadInt32(replyCode);
1134 }
1135 USB_HILOGI(MODULE_USB_SERVICE, "CloseDialog: ret=%{public}d, %{public}d, %{public}d", ret, success, replyCode);
1136 }
1137 } // namespace USB
1138 } // namespace OHOS