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