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
41using namespace OHOS::AppExecFwk;
42using namespace OHOS::EventFwk;
43using namespace OHOS::Security::AccessToken;
44
45namespace OHOS {
46namespace USB {
47
48constexpr int32_t PARAM_BUF_LEN = 128;
49constexpr int32_t USB_RIGHT_USERID_INVALID = -1;
50constexpr int32_t USB_RIGHT_USERID_DEFAULT = 100;
51constexpr int32_t USB_RIGHT_USERID_CONSOLE = 0;
52const std::string USB_MANAGE_ACCESS_USB_DEVICE = "ohos.permission.MANAGE_USB_CONFIG";
53const std::string DEVELOPERMODE_STATE = "const.security.developermode.state";
54enum UsbRightTightUpChoose : uint32_t {
55    TIGHT_UP_USB_RIGHT_RECORD_NONE = 0,
56    TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED = 1 << 0,
57    TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED = 1 << 1,
58    TIGHT_UP_USB_RIGHT_RECORD_EXPIRED = 1 << 2,
59    TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED = 1 << 3,
60};
61
62constexpr uint32_t TIGHT_UP_USB_RIGHT_RECORD_ALL =
63    (TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED | TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED |
64        TIGHT_UP_USB_RIGHT_RECORD_EXPIRED | TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED);
65
66sem_t UsbRightManager::waitDialogDisappear_ {0};
67
68class RightSubscriber : public CommonEventSubscriber {
69public:
70    explicit RightSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}
71
72    void OnReceiveEvent(const CommonEventData &data) override
73    {
74        auto &want = data.GetWant();
75        std::string wantAction = want.GetAction();
76        if (wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
77            wantAction == CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED ||
78            wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) {
79            int32_t uid = want.GetParams().GetIntParam("userId", USB_RIGHT_USERID_DEFAULT);
80            std::string bundleName = want.GetBundle();
81            int32_t ret = UsbRightManager::CleanUpRightAppUninstalled(uid, bundleName);
82            USB_HILOGD(MODULE_USB_SERVICE,
83                "recv event uninstall: event=%{public}s bunndleName=%{public}s uid=%{public}d, delete_ret=%{public}d",
84                wantAction.c_str(), bundleName.c_str(), uid, ret);
85        } else if (wantAction == CommonEventSupport::COMMON_EVENT_UID_REMOVED ||
86            wantAction == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
87            int32_t totalUsers = 0;
88            int32_t deleteUsers = 0;
89            int32_t ret = UsbRightManager::CleanUpRightUserDeleted(totalUsers, deleteUsers);
90            USB_HILOGD(MODULE_USB_SERVICE,
91                "recv event user delete: event=%{public}s, delete detail[%{public}d/%{public}d]: %{public}d",
92                wantAction.c_str(), deleteUsers, totalUsers, ret);
93        } else if (wantAction == CommonEventSupport::COMMON_EVENT_USER_STOPPED) {
94            int32_t uid = data.GetCode();
95            int32_t ret = UsbRightManager::CleanUpRightUserStopped(uid);
96            USB_HILOGD(MODULE_USB_SERVICE, "on user %{public}d stopped, ret=%{public}d", uid, ret);
97        }
98    }
99};
100
101int32_t UsbRightManager::Init()
102{
103    USB_HILOGI(MODULE_USB_SERVICE, "subscriber app/bundle remove event and uid/user remove event");
104    MatchingSkills matchingSkills;
105    /* subscribe app/bundle remove event, need permission: ohos.permission.LISTEN_BUNDLE_CHANGE */
106    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
107    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
108    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
109    /* subscribe uid/user remove event */
110    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_UID_REMOVED);
111    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
112    matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED);
113    CommonEventSubscribeInfo subscriberInfo(matchingSkills);
114    std::shared_ptr<RightSubscriber> subscriber = std::make_shared<RightSubscriber>(subscriberInfo);
115    bool ret = CommonEventManager::SubscribeCommonEvent(subscriber);
116    if (!ret) {
117        USB_HILOGW(MODULE_USB_SERVICE, "subscriber event for right manager failed: %{public}d", ret);
118        return UEC_SERVICE_INNER_ERR;
119    }
120    return UEC_OK;
121}
122
123bool UsbRightManager::HasRight(const std::string &deviceName, const std::string &bundleName,
124    const std::string &tokenId, const int32_t &userId)
125{
126    USB_HILOGI(MODULE_USB_SERVICE, "HasRight: uid=%{public}d app=%{public}s",
127        userId, bundleName.c_str());
128    if (userId == USB_RIGHT_USERID_CONSOLE) {
129        USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
130        return true;
131    }
132    uint64_t nowTime = GetCurrentTimestamp();
133    (void)TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_EXPIRED);
134    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
135    // no record or expired record: expired true, has right false, add right next time
136    // valid record: expired false, has right true, no need add right
137    if (helper == nullptr) {
138        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
139        return false;
140    }
141    return !helper->IsRecordExpired(userId, deviceName, bundleName, tokenId, nowTime);
142}
143
144int32_t UsbRightManager::RequestRight(const std::string &busDev, const std::string &deviceName,
145    const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
146{
147    USB_HILOGD(MODULE_USB_SERVICE, "RequestRight: busdev=%{private}s app=%{public}s", busDev.c_str(),
148        bundleName.c_str());
149    if (HasRight(deviceName, bundleName, tokenId, userId)) {
150        USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
151        return UEC_OK;
152    }
153    if (!GetUserAgreementByDiag(busDev, deviceName, bundleName, tokenId, userId)) {
154        USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
155        return UEC_SERVICE_PERMISSION_DENIED;
156    }
157    return UEC_OK;
158}
159
160bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &tokenIdStr)
161{
162    if (!IsAllDigits(tokenIdStr)) {
163        USB_HILOGE(MODULE_USB_SERVICE, "tokenIdStr invalid");
164        return false;
165    }
166    /* already checked system app/hap when call */
167    uint32_t tokenId = stoul(tokenIdStr);
168    HapTokenInfo hapTokenInfoRes;
169    int32_t ret = AccessTokenKit::GetHapTokenInfo((AccessTokenID) tokenId, hapTokenInfoRes);
170    if (ret != UEC_OK) {
171        USB_HILOGE(MODULE_USB_SERVICE, "GetHapTokenInfo failed:ret:%{public}d", ret);
172        return false;
173    }
174    int32_t uid = hapTokenInfoRes.userID;
175    if (uid == USB_RIGHT_USERID_CONSOLE) {
176        USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
177        return true;
178    }
179    uint64_t installTime = GetCurrentTimestamp();
180    uint64_t updateTime = GetCurrentTimestamp();
181    if (!GetBundleInstallAndUpdateTime(uid, hapTokenInfoRes.bundleName, installTime, updateTime)) {
182        USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}d", uid);
183    }
184    struct UsbRightAppInfo info;
185    info.uid = uid;
186    info.installTime = installTime;
187    info.updateTime = updateTime;
188    info.requestTime = GetCurrentTimestamp();
189    info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
190
191    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
192    if (helper == nullptr) {
193        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
194        return false;
195    }
196    ret = helper->AddOrUpdateRightRecord(uid, deviceName, hapTokenInfoRes.bundleName, tokenIdStr, info);
197    if (ret < 0) {
198        USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}d, ret=%{public}d",
199            deviceName.c_str(), uid, ret);
200        return false;
201    }
202    return true;
203}
204
205bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &bundleName,
206    const std::string &tokenId, const int32_t &userId)
207{
208    /* already checked system app/hap when call */
209    if (userId == USB_RIGHT_USERID_CONSOLE) {
210        USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
211        return true;
212    }
213    uint64_t installTime = GetCurrentTimestamp();
214    uint64_t updateTime = GetCurrentTimestamp();
215    if (!GetBundleInstallAndUpdateTime(userId, bundleName, installTime, updateTime)) {
216        USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}s/%{public}d",
217            bundleName.c_str(), userId);
218    }
219    struct UsbRightAppInfo info;
220    info.uid = userId;
221    info.installTime = installTime;
222    info.updateTime = updateTime;
223    info.requestTime = GetCurrentTimestamp();
224    info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
225
226    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
227    if (helper == nullptr) {
228        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
229        return false;
230    }
231    auto ret = helper->AddOrUpdateRightRecord(userId, deviceName, bundleName, tokenId, info);
232    if (ret < 0) {
233        USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}s/%{public}d, ret=%{public}d",
234            deviceName.c_str(), bundleName.c_str(), userId, ret);
235        return false;
236    }
237    return true;
238}
239
240bool UsbRightManager::RemoveDeviceRight(const std::string &deviceName, const std::string &bundleName,
241    const std::string &tokenId, const int32_t &userId)
242{
243    if (userId == USB_RIGHT_USERID_CONSOLE) {
244        USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
245        return true;
246    }
247    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
248    if (helper == nullptr) {
249        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
250        return false;
251    }
252    int32_t ret = helper->DeleteRightRecord(userId, deviceName, bundleName, tokenId);
253    if (ret < 0) {
254        USB_HILOGE(MODULE_USB_SERVICE, "delete failed: %{public}s/%{public}s/%{public}d", deviceName.c_str(),
255            bundleName.c_str(), userId);
256        return false;
257    }
258    return true;
259}
260
261bool UsbRightManager::RemoveDeviceAllRight(const std::string &deviceName)
262{
263    USB_HILOGD(MODULE_USB_SERVICE, "device %{private}s detached, process right", deviceName.c_str());
264    CleanUpRightTemporaryExpired(deviceName);
265    TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_ALL);
266    return true;
267}
268
269bool UsbRightManager::ShowUsbDialog(
270    const std::string &busDev, const std::string &deviceName, const std::string &bundleName, const std::string &tokenId)
271{
272    auto abmc = AAFwk::AbilityManagerClient::GetInstance();
273    if (abmc == nullptr) {
274        USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed");
275        return false;
276    }
277
278    std::string appName;
279    if (!GetAppName(bundleName, appName)) {
280        appName = bundleName;
281    }
282
283    std::string productName;
284    if (!GetProductName(busDev, productName)) {
285        productName = busDev;
286    }
287
288    AAFwk::Want want;
289    want.SetElementName("com.usb.right", "UsbServiceExtAbility");
290    want.SetParam("bundleName", bundleName);
291    want.SetParam("deviceName", busDev);
292    want.SetParam("tokenId", tokenId);
293    want.SetParam("appName", appName);
294    want.SetParam("productName", productName);
295
296    sptr<UsbAbilityConn> usbAbilityConn_ = new (std::nothrow) UsbAbilityConn();
297    if (usbAbilityConn_ == nullptr) {
298        USB_HILOGE(MODULE_SERVICE, "new (std::nothrow) UsbAbilityConn() failed");
299        return false;
300    }
301    sem_init(&waitDialogDisappear_, 1, 0);
302    auto ret = abmc->ConnectAbility(want, usbAbilityConn_, -1);
303    if (ret != UEC_OK) {
304        USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
305        return false;
306    }
307    /* Waiting for the user to click */
308    sem_wait(&waitDialogDisappear_);
309    return true;
310}
311
312bool UsbRightManager::GetUserAgreementByDiag(const std::string &busDev, const std::string &deviceName,
313    const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
314{
315#ifdef USB_RIGHT_TEST
316    return true;
317#endif
318    /* There can only be one dialog at a time */
319    std::lock_guard<std::mutex> guard(dialogRunning_);
320    if (!ShowUsbDialog(busDev, deviceName, bundleName, tokenId)) {
321        USB_HILOGE(MODULE_USB_SERVICE, "ShowUsbDialog failed");
322        return false;
323    }
324
325    return HasRight(deviceName, bundleName, tokenId, userId);
326}
327
328sptr<IBundleMgr> UsbRightManager::GetBundleMgr()
329{
330    auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
331    if (sam == nullptr) {
332        USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbilityManager return nullptr");
333        return nullptr;
334    }
335    auto bundleMgrSa = sam->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
336    if (bundleMgrSa == nullptr) {
337        USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbility return nullptr");
338        return nullptr;
339    }
340    auto bundleMgr = iface_cast<IBundleMgr>(bundleMgrSa);
341    if (bundleMgr == nullptr) {
342        USB_HILOGW(MODULE_USB_SERVICE, "iface_cast return nullptr");
343    }
344    return bundleMgr;
345}
346
347sptr<IBundleResource> UsbRightManager::GetBundleResMgr()
348{
349    auto bundleMgr = GetBundleMgr();
350    if (bundleMgr == nullptr) {
351        return nullptr;
352    }
353    return bundleMgr->GetBundleResourceProxy();
354}
355
356bool UsbRightManager::GetAppName(const std::string &bundleName, std::string &appName)
357{
358    auto resMgr = GetBundleResMgr();
359    if (resMgr == nullptr) {
360        USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res mgr failed");
361        return false;
362    }
363
364    BundleResourceInfo info;
365    auto ret = resMgr->GetBundleResourceInfo(bundleName, (uint32_t)ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL, info);
366    if (ret != ERR_OK) {
367        USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res info failed: %{public}d", ret);
368        return false;
369    }
370    appName = info.label;
371    return true;
372}
373
374bool UsbRightManager::GetProductName(const std::string &devName, std::string &productName)
375{
376    auto usbService = UsbService::GetGlobalInstance();
377    if (usbService == nullptr) {
378        return false;
379    }
380    return usbService->GetDeviceProductName(devName, productName);
381}
382
383bool UsbRightManager::IsSystemAppOrSa()
384{
385    uint64_t tokenid = IPCSkeleton::GetCallingFullTokenID();
386    bool isSystemApp = TokenIdKit::IsSystemAppByFullTokenID(tokenid);
387    if (isSystemApp) {
388        return true;
389    }
390
391    AccessTokenID accessTokenId = IPCSkeleton::GetCallingTokenID();
392    ATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(accessTokenId);
393    if (tokenType == TOKEN_NATIVE) {
394        return true;
395    }
396
397    USB_HILOGW(MODULE_USB_SERVICE, "neither system app nor sa");
398    return false;
399}
400
401bool UsbRightManager::VerifyPermission()
402{
403    AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
404    int32_t ret = AccessTokenKit::VerifyAccessToken(tokenId, USB_MANAGE_ACCESS_USB_DEVICE);
405    if (ret == PermissionState::PERMISSION_DENIED) {
406        USB_HILOGW(MODULE_USB_SERVICE, "no permission");
407        return false;
408    }
409    return true;
410}
411
412bool UsbRightManager::IsAppInstalled(int32_t uid, const std::string &bundleName)
413{
414    auto bundleMgr = GetBundleMgr();
415    if (bundleMgr == nullptr) {
416        USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
417        return false;
418    }
419    ApplicationInfo appInfo;
420    if (!bundleMgr->GetApplicationInfo(bundleName, GET_BASIC_APPLICATION_INFO, uid, appInfo)) {
421        USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr GetApplicationInfo failed");
422        return false;
423    }
424    return true;
425}
426
427bool UsbRightManager::GetBundleInstallAndUpdateTime(
428    int32_t uid, const std::string &bundleName, uint64_t &installTime, uint64_t &updateTime)
429{
430    BundleInfo bundleInfo;
431    auto bundleMgr = GetBundleMgr();
432    if (bundleMgr == nullptr) {
433        USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
434        return false;
435    }
436    if (!bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, uid)) {
437        USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr GetBundleInfo(uid) failed");
438        return false;
439    }
440    installTime = static_cast<uint64_t>(bundleInfo.installTime);
441    updateTime = static_cast<uint64_t>(bundleInfo.updateTime);
442    return true;
443}
444
445uint64_t UsbRightManager::GetCurrentTimestamp()
446{
447    int64_t time =
448        std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
449    return static_cast<uint64_t>(time);
450}
451
452void UsbRightManager::GetCurrentUserId(int32_t &uid)
453{
454    int32_t ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), uid);
455    if (ret != UEC_OK) {
456        USB_HILOGE(MODULE_USB_SERVICE, "GetOsAccountLocalIdFromUid failed: %{public}d, set to defult", ret);
457        uid = USB_RIGHT_USERID_DEFAULT; /* default user id */
458    }
459    USB_HILOGD(MODULE_USB_SERVICE, "usb get userid success: %{public}d, uid: %{public}d", ret, uid);
460}
461
462int32_t UsbRightManager::IsOsAccountExists(int32_t id, bool &isAccountExists)
463{
464    int32_t ret = AccountSA::OsAccountManager::IsOsAccountExists(id, isAccountExists);
465    if (ret != UEC_OK) {
466        USB_HILOGE(MODULE_USB_SERVICE, " api IsOsAccountExists failed: ret=%{public}d id=%{public}d", ret, id);
467        return USB_RIGHT_FAILURE;
468    }
469    return USB_RIGHT_OK;
470}
471
472int32_t UsbRightManager::HasSetFuncRight(int32_t functions)
473{
474    if (!(IsSystemAppOrSa() && VerifyPermission())) {
475        return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
476    }
477    if (!(static_cast<uint32_t>(functions) & UsbSrvSupport::FUNCTION_HDC)) {
478        return UEC_OK;
479    }
480    USB_HILOGI(MODULE_USB_SERVICE, "Set up function permission validation");
481    char paramValue[PARAM_BUF_LEN] = { 0 };
482    int32_t ret = GetParameter("persist.hdc.control", "true", paramValue, sizeof(paramValue));
483    if (ret < 0) {
484        USB_HILOGW(MODULE_USB_SERVICE, "GetParameter fail");
485    }
486    ret = strcmp(paramValue, "true");
487    if (ret != 0) {
488        USB_HILOGE(MODULE_USB_SERVICE, "HDC setup failed");
489        return UEC_SERVICE_PERMISSION_CHECK_HDC;
490    }
491    if (!OHOS::system::GetBoolParameter(DEVELOPERMODE_STATE, false)) {
492        USB_HILOGE(MODULE_USB_SERVICE, "Developer mode unabled, FUNCTION_HDC cannot be set");
493        return UEC_SERVICE_PERMISSION_CHECK_HDC;
494    }
495    return UEC_OK;
496}
497
498int32_t UsbRightManager::CleanUpRightExpired(std::vector<std::string> &devices)
499{
500    USB_HILOGD(MODULE_USB_SERVICE, "clean up expired right: size=%{public}zu", devices.size());
501    size_t len = devices.size();
502    int32_t ret = USB_RIGHT_OK;
503    for (size_t i = 0; i < len; i++) {
504        std::string dev = devices.at(i);
505        ret = CleanUpRightTemporaryExpired(dev);
506        if (ret != USB_RIGHT_OK) {
507            USB_HILOGE(MODULE_USB_SERVICE,
508                "failed(%{public}zu/%{public}zu): delete temporary expiried record, dev=%{private}s", i, len,
509                dev.c_str());
510            continue;
511        }
512    }
513    int32_t uid = USB_RIGHT_USERID_INVALID;
514    GetCurrentUserId(uid);
515    ret = CleanUpRightNormalExpired(uid);
516    if (ret != USB_RIGHT_OK) {
517        USB_HILOGE(MODULE_USB_SERVICE, "delete expired record with uid(%{public}d) failed: %{public}d", uid, ret);
518    }
519    return ret;
520}
521
522int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, int32_t &totalApps, int32_t &deleteApps)
523{
524    std::vector<std::string> apps;
525    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
526    if (helper == nullptr) {
527        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
528        return false;
529    }
530    int32_t ret = helper->QueryRightRecordApps(uid, apps);
531    if (ret <= 0) {
532        /* error or empty record */
533        return USB_RIGHT_NOP;
534    }
535    totalApps = static_cast<int32_t>(apps.size());
536    deleteApps = 0;
537    for (int32_t i = 0; i < totalApps; i++) {
538        std::string app = apps.at(i);
539        if (!IsAppInstalled(uid, app)) {
540            ret = helper->DeleteAppRightRecord(uid, app);
541            if (ret != USB_RIGHT_OK) {
542                USB_HILOGW(MODULE_USB_SERVICE, "clean failed: app=%{public}s, ret=%{public}d", app.c_str(), ret);
543                continue;
544            }
545            deleteApps++;
546        }
547    }
548    USB_HILOGD(MODULE_USB_SERVICE, "clean uninstall app record[%{public}d/%{public}d]: uid=%{public}d", deleteApps,
549        totalApps, uid);
550    return ret;
551}
552
553int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, const std::string &bundleName)
554{
555    std::vector<std::string> apps;
556    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
557    if (helper == nullptr) {
558        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
559        return false;
560    }
561    int32_t ret = helper->QueryRightRecordApps(uid, apps);
562    if (ret <= 0) {
563        /* error or empty record */
564        return USB_RIGHT_NOP;
565    }
566    int32_t index = 0;
567    if (!StringVectorFound(apps, bundleName, index)) {
568        /* app not in record, ignore */
569        return USB_RIGHT_NOP;
570    }
571    ret = helper->DeleteAppRightRecord(uid, apps.at(index));
572    USB_HILOGD(MODULE_USB_SERVICE, "clean[%{public}d/%{public}zu]: uid=%{public}d, app=%{public}s, ret=%{public}d",
573        index, apps.size(), uid, bundleName.c_str(), ret);
574    return ret;
575}
576
577void UsbRightManager::StringVectorSortAndUniq(std::vector<std::string> &strings)
578{
579    sort(strings.begin(), strings.end());
580    auto last = unique(strings.begin(), strings.end());
581    strings.erase(last, strings.end());
582}
583
584bool UsbRightManager::StringVectorFound(
585    const std::vector<std::string> &strings, const std::string &value, int32_t &index)
586{
587    size_t len = strings.size();
588    for (size_t i = 0; i < len; i++) {
589        if (value == strings.at(i)) {
590            index = static_cast<int32_t>(i);
591            return true;
592        }
593    }
594    return false;
595}
596
597int32_t UsbRightManager::CleanUpRightAppReinstalled(int32_t uid, uint32_t &totalApps, uint32_t &deleteApps)
598{
599    std::vector<std::string> apps;
600    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
601    if (helper == nullptr) {
602        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
603        return false;
604    }
605    int32_t ret = helper->QueryRightRecordApps(uid, apps);
606    if (ret <= 0) {
607        USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
608        return USB_RIGHT_NOP;
609    }
610    StringVectorSortAndUniq(apps);
611    deleteApps = 0;
612    totalApps = apps.size();
613    std::vector<std::string> deleteBundleNames;
614    for (size_t i = 0; i < apps.size(); i++) {
615        std::string bundleName = apps.at(i);
616        std::vector<struct UsbRightAppInfo> infos;
617        ret = helper->QueryAppRightRecord(uid, bundleName, infos);
618        if (ret < 0) {
619            USB_HILOGE(MODULE_USB_SERVICE, "query app info %{public}s failed: %{public}d", bundleName.c_str(), ret);
620            return USB_RIGHT_FAILURE;
621        }
622        uint64_t installTime = 0;
623        uint64_t updateTime = 0;
624        if (!GetBundleInstallAndUpdateTime(uid, bundleName, installTime, updateTime)) {
625            USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: app=%{public}s uid=%{public}d",
626                bundleName.c_str(), uid);
627            return USB_RIGHT_FAILURE;
628        }
629        for (size_t j = 0; j < infos.size(); j++) {
630            struct UsbRightAppInfo info = infos.at(j);
631            if (info.installTime != installTime) {
632                deleteBundleNames.push_back(bundleName);
633                break;
634            }
635        }
636    }
637    StringVectorSortAndUniq(deleteBundleNames);
638    ret = helper->DeleteAppsRightRecord(uid, deleteBundleNames);
639    if (ret != USB_RIGHT_OK) {
640        USB_HILOGE(MODULE_USB_SERVICE, "delete apps failed: %{public}d", ret);
641    } else {
642        deleteApps = deleteBundleNames.size();
643    }
644    return ret;
645}
646
647int32_t UsbRightManager::CleanUpRightUserDeleted(int32_t &totalUsers, int32_t &deleteUsers)
648{
649    std::vector<std::string> rightRecordUids;
650    bool isAccountExists = false;
651    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
652    if (helper == nullptr) {
653        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
654        return false;
655    }
656    int32_t ret = helper->QueryRightRecordUids(rightRecordUids);
657    if (ret <= 0) {
658        USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
659        return USB_RIGHT_NOP;
660    }
661    size_t len = rightRecordUids.size();
662    deleteUsers = 0;
663    for (size_t i = 0; i < len; i++) {
664        int32_t uid = 0;
665        if (!StrToInt(rightRecordUids.at(i), uid)) {
666            USB_HILOGE(MODULE_USB_SERVICE, "convert failed: %{public}s", rightRecordUids.at(i).c_str());
667            continue;
668        }
669        ret = IsOsAccountExists(uid, isAccountExists);
670        if (ret != USB_RIGHT_OK) {
671            USB_HILOGE(MODULE_USB_SERVICE, "call IsOsAccountExists failed: %{public}d", ret);
672            continue;
673        }
674        if (!isAccountExists) {
675            ret = helper->DeleteUidRightRecord(uid);
676            USB_HILOGE(MODULE_USB_SERVICE, "detecte delete uid=%{public}d: %{public}d", uid, ret);
677            deleteUsers++;
678        }
679        USB_HILOGD(MODULE_USB_SERVICE, "uid exist, ignore: %{public}d", uid);
680    }
681    totalUsers = static_cast<int32_t>(rightRecordUids.size());
682    return USB_RIGHT_OK;
683}
684
685int32_t UsbRightManager::CleanUpRightUserStopped(int32_t uid)
686{
687    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
688    if (helper == nullptr) {
689        USB_HILOGE(MODULE_USB_SERVICE, "CleanUpRightUserStopped %{public}d: helper is null", uid);
690        return false;
691    }
692
693    return helper->DeleteUidRightRecord(uid);
694}
695
696int32_t UsbRightManager::CleanUpRightTemporaryExpired(const std::string &deviceName)
697{
698    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
699    if (helper == nullptr) {
700        USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
701        return false;
702    }
703    int32_t ret = helper->DeleteValidPeriodRightRecord(USB_RIGHT_VALID_PERIOD_MIN, deviceName);
704    if (ret != USB_RIGHT_OK) {
705        USB_HILOGE(MODULE_USB_SERVICE, "failed: delete temporary expiried record: dev=%{private}s", deviceName.c_str());
706    }
707    return ret;
708}
709
710int32_t UsbRightManager::CleanUpRightNormalExpired(int32_t uid)
711{
712    uint64_t nowTime = GetCurrentTimestamp();
713    std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
714    int32_t ret = helper->DeleteNormalExpiredRightRecord(uid, nowTime);
715    if (ret != USB_RIGHT_OK) {
716        USB_HILOGD(MODULE_USB_SERVICE, "failed: clean up expired record at %{public}" PRIu64 "", nowTime);
717    }
718    return ret;
719}
720
721int32_t UsbRightManager::TidyUpRight(uint32_t choose)
722{
723    if (choose == TIGHT_UP_USB_RIGHT_RECORD_NONE) {
724        /* ignore */
725        return USB_RIGHT_NOP;
726    }
727    if ((choose | TIGHT_UP_USB_RIGHT_RECORD_ALL) != TIGHT_UP_USB_RIGHT_RECORD_ALL) {
728        USB_HILOGE(MODULE_USB_SERVICE, "choose invalid");
729        return UEC_SERVICE_INVALID_VALUE;
730    }
731    int32_t uid = USB_RIGHT_USERID_INVALID;
732    GetCurrentUserId(uid);
733    if (uid == USB_RIGHT_USERID_CONSOLE) {
734        USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
735        return true;
736    }
737    int32_t ret = 0;
738    if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED) != 0) {
739        int32_t totalUninstalledApps = 0;
740        int32_t deleteUninstalledApps = 0;
741        ret = CleanUpRightAppUninstalled(uid, totalUninstalledApps, deleteUninstalledApps);
742        USB_HILOGD(MODULE_USB_SERVICE, "delete app uninstalled record[%{public}d/%{public}d]: %{public}d",
743            deleteUninstalledApps, totalUninstalledApps, ret);
744    }
745    if ((choose & TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED) != 0) {
746        int32_t totalUsers = 0;
747        int32_t deleteUsers = 0;
748        ret = CleanUpRightUserDeleted(totalUsers, deleteUsers);
749        USB_HILOGD(MODULE_USB_SERVICE, "delete user deleted record[%{public}d/%{public}d]: %{public}d", deleteUsers,
750            totalUsers, ret);
751    }
752    if ((choose & TIGHT_UP_USB_RIGHT_RECORD_EXPIRED) != 0) {
753        ret = CleanUpRightNormalExpired(uid);
754        USB_HILOGD(MODULE_USB_SERVICE, "delete expired record: %{public}d", ret);
755    }
756    if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED) != 0) {
757        uint32_t totalReinstalledApps = 0;
758        uint32_t deleteReinstalledApps = 0;
759        ret = CleanUpRightAppReinstalled(uid, totalReinstalledApps, deleteReinstalledApps);
760        USB_HILOGD(MODULE_USB_SERVICE, "delete app reinstalled record[%{public}u/%{public}u]: %{public}d",
761            deleteReinstalledApps, totalReinstalledApps, ret);
762    }
763    return ret;
764}
765
766bool UsbRightManager::IsAllDigits(const std::string &bundleName)
767{
768    size_t len = bundleName.length();
769    for (size_t i = 0; i < len; i++) {
770        if (!isdigit(bundleName[i])) {
771            return false;
772        }
773    }
774    return true;
775}
776} // namespace USB
777} // namespace OHOS