1 /*
2  * Copyright (c) 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_db_helper.h"
17 
18 #include <string>
19 
20 #include "bundle_installer_interface.h"
21 #include "hilog_wrapper.h"
22 #include "usb_errors.h"
23 #include "usb_right_database.h"
24 
25 using namespace OHOS::NativeRdb;
26 
27 namespace OHOS {
28 namespace USB {
29 std::shared_ptr<UsbRightDbHelper> UsbRightDbHelper::instance_;
30 
UsbRightDbHelper()31 UsbRightDbHelper::UsbRightDbHelper()
32 {
33     rightDatabase_ = UsbRightDataBase::GetInstance();
34 }
35 
GetInstance()36 std::shared_ptr<UsbRightDbHelper> UsbRightDbHelper::GetInstance()
37 {
38     static std::mutex instanceMutex;
39     std::lock_guard<std::mutex> guard(instanceMutex);
40     if (instance_ == nullptr) {
41         instance_.reset(new UsbRightDbHelper());
42     }
43     return instance_;
44 }
45 
IsRecordExpired(int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,uint64_t expiredTime)46 bool UsbRightDbHelper::IsRecordExpired(int32_t uid, const std::string &deviceName, const std::string &bundleName,
47     const std::string &tokenId, uint64_t expiredTime)
48 {
49     USB_HILOGI(MODULE_USB_SERVICE, "info: uid=%{public}d app=%{public}s", uid, bundleName.c_str());
50     std::vector<struct UsbRightAppInfo> infos;
51     int32_t ret = QueryRightRecord(uid, deviceName, bundleName, tokenId, infos);
52     if (ret <= 0) {
53         USB_HILOGI(MODULE_USB_SERVICE, "usb query no record/error: %{public}d", ret);
54         return true;
55     }
56     size_t len = infos.size();
57     for (size_t i = 0; i < len; i++) {
58         if (!IsRecordExpired(infos.at(i), expiredTime)) {
59             return false;
60         }
61     }
62     return true;
63 }
64 
IsRecordExpired(const struct UsbRightAppInfo & info,uint64_t expiredTime)65 bool UsbRightDbHelper::IsRecordExpired(const struct UsbRightAppInfo &info, uint64_t expiredTime)
66 {
67     if (info.validPeriod == USB_RIGHT_VALID_PERIOD_MIN) {
68         USB_HILOGD(MODULE_USB_SERVICE, "allow temporary");
69         return false;
70     } else if (info.validPeriod == USB_RIGHT_VALID_PERIOD_MAX) {
71         USB_HILOGD(MODULE_USB_SERVICE, "allow forever");
72         return false;
73     } else if (expiredTime - info.requestTime < info.validPeriod) {
74         USB_HILOGD(MODULE_USB_SERVICE, "allow based on request time");
75         return false;
76     } else if ((info.installTime > info.updateTime) || (info.installTime > info.requestTime)) {
77         USB_HILOGW(MODULE_USB_SERVICE,
78             "invalid: inst=%{public}" PRIu64 " updt=%{public}" PRIu64 " rqst=%{public}" PRIu64 "", info.installTime,
79             info.updateTime, info.requestTime);
80         /* ignore, return true to add right */
81         return true;
82     }
83     /* unknown, return true to add right */
84     USB_HILOGW(MODULE_USB_SERVICE,
85         "info: inst=%{public}" PRIu64 " updt=%{public}" PRIu64 " rqst=%{public}" PRIu64 " expr=%{public}" PRIu64
86         " valid=%{public}" PRIu64 "",
87         info.installTime, info.updateTime, info.requestTime, expiredTime, info.validPeriod);
88     return true;
89 }
90 
AddRightRecord(const std::string & deviceName,const std::string & bundleName,struct UsbRightAppInfo & info)91 int32_t UsbRightDbHelper::AddRightRecord(
92     const std::string &deviceName, const std::string &bundleName, struct UsbRightAppInfo &info)
93 {
94     if (rightDatabase_ == nullptr) {
95         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
96         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
97     }
98     std::lock_guard<std::mutex> guard(databaseMutex_);
99     ValuesBucket values;
100     values.Clear();
101     values.PutInt("uid", info.uid);
102     values.PutLong("installTime", info.installTime);
103     values.PutLong("updateTime", info.updateTime);
104     values.PutLong("requestTime", info.requestTime);
105     values.PutLong("validPeriod", info.validPeriod);
106     values.PutString("deviceName", deviceName);
107     values.PutString("bundleName", bundleName);
108     int32_t ret = rightDatabase_->BeginTransaction();
109     if (ret < USB_RIGHT_OK) {
110         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
111         return ret;
112     }
113     ret = rightDatabase_->Insert(values);
114     if (ret < USB_RIGHT_OK) {
115         USB_HILOGE(MODULE_USB_SERVICE, "Insert error: %{public}d", ret);
116         (void)rightDatabase_->RollBack();
117         return ret;
118     }
119     ret = rightDatabase_->Commit();
120     if (ret < USB_RIGHT_OK) {
121         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
122         (void)rightDatabase_->RollBack();
123         return ret;
124     }
125     USB_HILOGI(MODULE_USB_SERVICE,
126         "add success: uid=%{public}d inst=%{public}" PRIu64 " updt=%{public}" PRIu64 " rqst=%{public}" PRIu64
127         " vald=%{public}" PRIu64 " app=%{public}s",
128         info.uid, info.installTime, info.updateTime, info.requestTime, info.validPeriod, bundleName.c_str());
129     return ret;
130 }
131 
QueryAndGetResult(const RdbPredicates & rdbPredicates,const std::vector<std::string> & columns,std::vector<struct UsbRightAppInfo> & infos)132 int32_t UsbRightDbHelper::QueryAndGetResult(const RdbPredicates &rdbPredicates, const std::vector<std::string> &columns,
133     std::vector<struct UsbRightAppInfo> &infos)
134 {
135     if (rightDatabase_ == nullptr) {
136         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
137         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
138     }
139     int32_t ret = rightDatabase_->BeginTransaction();
140     if (ret < USB_RIGHT_OK) {
141         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
142         return ret;
143     }
144     auto resultSet = rightDatabase_->Query(rdbPredicates, columns);
145     if (resultSet == nullptr) {
146         USB_HILOGE(MODULE_USB_SERVICE, "Query error");
147         (void)rightDatabase_->RollBack();
148         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
149     }
150     ret = rightDatabase_->Commit();
151     if (ret < USB_RIGHT_OK) {
152         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
153         (void)rightDatabase_->RollBack();
154         return ret;
155     }
156     return GetResultRightRecordEx(resultSet, infos);
157 }
158 
QueryRightRecord(int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,std::vector<struct UsbRightAppInfo> & infos)159 int32_t UsbRightDbHelper::QueryRightRecord(int32_t uid, const std::string &deviceName, const std::string &bundleName,
160     const std::string &tokenId, std::vector<struct UsbRightAppInfo> &infos)
161 {
162     std::lock_guard<std::mutex> guard(databaseMutex_);
163     USB_HILOGI(MODULE_USB_SERVICE, "Query detail: uid=%{public}d app=%{public}s", uid, bundleName.c_str());
164     std::vector<std::string> columns;
165     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
166     rdbPredicates.BeginWrap()
167         ->EqualTo("uid", std::to_string(uid))
168         ->And()
169         ->EqualTo("deviceName", deviceName)
170         ->And()
171         ->EqualTo("bundleName", bundleName)
172         ->And()
173         ->EqualTo("tokenId", tokenId)
174         ->EndWrap();
175     return QueryAndGetResult(rdbPredicates, columns, infos);
176 }
177 
QueryUserRightRecord(int32_t uid,std::vector<struct UsbRightAppInfo> & infos)178 int32_t UsbRightDbHelper::QueryUserRightRecord(int32_t uid, std::vector<struct UsbRightAppInfo> &infos)
179 {
180     std::lock_guard<std::mutex> guard(databaseMutex_);
181     USB_HILOGD(MODULE_USB_SERVICE, "Query detail: uid=%{public}d", uid);
182     std::vector<std::string> columns;
183     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
184     rdbPredicates.EqualTo("uid", std::to_string(uid));
185     return QueryAndGetResult(rdbPredicates, columns, infos);
186 }
187 
QueryDeviceRightRecord(int32_t uid,const std::string & deviceName,std::vector<struct UsbRightAppInfo> & infos)188 int32_t UsbRightDbHelper::QueryDeviceRightRecord(
189     int32_t uid, const std::string &deviceName, std::vector<struct UsbRightAppInfo> &infos)
190 {
191     std::lock_guard<std::mutex> guard(databaseMutex_);
192     USB_HILOGD(MODULE_USB_SERVICE, "Query detail: uid=%{public}d", uid);
193     std::vector<std::string> columns;
194     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
195     rdbPredicates.BeginWrap()->EqualTo("uid", std::to_string(uid))->And()->EqualTo("deviceName", deviceName)->EndWrap();
196     return QueryAndGetResult(rdbPredicates, columns, infos);
197 }
198 
QueryAppRightRecord(int32_t uid,const std::string & bundleName,std::vector<struct UsbRightAppInfo> & infos)199 int32_t UsbRightDbHelper::QueryAppRightRecord(
200     int32_t uid, const std::string &bundleName, std::vector<struct UsbRightAppInfo> &infos)
201 {
202     std::lock_guard<std::mutex> guard(databaseMutex_);
203     USB_HILOGD(MODULE_USB_SERVICE, "Query detail: uid=%{public}d dev=%{public}s", uid, bundleName.c_str());
204     std::vector<std::string> columns;
205     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
206     rdbPredicates.BeginWrap()->EqualTo("uid", std::to_string(uid))->And()->EqualTo("bundleName", bundleName)->EndWrap();
207     return QueryAndGetResult(rdbPredicates, columns, infos);
208 }
209 
QueryRightRecordUids(std::vector<std::string> & uids)210 int32_t UsbRightDbHelper::QueryRightRecordUids(std::vector<std::string> &uids)
211 {
212     std::lock_guard<std::mutex> guard(databaseMutex_);
213     std::vector<std::string> columns = {"uid"};
214     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
215     rdbPredicates.Distinct();
216     return QueryAndGetResultColumnValues(rdbPredicates, columns, "uid", uids);
217 }
218 
QueryRightRecordApps(int32_t uid,std::vector<std::string> & apps)219 int32_t UsbRightDbHelper::QueryRightRecordApps(int32_t uid, std::vector<std::string> &apps)
220 {
221     std::lock_guard<std::mutex> guard(databaseMutex_);
222     std::vector<std::string> columns = {"bundleName"};
223     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
224     rdbPredicates.EqualTo("uid", std::to_string(uid))->Distinct();
225     return QueryAndGetResultColumnValues(rdbPredicates, columns, "bundleName", apps);
226 }
227 
QueryAndGetResultColumnValues(const RdbPredicates & rdbPredicates,const std::vector<std::string> & columns,const std::string & columnName,std::vector<std::string> & columnValues)228 int32_t UsbRightDbHelper::QueryAndGetResultColumnValues(const RdbPredicates &rdbPredicates,
229     const std::vector<std::string> &columns, const std::string &columnName, std::vector<std::string> &columnValues)
230 {
231     if (rightDatabase_ == nullptr) {
232         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
233         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
234     }
235     int32_t ret = rightDatabase_->BeginTransaction();
236     if (ret < USB_RIGHT_OK) {
237         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
238         return ret;
239     }
240     auto resultSet = rightDatabase_->Query(rdbPredicates, columns);
241     if (resultSet == nullptr) {
242         USB_HILOGE(MODULE_USB_SERVICE, "Query error");
243         (void)rightDatabase_->RollBack();
244         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
245     }
246     ret = rightDatabase_->Commit();
247     if (ret < USB_RIGHT_OK) {
248         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
249         (void)rightDatabase_->RollBack();
250         return ret;
251     }
252     int32_t rowCount = 0;
253     int32_t columnIndex = 0;
254     if (resultSet->GetRowCount(rowCount) != E_OK || resultSet->GetColumnIndex(columnName, columnIndex) != E_OK) {
255         USB_HILOGE(MODULE_USB_SERVICE, "get table info failed");
256         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
257     }
258     bool endFlag = false;
259     for (int32_t i = 0; (i < rowCount) && !endFlag; i++) {
260         if (resultSet->GoToRow(i) != E_OK) {
261             USB_HILOGE(MODULE_USB_SERVICE, "GoToRow %{public}d", i);
262             return USB_RIGHT_RDB_EXECUTE_FAILTURE;
263         }
264         std::string tempStr;
265         if (resultSet->GetString(columnIndex, tempStr) == E_OK) {
266             columnValues.push_back(tempStr);
267         }
268         resultSet->IsEnded(endFlag);
269     }
270     int32_t position = 0;
271     resultSet->GetRowIndex(position);
272     resultSet->IsEnded(endFlag);
273     USB_HILOGD(MODULE_USB_SERVICE, "idx=%{public}d rows=%{public}d pos=%{public}d ret=%{public}zu end=%{public}s",
274         columnIndex, rowCount, position, columnValues.size(), (endFlag ? "yes" : "no"));
275     return columnValues.size();
276 }
277 
UpdateRightRecord(int32_t uid,const std::string & deviceName,const std::string & bundleName,struct UsbRightAppInfo & info)278 int32_t UsbRightDbHelper::UpdateRightRecord(
279     int32_t uid, const std::string &deviceName, const std::string &bundleName, struct UsbRightAppInfo &info)
280 {
281     if (rightDatabase_ == nullptr) {
282         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
283         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
284     }
285     std::lock_guard<std::mutex> guard(databaseMutex_);
286     ValuesBucket values;
287     values.Clear();
288     values.PutInt("uid", info.uid);
289     values.PutLong("installTime", info.installTime);
290     values.PutLong("updateTime", info.updateTime);
291     values.PutLong("requestTime", info.requestTime);
292     values.PutLong("validPeriod", info.validPeriod);
293     values.PutString("deviceName", deviceName);
294     values.PutString("bundleName", bundleName);
295     int32_t ret = rightDatabase_->BeginTransaction();
296     if (ret < USB_RIGHT_OK) {
297         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
298         return ret;
299     }
300     int32_t changedRows = 0;
301     ret = rightDatabase_->Update(changedRows, values, "uid = ? AND deviceName = ? AND bundleName = ?",
302         std::vector<std::string> {std::to_string(info.uid), deviceName, bundleName});
303     if (ret < USB_RIGHT_OK) {
304         USB_HILOGE(MODULE_USB_SERVICE, "Update error: %{public}d", ret);
305         (void)rightDatabase_->RollBack();
306         return ret;
307     }
308     ret = rightDatabase_->Commit();
309     if (ret < USB_RIGHT_OK) {
310         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
311         (void)rightDatabase_->RollBack();
312     }
313     return ret;
314 }
315 
DeleteAndNoOtherOperation(const std::string & whereClause,const std::vector<std::string> & whereArgs)316 int32_t UsbRightDbHelper::DeleteAndNoOtherOperation(
317     const std::string &whereClause, const std::vector<std::string> &whereArgs)
318 {
319     if (rightDatabase_ == nullptr) {
320         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
321         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
322     }
323     int32_t ret = rightDatabase_->BeginTransaction();
324     if (ret < USB_RIGHT_OK) {
325         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
326         return ret;
327     }
328     int32_t changedRows = 0;
329     ret = rightDatabase_->Delete(changedRows, whereClause, whereArgs);
330     if (ret < USB_RIGHT_OK) {
331         USB_HILOGE(MODULE_USB_SERVICE, "Delete error: %{public}d", ret);
332         (void)rightDatabase_->RollBack();
333         return ret;
334     }
335     ret = rightDatabase_->Commit();
336     if (ret < USB_RIGHT_OK) {
337         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
338         (void)rightDatabase_->RollBack();
339     }
340 
341     if (changedRows <= 0) {
342         USB_HILOGI(MODULE_USB_SERVICE, "no row change: %{public}d", changedRows);
343         return USB_RIGHT_RDB_EMPTY;
344     }
345     return ret;
346 }
347 
DeleteAndNoOtherOperation(const OHOS::NativeRdb::RdbPredicates & rdbPredicates)348 int32_t UsbRightDbHelper::DeleteAndNoOtherOperation(const OHOS::NativeRdb::RdbPredicates &rdbPredicates)
349 {
350     if (rightDatabase_ == nullptr) {
351         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
352         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
353     }
354     int32_t ret = rightDatabase_->BeginTransaction();
355     if (ret < USB_RIGHT_OK) {
356         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
357         return ret;
358     }
359     ret = rightDatabase_->Delete(rdbPredicates);
360     if (ret < USB_RIGHT_OK) {
361         USB_HILOGE(MODULE_USB_SERVICE, "Delete error: %{public}d", ret);
362         (void)rightDatabase_->RollBack();
363         return ret;
364     }
365     ret = rightDatabase_->Commit();
366     if (ret < USB_RIGHT_OK) {
367         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
368         (void)rightDatabase_->RollBack();
369     }
370     return ret;
371 }
372 
DeleteRightRecord(int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId)373 int32_t UsbRightDbHelper::DeleteRightRecord(int32_t uid, const std::string &deviceName,
374     const std::string &bundleName, const std::string &tokenId)
375 {
376     std::lock_guard<std::mutex> guard(databaseMutex_);
377     std::string whereClause = {"uid = ? AND deviceName = ? AND bundleName = ? AND tokenId = ?"};
378     std::vector<std::string> whereArgs = {std::to_string(uid), deviceName, bundleName, tokenId};
379     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
380     if (ret != USB_RIGHT_OK) {
381         USB_HILOGE(MODULE_USB_SERVICE, "failed: detale(uid, dev, app): %{public}d", ret);
382     }
383     return ret;
384 }
385 
DeleteDeviceRightRecord(int32_t uid,const std::string & deviceName)386 int32_t UsbRightDbHelper::DeleteDeviceRightRecord(int32_t uid, const std::string &deviceName)
387 {
388     std::lock_guard<std::mutex> guard(databaseMutex_);
389     std::string whereClause = {"uid = ? AND deviceName = ?"};
390     std::vector<std::string> whereArgs = {std::to_string(uid), deviceName};
391     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
392     if (ret != USB_RIGHT_OK) {
393         USB_HILOGE(MODULE_USB_SERVICE, "failed: delete(uid, dev): %{public}d", ret);
394     }
395     return ret;
396 }
397 
DeleteAppRightRecord(int32_t uid,const std::string & bundleName)398 int32_t UsbRightDbHelper::DeleteAppRightRecord(int32_t uid, const std::string &bundleName)
399 {
400     std::lock_guard<std::mutex> guard(databaseMutex_);
401     std::string whereClause = {"uid = ? AND bundleName = ?"};
402     std::vector<std::string> whereArgs = {std::to_string(uid), bundleName};
403     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
404     if (ret != USB_RIGHT_OK) {
405         USB_HILOGE(MODULE_USB_SERVICE, "failed: delete(uid, app): %{public}d", ret);
406     }
407     return ret;
408 }
409 
DeleteAppsRightRecord(int32_t uid,const std::vector<std::string> & bundleNames)410 int32_t UsbRightDbHelper::DeleteAppsRightRecord(int32_t uid, const std::vector<std::string> &bundleNames)
411 {
412     std::lock_guard<std::mutex> guard(databaseMutex_);
413     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
414     rdbPredicates.BeginWrap()->EqualTo("uid", std::to_string(uid))->And()->In("bundleName", bundleNames)->EndWrap();
415     int32_t ret = DeleteAndNoOtherOperation(rdbPredicates);
416     if (ret != USB_RIGHT_OK) {
417         USB_HILOGE(MODULE_USB_SERVICE, "failed: delete(uid, devs): %{public}d", ret);
418     }
419     return ret;
420 }
421 
DeleteUidRightRecord(int32_t uid)422 int32_t UsbRightDbHelper::DeleteUidRightRecord(int32_t uid)
423 {
424     std::lock_guard<std::mutex> guard(databaseMutex_);
425     std::string whereClause = {"uid = ?"};
426     std::vector<std::string> whereArgs = {std::to_string(uid)};
427     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
428     if (ret != USB_RIGHT_OK) {
429         USB_HILOGE(MODULE_USB_SERVICE, "failed: delete(uid): %{public}d", ret);
430     }
431     return ret;
432 }
433 
DeleteNormalExpiredRightRecord(int32_t uid,uint64_t expiredTime)434 int32_t UsbRightDbHelper::DeleteNormalExpiredRightRecord(int32_t uid, uint64_t expiredTime)
435 {
436     std::lock_guard<std::mutex> guard(databaseMutex_);
437     std::string whereClause = {"uid = ? AND requestTime < ? AND validPeriod NOT IN (?, ?)"};
438 
439     uint64_t relativeExpiredTime = (expiredTime <= USB_RIGHT_VALID_PERIOD_SET) ? 0 :
440         (expiredTime - USB_RIGHT_VALID_PERIOD_SET);
441     std::vector<std::string> whereArgs = {std::to_string(uid), std::to_string(relativeExpiredTime),
442         std::to_string(USB_RIGHT_VALID_PERIOD_MIN), std::to_string(USB_RIGHT_VALID_PERIOD_MAX)};
443     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
444     if (ret != USB_RIGHT_OK) {
445         USB_HILOGE(MODULE_USB_SERVICE,
446         "failed: delete(uid=%{public}d, expr<%{public}" PRIu64 "): %{public}d", uid, expiredTime, ret);
447     }
448     return ret;
449 }
450 
DeleteValidPeriodRightRecord(long validPeriod,const std::string & deviceName)451 int32_t UsbRightDbHelper::DeleteValidPeriodRightRecord(long validPeriod, const std::string &deviceName)
452 {
453     std::lock_guard<std::mutex> guard(databaseMutex_);
454     std::string whereClause = {"validPeriod = ? AND deviceName = ?"};
455     std::vector<std::string> whereArgs = {std::to_string(validPeriod), deviceName};
456     int32_t ret = DeleteAndNoOtherOperation(whereClause, whereArgs);
457     if (ret != USB_RIGHT_OK) {
458         USB_HILOGE(MODULE_USB_SERVICE, "failed: delete(dev, valid): %{public}d", ret);
459     }
460     return ret;
461 }
462 
GetResultSetTableInfo(const std::shared_ptr<OHOS::NativeRdb::ResultSet> & resultSet,struct UsbRightTableInfo & table)463 int32_t UsbRightDbHelper::GetResultSetTableInfo(
464     const std::shared_ptr<OHOS::NativeRdb::ResultSet> &resultSet, struct UsbRightTableInfo &table)
465 {
466     if (resultSet == nullptr) {
467         USB_HILOGE(MODULE_USB_SERVICE, "resultSet is null");
468         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
469     }
470     int32_t rowCount = 0;
471     int32_t columnCount = 0;
472     std::vector<std::string> columnNames;
473     if (resultSet->GetRowCount(rowCount) != E_OK || resultSet->GetColumnCount(columnCount) != E_OK ||
474         resultSet->GetAllColumnNames(columnNames) != E_OK) {
475         USB_HILOGE(MODULE_USB_SERVICE, "get table info failed");
476         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
477     }
478     int32_t columnNamesCount = static_cast<int32_t>(columnNames.size());
479     for (int32_t i = 0; i < columnNamesCount; i++) {
480         std::string &columnName = columnNames.at(i);
481         if (columnName == "id") {
482             table.primaryKeyIndex = i;
483         }
484         if (columnName == "uid") {
485             table.uidIndex = i;
486         }
487         if (columnName == "installTime") {
488             table.installTimeIndex = i;
489         }
490         if (columnName == "updateTime") {
491             table.updateTimeIndex = i;
492         }
493         if (columnName == "requestTime") {
494             table.requestTimeIndex = i;
495         }
496         if (columnName == "validPeriod") {
497             table.validPeriodIndex = i;
498         }
499         if (columnName == "bundleName") {
500             table.bundleNameIndex = i;
501         }
502         if (columnName == "deviceName") {
503             table.deviceNameIndex = i;
504         }
505     }
506     table.rowCount = rowCount;
507     table.columnCount = columnCount;
508     USB_HILOGD(MODULE_USB_SERVICE,
509         "info[%{public}d/%{public}d]: "
510         "%{public}d/%{public}d/%{public}d/%{public}d/%{public}d/%{public}d/%{public}d/%{public}d",
511         rowCount, columnCount, table.primaryKeyIndex, table.uidIndex, table.installTimeIndex, table.updateTimeIndex,
512         table.requestTimeIndex, table.validPeriodIndex, table.deviceNameIndex, table.bundleNameIndex);
513     return USB_RIGHT_OK;
514 }
515 
GetResultRightRecordEx(const std::shared_ptr<OHOS::NativeRdb::ResultSet> & resultSet,std::vector<struct UsbRightAppInfo> & infos)516 int32_t UsbRightDbHelper::GetResultRightRecordEx(
517     const std::shared_ptr<OHOS::NativeRdb::ResultSet> &resultSet, std::vector<struct UsbRightAppInfo> &infos)
518 {
519     struct UsbRightTableInfo table;
520     int32_t ret = GetResultSetTableInfo(resultSet, table);
521     if (ret < USB_RIGHT_OK) {
522         USB_HILOGE(MODULE_USB_SERVICE, "GetResultSetTableInfo failed");
523         return ret;
524     }
525     bool endFlag = false;
526     int32_t primaryKeyId = 0;
527     int64_t installTime = 0;
528     int64_t updateTime = 0;
529     int64_t requestTime = 0;
530     int64_t validPeriod = 0;
531     for (int32_t i = 0; (i < table.rowCount) && !endFlag; i++) {
532         if (resultSet->GoToRow(i) != E_OK) {
533             USB_HILOGE(MODULE_USB_SERVICE, "GoToRow %{public}d", i);
534             break;
535         }
536         struct UsbRightAppInfo info;
537         if (resultSet->GetInt(table.primaryKeyIndex, primaryKeyId) == E_OK &&
538             resultSet->GetInt(table.uidIndex, info.uid) == E_OK &&
539             resultSet->GetLong(table.installTimeIndex, installTime) == E_OK &&
540             resultSet->GetLong(table.updateTimeIndex, updateTime) == E_OK &&
541             resultSet->GetLong(table.requestTimeIndex, requestTime) == E_OK &&
542             resultSet->GetLong(table.validPeriodIndex, validPeriod) == E_OK) {
543             info.primaryKeyId = static_cast<uint32_t>(primaryKeyId);
544             info.installTime = static_cast<uint64_t>(installTime);
545             info.updateTime = static_cast<uint64_t>(updateTime);
546             info.requestTime = static_cast<uint64_t>(requestTime);
547             info.validPeriod = static_cast<uint64_t>(validPeriod);
548             infos.push_back(info);
549         }
550         resultSet->IsEnded(endFlag);
551     }
552     int32_t position = 0;
553     resultSet->GetRowIndex(position);
554     resultSet->IsEnded(endFlag);
555     USB_HILOGD(MODULE_USB_SERVICE, "row=%{public}d col=%{public}d pos=%{public}d ret=%{public}zu end=%{public}s",
556         table.rowCount, table.columnCount, position, infos.size(), (endFlag ? "yes" : "no"));
557     return infos.size();
558 }
559 
AddOrUpdateRightRecord(int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,struct UsbRightAppInfo & info)560 int32_t UsbRightDbHelper::AddOrUpdateRightRecord(int32_t uid, const std::string &deviceName,
561     const std::string &bundleName, const std::string &tokenId, struct UsbRightAppInfo &info)
562 {
563     if (rightDatabase_ == nullptr) {
564         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
565         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
566     }
567     std::lock_guard<std::mutex> guard(databaseMutex_);
568     int32_t ret = rightDatabase_->BeginTransaction();
569     if (ret < USB_RIGHT_OK) {
570         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error: %{public}d", ret);
571         return ret;
572     }
573     bool isUpdate = false;
574     ret = CheckIfNeedUpdateEx(isUpdate, uid, deviceName, bundleName, tokenId);
575     if (ret < USB_RIGHT_OK) {
576         USB_HILOGE(MODULE_USB_SERVICE, "check if need update error: %{public}d", ret);
577         return ret;
578     }
579     ret = AddOrUpdateRightRecordEx(isUpdate, uid, deviceName, bundleName, tokenId, info);
580     if (ret < USB_RIGHT_OK) {
581         USB_HILOGE(MODULE_USB_SERVICE, "add or update error: %{public}d", ret);
582         return ret;
583     }
584     ret = rightDatabase_->Commit();
585     if (ret < USB_RIGHT_OK) {
586         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
587         (void)rightDatabase_->RollBack();
588     }
589     return ret;
590 }
591 
CheckIfNeedUpdateEx(bool & isUpdate,int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId)592 int32_t UsbRightDbHelper::CheckIfNeedUpdateEx(bool &isUpdate, int32_t uid, const std::string &deviceName,
593     const std::string &bundleName, const std::string &tokenId)
594 {
595     if (rightDatabase_ == nullptr) {
596         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
597         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
598     }
599     std::vector<std::string> columns;
600     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
601     rdbPredicates.BeginWrap()
602         ->EqualTo("uid", std::to_string(uid))
603         ->And()
604         ->EqualTo("deviceName", deviceName)
605         ->And()
606         ->EqualTo("bundleName", bundleName)
607         ->And()
608         ->EqualTo("tokenId", tokenId)
609         ->EndWrap();
610     auto resultSet = rightDatabase_->Query(rdbPredicates, columns);
611     if (resultSet == nullptr) {
612         USB_HILOGE(MODULE_USB_SERVICE, "Query error");
613         (void)rightDatabase_->RollBack();
614         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
615     }
616     int32_t rowCount = 0;
617     if (resultSet->GetRowCount(rowCount) != E_OK) {
618         USB_HILOGE(MODULE_USB_SERVICE, "GetRowCount error");
619         (void)rightDatabase_->RollBack();
620         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
621     }
622     isUpdate = (rowCount > 0 ? true : false);
623     return USB_RIGHT_OK;
624 }
625 
AddOrUpdateRightRecordEx(bool isUpdate,int32_t uid,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,struct UsbRightAppInfo & info)626 int32_t UsbRightDbHelper::AddOrUpdateRightRecordEx(bool isUpdate, int32_t uid, const std::string &deviceName,
627     const std::string &bundleName, const std::string &tokenId, struct UsbRightAppInfo &info)
628 {
629     if (rightDatabase_ == nullptr) {
630         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
631         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
632     }
633     int32_t ret = 0;
634     ValuesBucket values;
635     values.Clear();
636     values.PutInt("uid", info.uid);
637     values.PutLong("installTime", info.installTime);
638     values.PutLong("updateTime", info.updateTime);
639     values.PutLong("requestTime", info.requestTime);
640     values.PutLong("validPeriod", info.validPeriod);
641     values.PutString("deviceName", deviceName);
642     values.PutString("bundleName", bundleName);
643     values.PutString("tokenId", tokenId);
644 
645     if (isUpdate) {
646         int32_t changedRows = 0;
647         ret = rightDatabase_->Update(changedRows, values,
648             "uid = ? AND deviceName = ? AND bundleName = ? AND tokenId = ?",
649             std::vector<std::string> {std::to_string(info.uid), deviceName, bundleName, tokenId});
650     } else {
651         ret = rightDatabase_->Insert(values);
652     }
653     if (ret < USB_RIGHT_OK) {
654         USB_HILOGE(MODULE_USB_SERVICE, "Insert or Update error: %{public}d", ret);
655         (void)rightDatabase_->RollBack();
656     }
657     return ret;
658 }
659 
QueryRightRecordCount()660 int32_t UsbRightDbHelper::QueryRightRecordCount()
661 {
662     if (rightDatabase_ == nullptr) {
663         USB_HILOGE(MODULE_USB_SERVICE, "rightDatabase_ is null");
664         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
665     }
666     int32_t ret = rightDatabase_->BeginTransaction();
667     if (ret < USB_RIGHT_OK) {
668         USB_HILOGE(MODULE_USB_SERVICE, "BeginTransaction error :%{public}d", ret);
669         return ret;
670     }
671     std::vector<std::string> columns;
672     RdbPredicates rdbPredicates(USB_RIGHT_TABLE_NAME);
673     auto resultSet = rightDatabase_->Query(rdbPredicates, columns);
674     if (resultSet == nullptr) {
675         USB_HILOGE(MODULE_USB_SERVICE, "Query error");
676         (void)rightDatabase_->RollBack();
677         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
678     }
679     ret = rightDatabase_->Commit();
680     if (ret < USB_RIGHT_OK) {
681         USB_HILOGE(MODULE_USB_SERVICE, "Commit error: %{public}d", ret);
682         (void)rightDatabase_->RollBack();
683         return ret;
684     }
685     int32_t rowCount = 0;
686     if (resultSet->GetRowCount(rowCount) != E_OK) {
687         USB_HILOGE(MODULE_USB_SERVICE, "GetRowCount error");
688         return USB_RIGHT_RDB_EXECUTE_FAILTURE;
689     }
690     return rowCount;
691 }
692 
693 } // namespace USB
694 } // namespace OHOS
695