• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "oaid_service.h"
16 #include <mutex>
17 #include <openssl/rand.h>
18 #include <singleton.h>
19 #include <string>
20 #include <unistd.h>
21 #include <ctime>
22 #include <future>
23 #include "oaid_common.h"
24 #include "oaid_file_operator.h"
25 #include "system_ability.h"
26 #include "system_ability_definition.h"
27 #include "oaid_service_stub.h"
28 #include "oaid_service_define.h"
29 #include "oaid_observer_manager.h"
30 #include "config_policy_utils.h"
31 #include "connect_ads_stub.h"
32 
33 using namespace std::chrono;
34 
35 namespace OHOS {
36 namespace Cloud {
37 const std::string OAID_VIRTUAL_STR = "-****-****-****-************";
38 namespace {
HexToChar(uint8_t hex)39 char HexToChar(uint8_t hex)
40 {
41     static const uint8_t MAX_SINGLE_DIGIT = 9;  // 9 is the largest single digit
42     return (hex > MAX_SINGLE_DIGIT) ? (hex + 0x57) : (hex + 0x30);
43 }
44 
45 /**
46  * Get v4 uuid.
47  *
48  * @return std::string, uuid.
49  */
GetUUID()50 std::string GetUUID()
51 {
52     static const int8_t UUID_LENGTH = 16;    // The UUID is 128 bits, that is 16 bytes.
53     static const int8_t VERSION_INDEX = 6;   // Obtain the seventh byte of the randomly generated UUID, that is uuid[6].
54     static const int8_t CHAR_LOW_WIDTH = 4;  // Lower 4 bits of the char type
55     static const int8_t N_INDEX = 8;         // Reset the ninth byte of the UUID, that is UUID[8].
56     unsigned char uuid[UUID_LENGTH] = {0};
57     int re = RAND_bytes(uuid, sizeof(uuid));
58     if (re == 0) {
59         return "";
60     }
61 
62     /**
63      * xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
64      * M is uuid version: 4
65      * N is 8,9,a,b
66      */
67     uuid[VERSION_INDEX] = (uuid[VERSION_INDEX] & 0x0F) | 0x40;
68     int minN = 0x8;
69     int maxN = 0xb;
70     unsigned char randNumber[1] = {minN};
71     RAND_bytes(randNumber, sizeof(randNumber));
72     unsigned char num = static_cast<unsigned char>(randNumber[0] % (maxN - minN + 1) + minN);
73     uuid[N_INDEX] = (uuid[N_INDEX] & 0x0F) | (num << CHAR_LOW_WIDTH);
74 
75     static const size_t LINE_INDEX_MAX = 10;  // until i=10
76     static const size_t LINE_INDEX_MIN = 4;   // Add a hyphen (-) every two bytes starting from i=4.
77     static const size_t EVEN_FACTOR = 2;  // the even factor is assigned to 2, and all even numbers are divisible by 2.
78     std::string formatUuid = "";
79     for (size_t i = 0; i < sizeof(uuid); i++) {
80         unsigned char value = uuid[i];
81         if (i >= LINE_INDEX_MIN && i <= LINE_INDEX_MAX && i % EVEN_FACTOR == 0) {
82             formatUuid += "-";
83         }
84         formatUuid += HexToChar(value >> CHAR_LOW_WIDTH);
85         unsigned char highValue = value & 0xF0;
86         if (highValue == 0) {
87             formatUuid += HexToChar(value);
88         } else {
89             formatUuid += HexToChar(value % (value & highValue));
90         }
91     }
92     return formatUuid;
93 }
94 }  // namespace
95 
96 REGISTER_SYSTEM_ABILITY_BY_ID(OAIDService, OAID_SYSTME_ID, true);
97 std::mutex OAIDService::mutex_;
98 sptr<OAIDService> OAIDService::instance_;
99 
OAIDService(int32_t systemAbilityId,bool runOnCreate)100 OAIDService::OAIDService(int32_t systemAbilityId, bool runOnCreate)
101     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
102 {
103     OAID_HILOGI(OAID_MODULE_SERVICE, "Start.");
104 }
105 
OAIDService()106 OAIDService::OAIDService() : state_(ServiceRunningState::STATE_NOT_START)
107 {}
108 
~OAIDService()109 OAIDService::~OAIDService(){};
110 
GetInstance()111 sptr<OAIDService> OAIDService::GetInstance()
112 {
113     if (instance_ == nullptr) {
114         std::lock_guard<std::mutex> autoLock(mutex_);
115         if (instance_ == nullptr) {
116             OAID_HILOGI(OAID_MODULE_SERVICE, "Instance success.");
117             instance_ = new OAIDService;
118         }
119     }
120     return instance_;
121 }
122 
OnStart()123 void OAIDService::OnStart()
124 {
125     if (state_ == ServiceRunningState::STATE_RUNNING) {
126         OAID_HILOGE(OAID_MODULE_SERVICE, " OAIDService is already running.");
127         return;
128     }
129 
130     if (Init() != ERR_OK) {
131         OAID_HILOGE(OAID_MODULE_SERVICE, "Init failed, Try again 10s later.");
132         return;
133     }
134     AddSystemAbilityListener(OAID_SYSTME_ID);
135 
136     OAID_HILOGI(OAID_MODULE_SERVICE, "Start OAID service success.");
137     return;
138 }
139 
Init()140 int32_t OAIDService::Init()
141 {
142     bool ret = Publish(this);
143     if (!ret) {
144         OAID_HILOGE(OAID_MODULE_SERVICE, "OAID service init failed.");
145         return ERR_SYSYTEM_ERROR;
146     }
147 
148     OAID_HILOGI(OAID_MODULE_SERVICE, "OAID service init Success.");
149     state_ = ServiceRunningState::STATE_RUNNING;
150     return ERR_OK;
151 }
152 
OnStop()153 void OAIDService::OnStop()
154 {
155     if (state_ != ServiceRunningState::STATE_RUNNING) {
156         return;
157     }
158 
159     state_ = ServiceRunningState::STATE_NOT_START;
160     OAID_HILOGI(OAID_MODULE_SERVICE, "Stop success.");
161 }
162 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)163 void OAIDService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
164 {
165     OAID_HILOGI(OAID_MODULE_SERVICE, "OnAddSystemAbility OAIDService");
166     bool initBaseKvResult = false;
167     bool initUnderAgeKvResult = false;
168     switch (systemAbilityId) {
169         case OAID_SYSTME_ID:
170             OAID_HILOGI(OAID_MODULE_SERVICE, "OnAddSystemAbility kv data service start");
171             initBaseKvResult = InitKvStore(OAID_DATA_BASE_STORE_ID);
172             initUnderAgeKvResult = InitKvStore(OAID_UNDER_AGE_STORE_ID);
173                 OAID_HILOGI(OAID_MODULE_SERVICE,
174                     "OnAddSystemAbility InitOaidKvStore is %{public}d, InitUnderAgeKvStore is %{public}d",
175                     initBaseKvResult,
176                     initUnderAgeKvResult);
177             break;
178         default:
179             OAID_HILOGI(OAID_MODULE_SERVICE, "OnAddSystemAbility unhandled sysabilityId: %{public}d", systemAbilityId);
180             break;
181     }
182 }
183 
CheckKvStore()184 bool OAIDService::CheckKvStore()
185 {
186     if (oaidKvStore_ != nullptr) {
187         return true;
188     }
189     bool result = InitKvStore(OAID_DATA_BASE_STORE_ID);
190     OAID_HILOGI(OAID_MODULE_SERVICE, "InitOaidKvStore: %{public}s", result == true ? "success" : "failed");
191     return result;
192 }
193 
ReadValueFromKvStore(const std::string & kvStoreKey,std::string & kvStoreValue)194 bool OAIDService::ReadValueFromKvStore(const std::string &kvStoreKey, std::string &kvStoreValue)
195 {
196     std::lock_guard<std::mutex> lock(mutex_);
197 
198     if (!CheckKvStore()) {
199         OAID_HILOGE(OAID_MODULE_SERVICE, "ReadValueFromKvStore:oaidKvStore_ is nullptr");
200         return false;
201     }
202 
203     DistributedKv::Key key(kvStoreKey);
204     DistributedKv::Value value;
205     DistributedKv::Status status = oaidKvStore_->Get(key, value);
206     if (status == DistributedKv::Status::SUCCESS) {
207         OAID_HILOGI(OAID_MODULE_SERVICE, "%{public}d get value from kvStore", status);
208     } else {
209         OAID_HILOGE(OAID_MODULE_SERVICE, "%{public}d get value from kvStore failed", status);
210         return false;
211     }
212     kvStoreValue = value.ToString();
213 
214     return true;
215 }
216 
WriteValueToKvStore(const std::string & kvStoreKey,const std::string & kvStoreValue)217 bool OAIDService::WriteValueToKvStore(const std::string &kvStoreKey, const std::string &kvStoreValue)
218 {
219     std::lock_guard<std::mutex> lock(mutex_);
220 
221     if (!CheckKvStore()) {
222         OAID_HILOGE(OAID_MODULE_SERVICE, "WriteValueToKvStore:oaidKvStore_ is nullptr");
223         return false;
224     }
225 
226     DistributedKv::Key key(kvStoreKey);
227     DistributedKv::Value value(kvStoreValue);
228     DistributedKv::Status status = oaidKvStore_->Put(key, value);
229     if (status == DistributedKv::Status::SUCCESS) {
230         OAID_HILOGI(OAID_MODULE_SERVICE, "%{public}d updated to kvStore", status);
231     } else {
232         OAID_HILOGE(OAID_MODULE_SERVICE, "%{public}d update to kvStore failed", status);
233         return false;
234     }
235 
236     return true;
237 }
238 
GainOAID()239 std::string OAIDService::GainOAID()
240 {
241     OAID_HILOGI(OAID_MODULE_SERVICE, "Gain OAID Begin.");
242     std::string oaidKvStoreStr = OAID_ALLZERO_STR;
243     updateMutex_.lock();
244     if (OAIDFileOperator::IsFileExsit(OAID_UPDATE)) {
245         OAIDFileOperator::OpenAndReadFile(OAID_UPDATE, oaidKvStoreStr);
246         OAIDFileOperator::ClearFile(OAID_UPDATE);
247         std::string oaid;
248         cJSON *root = cJSON_Parse(oaidKvStoreStr.c_str());
249         if (root != nullptr && !cJSON_IsInvalid(root)) {
250             cJSON *oaidObj = cJSON_GetObjectItem(root, "oaid");
251             if (cJSON_IsString(oaidObj)) {
252                 oaid = oaidObj->valuestring;
253             }
254         }
255         cJSON_Delete(root);
256         oaid_ = oaid;
257         bool update = WriteValueToKvStore(OAID_KVSTORE_KEY, oaid_);
258         OAID_HILOGI(OAID_MODULE_SERVICE, "update oaid %{public}s", update ? "success" : "failed");
259         updateMutex_.unlock();
260         return oaid_;
261     }
262     updateMutex_.unlock();
263     if (!ConnectAdsManager::GetInstance()->checkAllowGetOaid()) {
264         OAID_HILOGI(OAID_MODULE_SERVICE, "under age, not allow get oaid");
265         return OAID_ALLZERO_STR;
266     }
267     bool result = ReadValueFromKvStore(OAID_KVSTORE_KEY, oaidKvStoreStr);
268     OAID_HILOGI(OAID_MODULE_SERVICE, "ReadValueFromKvStore %{public}s", result ? "success" : "failed");
269 
270     if (oaidKvStoreStr != OAID_ALLZERO_STR && !oaidKvStoreStr.empty()) {
271         if (oaid_.empty()) {
272             oaid_ = oaidKvStoreStr;
273             OAID_HILOGI(OAID_MODULE_SERVICE, "The Oaid in the memory is empty, it get oaid from kvdb successfully");
274         }
275         return oaid_;
276     } else {
277         if (oaid_.empty()) {
278             oaid_ = GetUUID();
279             OAID_HILOGI(OAID_MODULE_SERVICE, "The oaid has been regenerated.");
280         }
281     }
282     result = WriteValueToKvStore(OAID_KVSTORE_KEY, oaid_);
283     OAID_HILOGI(OAID_MODULE_SERVICE, "WriteValueToKvStore %{public}s", result == true ? "success" : "failed");
284     OAID_HILOGI(OAID_MODULE_SERVICE, "Gain OAID Finish.");
285     return oaid_;
286 }
287 
GetOAID()288 std::string OAIDService::GetOAID()
289 {
290     OAID_HILOGI(OAID_MODULE_SERVICE, "Begin.");
291 
292     std::string oaid = GainOAID();
293     std::string target = oaid.substr(0, 9).append(OAID_VIRTUAL_STR);
294     OAID_HILOGI(OAID_MODULE_SERVICE, "getOaid success oaid is: %{public}s", target.c_str());
295     OAID_HILOGI(OAID_MODULE_SERVICE, "End.");
296     return oaid;
297 }
298 
ResetOAID()299 int32_t OAIDService::ResetOAID()
300 {
301     OAID_HILOGI(OAID_MODULE_SERVICE, "ResetOAID.");
302     std::string resetOaid = GetUUID();
303     oaid_ = resetOaid;
304     bool result = WriteValueToKvStore(OAID_KVSTORE_KEY, resetOaid);
305     OAID_HILOGI(OAID_MODULE_SERVICE, "ResetOAID WriteValueToKvStore %{public}s", result == true ? "success" : "failed");
306     std::string target = resetOaid.substr(0, 9).append(OAID_VIRTUAL_STR);
307     OAID_HILOGI(OAID_MODULE_SERVICE, "resetOaid success oaid is: %{public}s", target.c_str());
308     // 调用单例对象的oberser->OnUpdateOaid
309     DelayedSingleton<OaidObserverManager>::GetInstance()->OnUpdateOaid(resetOaid);
310     return ERR_OK;
311 }
312 
getOptions()313 DistributedKv::Options getOptions()
314 {
315     DistributedKv::Options options;
316     options.createIfMissing = true;
317     options.encrypt = true;
318     options.autoSync = false;
319     options.kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION;
320     options.area = DistributedKv::EL1;
321     options.baseDir = OAID_DATA_BASE_DIR + OAID_DATA_BASE_APP_ID;
322     options.securityLevel = DistributedKv::SecurityLevel::S1;
323     return options;
324 }
325 
InitKvStore(std::string storeIdStr)326 bool OAIDService::InitKvStore(std::string storeIdStr)
327 {
328     DistributedKv::DistributedKvDataManager manager;
329     DistributedKv::Options options = getOptions();
330     DistributedKv::AppId appId;
331     appId.appId = OAID_DATA_BASE_APP_ID;
332     DistributedKv::StoreId storeId;
333     storeId.storeId = storeIdStr;
334     DistributedKv::Status status = DistributedKv::Status::SUCCESS;
335     std::shared_ptr<DistributedKv::SingleKvStore> kvStore_;
336     if (kvStore_ == nullptr) {
337         uint32_t retries = 0;
338         do {
339             status = manager.GetSingleKvStore(options, appId, storeId, kvStore_);
340             if (status == DistributedKv::Status::STORE_NOT_FOUND) {
341                 OAID_HILOGE(OAID_MODULE_SERVICE, "InitOaidKvStore: STORE_NOT_FOUND!");
342             }
343             if ((status == DistributedKv::Status::SUCCESS) || (status == DistributedKv::Status::STORE_NOT_FOUND)) {
344                 break;
345             } else {
346                 OAID_HILOGE(OAID_MODULE_SERVICE, "Kvstore Connect failed! Retrying.retries=%{public}u", retries);
347                 retries++;
348                 usleep(KVSTORE_CONNECT_RETRY_DELAY_TIME);
349             }
350         } while (retries <= KVSTORE_CONNECT_RETRY_COUNT);
351     }
352     if (kvStore_ == nullptr) {
353         if (status == DistributedKv::Status::STORE_NOT_FOUND) {
354             OAID_HILOGI(OAID_MODULE_SERVICE, "First Boot: Create OaidKvStore");
355             options.createIfMissing = true;
356             status = manager.GetSingleKvStore(options, appId, storeId, kvStore_);
357             if (status == DistributedKv::Status::SUCCESS) {
358                 OAID_HILOGE(OAID_MODULE_SERVICE, "Create OaidKvStore success!");
359             } else {
360                 OAID_HILOGE(OAID_MODULE_SERVICE, "Create OaidKvStore Failed!");
361             }
362         }
363     }
364     if (kvStore_ == nullptr) {
365         OAID_HILOGE(OAID_MODULE_SERVICE, "InitOaidKvStore: Failed!");
366         return false;
367     }
368     if (storeIdStr == OAID_DATA_BASE_STORE_ID) {
369         oaidKvStore_ = kvStore_;
370     } else if (storeIdStr == OAID_UNDER_AGE_STORE_ID) {
371         oaidUnderAgeKvStore_ = kvStore_;
372     }
373     return true;
374 }
375 
CheckUnderAgeKvStore()376 bool OAIDService::CheckUnderAgeKvStore()
377 {
378     if (oaidUnderAgeKvStore_ != nullptr) {
379         return true;
380     }
381     bool result = InitKvStore(OAID_UNDER_AGE_STORE_ID);
382     OAID_HILOGI(OAID_MODULE_SERVICE, "InitUnderAgeKvStore: %{public}s", result == true ? "success" : "failed");
383     return result;
384 }
385 
ReadValueFromUnderAgeKvStore(const std::string & kvStoreKey,DistributedKv::Value & kvStoreValue)386 bool OAIDService::ReadValueFromUnderAgeKvStore(const std::string &kvStoreKey, DistributedKv::Value &kvStoreValue)
387 {
388     std::lock_guard<std::mutex> lock(mutex_);
389     if (!CheckUnderAgeKvStore()) {
390         OAID_HILOGE(OAID_MODULE_SERVICE, "ReadValueFromUnderAgeKvStore:oaidUnderAgeKvStore_ is nullptr");
391         return false;
392     }
393     DistributedKv::Key key(kvStoreKey);
394     DistributedKv::Status status = oaidUnderAgeKvStore_->Get(key, kvStoreValue);
395     if (status == DistributedKv::Status::SUCCESS) {
396         OAID_HILOGI(OAID_MODULE_SERVICE, "%{public}d get value from kvStore", status);
397     } else {
398         OAID_HILOGE(OAID_MODULE_SERVICE, "%{public}d get value from kvStore failed", status);
399         return false;
400     }
401     return true;
402 }
403 
WriteValueToUnderAgeKvStore(const std::string & kvStoreKey,const DistributedKv::Value & kvStoreValue)404 bool OAIDService::WriteValueToUnderAgeKvStore(const std::string &kvStoreKey, const DistributedKv::Value &kvStoreValue)
405 {
406     std::lock_guard<std::mutex> lock(mutex_);
407 
408     if (!CheckUnderAgeKvStore()) {
409         OAID_HILOGE(OAID_MODULE_SERVICE, "WriteValueToUnderAgeKvStore:oaidKvStore_ is nullptr");
410         return false;
411     }
412 
413     DistributedKv::Key key(kvStoreKey);
414     DistributedKv::Status status = oaidUnderAgeKvStore_->Put(key, kvStoreValue);
415     if (status == DistributedKv::Status::SUCCESS) {
416         OAID_HILOGI(OAID_MODULE_SERVICE, "%{public}d updated to kvStore", status);
417     } else {
418         OAID_HILOGE(OAID_MODULE_SERVICE, "%{public}d update to kvStore failed", status);
419         return false;
420     }
421     return true;
422 }
423 
getWantInfo()424 Want ConnectAdsManager::getWantInfo()
425 {
426     OAID_HILOGI(OAID_MODULE_SERVICE, "enter getWantInfo ");
427     OHOS::AAFwk::Want connectionWant;
428     char pathBuff[MAX_PATH_LEN];
429     GetOneCfgFile(OAID_TRUSTLIST_EXTENSION_CONFIG_PATH.c_str(), pathBuff, MAX_PATH_LEN);
430     char realPath[PATH_MAX];
431     if (realpath(pathBuff, realPath) == nullptr) {
432         GetOneCfgFile(OAID_TRUSTLIST_CONFIG_PATH.c_str(), pathBuff, MAX_PATH_LEN);
433         if (realpath(pathBuff, realPath) == nullptr) {
434             OAID_HILOGE(OAID_MODULE_SERVICE, "Parse realpath fail");
435             return connectionWant;
436         }
437     }
438     std::ifstream inFile(realPath, std::ios::in);
439     if (!inFile.is_open()) {
440         OAID_HILOGE(OAID_MODULE_SERVICE, "Open file error.");
441         return connectionWant;
442     }
443     std::string fileContent((std::istreambuf_iterator<char>{inFile}), std::istreambuf_iterator<char>{});
444     cJSON *root = cJSON_Parse(fileContent.c_str());
445     inFile.close();
446     if (root == nullptr) {
447         OAID_HILOGE(OAID_MODULE_SERVICE, "ParseJsonFromFile is not in JSON format.");
448         return connectionWant;
449     }
450     cJSON *oaidProviderBundleNameConfig = cJSON_GetObjectItem(root, "providerBundleName");
451     if (oaidProviderBundleNameConfig == nullptr || oaidProviderBundleNameConfig->type != cJSON_String) {
452         OAID_HILOGE(OAID_MODULE_SERVICE, "not contain providerBundleName node.");
453         cJSON_Delete(root);
454         return connectionWant;
455     }
456     cJSON *oaidProviderAbilityNameConfig = cJSON_GetObjectItem(root, "providerAbilityName");
457     if (oaidProviderAbilityNameConfig == nullptr || oaidProviderAbilityNameConfig->type != cJSON_String) {
458         OAID_HILOGE(OAID_MODULE_SERVICE, "not contain providerAbilityName node.");
459         cJSON_Delete(root);
460         return connectionWant;
461     }
462     cJSON *oaidProviderTokenNameConfig = cJSON_GetObjectItem(root, "providerTokenName");
463     if (oaidProviderTokenNameConfig == nullptr || oaidProviderTokenNameConfig->type != cJSON_String
464         || oaidProviderTokenNameConfig->valuestring == nullptr) {
465         OAID_HILOGE(OAID_MODULE_SERVICE, "not contain providerTokenName node.");
466         cJSON_Delete(root);
467         return connectionWant;
468     }
469     ConnectAdsStub::setToken(Str8ToStr16(oaidProviderTokenNameConfig->valuestring));
470     connectionWant.SetElementName(oaidProviderBundleNameConfig->valuestring,
471         oaidProviderAbilityNameConfig->valuestring);
472     cJSON_Delete(root);
473     return connectionWant;
474 }
475 
checkAllowGetOaid()476 bool ConnectAdsManager::checkAllowGetOaid()
477 {
478     OAID_HILOGI(OAID_MODULE_SERVICE, "checkAllowGetOaid enter ");
479     DistributedKv::Value allowGetOaid;
480     DistributedKv::Value updateTime;
481     OAIDService::GetInstance()->ReadValueFromUnderAgeKvStore(ALLOW_GET_OAID_KEY, allowGetOaid);
482     OAIDService::GetInstance()->ReadValueFromUnderAgeKvStore(LAST_UPDATE_TIME_KEY, updateTime);
483     OAID_HILOGI(OAID_MODULE_SERVICE, "checkAllowGetOaid kvdata allowGetOaid = %{public}s  updateTime = %{public}s",
484         allowGetOaid.ToString().c_str(), updateTime.ToString().c_str());
485     if (allowGetOaid == nullptr || updateTime == nullptr) {
486         OAID_HILOGI(OAID_MODULE_SERVICE, "checkAllowGetOaid get kvData failed");
487         std::future<void> resultFromDB = std::async(std::launch::async, ConnectAdsManager::getAllowGetOAIDFromKit);
488         return true;
489     }
490     std::string updateTimeStr = updateTime.ToString();
491     long long updateTimestamp = std::stol(updateTimeStr);
492     long long nowTimestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
493         std::chrono::system_clock::now().time_since_epoch()).count();
494     if (nowTimestamp < updateTimestamp) {
495         OAID_HILOGW(OAID_MODULE_SERVICE, "user time illegal");
496     } else {
497         long long interval = nowTimestamp - updateTimestamp;
498         OAID_HILOGI(OAID_MODULE_SERVICE,
499             "checkAllowGetOaid kvdata nowTimestamp = %{public}lld  updateTime = %{public}s  interval = %{public}lld",
500             nowTimestamp,
501             updateTimeStr.c_str(),
502             interval);
503         if (interval >= EXPIRATION_TIME) {
504             OAID_HILOGI(OAID_MODULE_SERVICE, "checkAllowGetOaid info expiration");
505             std::future<void> resultFromDB = std::async(std::launch::async, ConnectAdsManager::getAllowGetOAIDFromKit);
506         }
507     }
508     if (allowGetOaid.ToString() == "true") {
509         return true;
510     } else {
511         return false;
512     }
513 }
514 
OnRemoteRequest(uint32_t code,MessageParcel & data,MessageParcel & reply,MessageOption & option)515 int ADSCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
516 {
517     OAID_HILOGI(OAID_MODULE_SERVICE, "OnRemoteRequest enter");
518     int32_t respCode = data.ReadInt32();
519     OAID_HILOGI(OAID_MODULE_SERVICE, "OnRemoteRequest respCode = %{public}d", respCode);
520     std::string isAllowGetOaid = Str16ToStr8(data.ReadString16());
521     std::string updateTimeStr = Str16ToStr8(data.ReadString16());
522     OAID_HILOGI(OAID_MODULE_SERVICE, "isAllowGetOaid = %{public}s, updateTimeStr = %{public}s", isAllowGetOaid.c_str(),
523         updateTimeStr.c_str());
524     if (isAllowGetOaid.empty() || updateTimeStr.empty()) {
525         OAID_HILOGI(OAID_MODULE_SERVICE, "OnRemoteRequest return info is empty");
526         return ERR_OK;
527     }
528     DistributedKv::Value value1(isAllowGetOaid);
529     DistributedKv::Value value2(updateTimeStr);
530     bool allowGetOaidResult = OAIDService::GetInstance()->WriteValueToUnderAgeKvStore(ALLOW_GET_OAID_KEY, value1);
531     bool lastUpdateTimeResult = OAIDService::GetInstance()->WriteValueToUnderAgeKvStore(LAST_UPDATE_TIME_KEY, value2);
532     OAID_HILOGI(OAID_MODULE_SERVICE,
533         "OnRemoteRequest Write AllowGetOaid result=%{public}s.OnRemoteRequest Write lastUpdateTime result=%{public}s",
534         allowGetOaidResult == true ? "success" : "failed",
535         lastUpdateTimeResult == true ? "success" : "failed");
536     ConnectAdsManager::GetInstance()->DisconnectService();
537     return ERR_OK;
538 }
539 
Str16ToStr8(const std::u16string & str)540 std::string Str16ToStr8(const std::u16string &str)
541 {
542     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
543     std::string result = convert.to_bytes(str);
544     return result;
545 }
546 
Str8ToStr16(const std::string & str)547 std::u16string Str8ToStr16(const std::string &str)
548 {
549     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
550     std::u16string result = convert.from_bytes(str);
551     return result;
552 }
553 }  // namespace Cloud
554 }  // namespace OHOS
555