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