• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 "pdp_profile_ability.h"
17 
18 #include "ability_context.h"
19 #include "ability_loader.h"
20 #include "abs_rdb_predicates.h"
21 #include "abs_shared_result_set.h"
22 #include "apn_encryption_util.h"
23 #include "core_service_client.h"
24 #include "data_storage_errors.h"
25 #include "data_storage_log_wrapper.h"
26 #include "datashare_ext_ability.h"
27 #include "datashare_predicates.h"
28 #include "new"
29 #include "shared_block.h"
30 #include "pdp_profile_data.h"
31 #include "permission_util.h"
32 #include "preferences_util.h"
33 #include "rdb_errno.h"
34 #include "rdb_utils.h"
35 #include "string_ex.h"
36 #include "telephony_datashare_stub_impl.h"
37 #include "uri.h"
38 #include "utility"
39 
40 namespace OHOS {
41 using AppExecFwk::Ability;
42 using AppExecFwk::AbilityLoader;
43 namespace Telephony {
44 const int32_t CHANGED_ROWS = 0;
45 static const std::map<std::string, PdpProfileUriType> pdpProfileUriMap_ = {
46     { "/net/pdp_profile", PdpProfileUriType::PDP_PROFILE },
47     { "/net/pdp_profile/init", PdpProfileUriType::INIT},
48     { "/net/pdp_profile/reset", PdpProfileUriType::RESET },
49     { "/net/pdp_profile/preferapn", PdpProfileUriType::PREFER_APN },
50     { "/net/pse_base_station", PdpProfileUriType::PSE_BASE_STATION },
51 };
52 
PdpProfileAbility()53 PdpProfileAbility::PdpProfileAbility() : DataShareExtAbility() {}
54 
~PdpProfileAbility()55 PdpProfileAbility::~PdpProfileAbility() {}
56 
Create()57 PdpProfileAbility* PdpProfileAbility::Create()
58 {
59     DATA_STORAGE_LOGD("PdpProfileAbility::Create begin.");
60     auto self =  new PdpProfileAbility();
61     self->DoInit();
62     return self;
63 }
64 
DoInit()65 void PdpProfileAbility::DoInit()
66 {
67     if (initDatabaseDir && initRdbStore) {
68         DATA_STORAGE_LOGE("DoInit has done");
69         return;
70     }
71     auto abilityContext = AbilityRuntime::Context::GetApplicationContext();
72     if (abilityContext == nullptr) {
73         DATA_STORAGE_LOGE("DoInit GetAbilityContext is null");
74         return;
75     }
76     // switch database dir to el1 for init before unlock
77     abilityContext->SwitchArea(0);
78     std::string path = abilityContext->GetDatabaseDir();
79     if (!path.empty()) {
80         initDatabaseDir = true;
81         path.append("/");
82         helper_.UpdateDbPath(path);
83         int rdbInitCode = helper_.Init();
84         if (rdbInitCode == NativeRdb::E_OK) {
85             initRdbStore = true;
86         } else {
87             DATA_STORAGE_LOGE("DoInit rdb init fail!");
88             initRdbStore = false;
89         }
90     } else {
91         DATA_STORAGE_LOGE("DoInit##databaseDir is empty!");
92         initDatabaseDir = false;
93     }
94 }
95 
OnConnect(const AAFwk::Want & want)96 sptr<IRemoteObject> PdpProfileAbility::OnConnect(const AAFwk::Want &want)
97 {
98     DATA_STORAGE_LOGI("PdpProfileAbility %{public}s begin.", __func__);
99     Extension::OnConnect(want);
100     sptr<DataShare::TelephonyDataShareStubImpl> remoteObject =
101         new (std::nothrow) DataShare::TelephonyDataShareStubImpl();
102     if (remoteObject == nullptr) {
103         DATA_STORAGE_LOGE("%{public}s No memory allocated for DataShareStubImpl", __func__);
104         return nullptr;
105     }
106     remoteObject->SetPdpProfileAbility(std::static_pointer_cast<PdpProfileAbility>(shared_from_this()));
107     DATA_STORAGE_LOGI("PdpProfileAbility %{public}s end.", __func__);
108     return remoteObject->AsObject();
109 }
110 
OnStart(const AppExecFwk::Want & want)111 void PdpProfileAbility::OnStart(const AppExecFwk::Want &want)
112 {
113     DATA_STORAGE_LOGI("PdpProfileAbility::OnStart");
114     Extension::OnStart(want);
115     DoInit();
116 }
117 
BatchInsert(const Uri & uri,const std::vector<DataShare::DataShareValuesBucket> & values)118 int PdpProfileAbility::BatchInsert(const Uri &uri, const std::vector<DataShare::DataShareValuesBucket> &values)
119 {
120     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
121         DATA_STORAGE_LOGE("Permission denied!");
122         return DATA_STORAGE_ERR_PERMISSION_ERR;
123     }
124     if (!IsInitOk()) {
125         return DATA_STORAGE_ERROR;
126     }
127     Uri tempUri = uri;
128     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
129     int result = DATA_STORAGE_ERROR;
130     if (pdpProfileUriType == PdpProfileUriType::INIT && !values.empty()) {
131         for (const auto &item : values) {
132             OHOS::NativeRdb::ValuesBucket valuesBucket = RdbDataShareAdapter::RdbUtils::ToValuesBucket(item);
133             int slotId = 0;
134             if (GetIntFromValuesBucket(valuesBucket, "slotId", slotId) != NativeRdb::E_OK) {
135                 continue;
136             }
137             std::string opkey;
138             GetTargetOpkey(slotId, opkey);
139             result = helper_.InitAPNDatabase(slotId, opkey, true);
140             DATA_STORAGE_LOGI(
141                 "PdpProfileAbility::BatchInsert INIT, slotId = %{public}d, result = %{public}d", slotId, result);
142         }
143     }
144     return result;
145 }
146 
GetNativeData(std::shared_ptr<DataShare::DataShareResultSet> resultSet,int columnIndex,NativeData & data)147 int PdpProfileAbility::GetNativeData(std::shared_ptr<DataShare::DataShareResultSet> resultSet,
148     int columnIndex, NativeData &data)
149 {
150     int64_t valueInt;
151     double_t valueDouble;
152     std::string valueStr;
153     std::vector<uint8_t> blob;
154     DataShare::DataType dataType;
155     int errCode = resultSet->GetDataType(columnIndex, dataType);
156     DATA_STORAGE_LOGI("dataType %{public}d.", dataType);
157     if (errCode != 0) {
158         DATA_STORAGE_LOGE("GetDataType fail");
159         return errCode;
160     }
161     switch (dataType) {
162         case DataShare::DataType::TYPE_INTEGER:
163             errCode = resultSet->GetLong(columnIndex, valueInt);
164             if (errCode != 0) {
165                 return errCode;
166             }
167             data = valueInt;
168             break;
169         case DataShare::DataType::TYPE_FLOAT:
170             errCode = resultSet->GetDouble(columnIndex, valueDouble);
171             if (errCode != 0) {
172                 return errCode;
173             }
174             data = valueDouble;
175             break;
176         case DataShare::DataType::TYPE_STRING:
177             errCode = resultSet->GetString(columnIndex, valueStr);
178             if (errCode != 0) {
179                 return errCode;
180             }
181             data = valueStr;
182             break;
183         case DataShare::DataType::TYPE_BLOB:
184             errCode = resultSet->GetBlob(columnIndex, blob);
185             if (errCode != 0) {
186                 return errCode;
187             }
188             data = blob;
189             break;
190         case DataShare::DataType::TYPE_NULL:
191         default:
192             data = std::monostate{};
193             break;
194     }
195     return errCode;
196 }
197 
ToNativeDataSet(std::shared_ptr<DataShare::DataShareResultSet> resultSet,NativeDataSet & dataSet)198 int PdpProfileAbility::ToNativeDataSet(
199     std::shared_ptr<DataShare::DataShareResultSet> resultSet, NativeDataSet &dataSet)
200 {
201     int errCode = 0;
202     int rowCount = 0;
203     errCode = resultSet->GetAllColumnNames(dataSet.columnNames);
204     const auto &columnNames = dataSet.columnNames;
205     if (errCode != 0) {
206         DATA_STORAGE_LOGE("GetAllColumnNames fail");
207         return errCode;
208     }
209     std::vector<int> columnIndexes(columnNames.size());
210     int columnIndex;
211     for (size_t i = 0; i < columnNames.size(); ++i) {
212         errCode = resultSet->GetColumnIndex(columnNames[i], columnIndex);
213         if (errCode != 0) {
214             DATA_STORAGE_LOGE("GetColumnIndex fail");
215             return errCode;
216         }
217         columnIndexes[i] = columnIndex; // Assert the comlun index will not change.
218     }
219     errCode = resultSet->GetRowCount(rowCount);
220     if (errCode != 0) {
221         DATA_STORAGE_LOGE("GetRowCount fail");
222         return errCode;
223     }
224     dataSet.records = {};
225     dataSet.records.resize(rowCount);
226     for (int i = 0; i < rowCount; ++i) {
227         auto &record = dataSet.records[i];
228         record.resize(columnNames.size());
229         errCode = resultSet->GoToRow(i);
230         if (errCode != 0) {
231             DATA_STORAGE_LOGE("GoToRow fail");
232             return errCode;
233         }
234         for (size_t j = 0; j < columnNames.size(); ++j) {
235             columnIndex = columnIndexes[j];
236             NativeData data;
237             errCode = GetNativeData(resultSet, columnIndex, data);
238             if (errCode != 0) {
239                 DATA_STORAGE_LOGE("GetNativeData fail");
240                 return errCode;
241             }
242             record[columnIndex] = data;
243         }
244     }
245     return errCode;
246 }
247 
NeedUpdatePdpSharedPtrResult(std::shared_ptr<DataShare::DataShareResultSet> sharedPtrResult,bool & isNeedUpdate)248 std::shared_ptr<DataShare::DataShareResultSet> PdpProfileAbility::NeedUpdatePdpSharedPtrResult(
249     std::shared_ptr<DataShare::DataShareResultSet> sharedPtrResult, bool &isNeedUpdate)
250 {
251     isNeedUpdate = false;
252     if (sharedPtrResult == nullptr) {
253         return nullptr;
254     }
255     std::vector<std::string> columnNames;
256     int errCode = sharedPtrResult->GetAllColumnNames(columnNames);
257     if (errCode != 0) {
258         return nullptr;
259     }
260     auto editedIter = std::find(columnNames.cbegin(), columnNames.cend(), "edited");
261     auto iter = std::find(columnNames.cbegin(), columnNames.cend(), "auth_pwd");
262     if (iter == columnNames.cend() || editedIter == columnNames.cend()) {
263         return nullptr;
264     }
265     auto editedIndex = editedIter - columnNames.cbegin();
266     auto replaceIndex = iter - columnNames.cbegin();
267     NativeDataSet dataSet;
268     errCode = ToNativeDataSet(sharedPtrResult, dataSet);
269     if (errCode != 0) {
270         return nullptr;
271     }
272     NativeDataSet resultDataSet;
273     resultDataSet.columnNames = columnNames;
274     for (auto &record : dataSet.records) {
275         NativeData *stringData = &record[replaceIndex];
276         std::string pwdStr;
277         if (auto ptr = std::get_if<std::string>(stringData); ptr != nullptr) {
278             pwdStr = *ptr;
279         }
280         NativeData *editedStatus = &record[editedIndex];
281         int64_t edited = 0;
282         if (auto ptr = std::get_if<int64_t>(editedStatus); ptr != nullptr) {
283             edited =  *ptr;
284         }
285         if (edited != 0 && !pwdStr.empty()) {
286             isNeedUpdate = true;
287             DATA_STORAGE_LOGI("NeedUpdatePdpSharedPtrResult isNeedUpdate is true");
288             NativeData dePwdNativeData = DecryptData(pwdStr);
289             record[replaceIndex] = dePwdNativeData;
290         }
291         resultDataSet.records.emplace_back(record);
292     }
293     std::shared_ptr<DataShare::ResultSetBridge> resultSetNew =  std::make_shared<PdpResultSetBridge>(resultDataSet);
294     return std::make_shared<DataShare::DataShareResultSet>(resultSetNew);
295 }
296 
NeedUpdateValuesBucket(const DataShare::DataShareValuesBucket & valuesBucket,DataShare::DataShareValuesBucket & newValuesBucket)297 bool PdpProfileAbility::NeedUpdateValuesBucket(const DataShare::DataShareValuesBucket &valuesBucket,
298     DataShare::DataShareValuesBucket &newValuesBucket)
299 {
300     bool isValid = false;
301     std::map<std::string, DataShare::DataShareValueObject::Type> valuesMapNew;
302     std::string ahtuPwdKey(PdpProfileData::AUTH_PWD);
303     DataShare::DataShareValueObject authPwdKeyObject = valuesBucket.Get(ahtuPwdKey, isValid);
304     if (!isValid) {
305         DATA_STORAGE_LOGE("NeedUpdateValuesBucket not find AUTH_PWD");
306         return false;
307     }
308     std::string pwdStr = authPwdKeyObject;
309     std::string encryptData;
310     if (pwdStr.empty()) {
311         return false;
312     } else {
313         DATA_STORAGE_LOGI("NeedUpdateValuesBucket AUTH_PWD is not empty");
314         encryptData = EncryptData(pwdStr);
315     }
316 
317     for (auto &[k, v] : valuesBucket.valuesMap) {
318         if (strcmp(k.c_str(), PdpProfileData::AUTH_PWD) == 0) {
319             valuesMapNew.insert(std::make_pair(k, encryptData));
320         } else {
321             valuesMapNew.insert(std::make_pair(k, v));
322         }
323     }
324     newValuesBucket = DataShare::DataShareValuesBucket(valuesMapNew);
325     return true;
326 }
327 
Insert(const Uri & uri,const DataShare::DataShareValuesBucket & value)328 int PdpProfileAbility::Insert(const Uri &uri, const DataShare::DataShareValuesBucket &value)
329 {
330     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
331         DATA_STORAGE_LOGE("Permission denied!");
332         return DATA_STORAGE_ERR_PERMISSION_ERR;
333     }
334     if (!IsInitOk()) {
335         return DATA_STORAGE_ERROR;
336     }
337     std::lock_guard<std::mutex> guard(lock_);
338     Uri tempUri = uri;
339     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
340     int64_t id = DATA_STORAGE_ERROR;
341     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
342         DataShare::DataShareValuesBucket newValue;
343         bool useNewBucket = NeedUpdateValuesBucket(value, newValue);
344         OHOS::NativeRdb::ValuesBucket values = useNewBucket ? RdbDataShareAdapter::RdbUtils::ToValuesBucket(newValue)
345             : RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
346         helper_.Insert(id, values, TABLE_PDP_PROFILE);
347     } else if (pdpProfileUriType == PdpProfileUriType::PSE_BASE_STATION) {
348         OHOS::NativeRdb::ValuesBucket values = RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
349         helper_.Insert(id, values, TABLE_PSE_BASE_STATION);
350     } else {
351         DATA_STORAGE_LOGE("PdpProfileAbility::Insert##uri = %{public}s", uri.ToString().c_str());
352     }
353     return id;
354 }
355 
GetQueryKey(const std::string & queryString,const std::string & key)356 std::string PdpProfileAbility::GetQueryKey(const std::string &queryString, const std::string &key)
357 {
358     size_t pos = queryString.find(key);
359     if (pos != std::string::npos) {
360         return queryString.substr(pos + key.length());
361     }
362     return "";
363 }
364 
GetPreferApn(const std::string & queryString)365 int PdpProfileAbility::GetPreferApn(const std::string &queryString)
366 {
367     auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
368     if (preferencesUtil == nullptr) {
369         DATA_STORAGE_LOGE("preferencesUtil is nullptr!");
370         return NativePreferences::E_ERROR;
371     }
372     int preferApnId = preferencesUtil->ObtainInt(PREFER_APN_ID + GetQueryKey(queryString, "simId="),
373                                                  INVALID_PROFILE_ID);
374     DATA_STORAGE_LOGI("%{public}d.", preferApnId);
375     return preferApnId;
376 }
377 
SetPreferApn(int simId,int profileId)378 int PdpProfileAbility::SetPreferApn(int simId, int profileId)
379 {
380     auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
381     if (preferencesUtil == nullptr) {
382         DATA_STORAGE_LOGE("preferencesUtil is nullptr!");
383         return NativePreferences::E_ERROR;
384     }
385     DATA_STORAGE_LOGI("simId:%{public}d profileId:%{public}d", simId, profileId);
386     return preferencesUtil->SaveInt(PREFER_APN_ID + std::to_string(simId), profileId);
387 }
388 
Query(const Uri & uri,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns,DataShare::DatashareBusinessError & businessError)389 std::shared_ptr<DataShare::DataShareResultSet> PdpProfileAbility::Query(const Uri &uri,
390     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns,
391     DataShare::DatashareBusinessError &businessError)
392 {
393     if (!PermissionUtil::CheckPermission(Permission::GET_TELEPHONY_STATE)) {
394         DATA_STORAGE_LOGE("Permission denied!");
395         return nullptr;
396     }
397     std::shared_ptr<DataShare::DataShareResultSet> sharedPtrResult = nullptr;
398     if (!IsInitOk()) {
399         return nullptr;
400     }
401     Uri tempUri = uri;
402     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
403     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE || pdpProfileUriType == PdpProfileUriType::PREFER_APN) {
404         NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
405         if (absRdbPredicates == nullptr) {
406             DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::AbsRdbPredicates is null!");
407             return sharedPtrResult;
408         }
409         std::shared_ptr<NativeRdb::ResultSet> result = nullptr;
410         if (pdpProfileUriType == PdpProfileUriType::PREFER_APN) {
411             DataShare::DataSharePredicates preferapnPredicates;
412             preferapnPredicates.EqualTo(PdpProfileData::PROFILE_ID, GetPreferApn(tempUri.GetQuery()));
413             result = helper_.Query(ConvertPredicates(absRdbPredicates->GetTableName(), preferapnPredicates), columns);
414         } else if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
415             result = QueryPdpProfile(tempUri, absRdbPredicates->GetTableName(), predicates, columns);
416         }
417         if (result == nullptr) {
418             DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::ResultSet is null!");
419             delete absRdbPredicates;
420             return nullptr;
421         }
422         auto queryResultSet = RdbDataShareAdapter::RdbUtils::ToResultSetBridge(result);
423         sharedPtrResult = std::make_shared<DataShare::DataShareResultSet>(queryResultSet);
424         delete absRdbPredicates;
425         bool needUpdate = false;
426         std::shared_ptr<DataShare::DataShareResultSet> newSharedPtrResult =
427             NeedUpdatePdpSharedPtrResult(sharedPtrResult, needUpdate);
428         return needUpdate ? newSharedPtrResult : sharedPtrResult;
429     } else if (pdpProfileUriType == PdpProfileUriType::PSE_BASE_STATION) {
430         return QueryPseBaseStation(uri, predicates, columns);
431     }
432     DATA_STORAGE_LOGE("PdpProfileAbility::Query##uri = %{public}s", uri.ToString().c_str());
433     return sharedPtrResult;
434 }
435 
Update(const Uri & uri,const DataShare::DataSharePredicates & predicates,const DataShare::DataShareValuesBucket & value)436 int PdpProfileAbility::Update(const Uri &uri, const DataShare::DataSharePredicates &predicates,
437     const DataShare::DataShareValuesBucket &value)
438 {
439     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
440         DATA_STORAGE_LOGE("Permission denied!");
441         return DATA_STORAGE_ERR_PERMISSION_ERR;
442     }
443     int result = DATA_STORAGE_ERROR;
444     if (!IsInitOk()) {
445         return result;
446     }
447     std::lock_guard<std::mutex> guard(lock_);
448     Uri tempUri = uri;
449     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
450     NativeRdb::AbsRdbPredicates *absRdbPredicates = CreateAbsRdbPredicates(pdpProfileUriType);
451     switch (pdpProfileUriType) {
452         case PdpProfileUriType::PDP_PROFILE:
453         case PdpProfileUriType::PSE_BASE_STATION:
454             break;
455         case PdpProfileUriType::RESET: {
456             result = ResetApn(value);
457             if (result != NativeRdb::E_OK) {
458                 DATA_STORAGE_LOGE("PdpProfileAbility::Update  ResetApn fail!");
459                 result = static_cast<int>(LoadProFileErrorType::RESET_APN_FAIL);
460             }
461             break;
462         }
463         case PdpProfileUriType::PREFER_APN: {
464             result = (UpdatePreferApn(value) == NativeRdb::E_OK) ? NativeRdb::E_OK
465                          : static_cast<int>(LoadProFileErrorType::PREFER_APN_FAIL);
466             break;
467         }
468         default:
469             DATA_STORAGE_LOGE("PdpProfileAbility::Update##uri = %{public}s", uri.ToString().c_str());
470             break;
471     }
472     if (absRdbPredicates != nullptr) {
473         int changedRows = CHANGED_ROWS;
474         NativeRdb::RdbPredicates rdbPredicates = ConvertPredicates(absRdbPredicates->GetTableName(), predicates);
475         DataShare::DataShareValuesBucket newValue;
476         bool useNewBucket = NeedUpdateValuesBucket(value, newValue);
477         OHOS::NativeRdb::ValuesBucket values = useNewBucket ? RdbDataShareAdapter::RdbUtils::ToValuesBucket(newValue)
478             : RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
479         result = helper_.Update(changedRows, values, rdbPredicates);
480         delete absRdbPredicates;
481         absRdbPredicates = nullptr;
482     } else if (result == DATA_STORAGE_ERROR) {
483         DATA_STORAGE_LOGE("PdpProfileAbility::Update  NativeRdb::AbsRdbPredicates is null!");
484     }
485     return result;
486 }
487 
UpdatePreferApn(const DataShare::DataShareValuesBucket & sharedValue)488 int PdpProfileAbility::UpdatePreferApn(const DataShare::DataShareValuesBucket &sharedValue)
489 {
490     OHOS::NativeRdb::ValuesBucket value = RdbDataShareAdapter::RdbUtils::ToValuesBucket(sharedValue);
491     int result = DATA_STORAGE_ERROR;
492     NativeRdb::ValueObject valueObject;
493     if (!HasColumnValue(value, PdpProfileData::PROFILE_ID, valueObject)) {
494         return result;
495     }
496     double temp = 0;
497     int profileId = INVALID_PROFILE_ID;
498     if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
499         profileId = ceil(temp);
500     }
501     if (!HasColumnValue(value, PdpProfileData::SIM_ID, valueObject)) {
502         return result;
503     }
504     int simId = DEFAULT_SIM_ID;
505     if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
506         simId = ceil(temp);
507     }
508     return SetPreferApn(simId, profileId);
509 }
510 
HasColumnValue(const OHOS::NativeRdb::ValuesBucket & value,const char * columnName,NativeRdb::ValueObject & valueObject)511 bool PdpProfileAbility::HasColumnValue(
512     const OHOS::NativeRdb::ValuesBucket &value, const char *columnName, NativeRdb::ValueObject &valueObject)
513 {
514     if (!value.HasColumn(columnName)) {
515         DATA_STORAGE_LOGE("the column in valuesBucket does not exist!");
516         return false;
517     }
518     bool isExistValue = value.GetObject(columnName, valueObject);
519     if (!isExistValue) {
520         DATA_STORAGE_LOGE("failed to get value in valuesBucket!");
521         return false;
522     }
523     return true;
524 }
525 
Delete(const Uri & uri,const DataShare::DataSharePredicates & predicates)526 int PdpProfileAbility::Delete(const Uri &uri, const DataShare::DataSharePredicates &predicates)
527 {
528     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
529         DATA_STORAGE_LOGE("Permission denied!");
530         return DATA_STORAGE_ERR_PERMISSION_ERR;
531     }
532     int result = DATA_STORAGE_ERROR;
533     if (!IsInitOk()) {
534         return result;
535     }
536     std::lock_guard<std::mutex> guard(lock_);
537     Uri tempUri = uri;
538     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
539     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
540         NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
541         if (absRdbPredicates != nullptr) {
542             NativeRdb::RdbPredicates rdbPredicates = ConvertPredicates(absRdbPredicates->GetTableName(), predicates);
543             int deletedRows = CHANGED_ROWS;
544             result = helper_.Delete(deletedRows, rdbPredicates);
545             delete absRdbPredicates;
546             absRdbPredicates = nullptr;
547         } else {
548             DATA_STORAGE_LOGE("PdpProfileAbility::Delete  NativeRdb::AbsRdbPredicates is null!");
549         }
550     } else {
551         DATA_STORAGE_LOGI("PdpProfileAbility::Delete##uri = %{public}s", uri.ToString().c_str());
552     }
553     return result;
554 }
555 
IsInitOk()556 bool PdpProfileAbility::IsInitOk()
557 {
558     if (!initDatabaseDir) {
559         DATA_STORAGE_LOGE("PdpProfileAbility::IsInitOk initDatabaseDir failed!");
560         return false;
561     }
562     if (!initRdbStore) {
563         DATA_STORAGE_LOGE("PdpProfileAbility::IsInitOk initRdbStore failed!");
564         return false;
565     }
566     return true;
567 }
568 
GetType(const Uri & uri)569 std::string PdpProfileAbility::GetType(const Uri &uri)
570 {
571     DATA_STORAGE_LOGI("PdpProfileAbility::GetType##uri = %{public}s", uri.ToString().c_str());
572     std::string retval(uri.ToString());
573     return retval;
574 }
575 
OpenFile(const Uri & uri,const std::string & mode)576 int PdpProfileAbility::OpenFile(const Uri &uri, const std::string &mode)
577 {
578     DATA_STORAGE_LOGI("PdpProfileAbility::OpenFile##uri = %{public}s", uri.ToString().c_str());
579     Uri tempUri = uri;
580     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
581     return static_cast<int>(pdpProfileUriType);
582 }
583 
ParseUriType(Uri & uri)584 PdpProfileUriType PdpProfileAbility::ParseUriType(Uri &uri)
585 {
586     DATA_STORAGE_LOGD("PdpProfileAbility::ParseUriType start");
587     PdpProfileUriType pdpProfileUriType = PdpProfileUriType::UNKNOW;
588     std::string uriPath = uri.ToString();
589     if (!uriPath.empty()) {
590         helper_.ReplaceAllStr(uriPath, ":///", "://");
591         Uri tempUri(uriPath);
592         std::string path = tempUri.GetPath();
593         if (!path.empty() && !pdpProfileUriMap_.empty()) {
594             auto it = pdpProfileUriMap_.find(path);
595             if (it != pdpProfileUriMap_.end()) {
596                 pdpProfileUriType = it->second;
597                 DATA_STORAGE_LOGD("PdpProfileAbility::ParseUriType##pdpProfileUriType = %{public}d",
598                     pdpProfileUriType);
599             }
600         }
601     }
602     return pdpProfileUriType;
603 }
604 
ConvertPredicates(const std::string & tableName,const DataShare::DataSharePredicates & predicates)605 OHOS::NativeRdb::RdbPredicates PdpProfileAbility::ConvertPredicates(
606     const std::string &tableName, const DataShare::DataSharePredicates &predicates)
607 {
608     OHOS::NativeRdb::RdbPredicates res = RdbDataShareAdapter::RdbUtils::ToPredicates(predicates, tableName);
609     return res;
610 }
611 
QueryPdpProfile(Uri & uri,const std::string & tableName,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns)612 std::shared_ptr<NativeRdb::ResultSet> PdpProfileAbility::QueryPdpProfile(Uri &uri, const std::string &tableName,
613     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns)
614 {
615     const std::string &simIdStr = GetQueryKey(uri.GetQuery(), "simId=");
616     std::string opkey;
617     int simId = DEFAULT_SIM_ID;
618     if (StrToInt(simIdStr, simId)) {
619         int32_t slotId = DelayedRefSingleton<CoreServiceClient>::GetInstance().GetSlotId(simId);
620         GetTargetOpkey(slotId, opkey);
621     }
622     if (opkey.empty() || strcmp(opkey.c_str(), INVALID_OPKEY) == 0) {
623         return helper_.Query(ConvertPredicates(tableName, predicates), columns);
624     }
625     constexpr int32_t FIELD_IDX = 0;
626     auto &operations = predicates.GetOperationList();
627     std::vector<DataShare::OperationItem> operationsRes;
628     bool isMccMnc = false;
629     for (const auto &oper : operations) {
630         if (oper.singleParams.empty()) {
631             operationsRes.push_back(oper);
632             continue;
633         }
634         std::string filed = static_cast<std::string>(oper.GetSingle(FIELD_IDX));
635         if (strcmp(filed.c_str(), PdpProfileData::MCCMNC) == 0 && oper.operation == DataShare::EQUAL_TO) {
636             isMccMnc = true;
637             operationsRes.push_back({DataShare::EQUAL_TO, {PdpProfileData::OPKEY, opkey}});
638             continue;
639         }
640         operationsRes.push_back(oper);
641     }
642     DATA_STORAGE_LOGI(
643         "PdpProfileAbility::QueryPdpProfile, simId= %{public}d, isMccMnc= %{public}d", simId, isMccMnc);
644     if (isMccMnc) {
645         const std::shared_ptr<NativeRdb::ResultSet> &result =
646             helper_.Query(ConvertPredicates(tableName, DataShare::DataSharePredicates(move(operationsRes))), columns);
647         if (result != nullptr) {
648             int count = 0;
649             result->GetRowCount(count);
650             DATA_STORAGE_LOGI("PdpProfileAbility::QueryPdpProfile, count= %{public}d", count);
651             if (count > 0) {
652                 return result;
653             }
654         }
655     }
656     return helper_.Query(ConvertPredicates(tableName, predicates), columns);
657 }
658 
ResetApn(const DataShare::DataShareValuesBucket & valuesBucket)659 int PdpProfileAbility::ResetApn(const DataShare::DataShareValuesBucket &valuesBucket)
660 {
661     OHOS::NativeRdb::ValuesBucket values = RdbDataShareAdapter::RdbUtils::ToValuesBucket(valuesBucket);
662     int simId = DEFAULT_SIM_ID;
663     if (GetIntFromValuesBucket(values, "simId", simId) != NativeRdb::E_OK) {
664         DATA_STORAGE_LOGE("PdpProfileAbility::ResetApn no simId!");
665         return helper_.ResetApn();
666     }
667     int32_t slotId = DelayedRefSingleton<CoreServiceClient>::GetInstance().GetSlotId(simId);
668     std::string opkey;
669     GetTargetOpkey(slotId, opkey);
670     if (opkey.empty() || strcmp(opkey.c_str(), INVALID_OPKEY) == 0) {
671         DATA_STORAGE_LOGW("PdpProfileAbility::ResetApn opkey empty!");
672         return helper_.ResetApn();
673     }
674     DATA_STORAGE_LOGI("PdpProfileAbility::ResetApn##simId = %{public}d", simId);
675     SetPreferApn(simId, -1);
676     NativeRdb::RdbPredicates rdbPredicates(TABLE_PDP_PROFILE);
677     rdbPredicates.EqualTo(PdpProfileData::OPKEY, opkey);
678     int deletedRows = CHANGED_ROWS;
679     helper_.Delete(deletedRows, rdbPredicates);
680     int result = helper_.InitAPNDatabase(slotId, opkey, false);
681     if (result != NativeRdb::E_OK) {
682         DATA_STORAGE_LOGE("PdpProfileAbility::ResetApn fail!");
683         result = static_cast<int>(LoadProFileErrorType::RESET_APN_FAIL);
684     }
685     return result;
686 }
687 
GetIntFromValuesBucket(OHOS::NativeRdb::ValuesBucket & bucket,const char * key,int & value)688 int PdpProfileAbility::GetIntFromValuesBucket(OHOS::NativeRdb::ValuesBucket &bucket, const char *key, int &value)
689 {
690     NativeRdb::ValueObject valueObject;
691     if (!HasColumnValue(bucket, key, valueObject)) {
692         return OPERATION_ERROR;
693     }
694     if (valueObject.GetType() == NativeRdb::ValueObject::TYPE_INT) {
695         return valueObject.GetInt(value);
696     }
697     if (valueObject.GetType() == NativeRdb::ValueObject::TYPE_DOUBLE) {
698         double temp = 0;
699         if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
700             value = ceil(temp);
701             return NativeRdb::E_OK;
702         }
703     }
704     return OPERATION_ERROR;
705 }
706 
GetTargetOpkey(int slotId,std::string & opkey)707 void PdpProfileAbility::GetTargetOpkey(int slotId, std::string &opkey)
708 {
709     std::u16string opkeyU16;
710     DelayedRefSingleton<CoreServiceClient>::GetInstance().GetTargetOpkey(slotId, opkeyU16);
711     opkey = Str16ToStr8(opkeyU16);
712     DATA_STORAGE_LOGI(
713         "PdpProfileAbility::GetTargetOpkey##slotId = %{public}d, opkey = %{public}s", slotId, opkey.c_str());
714 }
715 
QueryPseBaseStation(const Uri & uri,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns)716 std::shared_ptr<DataShare::DataShareResultSet> PdpProfileAbility::QueryPseBaseStation(const Uri &uri,
717     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns)
718 {
719     DATA_STORAGE_LOGI("query PSE_BASE_STATION");
720     NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PSE_BASE_STATION);
721     if (absRdbPredicates == nullptr) {
722         DATA_STORAGE_LOGE("PdpProfileAbility::Query NativeRdb::AbsRdbPredicates is null!");
723         return nullptr;
724     }
725     std::shared_ptr<NativeRdb::ResultSet> result = nullptr;
726     result = helper_.Query(ConvertPredicates(absRdbPredicates->GetTableName(), predicates), columns);
727     if (result == nullptr) {
728         DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::ResultSet is null!");
729         delete absRdbPredicates;
730         return nullptr;
731     }
732     auto queryResultSet = RdbDataShareAdapter::RdbUtils::ToResultSetBridge(result);
733     auto sharedPtrResult = std::make_shared<DataShare::DataShareResultSet>(queryResultSet);
734     delete absRdbPredicates;
735     return sharedPtrResult;
736 }
737 
CreateAbsRdbPredicates(PdpProfileUriType type)738 NativeRdb::AbsRdbPredicates* PdpProfileAbility::CreateAbsRdbPredicates(PdpProfileUriType type)
739 {
740     NativeRdb::AbsRdbPredicates *absRdbPredicates = nullptr;
741     switch (type) {
742         case PdpProfileUriType::PDP_PROFILE:
743             absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
744             break;
745         case PdpProfileUriType::PSE_BASE_STATION:
746             absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PSE_BASE_STATION);
747             break;
748         default:
749             break;
750     }
751     return absRdbPredicates;
752 }
753 } // namespace Telephony
754 } // namespace OHOS
755