• 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     if (sharedPtrResult->GetAllColumnNames(columnNames) != 0) {
257         return nullptr;
258     }
259     auto editedIter = std::find(columnNames.cbegin(), columnNames.cend(), "edited");
260     auto iter = std::find(columnNames.cbegin(), columnNames.cend(), "auth_pwd");
261     if (iter == columnNames.cend() || editedIter == columnNames.cend()) {
262         return nullptr;
263     }
264     auto editedIndex = editedIter - columnNames.cbegin();
265     auto replaceIndex = iter - columnNames.cbegin();
266     NativeDataSet dataSet;
267     if (ToNativeDataSet(sharedPtrResult, dataSet) != 0) {
268         return nullptr;
269     }
270     NativeDataSet resultDataSet;
271     resultDataSet.columnNames = columnNames;
272     for (auto &record : dataSet.records) {
273         NativeData *stringData = &record[replaceIndex];
274         std::string pwdStr;
275         std::vector<uint8_t> pwdVec;
276         if (auto ptr = std::get_if<std::string>(stringData); ptr != nullptr) {
277             pwdStr = *ptr;
278         } else if (auto ptr = std::get_if<std::vector<uint8_t>>(stringData); ptr != nullptr) {
279             pwdVec = *ptr;
280         }
281         NativeData *editedStatus = &record[editedIndex];
282         int64_t edited = 0;
283         if (auto ptr = std::get_if<int64_t>(editedStatus); ptr != nullptr) {
284             edited =  *ptr;
285         }
286         if (edited != 0 && !pwdStr.empty()) {
287             isNeedUpdate = true;
288             NativeData dePwdNativeData = DecryptData(pwdStr);
289             record[replaceIndex] = dePwdNativeData;
290         } else if (edited != 0 && (pwdVec.size() != 0)) {
291             isNeedUpdate = true;
292             NativeData dePwdNativeData = DecryptUintVecData(pwdVec);
293             record[replaceIndex] = dePwdNativeData;
294         }
295         resultDataSet.records.emplace_back(record);
296     }
297     std::shared_ptr<DataShare::ResultSetBridge> resultSetNew =  std::make_shared<PdpResultSetBridge>(resultDataSet);
298     return std::make_shared<DataShare::DataShareResultSet>(resultSetNew);
299 }
300 
NeedUpdateValuesBucket(const DataShare::DataShareValuesBucket & valuesBucket,DataShare::DataShareValuesBucket & newValuesBucket)301 bool PdpProfileAbility::NeedUpdateValuesBucket(const DataShare::DataShareValuesBucket &valuesBucket,
302     DataShare::DataShareValuesBucket &newValuesBucket)
303 {
304     bool isValid = false;
305     std::map<std::string, DataShare::DataShareValueObject::Type> valuesMapNew;
306     std::string ahtuPwdKey(PdpProfileData::AUTH_PWD);
307     DataShare::DataShareValueObject authPwdKeyObject = valuesBucket.Get(ahtuPwdKey, isValid);
308     if (!isValid) {
309         DATA_STORAGE_LOGE("NeedUpdateValuesBucket not find AUTH_PWD");
310         return false;
311     }
312     std::string pwdStr = authPwdKeyObject;
313     std::vector<uint8_t> encryptData;
314     if (pwdStr.empty()) {
315         return false;
316     }
317     DATA_STORAGE_LOGI("NeedUpdateValuesBucket AUTH_PWD is not empty");
318     encryptData = EncryptData(pwdStr);
319 
320     for (auto &[k, v] : valuesBucket.valuesMap) {
321         if (strcmp(k.c_str(), PdpProfileData::AUTH_PWD) == 0) {
322             valuesMapNew.insert(std::make_pair(k, encryptData));
323         } else {
324             valuesMapNew.insert(std::make_pair(k, v));
325         }
326     }
327     newValuesBucket = DataShare::DataShareValuesBucket(valuesMapNew);
328     return true;
329 }
330 
Insert(const Uri & uri,const DataShare::DataShareValuesBucket & value)331 int PdpProfileAbility::Insert(const Uri &uri, const DataShare::DataShareValuesBucket &value)
332 {
333     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
334         DATA_STORAGE_LOGE("Permission denied!");
335         return DATA_STORAGE_ERR_PERMISSION_ERR;
336     }
337     if (!IsInitOk()) {
338         return DATA_STORAGE_ERROR;
339     }
340     std::lock_guard<std::mutex> guard(lock_);
341     Uri tempUri = uri;
342     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
343     int64_t id = DATA_STORAGE_ERROR;
344     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
345         DataShare::DataShareValuesBucket newValue;
346         bool useNewBucket = NeedUpdateValuesBucket(value, newValue);
347         OHOS::NativeRdb::ValuesBucket values = useNewBucket ? RdbDataShareAdapter::RdbUtils::ToValuesBucket(newValue)
348             : RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
349         helper_.Insert(id, values, TABLE_PDP_PROFILE);
350     } else if (pdpProfileUriType == PdpProfileUriType::PSE_BASE_STATION) {
351         OHOS::NativeRdb::ValuesBucket values = RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
352         helper_.Insert(id, values, TABLE_PSE_BASE_STATION);
353     } else {
354         DATA_STORAGE_LOGE("PdpProfileAbility::Insert##uri = %{public}s", uri.ToString().c_str());
355     }
356     return id;
357 }
358 
GetQueryKey(const std::string & queryString,const std::string & key)359 std::string PdpProfileAbility::GetQueryKey(const std::string &queryString, const std::string &key)
360 {
361     size_t pos = queryString.find(key);
362     if (pos != std::string::npos) {
363         return queryString.substr(pos + key.length());
364     }
365     return "";
366 }
367 
GetPreferApn(const std::string & queryString)368 int PdpProfileAbility::GetPreferApn(const std::string &queryString)
369 {
370     auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
371     if (preferencesUtil == nullptr) {
372         DATA_STORAGE_LOGE("preferencesUtil is nullptr!");
373         return NativePreferences::E_ERROR;
374     }
375     int preferApnId = preferencesUtil->ObtainInt(PREFER_APN_ID + GetQueryKey(queryString, "simId="),
376                                                  INVALID_PROFILE_ID);
377     DATA_STORAGE_LOGI("%{public}d.", preferApnId);
378     return preferApnId;
379 }
380 
SetPreferApn(int simId,int profileId)381 int PdpProfileAbility::SetPreferApn(int simId, int profileId)
382 {
383     auto preferencesUtil = DelayedSingleton<PreferencesUtil>::GetInstance();
384     if (preferencesUtil == nullptr) {
385         DATA_STORAGE_LOGE("preferencesUtil is nullptr!");
386         return NativePreferences::E_ERROR;
387     }
388     DATA_STORAGE_LOGI("simId:%{public}d profileId:%{public}d", simId, profileId);
389     return preferencesUtil->SaveInt(PREFER_APN_ID + std::to_string(simId), profileId);
390 }
391 
Query(const Uri & uri,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns,DataShare::DatashareBusinessError & businessError)392 std::shared_ptr<DataShare::DataShareResultSet> PdpProfileAbility::Query(const Uri &uri,
393     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns,
394     DataShare::DatashareBusinessError &businessError)
395 {
396     if (!PermissionUtil::CheckPermission(Permission::GET_TELEPHONY_STATE)) {
397         DATA_STORAGE_LOGE("Permission denied!");
398         return nullptr;
399     }
400     std::shared_ptr<DataShare::DataShareResultSet> sharedPtrResult = nullptr;
401     if (!IsInitOk()) {
402         return nullptr;
403     }
404     Uri tempUri = uri;
405     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
406     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE || pdpProfileUriType == PdpProfileUriType::PREFER_APN) {
407         NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
408         if (absRdbPredicates == nullptr) {
409             DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::AbsRdbPredicates is null!");
410             return sharedPtrResult;
411         }
412         std::shared_ptr<NativeRdb::ResultSet> result = nullptr;
413         if (pdpProfileUriType == PdpProfileUriType::PREFER_APN) {
414             DataShare::DataSharePredicates preferapnPredicates;
415             preferapnPredicates.EqualTo(PdpProfileData::PROFILE_ID, GetPreferApn(tempUri.GetQuery()));
416             result = helper_.Query(ConvertPredicates(absRdbPredicates->GetTableName(), preferapnPredicates), columns);
417         } else if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
418             result = QueryPdpProfile(tempUri, absRdbPredicates->GetTableName(), predicates, columns);
419         }
420         if (result == nullptr) {
421             DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::ResultSet is null!");
422             delete absRdbPredicates;
423             return nullptr;
424         }
425         auto queryResultSet = RdbDataShareAdapter::RdbUtils::ToResultSetBridge(result);
426         sharedPtrResult = std::make_shared<DataShare::DataShareResultSet>(queryResultSet);
427         delete absRdbPredicates;
428         bool needUpdate = false;
429         std::shared_ptr<DataShare::DataShareResultSet> newSharedPtrResult =
430             NeedUpdatePdpSharedPtrResult(sharedPtrResult, needUpdate);
431         return needUpdate ? newSharedPtrResult : sharedPtrResult;
432     } else if (pdpProfileUriType == PdpProfileUriType::PSE_BASE_STATION) {
433         return QueryPseBaseStation(uri, predicates, columns);
434     }
435     DATA_STORAGE_LOGE("PdpProfileAbility::Query##uri = %{public}s", uri.ToString().c_str());
436     return sharedPtrResult;
437 }
438 
Update(const Uri & uri,const DataShare::DataSharePredicates & predicates,const DataShare::DataShareValuesBucket & value)439 int PdpProfileAbility::Update(const Uri &uri, const DataShare::DataSharePredicates &predicates,
440     const DataShare::DataShareValuesBucket &value)
441 {
442     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
443         DATA_STORAGE_LOGE("Permission denied!");
444         return DATA_STORAGE_ERR_PERMISSION_ERR;
445     }
446     int result = DATA_STORAGE_ERROR;
447     if (!IsInitOk()) {
448         return result;
449     }
450     std::lock_guard<std::mutex> guard(lock_);
451     Uri tempUri = uri;
452     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
453     NativeRdb::AbsRdbPredicates *absRdbPredicates = CreateAbsRdbPredicates(pdpProfileUriType);
454     switch (pdpProfileUriType) {
455         case PdpProfileUriType::PDP_PROFILE:
456         case PdpProfileUriType::PSE_BASE_STATION:
457             break;
458         case PdpProfileUriType::RESET: {
459             result = ResetApn(value);
460             if (result != NativeRdb::E_OK) {
461                 DATA_STORAGE_LOGE("PdpProfileAbility::Update  ResetApn fail!");
462                 result = static_cast<int>(LoadProFileErrorType::RESET_APN_FAIL);
463             }
464             break;
465         }
466         case PdpProfileUriType::PREFER_APN: {
467             result = (UpdatePreferApn(value) == NativeRdb::E_OK) ? NativeRdb::E_OK
468                          : static_cast<int>(LoadProFileErrorType::PREFER_APN_FAIL);
469             break;
470         }
471         default:
472             DATA_STORAGE_LOGE("PdpProfileAbility::Update##uri = %{public}s", uri.ToString().c_str());
473             break;
474     }
475     if (absRdbPredicates != nullptr) {
476         int changedRows = CHANGED_ROWS;
477         NativeRdb::RdbPredicates rdbPredicates = ConvertPredicates(absRdbPredicates->GetTableName(), predicates);
478         DataShare::DataShareValuesBucket newValue;
479         bool useNewBucket = NeedUpdateValuesBucket(value, newValue);
480         OHOS::NativeRdb::ValuesBucket values = useNewBucket ? RdbDataShareAdapter::RdbUtils::ToValuesBucket(newValue)
481             : RdbDataShareAdapter::RdbUtils::ToValuesBucket(value);
482         result = helper_.Update(changedRows, values, rdbPredicates);
483         delete absRdbPredicates;
484         absRdbPredicates = nullptr;
485     } else if (result == DATA_STORAGE_ERROR) {
486         DATA_STORAGE_LOGE("PdpProfileAbility::Update  NativeRdb::AbsRdbPredicates is null!");
487     }
488     return result;
489 }
490 
UpdatePreferApn(const DataShare::DataShareValuesBucket & sharedValue)491 int PdpProfileAbility::UpdatePreferApn(const DataShare::DataShareValuesBucket &sharedValue)
492 {
493     OHOS::NativeRdb::ValuesBucket value = RdbDataShareAdapter::RdbUtils::ToValuesBucket(sharedValue);
494     int result = DATA_STORAGE_ERROR;
495     NativeRdb::ValueObject valueObject;
496     if (!HasColumnValue(value, PdpProfileData::PROFILE_ID, valueObject)) {
497         return result;
498     }
499     double temp = 0;
500     int profileId = INVALID_PROFILE_ID;
501     if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
502         profileId = ceil(temp);
503     }
504     if (!HasColumnValue(value, PdpProfileData::SIM_ID, valueObject)) {
505         return result;
506     }
507     int simId = DEFAULT_SIM_ID;
508     if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
509         simId = ceil(temp);
510     }
511     return SetPreferApn(simId, profileId);
512 }
513 
HasColumnValue(const OHOS::NativeRdb::ValuesBucket & value,const char * columnName,NativeRdb::ValueObject & valueObject)514 bool PdpProfileAbility::HasColumnValue(
515     const OHOS::NativeRdb::ValuesBucket &value, const char *columnName, NativeRdb::ValueObject &valueObject)
516 {
517     if (!value.HasColumn(columnName)) {
518         DATA_STORAGE_LOGE("the column in valuesBucket does not exist!");
519         return false;
520     }
521     bool isExistValue = value.GetObject(columnName, valueObject);
522     if (!isExistValue) {
523         DATA_STORAGE_LOGE("failed to get value in valuesBucket!");
524         return false;
525     }
526     return true;
527 }
528 
Delete(const Uri & uri,const DataShare::DataSharePredicates & predicates)529 int PdpProfileAbility::Delete(const Uri &uri, const DataShare::DataSharePredicates &predicates)
530 {
531     if (!PermissionUtil::CheckPermission(Permission::SET_TELEPHONY_STATE)) {
532         DATA_STORAGE_LOGE("Permission denied!");
533         return DATA_STORAGE_ERR_PERMISSION_ERR;
534     }
535     int result = DATA_STORAGE_ERROR;
536     if (!IsInitOk()) {
537         return result;
538     }
539     std::lock_guard<std::mutex> guard(lock_);
540     Uri tempUri = uri;
541     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
542     if (pdpProfileUriType == PdpProfileUriType::PDP_PROFILE) {
543         NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
544         if (absRdbPredicates != nullptr) {
545             NativeRdb::RdbPredicates rdbPredicates = ConvertPredicates(absRdbPredicates->GetTableName(), predicates);
546             int deletedRows = CHANGED_ROWS;
547             result = helper_.Delete(deletedRows, rdbPredicates);
548             delete absRdbPredicates;
549             absRdbPredicates = nullptr;
550         } else {
551             DATA_STORAGE_LOGE("PdpProfileAbility::Delete  NativeRdb::AbsRdbPredicates is null!");
552         }
553     } else {
554         DATA_STORAGE_LOGI("PdpProfileAbility::Delete##uri = %{public}s", uri.ToString().c_str());
555     }
556     return result;
557 }
558 
IsInitOk()559 bool PdpProfileAbility::IsInitOk()
560 {
561     if (!initDatabaseDir) {
562         DATA_STORAGE_LOGE("PdpProfileAbility::IsInitOk initDatabaseDir failed!");
563         return false;
564     }
565     if (!initRdbStore) {
566         DATA_STORAGE_LOGE("PdpProfileAbility::IsInitOk initRdbStore failed!");
567         return false;
568     }
569     return true;
570 }
571 
GetType(const Uri & uri)572 std::string PdpProfileAbility::GetType(const Uri &uri)
573 {
574     DATA_STORAGE_LOGI("PdpProfileAbility::GetType##uri = %{public}s", uri.ToString().c_str());
575     std::string retval(uri.ToString());
576     return retval;
577 }
578 
OpenFile(const Uri & uri,const std::string & mode)579 int PdpProfileAbility::OpenFile(const Uri &uri, const std::string &mode)
580 {
581     DATA_STORAGE_LOGI("PdpProfileAbility::OpenFile##uri = %{public}s", uri.ToString().c_str());
582     Uri tempUri = uri;
583     PdpProfileUriType pdpProfileUriType = ParseUriType(tempUri);
584     return static_cast<int>(pdpProfileUriType);
585 }
586 
ParseUriType(Uri & uri)587 PdpProfileUriType PdpProfileAbility::ParseUriType(Uri &uri)
588 {
589     DATA_STORAGE_LOGD("PdpProfileAbility::ParseUriType start");
590     PdpProfileUriType pdpProfileUriType = PdpProfileUriType::UNKNOW;
591     std::string uriPath = uri.ToString();
592     if (!uriPath.empty()) {
593         helper_.ReplaceAllStr(uriPath, ":///", "://");
594         Uri tempUri(uriPath);
595         std::string path = tempUri.GetPath();
596         if (!path.empty() && !pdpProfileUriMap_.empty()) {
597             auto it = pdpProfileUriMap_.find(path);
598             if (it != pdpProfileUriMap_.end()) {
599                 pdpProfileUriType = it->second;
600                 DATA_STORAGE_LOGD("PdpProfileAbility::ParseUriType##pdpProfileUriType = %{public}d",
601                     pdpProfileUriType);
602             }
603         }
604     }
605     return pdpProfileUriType;
606 }
607 
ConvertPredicates(const std::string & tableName,const DataShare::DataSharePredicates & predicates)608 OHOS::NativeRdb::RdbPredicates PdpProfileAbility::ConvertPredicates(
609     const std::string &tableName, const DataShare::DataSharePredicates &predicates)
610 {
611     OHOS::NativeRdb::RdbPredicates res = RdbDataShareAdapter::RdbUtils::ToPredicates(predicates, tableName);
612     return res;
613 }
614 
QueryPdpProfile(Uri & uri,const std::string & tableName,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns)615 std::shared_ptr<NativeRdb::ResultSet> PdpProfileAbility::QueryPdpProfile(Uri &uri, const std::string &tableName,
616     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns)
617 {
618     const std::string &simIdStr = GetQueryKey(uri.GetQuery(), "simId=");
619     std::string opkey;
620     int simId = DEFAULT_SIM_ID;
621     if (StrToInt(simIdStr, simId)) {
622         int32_t slotId = DelayedRefSingleton<CoreServiceClient>::GetInstance().GetSlotId(simId);
623         GetTargetOpkey(slotId, opkey);
624     }
625     if (opkey.empty() || strcmp(opkey.c_str(), INVALID_OPKEY) == 0) {
626         return helper_.Query(ConvertPredicates(tableName, predicates), columns);
627     }
628     constexpr int32_t FIELD_IDX = 0;
629     auto &operations = predicates.GetOperationList();
630     std::vector<DataShare::OperationItem> operationsRes;
631     bool isMccMnc = false;
632     for (const auto &oper : operations) {
633         if (oper.singleParams.empty()) {
634             operationsRes.push_back(oper);
635             continue;
636         }
637         std::string filed = static_cast<std::string>(oper.GetSingle(FIELD_IDX));
638         if (strcmp(filed.c_str(), PdpProfileData::MCCMNC) == 0 && oper.operation == DataShare::EQUAL_TO) {
639             isMccMnc = true;
640             operationsRes.push_back({DataShare::EQUAL_TO, {PdpProfileData::OPKEY, opkey}});
641             continue;
642         }
643         operationsRes.push_back(oper);
644     }
645     DATA_STORAGE_LOGI(
646         "PdpProfileAbility::QueryPdpProfile, simId= %{public}d, isMccMnc= %{public}d", simId, isMccMnc);
647     if (isMccMnc) {
648         const std::shared_ptr<NativeRdb::ResultSet> &result =
649             helper_.Query(ConvertPredicates(tableName, DataShare::DataSharePredicates(move(operationsRes))), columns);
650         if (result != nullptr) {
651             int count = 0;
652             result->GetRowCount(count);
653             DATA_STORAGE_LOGI("PdpProfileAbility::QueryPdpProfile, count= %{public}d", count);
654             if (count > 0) {
655                 return result;
656             }
657         }
658     }
659     return helper_.Query(ConvertPredicates(tableName, predicates), columns);
660 }
661 
ResetApn(const DataShare::DataShareValuesBucket & valuesBucket)662 int PdpProfileAbility::ResetApn(const DataShare::DataShareValuesBucket &valuesBucket)
663 {
664     OHOS::NativeRdb::ValuesBucket values = RdbDataShareAdapter::RdbUtils::ToValuesBucket(valuesBucket);
665     int simId = DEFAULT_SIM_ID;
666     if (GetIntFromValuesBucket(values, "simId", simId) != NativeRdb::E_OK) {
667         DATA_STORAGE_LOGE("PdpProfileAbility::ResetApn no simId!");
668         return helper_.ResetApn();
669     }
670     int32_t slotId = DelayedRefSingleton<CoreServiceClient>::GetInstance().GetSlotId(simId);
671     std::string opkey;
672     GetTargetOpkey(slotId, opkey);
673     if (opkey.empty() || strcmp(opkey.c_str(), INVALID_OPKEY) == 0) {
674         DATA_STORAGE_LOGW("PdpProfileAbility::ResetApn opkey empty!");
675         return helper_.ResetApn();
676     }
677     DATA_STORAGE_LOGI("PdpProfileAbility::ResetApn##simId = %{public}d", simId);
678     SetPreferApn(simId, -1);
679     NativeRdb::RdbPredicates rdbPredicates(TABLE_PDP_PROFILE);
680     rdbPredicates.EqualTo(PdpProfileData::OPKEY, opkey);
681     int deletedRows = CHANGED_ROWS;
682     helper_.Delete(deletedRows, rdbPredicates);
683     int result = helper_.InitAPNDatabase(slotId, opkey, false);
684     if (result != NativeRdb::E_OK) {
685         DATA_STORAGE_LOGE("PdpProfileAbility::ResetApn fail!");
686         result = static_cast<int>(LoadProFileErrorType::RESET_APN_FAIL);
687     }
688     return result;
689 }
690 
GetIntFromValuesBucket(OHOS::NativeRdb::ValuesBucket & bucket,const char * key,int & value)691 int PdpProfileAbility::GetIntFromValuesBucket(OHOS::NativeRdb::ValuesBucket &bucket, const char *key, int &value)
692 {
693     NativeRdb::ValueObject valueObject;
694     if (!HasColumnValue(bucket, key, valueObject)) {
695         return OPERATION_ERROR;
696     }
697     if (valueObject.GetType() == NativeRdb::ValueObject::TYPE_INT) {
698         return valueObject.GetInt(value);
699     }
700     if (valueObject.GetType() == NativeRdb::ValueObject::TYPE_DOUBLE) {
701         double temp = 0;
702         if (valueObject.GetDouble(temp) == NativeRdb::E_OK) {
703             value = ceil(temp);
704             return NativeRdb::E_OK;
705         }
706     }
707     return OPERATION_ERROR;
708 }
709 
GetTargetOpkey(int slotId,std::string & opkey)710 void PdpProfileAbility::GetTargetOpkey(int slotId, std::string &opkey)
711 {
712     std::u16string opkeyU16;
713     DelayedRefSingleton<CoreServiceClient>::GetInstance().GetTargetOpkey(slotId, opkeyU16);
714     opkey = Str16ToStr8(opkeyU16);
715     DATA_STORAGE_LOGI(
716         "PdpProfileAbility::GetTargetOpkey##slotId = %{public}d, opkey = %{public}s", slotId, opkey.c_str());
717 }
718 
QueryPseBaseStation(const Uri & uri,const DataShare::DataSharePredicates & predicates,std::vector<std::string> & columns)719 std::shared_ptr<DataShare::DataShareResultSet> PdpProfileAbility::QueryPseBaseStation(const Uri &uri,
720     const DataShare::DataSharePredicates &predicates, std::vector<std::string> &columns)
721 {
722     DATA_STORAGE_LOGI("query PSE_BASE_STATION");
723     NativeRdb::AbsRdbPredicates *absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PSE_BASE_STATION);
724     if (absRdbPredicates == nullptr) {
725         DATA_STORAGE_LOGE("PdpProfileAbility::Query NativeRdb::AbsRdbPredicates is null!");
726         return nullptr;
727     }
728     std::shared_ptr<NativeRdb::ResultSet> result = nullptr;
729     result = helper_.Query(ConvertPredicates(absRdbPredicates->GetTableName(), predicates), columns);
730     if (result == nullptr) {
731         DATA_STORAGE_LOGE("PdpProfileAbility::Query  NativeRdb::ResultSet is null!");
732         delete absRdbPredicates;
733         return nullptr;
734     }
735     auto queryResultSet = RdbDataShareAdapter::RdbUtils::ToResultSetBridge(result);
736     auto sharedPtrResult = std::make_shared<DataShare::DataShareResultSet>(queryResultSet);
737     delete absRdbPredicates;
738     return sharedPtrResult;
739 }
740 
CreateAbsRdbPredicates(PdpProfileUriType type)741 NativeRdb::AbsRdbPredicates* PdpProfileAbility::CreateAbsRdbPredicates(PdpProfileUriType type)
742 {
743     NativeRdb::AbsRdbPredicates *absRdbPredicates = nullptr;
744     switch (type) {
745         case PdpProfileUriType::PDP_PROFILE:
746             absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PDP_PROFILE);
747             break;
748         case PdpProfileUriType::PSE_BASE_STATION:
749             absRdbPredicates = new NativeRdb::AbsRdbPredicates(TABLE_PSE_BASE_STATION);
750             break;
751         default:
752             break;
753     }
754     return absRdbPredicates;
755 }
756 } // namespace Telephony
757 } // namespace OHOS
758