• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 "time_system_ability.h"
16 
17 #include <dirent.h>
18 #include <linux/rtc.h>
19 #include <sstream>
20 #include <sys/ioctl.h>
21 #include <sys/timerfd.h>
22 
23 #include "iservice_registry.h"
24 #include "ntp_update_time.h"
25 #include "ntp_trusted_time.h"
26 #include "system_ability_definition.h"
27 #include "time_tick_notify.h"
28 #include "time_zone_info.h"
29 #include "timer_proxy.h"
30 #include "time_file_utils.h"
31 #include "time_xcollie.h"
32 #include "parameters.h"
33 #include "event_manager.h"
34 #include "simple_timer_info.h"
35 
36 #ifdef MULTI_ACCOUNT_ENABLE
37 #include "os_account.h"
38 #include "os_account_manager.h"
39 #endif
40 
41 using namespace std::chrono;
42 using namespace OHOS::EventFwk;
43 using namespace OHOS::HiviewDFX;
44 
45 namespace OHOS {
46 namespace MiscServices {
47 namespace {
48 // Unit of measure conversion , BASE: second
49 static constexpr int MILLI_TO_BASE = 1000LL;
50 static constexpr int MICR_TO_BASE = 1000000LL;
51 static constexpr int NANO_TO_BASE = 1000000000LL;
52 static constexpr std::int32_t INIT_INTERVAL = 10L;
53 static constexpr uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
54 static constexpr uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
55 static constexpr uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
56 static constexpr uint32_t TIMER_TYPE_IDLE_MASK = 1 << 3;
57 static constexpr uint32_t TIMER_TYPE_INEXACT_REMINDER_MASK = 1 << 4;
58 static constexpr int32_t STR_MAX_LENGTH = 64;
59 constexpr int32_t MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
60 constexpr int32_t NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
61 constexpr int32_t ONE_MILLI = 1000;
62 static const std::vector<std::string> ALL_DATA = { "timerId", "type", "flag", "windowLength", "interval", \
63                                                    "uid", "bundleName", "wantAgent", "state", "triggerTime", \
64                                                    "pid", "name"};
65 constexpr const char* BOOTEVENT_PARAMETER = "bootevent.boot.completed";
66 static constexpr int MAX_PID_LIST_SIZE = 1024;
67 static constexpr uint32_t MAX_EXEMPTION_SIZE = 1000;
68 
69 #ifdef SET_AUTO_REBOOT_ENABLE
70 constexpr int64_t MILLISECOND_TO_NANO = 1000000;
71 constexpr uint64_t TWO_MINUTES_TO_MILLI = 120000;
72 constexpr const char* SCHEDULED_POWER_ON_APPS = "persist.time.scheduled_power_on_apps";
73 constexpr int CLOCK_POWEROFF_ALARM = 12;
74 constexpr size_t INDEX_TWO = 2;
75 #endif
76 
77 #ifdef MULTI_ACCOUNT_ENABLE
78 constexpr const char* SUBSCRIBE_REMOVED = "UserRemoved";
79 #endif
80 } // namespace
81 
82 REGISTER_SYSTEM_ABILITY_BY_ID(TimeSystemAbility, TIME_SERVICE_ID, true);
83 
84 std::mutex TimeSystemAbility::instanceLock_;
85 sptr<TimeSystemAbility> TimeSystemAbility::instance_;
86 
87 #ifdef MULTI_ACCOUNT_ENABLE
88 class UserRemovedSubscriber : public AccountSA::OsAccountSubscriber {
89 public:
UserRemovedSubscriber(const AccountSA::OsAccountSubscribeInfo & subscribeInfo)90     explicit UserRemovedSubscriber(const AccountSA::OsAccountSubscribeInfo &subscribeInfo)
91         : AccountSA::OsAccountSubscriber(subscribeInfo)
92     {}
93 
OnAccountsChanged(const int & id)94     void OnAccountsChanged(const int &id)
95     {
96         auto timerManager = TimerManager::GetInstance();
97         if (timerManager == nullptr) {
98             return;
99         }
100         timerManager->OnUserRemoved(id);
101     }
102 
OnAccountsSwitch(const int & newId,const int & oldId)103     void OnAccountsSwitch(const int &newId, const int &oldId) {}
104 };
105 #endif
106 
TimeSystemAbility(int32_t systemAbilityId,bool runOnCreate)107 TimeSystemAbility::TimeSystemAbility(int32_t systemAbilityId, bool runOnCreate)
108     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
109       rtcId(GetWallClockRtcId())
110 {
111     TIME_HILOGD(TIME_MODULE_SERVICE, " TimeSystemAbility Start");
112 }
113 
TimeSystemAbility()114 TimeSystemAbility::TimeSystemAbility() : state_(ServiceRunningState::STATE_NOT_START), rtcId(GetWallClockRtcId())
115 {
116 }
117 
~TimeSystemAbility()118 TimeSystemAbility::~TimeSystemAbility(){};
119 
GetInstance()120 sptr<TimeSystemAbility> TimeSystemAbility::GetInstance()
121 {
122     if (instance_ == nullptr) {
123         std::lock_guard<std::mutex> autoLock(instanceLock_);
124         if (instance_ == nullptr) {
125             instance_ = new TimeSystemAbility;
126         }
127     }
128     return instance_;
129 }
130 
131 #ifdef HIDUMPER_ENABLE
InitDumpCmd()132 void TimeSystemAbility::InitDumpCmd()
133 {
134     auto cmdTime = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-time" }),
135         "dump current time info,include localtime,timezone info",
136         [this](int fd, const std::vector<std::string> &input) { DumpAllTimeInfo(fd, input); });
137     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTime);
138 
139     auto cmdTimerAll = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-a" }),
140         "dump all timer info", [this](int fd, const std::vector<std::string> &input) { DumpTimerInfo(fd, input); });
141     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerAll);
142 
143     auto cmdTimerInfo = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-i", "[n]" }),
144         "dump the timer info with timer id",
145         [this](int fd, const std::vector<std::string> &input) { DumpTimerInfoById(fd, input); });
146     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerInfo);
147 
148     auto cmdTimerTrigger = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-s", "[n]" }),
149         "dump current time info,include localtime,timezone info",
150         [this](int fd, const std::vector<std::string> &input) { DumpTimerTriggerById(fd, input); });
151     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerTrigger);
152 
153     auto cmdTimerIdle = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-idle", "-a" }),
154         "dump idle state and timer info, include pending delay timers and delayed info.",
155         [this](int fd, const std::vector<std::string> &input) { DumpIdleTimerInfo(fd, input); });
156     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerIdle);
157 
158     auto cmdProxyTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyTimer", "-l" }),
159         "dump proxy timer info.",
160         [this](int fd, const std::vector<std::string> &input) { DumpProxyTimerInfo(fd, input); });
161     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdProxyTimer);
162 
163     auto cmdUidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-UidTimer", "-l" }),
164         "dump uid timer map.",
165         [this](int fd, const std::vector<std::string> &input) { DumpUidTimerMapInfo(fd, input); });
166     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdUidTimer);
167 
168     auto cmdShowDelayTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyDelayTime", "-l" }),
169         "dump proxy delay time.",
170         [this](int fd, const std::vector<std::string> &input) { DumpProxyDelayTime(fd, input); });
171     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdShowDelayTimer);
172 
173     auto cmdAdjustTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-adjust", "-a" }),
174         "dump adjust time.",
175         [this](int fd, const std::vector<std::string> &input) { DumpAdjustTime(fd, input); });
176     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdAdjustTimer);
177 }
178 #endif
179 
OnStart()180 void TimeSystemAbility::OnStart()
181 {
182     TIME_HILOGI(TIME_MODULE_SERVICE, "TimeSystemAbility OnStart");
183     if (state_ == ServiceRunningState::STATE_RUNNING) {
184         TIME_HILOGE(TIME_MODULE_SERVICE, "TimeSystemAbility is already running");
185         return;
186     }
187     TimerManager::GetInstance();
188     TimeTickNotify::GetInstance().Init();
189     TimeZoneInfo::GetInstance().Init();
190     NtpUpdateTime::GetInstance().Init();
191     // This parameter is set to true by init only after all services have been started,
192     // and is automatically set to false after shutdown. Otherwise it will not be modified.
193     std::string bootCompleted = system::GetParameter(BOOTEVENT_PARAMETER, "");
194     TIME_HILOGI(TIME_MODULE_SERVICE, "bootCompleted: %{public}s", bootCompleted.c_str());
195     if (bootCompleted != "true") {
196         #ifdef RDB_ENABLE
197         TimeDatabase::GetInstance().ClearDropOnReboot();
198         #else
199         CjsonHelper::GetInstance().Clear(DROP_ON_REBOOT);
200         #endif
201     }
202     AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
203     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
204     AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
205     #ifdef SET_AUTO_REBOOT_ENABLE
206     AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
207     #endif
208     AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
209     #ifdef MULTI_ACCOUNT_ENABLE
210     AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
211     #endif
212     #ifdef HIDUMPER_ENABLE
213     InitDumpCmd();
214     #endif
215     if (Init() != ERR_OK) {
216         auto callback = [this]() {
217             sleep(INIT_INTERVAL);
218             Init();
219         };
220         std::thread thread(callback);
221         thread.detach();
222         TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later");
223     }
224 }
225 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)226 void TimeSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
227 {
228     TIME_HILOGD(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId:%{public}d added", systemAbilityId);
229     switch (systemAbilityId) {
230         case COMMON_EVENT_SERVICE_ID:
231             RegisterCommonEventSubscriber();
232             RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
233             break;
234         case DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID:
235             RegisterRSSDeathCallback();
236             break;
237         #ifdef SET_AUTO_REBOOT_ENABLE
238         case POWER_MANAGER_SERVICE_ID:
239             RegisterPowerStateListener();
240             break;
241         #endif
242         case ABILITY_MGR_SERVICE_ID:
243             AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
244             RemoveSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
245             break;
246         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
247             RecoverTimer();
248             RemoveSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
249             break;
250         #ifdef MULTI_ACCOUNT_ENABLE
251         case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
252             RegisterOsAccountSubscriber();
253             break;
254         #endif
255         default:
256             TIME_HILOGE(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId is not valid, id is %{public}d",
257                 systemAbilityId);
258     }
259 }
260 
RegisterSubscriber()261 void TimeSystemAbility::RegisterSubscriber()
262 {
263     MatchingSkills matchingSkills;
264     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_CONNECTIVITY_CHANGE);
265     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
266     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_NITZ_TIME_CHANGED);
267     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
268     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
269     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
270     CommonEventSubscribeInfo subscriberInfo(matchingSkills);
271     std::shared_ptr<EventManager> subscriberPtr = std::make_shared<EventManager>(subscriberInfo);
272     bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriberPtr);
273     TIME_HILOGI(TIME_MODULE_SERVICE, "Register com event res:%{public}d", subscribeResult);
274 }
275 
RegisterCommonEventSubscriber()276 void TimeSystemAbility::RegisterCommonEventSubscriber()
277 {
278     TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterCommonEventSubscriber Started");
279     bool subRes = TimeServiceNotify::GetInstance().RepublishEvents();
280     if (!subRes) {
281         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to RegisterCommonEventSubscriber");
282         auto callback = [this]() {
283             sleep(INIT_INTERVAL);
284             TimeServiceNotify::GetInstance().RepublishEvents();
285         };
286         std::thread thread(callback);
287         thread.detach();
288     }
289     RegisterSubscriber();
290     NtpUpdateTime::SetSystemTime();
291 }
292 
293 #ifdef MULTI_ACCOUNT_ENABLE
RegisterOsAccountSubscriber()294 void TimeSystemAbility::RegisterOsAccountSubscriber()
295 {
296     TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterOsAccountSubscriber Started");
297     AccountSA::OsAccountSubscribeInfo subscribeInfo(AccountSA::OS_ACCOUNT_SUBSCRIBE_TYPE::REMOVED, SUBSCRIBE_REMOVED);
298     auto userChangedSubscriber = std::make_shared<UserRemovedSubscriber>(subscribeInfo);
299     int err = AccountSA::OsAccountManager::SubscribeOsAccount(userChangedSubscriber);
300     if (err != ERR_OK) {
301         TIME_HILOGE(TIME_MODULE_SERVICE, "Subscribe user removed event failed, errcode: %{public}d", err);
302     }
303 }
304 #endif
305 
Init()306 int32_t TimeSystemAbility::Init()
307 {
308     bool ret = Publish(TimeSystemAbility::GetInstance());
309     if (!ret) {
310         TIME_HILOGE(TIME_MODULE_SERVICE, "Init Failed");
311         return E_TIME_PUBLISH_FAIL;
312     }
313     TIME_HILOGI(TIME_MODULE_SERVICE, "Init success");
314     state_ = ServiceRunningState::STATE_RUNNING;
315     return ERR_OK;
316 }
317 
OnStop()318 void TimeSystemAbility::OnStop()
319 {
320     TIME_HILOGD(TIME_MODULE_SERVICE, "OnStop Started");
321     if (state_ != ServiceRunningState::STATE_RUNNING) {
322         TIME_HILOGI(TIME_MODULE_SERVICE, "state is running");
323         return;
324     }
325     TimeTickNotify::GetInstance().Stop();
326     state_ = ServiceRunningState::STATE_NOT_START;
327     TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End");
328 }
329 
ParseTimerPara(const std::shared_ptr<ITimerInfo> & timerOptions,TimerPara & paras)330 void TimeSystemAbility::ParseTimerPara(const std::shared_ptr<ITimerInfo> &timerOptions, TimerPara &paras)
331 {
332     auto uIntType = static_cast<uint32_t>(timerOptions->type);
333     bool isRealtime = (uIntType & TIMER_TYPE_REALTIME_MASK) > 0;
334     bool isWakeup = (uIntType & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0;
335     paras.windowLength = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 0 : -1;
336     paras.flag = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 1 : 0;
337     paras.autoRestore = timerOptions->autoRestore;
338     if (isRealtime && isWakeup) {
339         paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP;
340     } else if (isRealtime) {
341         paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
342     } else if (isWakeup) {
343         paras.timerType = ITimerManager::TimerType::RTC_WAKEUP;
344     } else {
345         paras.timerType = ITimerManager::TimerType::RTC;
346     }
347     if ((uIntType & TIMER_TYPE_IDLE_MASK) > 0) {
348         paras.flag |= ITimerManager::TimerFlag::IDLE_UNTIL;
349     }
350     if ((uIntType & TIMER_TYPE_INEXACT_REMINDER_MASK) > 0) {
351         paras.flag |= ITimerManager::TimerFlag::INEXACT_REMINDER;
352     }
353     if (timerOptions->disposable) {
354         paras.flag |= ITimerManager::TimerFlag::IS_DISPOSABLE;
355     }
356     if (timerOptions->name != "") {
357         paras.name = timerOptions->name;
358     }
359     paras.interval = timerOptions->repeat ? timerOptions->interval : 0;
360 }
361 
CheckTimerPara(const DatabaseType type,const TimerPara & paras)362 int32_t TimeSystemAbility::CheckTimerPara(const DatabaseType type, const TimerPara &paras)
363 {
364     if (paras.autoRestore && (paras.timerType == ITimerManager::TimerType::ELAPSED_REALTIME ||
365         paras.timerType == ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP || type == DatabaseType::NOT_STORE)) {
366         return E_TIME_AUTO_RESTORE_ERROR;
367     }
368     if (paras.name.size() > STR_MAX_LENGTH) {
369         return E_TIME_PARAMETERS_INVALID;
370     }
371     return E_TIME_OK;
372 }
373 
CreateTimer(const SimpleTimerInfo & simpleTimerInfo,const sptr<IRemoteObject> & timerCallback,uint64_t & timerId)374 int32_t TimeSystemAbility::CreateTimer(const SimpleTimerInfo& simpleTimerInfo,
375                                        const sptr<IRemoteObject> &timerCallback,
376                                        uint64_t &timerId)
377 {
378     TimeXCollie timeXCollie("TimeService::CreateTimer");
379     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
380         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
381         return E_TIME_NOT_SYSTEM_APP;
382     }
383     auto timerInfo = std::make_shared<SimpleTimerInfo>(simpleTimerInfo);
384     auto ret = CreateTimer(timerInfo, timerCallback, timerId);
385     if (ret != E_TIME_OK) {
386         return E_TIME_DEAL_FAILED;
387     }
388     return E_TIME_OK;
389 }
390 
CreateTimer(const std::shared_ptr<ITimerInfo> & timerOptions,const sptr<IRemoteObject> & obj,uint64_t & timerId)391 int32_t TimeSystemAbility::CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, const sptr<IRemoteObject> &obj,
392     uint64_t &timerId)
393 {
394     if (obj == nullptr) {
395         TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr");
396         return E_TIME_NULLPTR;
397     }
398     sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
399     if (timerCallback == nullptr) {
400         TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr");
401         return E_TIME_NULLPTR;
402     }
403     auto type = DatabaseType::NOT_STORE;
404     if (timerOptions->wantAgent != nullptr) {
405         type = DatabaseType::STORE;
406     }
407     int uid = IPCSkeleton::GetCallingUid();
408     int pid = IPCSkeleton::GetCallingPid();
409     struct TimerPara paras {};
410     ParseTimerPara(timerOptions, paras);
411     int32_t res = CheckTimerPara(type, paras);
412     if (res != E_TIME_OK) {
413         TIME_HILOGE(TIME_MODULE_SERVICE, "check para err:%{public}d,uid:%{public}d", res, uid);
414         return res;
415     }
416     auto timerManager = TimerManager::GetInstance();
417     if (timerManager == nullptr) {
418         return E_TIME_NULLPTR;
419     }
420     auto callbackFunc = [timerCallback](uint64_t id) -> int32_t {
421         return timerCallback->NotifyTimer(id);
422     };
423     if ((paras.flag & ITimerManager::TimerFlag::IDLE_UNTIL) > 0 &&
424         !TimePermission::CheckProxyCallingPermission()) {
425         TIME_HILOGW(TIME_MODULE_SERVICE, "App not support create idle timer");
426         paras.flag &= ~ITimerManager::TimerFlag::IDLE_UNTIL;
427     }
428     return timerManager->CreateTimer(paras, callbackFunc, timerOptions->wantAgent,
429                                      uid, pid, timerId, type);
430 }
431 
CreateTimer(TimerPara & paras,std::function<int32_t (const uint64_t)> callback,uint64_t & timerId)432 int32_t TimeSystemAbility::CreateTimer(TimerPara &paras, std::function<int32_t (const uint64_t)> callback,
433     uint64_t &timerId)
434 {
435     auto timerManager = TimerManager::GetInstance();
436     if (timerManager == nullptr) {
437         return E_TIME_NULLPTR;
438     }
439     return timerManager->CreateTimer(paras, std::move(callback), nullptr, 0, 0, timerId, NOT_STORE);
440 }
441 
StartTimer(uint64_t timerId,uint64_t triggerTime)442 int32_t TimeSystemAbility::StartTimer(uint64_t timerId, uint64_t triggerTime)
443 {
444     TimeXCollie timeXCollie("TimeService::StartTimer");
445     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
446         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
447         return E_TIME_NOT_SYSTEM_APP;
448     }
449     auto timerManager = TimerManager::GetInstance();
450     if (timerManager == nullptr) {
451         return E_TIME_NULLPTR;
452     }
453     auto ret = timerManager->StartTimer(timerId, triggerTime);
454     if (ret != E_TIME_OK) {
455         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to start timer");
456         return E_TIME_DEAL_FAILED;
457     }
458     return ret;
459 }
460 
StopTimer(uint64_t timerId)461 int32_t TimeSystemAbility::StopTimer(uint64_t timerId)
462 {
463     TimeXCollie timeXCollie("TimeService::StopTimer");
464     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
465         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
466         return E_TIME_NOT_SYSTEM_APP;
467     }
468     auto timerManager = TimerManager::GetInstance();
469     if (timerManager == nullptr) {
470         return E_TIME_NULLPTR;
471     }
472     auto ret = timerManager->StopTimer(timerId);
473     if (ret != E_TIME_OK) {
474         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to stop timer");
475         return E_TIME_DEAL_FAILED;
476     }
477     return ret;
478 }
479 
DestroyTimer(uint64_t timerId)480 int32_t TimeSystemAbility::DestroyTimer(uint64_t timerId)
481 {
482     TimeXCollie timeXCollie("TimeService::DestroyTimer");
483     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
484         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
485         return E_TIME_NOT_SYSTEM_APP;
486     }
487     auto timerManager = TimerManager::GetInstance();
488     if (timerManager == nullptr) {
489         return E_TIME_NULLPTR;
490     }
491     auto ret = timerManager->DestroyTimer(timerId);
492     if (ret != E_TIME_OK) {
493         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to destory timer");
494         return E_TIME_DEAL_FAILED;
495     }
496     return ret;
497 }
498 
DestroyTimerAsync(uint64_t timerId)499 int32_t TimeSystemAbility::DestroyTimerAsync(uint64_t timerId)
500 {
501     return DestroyTimer(timerId);
502 }
503 
IsValidTime(int64_t time)504 bool TimeSystemAbility::IsValidTime(int64_t time)
505 {
506 #if __SIZEOF_POINTER__ == 4
507     if (time / MILLI_TO_BASE > LONG_MAX) {
508         return false;
509     }
510 #endif
511     return true;
512 }
513 
SetRealTime(int64_t time)514 bool TimeSystemAbility::SetRealTime(int64_t time)
515 {
516     if (!IsValidTime(time)) {
517         TIME_HILOGE(TIME_MODULE_SERVICE, "time is invalid: %{public}s", std::to_string(time).c_str());
518         return false;
519     }
520     sptr<TimeSystemAbility> instance = TimeSystemAbility::GetInstance();
521     int64_t beforeTime = 0;
522     TimeUtils::GetWallTimeMs(beforeTime);
523     int64_t bootTime = 0;
524     TimeUtils::GetBootTimeMs(bootTime);
525     TIME_HILOGI(TIME_MODULE_SERVICE,
526         "Before Current Time: %{public}s"
527         " Set time: %{public}s"
528         " Difference: %{public}s"
529         " uid:%{public}d pid:%{public}d ",
530         std::to_string(beforeTime).c_str(), std::to_string(time).c_str(), std::to_string(time - bootTime).c_str(),
531         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
532     if (time < 0) {
533         TIME_HILOGE(TIME_MODULE_SERVICE, "input param error %{public}" PRId64 "", time);
534         return false;
535     }
536     int64_t currentTime = 0;
537     if (TimeUtils::GetWallTimeMs(currentTime) != ERR_OK) {
538         TIME_HILOGE(TIME_MODULE_SERVICE, "currentTime get failed");
539         return false;
540     }
541     struct timeval tv {};
542     tv.tv_sec = (time_t)(time / MILLI_TO_BASE);
543     tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR);
544     int result = settimeofday(&tv, nullptr);
545     if (result < 0) {
546         TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday time fail: %{public}d. error: %{public}s", result,
547             strerror(errno));
548         return false;
549     }
550     auto ret = SetRtcTime(tv.tv_sec);
551     if (ret == E_TIME_SET_RTC_FAILED) {
552         TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d", ret);
553         return false;
554     }
555     TIME_HILOGD(TIME_MODULE_SERVICE, "getting currentTime to milliseconds: %{public}" PRId64 "", currentTime);
556     if (currentTime < (time - ONE_MILLI) || currentTime > (time + ONE_MILLI)) {
557         TimeServiceNotify::GetInstance().PublishTimeChangeEvents(currentTime);
558     }
559     TimeTickNotify::GetInstance().Callback();
560     int64_t curtime = NtpTrustedTime::GetInstance().CurrentTimeMillis();
561     TimeBehaviorReport(ReportEventCode::SET_TIME, std::to_string(beforeTime), std::to_string(time), curtime);
562     return true;
563 }
564 
SetTime(int64_t time,int8_t apiVersion)565 int32_t TimeSystemAbility::SetTime(int64_t time, int8_t apiVersion)
566 {
567     TimeXCollie timeXCollie("TimeService::SetTime");
568     if (apiVersion == APIVersion::API_VERSION_9) {
569         if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
570             TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
571             return E_TIME_NOT_SYSTEM_APP;
572         }
573     }
574     if (!TimePermission::CheckCallingPermission(TimePermission::setTime)) {
575         TIME_HILOGE(TIME_MODULE_SERVICE, "permission check setTime failed");
576         return E_TIME_NO_PERMISSION;
577     }
578     return SetTimeInner(time, apiVersion);
579 }
580 
SetTimeInner(int64_t time,int8_t apiVersion)581 int32_t TimeSystemAbility::SetTimeInner(int64_t time, int8_t apiVersion)
582 {
583     if (!SetRealTime(time)) {
584         return E_TIME_DEAL_FAILED;
585     }
586     return ERR_OK;
587 }
588 
589 #ifdef HIDUMPER_ENABLE
Dump(int fd,const std::vector<std::u16string> & args)590 int TimeSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
591 {
592     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
593     const int maxUid = 10000;
594     if (uid > maxUid) {
595         return E_TIME_DEAL_FAILED;
596     }
597 
598     std::vector<std::string> argsStr;
599     for (auto &item : args) {
600         argsStr.emplace_back(Str16ToStr8(item));
601     }
602 
603     TimeCmdDispatcher::GetInstance().Dispatch(fd, argsStr);
604     return ERR_OK;
605 }
606 
DumpAllTimeInfo(int fd,const std::vector<std::string> & input)607 void TimeSystemAbility::DumpAllTimeInfo(int fd, const std::vector<std::string> &input)
608 {
609     dprintf(fd, "\n - dump all time info :\n");
610     struct timespec ts{};
611     struct tm timestr{};
612     char date_time[64];
613     if (GetTimeByClockId(CLOCK_BOOTTIME, ts)) {
614         auto localTime = localtime_r(&ts.tv_sec, &timestr);
615         if (localTime == nullptr) {
616             return;
617         }
618         strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localTime);
619         dprintf(fd, " * date time = %s\n", date_time);
620     } else {
621         dprintf(fd, " * dump date time error.\n");
622     }
623     dprintf(fd, " - dump the time Zone:\n");
624     std::string timeZone;
625     int32_t bRet = GetTimeZone(timeZone);
626     if (bRet == ERR_OK) {
627         dprintf(fd, " * time zone = %s\n", timeZone.c_str());
628     } else {
629         dprintf(fd, " * dump time zone error,is %s\n", timeZone.c_str());
630     }
631 }
632 
DumpTimerInfo(int fd,const std::vector<std::string> & input)633 void TimeSystemAbility::DumpTimerInfo(int fd, const std::vector<std::string> &input)
634 {
635     dprintf(fd, "\n - dump all timer info :\n");
636     auto timerManager = TimerManager::GetInstance();
637     if (timerManager == nullptr) {
638         return;
639     }
640     timerManager->ShowTimerEntryMap(fd);
641 }
642 
DumpTimerInfoById(int fd,const std::vector<std::string> & input)643 void TimeSystemAbility::DumpTimerInfoById(int fd, const std::vector<std::string> &input)
644 {
645     dprintf(fd, "\n - dump the timer info with timer id:\n");
646     int paramNumPos = 2;
647     auto timerManager = TimerManager::GetInstance();
648     if (timerManager == nullptr) {
649         return;
650     }
651     timerManager->ShowTimerEntryById(fd, std::atoi(input.at(paramNumPos).c_str()));
652 }
653 
DumpTimerTriggerById(int fd,const std::vector<std::string> & input)654 void TimeSystemAbility::DumpTimerTriggerById(int fd, const std::vector<std::string> &input)
655 {
656     dprintf(fd, "\n - dump timer trigger statics with timer id:\n");
657     int paramNumPos = 2;
658     auto timerManager = TimerManager::GetInstance();
659     if (timerManager == nullptr) {
660         return;
661     }
662     timerManager->ShowTimerTriggerById(fd, std::atoi(input.at(paramNumPos).c_str()));
663 }
664 
DumpIdleTimerInfo(int fd,const std::vector<std::string> & input)665 void TimeSystemAbility::DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)
666 {
667     dprintf(fd, "\n - dump idle timer info :\n");
668     auto timerManager = TimerManager::GetInstance();
669     if (timerManager == nullptr) {
670         return;
671     }
672     timerManager->ShowIdleTimerInfo(fd);
673 }
674 
DumpProxyTimerInfo(int fd,const std::vector<std::string> & input)675 void TimeSystemAbility::DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)
676 {
677     dprintf(fd, "\n - dump proxy map:\n");
678     int64_t times;
679     TimeUtils::GetBootTimeNs(times);
680     TimerProxy::GetInstance().ShowProxyTimerInfo(fd, times);
681 }
682 
DumpUidTimerMapInfo(int fd,const std::vector<std::string> & input)683 void TimeSystemAbility::DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)
684 {
685     dprintf(fd, "\n - dump uid timer map:\n");
686     int64_t times;
687     TimeUtils::GetBootTimeNs(times);
688     TimerProxy::GetInstance().ShowUidTimerMapInfo(fd, times);
689 }
690 
DumpProxyDelayTime(int fd,const std::vector<std::string> & input)691 void TimeSystemAbility::DumpProxyDelayTime(int fd, const std::vector<std::string> &input)
692 {
693     dprintf(fd, "\n - dump proxy delay time:\n");
694     TimerProxy::GetInstance().ShowProxyDelayTime(fd);
695 }
696 
DumpAdjustTime(int fd,const std::vector<std::string> & input)697 void TimeSystemAbility::DumpAdjustTime(int fd, const std::vector<std::string> &input)
698 {
699     dprintf(fd, "\n - dump adjust timer info:\n");
700     TimerProxy::GetInstance().ShowAdjustTimerInfo(fd);
701 }
702 #endif
703 
SetRtcTime(time_t sec)704 int TimeSystemAbility::SetRtcTime(time_t sec)
705 {
706     struct rtc_time rtc {};
707     struct tm tm {};
708     struct tm *gmtime_res = nullptr;
709     int fd = -1;
710     int res;
711     if (rtcId < 0) {
712         TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
713         return E_TIME_SET_RTC_FAILED;
714     }
715     std::stringstream strs;
716     strs << "/dev/rtc" << rtcId;
717     auto rtcDev = strs.str();
718     TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtcDev.data());
719     auto rtcData = rtcDev.data();
720     fd = open(rtcData, O_RDWR);
721     if (fd < 0) {
722         TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtcDev.data(), strerror(errno));
723         return E_TIME_SET_RTC_FAILED;
724     }
725     gmtime_res = gmtime_r(&sec, &tm);
726     if (gmtime_res) {
727         rtc.tm_sec = tm.tm_sec;
728         rtc.tm_min = tm.tm_min;
729         rtc.tm_hour = tm.tm_hour;
730         rtc.tm_mday = tm.tm_mday;
731         rtc.tm_mon = tm.tm_mon;
732         rtc.tm_year = tm.tm_year;
733         rtc.tm_wday = tm.tm_wday;
734         rtc.tm_yday = tm.tm_yday;
735         rtc.tm_isdst = tm.tm_isdst;
736         res = ioctl(fd, RTC_SET_TIME, &rtc);
737         if (res < 0) {
738             TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed,errno: %{public}s, res: %{public}d",
739                 strerror(errno), res);
740         }
741     } else {
742         TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
743         res = E_TIME_SET_RTC_FAILED;
744     }
745     close(fd);
746     return res;
747 }
748 
CheckRtc(const std::string & rtcPath,uint64_t rtcId)749 bool TimeSystemAbility::CheckRtc(const std::string &rtcPath, uint64_t rtcId)
750 {
751     std::stringstream strs;
752     strs << rtcPath << "/rtc" << rtcId << "/hctosys";
753     auto hctosys_path = strs.str();
754 
755     std::fstream file(hctosys_path.data(), std::ios_base::in);
756     if (file.is_open()) {
757         return true;
758     } else {
759         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
760         return false;
761     }
762 }
763 
GetWallClockRtcId()764 int TimeSystemAbility::GetWallClockRtcId()
765 {
766     std::string rtcPath = "/sys/class/rtc";
767 
768     std::unique_ptr<DIR, int (*)(DIR *)> dir(opendir(rtcPath.c_str()), closedir);
769     if (!dir.get()) {
770         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtcPath.c_str(), strerror(errno));
771         return -1;
772     }
773 
774     struct dirent *dirent;
775     std::string s = "rtc";
776     while (errno = 0, dirent = readdir(dir.get())) {
777         std::string name(dirent->d_name);
778         unsigned long rtcId = 0;
779         auto index = name.find(s);
780         if (index == std::string::npos) {
781             continue;
782         } else {
783             auto rtcIdStr = name.substr(index + s.length());
784             rtcId = std::stoul(rtcIdStr);
785         }
786         if (CheckRtc(rtcPath, rtcId)) {
787             TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}ld", rtcId);
788             return rtcId;
789         }
790     }
791 
792     if (errno == 0) {
793         TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
794     } else {
795         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
796     }
797     return -1;
798 }
799 
SetTimeZone(const std::string & timeZoneId,int8_t apiVersion)800 int32_t TimeSystemAbility::SetTimeZone(const std::string &timeZoneId, int8_t apiVersion)
801 {
802     TimeXCollie timeXCollie("TimeService::SetTimeZone");
803     if (apiVersion == APIVersion::API_VERSION_9) {
804         if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
805             TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
806             return E_TIME_NOT_SYSTEM_APP;
807         }
808     }
809     if (!TimePermission::CheckCallingPermission(TimePermission::setTimeZone)) {
810         TIME_HILOGE(TIME_MODULE_SERVICE, "permission check setTime failed");
811         return E_TIME_NO_PERMISSION;
812     }
813     return SetTimeZoneInner(timeZoneId, apiVersion);
814 }
815 
SetTimeZoneInner(const std::string & timeZoneId,int8_t apiVersion)816 int32_t TimeSystemAbility::SetTimeZoneInner(const std::string &timeZoneId, int8_t apiVersion)
817 {
818     if (!TimeZoneInfo::GetInstance().SetTimezone(timeZoneId)) {
819         TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
820         return E_TIME_DEAL_FAILED;
821     }
822     int64_t currentTime = 0;
823     TimeUtils::GetBootTimeMs(currentTime);
824     TimeServiceNotify::GetInstance().PublishTimeZoneChangeEvents(currentTime);
825     return ERR_OK;
826 }
827 
GetTimeZone(std::string & timeZoneId)828 int32_t TimeSystemAbility::GetTimeZone(std::string &timeZoneId)
829 {
830     TimeXCollie timeXCollie("TimeService::GetTimeZone");
831     if (!TimeZoneInfo::GetInstance().GetTimezone(timeZoneId)) {
832         TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed");
833         return E_TIME_DEAL_FAILED;
834     }
835     TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
836     return ERR_OK;
837 }
838 
GetThreadTimeMs(int64_t & time)839 int32_t TimeSystemAbility::GetThreadTimeMs(int64_t &time)
840 {
841     TimeXCollie timeXCollie("TimeService::GetThreadTimeMs");
842     struct timespec tv {};
843     clockid_t cid;
844     int ret = pthread_getcpuclockid(pthread_self(), &cid);
845     if (ret != E_TIME_OK) {
846         return E_TIME_PARAMETERS_INVALID;
847     }
848     if (GetTimeByClockId(cid, tv)) {
849         time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
850         return ERR_OK;
851     }
852     return E_TIME_DEAL_FAILED;
853 }
854 
GetThreadTimeNs(int64_t & time)855 int32_t TimeSystemAbility::GetThreadTimeNs(int64_t &time)
856 {
857     TimeXCollie timeXCollie("TimeService::GetThreadTimeNs");
858     struct timespec tv {};
859     clockid_t cid;
860     int ret = pthread_getcpuclockid(pthread_self(), &cid);
861     if (ret != E_TIME_OK) {
862         return E_TIME_PARAMETERS_INVALID;
863     }
864     if (GetTimeByClockId(cid, tv)) {
865         time = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
866         return ERR_OK;
867     }
868     return E_TIME_DEAL_FAILED;
869 }
870 
GetTimeByClockId(clockid_t clockId,struct timespec & tv)871 bool TimeSystemAbility::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
872 {
873     if (clock_gettime(clockId, &tv) < 0) {
874         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime");
875         return false;
876     }
877     return true;
878 }
879 
AdjustTimer(bool isAdjust,uint32_t interval,uint32_t delta)880 int32_t TimeSystemAbility::AdjustTimer(bool isAdjust, uint32_t interval, uint32_t delta)
881 {
882     TimeXCollie timeXCollie("TimeService::AdjustTimer");
883     if (!TimePermission::CheckProxyCallingPermission()) {
884         TIME_HILOGE(TIME_MODULE_SERVICE, "Adjust Timer permission check failed");
885         return E_TIME_NO_PERMISSION;
886     }
887     if (isAdjust && interval == 0) {
888         TIME_HILOGE(TIME_MODULE_SERVICE, "invalid parameter: interval");
889         return E_TIME_READ_PARCEL_ERROR;
890     }
891     auto timerManager = TimerManager::GetInstance();
892     if (timerManager == nullptr) {
893         return E_TIME_NULLPTR;
894     }
895     if (!timerManager->AdjustTimer(isAdjust, interval, delta)) {
896         TIME_HILOGE(TIME_MODULE_SERVICE, "Error adjust timer");
897         return E_TIME_DEAL_FAILED;
898     }
899     return E_TIME_OK;
900 }
901 
ProxyTimer(int32_t uid,const std::vector<int> & pidList,bool isProxy,bool needRetrigger)902 int32_t TimeSystemAbility::ProxyTimer(int32_t uid, const std::vector<int>& pidList, bool isProxy, bool needRetrigger)
903 {
904     TimeXCollie timeXCollie("TimeService::TimerProxy");
905     if (!TimePermission::CheckProxyCallingPermission()) {
906         TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
907         return E_TIME_NO_PERMISSION;
908     }
909     if (pidList.size() > MAX_PID_LIST_SIZE) {
910         TIME_HILOGE(TIME_MODULE_SERVICE, "Error pid list size");
911         return E_TIME_PARAMETERS_INVALID;
912     }
913     if (pidList.size() == 0) {
914         TIME_HILOGE(TIME_MODULE_SERVICE, "Error pidList");
915         return E_TIME_PARAMETERS_INVALID;
916     }
917     auto timerManager = TimerManager::GetInstance();
918     if (timerManager == nullptr) {
919         return E_TIME_NULLPTR;
920     }
921     std::set<int> pidSet;
922     std::copy(pidList.begin(), pidList.end(), std::insert_iterator<std::set<int>>(pidSet, pidSet.begin()));
923     auto ret = timerManager->ProxyTimer(uid, pidSet, isProxy, needRetrigger);
924     if (!ret) {
925         return E_TIME_DEAL_FAILED;
926     }
927     return ERR_OK;
928 }
929 
SetTimerExemption(const std::vector<std::string> & nameArr,bool isExemption)930 int32_t TimeSystemAbility::SetTimerExemption(const std::vector<std::string> &nameArr, bool isExemption)
931 {
932     TimeXCollie timeXCollie("TimeService::SetTimerExemption");
933     if (!TimePermission::CheckProxyCallingPermission()) {
934         TIME_HILOGE(TIME_MODULE_SERVICE, "Set Timer Exemption permission check failed");
935         return E_TIME_NO_PERMISSION;
936     }
937     if (nameArr.size() > MAX_EXEMPTION_SIZE) {
938         return E_TIME_PARAMETERS_INVALID;
939     }
940     auto timerManager = TimerManager::GetInstance();
941     if (timerManager == nullptr) {
942         return E_TIME_NULLPTR;
943     }
944     std::unordered_set<std::string> nameSet;
945     std::copy(nameArr.begin(), nameArr.end(), std::inserter(nameSet, nameSet.begin()));
946     timerManager->SetTimerExemption(nameSet, isExemption);
947     return E_TIME_OK;
948 }
949 
ResetAllProxy()950 int32_t TimeSystemAbility::ResetAllProxy()
951 {
952     if (!TimePermission::CheckProxyCallingPermission()) {
953         TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy permission check failed");
954         return E_TIME_NO_PERMISSION;
955     }
956     TIME_HILOGD(TIME_MODULE_SERVICE, "ResetAllProxy service");
957     auto timerManager = TimerManager::GetInstance();
958     if (timerManager == nullptr) {
959         return E_TIME_NULLPTR;
960     }
961     if (!timerManager->ResetAllProxy()) {
962         return E_TIME_DEAL_FAILED;
963     }
964     return E_TIME_OK;
965 }
966 
GetNtpTimeMs(int64_t & time)967 int32_t TimeSystemAbility::GetNtpTimeMs(int64_t &time)
968 {
969     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
970         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
971         return E_TIME_NOT_SYSTEM_APP;
972     }
973     auto ret = NtpUpdateTime::GetInstance().GetNtpTime(time);
974     if (!ret) {
975         TIME_HILOGE(TIME_MODULE_SERVICE, "GetNtpTimeMs failed");
976         return E_TIME_NTP_UPDATE_FAILED;
977     }
978     return E_TIME_OK;
979 }
980 
GetRealTimeMs(int64_t & time)981 int32_t TimeSystemAbility::GetRealTimeMs(int64_t &time)
982 {
983     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
984         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
985         return E_TIME_NOT_SYSTEM_APP;
986     }
987     auto ret = NtpUpdateTime::GetInstance().GetRealTime(time);
988     if (!ret) {
989         TIME_HILOGE(TIME_MODULE_SERVICE, "GetRealTimeMs failed");
990         return E_TIME_NTP_NOT_UPDATE;
991     }
992     return E_TIME_OK;
993 }
994 
OnRemoteDied(const wptr<IRemoteObject> & object)995 void TimeSystemAbility::RSSSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
996 {
997     auto timerManager = TimerManager::GetInstance();
998     if (timerManager == nullptr) {
999         return;
1000     }
1001     timerManager->HandleRSSDeath();
1002 }
1003 
RegisterRSSDeathCallback()1004 void TimeSystemAbility::RegisterRSSDeathCallback()
1005 {
1006     TIME_HILOGD(TIME_MODULE_SERVICE, "register rss death callback");
1007     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1008     if (systemAbilityManager == nullptr) {
1009         TIME_HILOGE(TIME_MODULE_CLIENT, "Getting SystemAbilityManager failed");
1010         return;
1011     }
1012 
1013     auto systemAbility = systemAbilityManager->GetSystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
1014     if (systemAbility == nullptr) {
1015         TIME_HILOGE(TIME_MODULE_CLIENT, "Get SystemAbility failed");
1016         return;
1017     }
1018 
1019     if (deathRecipient_ == nullptr) {
1020         deathRecipient_ = new RSSSaDeathRecipient();
1021     }
1022 
1023     systemAbility->AddDeathRecipient(deathRecipient_);
1024 }
1025 
1026 #ifdef SET_AUTO_REBOOT_ENABLE
OnSyncShutdown()1027 void TimeSystemAbility::TimePowerStateListener::OnSyncShutdown()
1028 {
1029     // Clears `drop_on_reboot` table.
1030     TIME_HILOGI(TIME_MODULE_SERVICE, "OnSyncShutdown");
1031     TimeSystemAbility::GetInstance()->SetAutoReboot();
1032     #ifdef RDB_ENABLE
1033     TimeDatabase::GetInstance().ClearDropOnReboot();
1034     TimeDatabase::GetInstance().ClearInvaildDataInHoldOnReboot();
1035     #else
1036     CjsonHelper::GetInstance().Clear(DROP_ON_REBOOT);
1037     CjsonHelper::GetInstance().ClearInvaildDataInHoldOnReboot();
1038     #endif
1039 }
1040 
RegisterPowerStateListener()1041 void TimeSystemAbility::RegisterPowerStateListener()
1042 {
1043     TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener");
1044     auto& powerManagerClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
1045     sptr<OHOS::PowerMgr::ISyncShutdownCallback> syncShutdownCallback = new TimePowerStateListener();
1046     if (!syncShutdownCallback) {
1047         TIME_HILOGE(TIME_MODULE_SERVICE, "Get TimePowerStateListener failed");
1048         return;
1049     }
1050     powerManagerClient.RegisterShutdownCallback(syncShutdownCallback, PowerMgr::ShutdownPriority::HIGH);
1051     TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener end");
1052 }
1053 #endif
1054 
RecoverTimerCjson(std::string tableName)1055 void TimeSystemAbility::RecoverTimerCjson(std::string tableName)
1056 {
1057     cJSON* db = NULL;
1058     auto result = CjsonHelper::GetInstance().QueryTable(tableName, &db);
1059     if (result == NULL) {
1060         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}s get table failed", tableName.c_str());
1061     } else {
1062         int count = cJSON_GetArraySize(result);
1063         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}s result rows count: %{public}d", tableName.c_str(), count);
1064         #ifdef RDB_ENABLE
1065         CjsonIntoDatabase(result, true, tableName);
1066         #else
1067         RecoverTimerInnerCjson(result, true, tableName);
1068         #endif
1069     }
1070     cJSON_Delete(db);
1071 }
1072 
RecoverTimer()1073 bool TimeSystemAbility::RecoverTimer()
1074 {
1075     RecoverTimerCjson(HOLD_ON_REBOOT);
1076     RecoverTimerCjson(DROP_ON_REBOOT);
1077 
1078     #ifdef RDB_ENABLE
1079     auto database = TimeDatabase::GetInstance();
1080     OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
1081     auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
1082     if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
1083         TIME_HILOGI(TIME_MODULE_SERVICE, "hold result set is nullptr or go to first row failed");
1084     } else {
1085         int count;
1086         holdResultSet->GetRowCount(count);
1087         TIME_HILOGI(TIME_MODULE_SERVICE, "hold result rows count: %{public}d", count);
1088         RecoverTimerInner(holdResultSet, true);
1089     }
1090     if (holdResultSet != nullptr) {
1091         holdResultSet->Close();
1092     }
1093 
1094     OHOS::NativeRdb::RdbPredicates dropRdbPredicates(DROP_ON_REBOOT);
1095     auto dropResultSet = database.Query(dropRdbPredicates, ALL_DATA);
1096     if (dropResultSet == nullptr || dropResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
1097         TIME_HILOGI(TIME_MODULE_SERVICE, "drop result set is nullptr or go to first row failed");
1098     } else {
1099         int count;
1100         dropResultSet->GetRowCount(count);
1101         TIME_HILOGI(TIME_MODULE_SERVICE, "drop result rows count: %{public}d", count);
1102         RecoverTimerInner(dropResultSet, false);
1103     }
1104     if (dropResultSet != nullptr) {
1105         dropResultSet->Close();
1106     }
1107     #endif
1108     return true;
1109 }
1110 
GetEntry(cJSON * obj,bool autoRestore)1111 std::shared_ptr<TimerEntry> TimeSystemAbility::GetEntry(cJSON* obj, bool autoRestore)
1112 {
1113     auto cjson = CjsonHelper::GetInstance();
1114     auto item = cJSON_GetObjectItem(obj, "name");
1115     if (!cjson.IsString(item)) return nullptr;
1116     auto name = item->valuestring;
1117     item = cJSON_GetObjectItem(obj, "timerId");
1118     if (!cjson.IsString(item)) return nullptr;
1119     int64_t tmp;
1120     if (!cjson.StrToI64(item->valuestring, tmp)) return nullptr;
1121     auto timerId = static_cast<uint64_t>(tmp);
1122     item = cJSON_GetObjectItem(obj, "type");
1123     if (!cjson.IsNumber(item)) return nullptr;
1124     int type = item->valueint;
1125     item = cJSON_GetObjectItem(obj, "windowLength");
1126     if (!cjson.IsNumber(item)) return nullptr;
1127     uint64_t windowLength = static_cast<uint64_t>(item->valueint);
1128     item = cJSON_GetObjectItem(obj, "interval");
1129     if (!cjson.IsNumber(item)) return nullptr;
1130     uint64_t interval = static_cast<uint64_t>(item->valueint);
1131     item = cJSON_GetObjectItem(obj, "flag");
1132     if (!cjson.IsNumber(item)) return nullptr;
1133     uint32_t flag = static_cast<uint32_t>(item->valueint);
1134     item = cJSON_GetObjectItem(obj, "wantAgent");
1135     if (!cjson.IsString(item)) return nullptr;
1136     auto wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(item->valuestring);
1137     item = cJSON_GetObjectItem(obj, "uid");
1138     if (!cjson.IsNumber(item)) return nullptr;
1139     int uid = item->valueint;
1140     item = cJSON_GetObjectItem(obj, "pid");
1141     if (!cjson.IsNumber(item)) return nullptr;
1142     int pid = item->valueint;
1143     item = cJSON_GetObjectItem(obj, "bundleName");
1144     if (!cjson.IsString(item)) return nullptr;
1145     auto bundleName = item->valuestring;
1146     return std::make_shared<TimerEntry>(TimerEntry {name, timerId, type, windowLength, interval, flag, autoRestore,
1147                                                     nullptr, wantAgent, uid, pid, bundleName});
1148 }
1149 
1150 #ifdef RDB_ENABLE
CjsonIntoDatabase(cJSON * resultSet,bool autoRestore,const std::string & table)1151 void TimeSystemAbility::CjsonIntoDatabase(cJSON* resultSet, bool autoRestore, const std::string &table)
1152 {
1153     int size = cJSON_GetArraySize(resultSet);
1154     for (int i = 0; i < size; ++i) {
1155         // Get data row
1156         cJSON* obj = cJSON_GetArrayItem(resultSet, i);
1157         auto timerInfo = GetEntry(obj, autoRestore);
1158         if (timerInfo == nullptr) {
1159             continue;
1160         }
1161         if (timerInfo->wantAgent == nullptr) {
1162             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1163                 timerInfo->uid, timerInfo->id);
1164             continue;
1165         }
1166         auto item = cJSON_GetObjectItem(obj, "state");
1167         if (!CjsonHelper::GetInstance().IsNumber(item)) {
1168             continue;
1169         };
1170         auto state = item->valueint;
1171         item = cJSON_GetObjectItem(obj, "triggerTime");
1172         if (!CjsonHelper::GetInstance().IsString(item)) {
1173             continue;
1174         }
1175         int64_t triggerTime;
1176         if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, triggerTime)) {
1177             continue;
1178         }
1179         OHOS::NativeRdb::ValuesBucket insertValues;
1180         insertValues.PutLong("timerId", timerInfo->id);
1181         insertValues.PutInt("type", timerInfo->type);
1182         insertValues.PutInt("flag", timerInfo->flag);
1183         insertValues.PutLong("windowLength", timerInfo->windowLength);
1184         insertValues.PutLong("interval", timerInfo->interval);
1185         insertValues.PutInt("uid", timerInfo->uid);
1186         insertValues.PutString("bundleName", timerInfo->bundleName);
1187         insertValues.PutString("wantAgent",
1188             OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(timerInfo->wantAgent));
1189         insertValues.PutInt("state", state);
1190         insertValues.PutLong("triggerTime", triggerTime);
1191         insertValues.PutInt("pid", timerInfo->pid);
1192         insertValues.PutString("name", timerInfo->name);
1193         TimeDatabase::GetInstance().Insert(table, insertValues);
1194     }
1195     CjsonHelper::GetInstance().Clear(std::string(table));
1196 }
1197 
RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet,bool autoRestore)1198 void TimeSystemAbility::RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet, bool autoRestore)
1199 {
1200     auto timerManager = TimerManager::GetInstance();
1201     if (timerManager == nullptr) {
1202         return;
1203     }
1204     do {
1205         auto timerId = static_cast<uint64_t>(GetLong(resultSet, 0));
1206         auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
1207             // line 11 is 'name'
1208             GetString(resultSet, 11),
1209             // Line 0 is 'timerId'
1210             timerId,
1211             // Line 1 is 'type'
1212             GetInt(resultSet, 1),
1213             // Line 3 is 'windowLength'
1214             static_cast<uint64_t>(GetLong(resultSet, 3)),
1215             // Line 4 is 'interval'
1216             static_cast<uint64_t>(GetLong(resultSet, 4)),
1217             // Line 2 is 'flag'
1218             GetInt(resultSet, 2),
1219             // autoRestore depends on the table type
1220             autoRestore,
1221             // Callback can't recover.
1222             nullptr,
1223             // Line 7 is 'wantAgent'
1224             OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(resultSet, 7)),
1225             // Line 5 is 'uid'
1226             GetInt(resultSet, 5),
1227             // Line 10 is 'pid'
1228             GetInt(resultSet, 10),
1229             // Line 6 is 'bundleName'
1230             GetString(resultSet, 6)
1231         });
1232         if (timerInfo->wantAgent == nullptr) {
1233             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1234                 timerInfo->uid, timerInfo->id);
1235             continue;
1236         }
1237         timerManager->ReCreateTimer(timerId, timerInfo);
1238         // Line 8 is 'state'
1239         auto state = static_cast<uint8_t>(GetInt(resultSet, 8));
1240         if (state == 1) {
1241             // Line 9 is 'triggerTime'
1242             auto triggerTime = static_cast<uint64_t>(GetLong(resultSet, 9));
1243             timerManager->StartTimer(timerId, triggerTime);
1244         }
1245     } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1246 }
1247 
1248 #else
RecoverTimerInnerCjson(cJSON * resultSet,bool autoRestore,std::string tableName)1249 void TimeSystemAbility::RecoverTimerInnerCjson(cJSON* resultSet, bool autoRestore, std::string tableName)
1250 {
1251     auto timerManager = TimerManager::GetInstance();
1252     if (timerManager == nullptr) {
1253         return;
1254     }
1255     std::vector<std::pair<uint64_t, uint64_t>> timerVec;
1256     int size = cJSON_GetArraySize(resultSet);
1257     for (int i = 0; i < size; ++i) {
1258         // Get data row
1259         cJSON* obj = cJSON_GetArrayItem(resultSet, i);
1260         auto timerInfo = GetEntry(obj, autoRestore);
1261         if (timerInfo == nullptr) {
1262             return;
1263         }
1264         if (timerInfo->wantAgent == nullptr) {
1265             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1266                 timerInfo->uid, timerInfo->id);
1267             continue;
1268         }
1269         timerManager->ReCreateTimer(timerInfo->id, timerInfo);
1270         // 'state'
1271         auto item = cJSON_GetObjectItem(obj, "state");
1272         if (!CjsonHelper::GetInstance().IsNumber(item)) {
1273             continue;
1274         }
1275         auto state = static_cast<uint8_t>(item->valueint);
1276         if (state == 1) {
1277             // 'triggerTime'
1278             item = cJSON_GetObjectItem(obj, "triggerTime");
1279             if (!CjsonHelper::GetInstance().IsString(item)) {
1280                 continue;
1281             }
1282             int64_t triggerTime;
1283             if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, triggerTime)) {
1284                 continue;
1285             }
1286             timerVec.push_back(std::make_pair(timerInfo->id, static_cast<uint64_t>(triggerTime)));
1287         }
1288     }
1289     timerManager->StartTimerGroup(timerVec, tableName);
1290 }
1291 #endif
1292 
1293 #ifdef SET_AUTO_REBOOT_ENABLE
SetAutoReboot()1294 void TimeSystemAbility::SetAutoReboot()
1295 {
1296     auto database = TimeDatabase::GetInstance();
1297     OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
1298     holdRdbPredicates.EqualTo("state", 1)->OrderByAsc("triggerTime");
1299     auto resultSet = database.Query(holdRdbPredicates, { "bundleName", "triggerTime", "name" });
1300     if (resultSet == nullptr) {
1301         TIME_HILOGI(TIME_MODULE_SERVICE, "no need to set RTC");
1302         return;
1303     }
1304     int64_t currentTime = 0;
1305     TimeUtils::GetWallTimeMs(currentTime);
1306     auto bundleList = TimeFileUtils::GetParameterList(SCHEDULED_POWER_ON_APPS);
1307     do {
1308         uint64_t triggerTime = static_cast<uint64_t>(GetLong(resultSet, 1));
1309         if (triggerTime < static_cast<uint64_t>(currentTime)) {
1310             TIME_HILOGI(TIME_MODULE_SERVICE,
1311                         "triggerTime: %{public}" PRIu64" currentTime: %{public}" PRId64"", triggerTime, currentTime);
1312             continue;
1313         }
1314         if (std::find(bundleList.begin(), bundleList.end(), GetString(resultSet, 0)) != bundleList.end() ||
1315             std::find(bundleList.begin(), bundleList.end(), GetString(resultSet, INDEX_TWO)) != bundleList.end()) {
1316             int tmfd = timerfd_create(CLOCK_POWEROFF_ALARM, TFD_NONBLOCK);
1317             if (tmfd < 0) {
1318                 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create error: %{public}s", strerror(errno));
1319                 resultSet->Close();
1320                 return;
1321             }
1322             if (static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI > triggerTime) {
1323                 TIME_HILOGI(TIME_MODULE_SERVICE, "interval less than 2min");
1324                 triggerTime = static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI;
1325             }
1326             struct itimerspec new_value;
1327             std::chrono::nanoseconds nsec(triggerTime * MILLISECOND_TO_NANO);
1328             auto second = std::chrono::duration_cast<std::chrono::seconds>(nsec);
1329             new_value.it_value.tv_sec = second.count();
1330             new_value.it_value.tv_nsec = (nsec - second).count();
1331             TIME_HILOGI(TIME_MODULE_SERVICE, "currentTime:%{public}" PRId64 ", second:%{public}" PRId64 ","
1332                         "nanosecond:%{public}" PRId64"", currentTime, static_cast<int64_t>(new_value.it_value.tv_sec),
1333                         static_cast<int64_t>(new_value.it_value.tv_nsec));
1334             int ret = timerfd_settime(tmfd, TFD_TIMER_ABSTIME, &new_value, nullptr);
1335             if (ret < 0) {
1336                 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime error: %{public}s", strerror(errno));
1337                 close(tmfd);
1338             }
1339             resultSet->Close();
1340             return;
1341         }
1342     } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1343     resultSet->Close();
1344 }
1345 #endif
1346 } // namespace MiscServices
1347 } // namespace OHOS