• 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 std::string & name,int type,bool repeat,bool disposable,bool autoRestore,uint64_t interval,const OHOS::AbilityRuntime::WantAgent::WantAgent & wantAgent,const sptr<IRemoteObject> & timerCallback,uint64_t & timerId)374 int32_t TimeSystemAbility::CreateTimer(const std::string &name, int type, bool repeat, bool disposable,
375                                        bool autoRestore, uint64_t interval,
376                                        const OHOS::AbilityRuntime::WantAgent::WantAgent &wantAgent,
377                                        const sptr<IRemoteObject> &timerCallback, uint64_t &timerId)
378 {
379     TimeXCollie timeXCollie("TimeService::CreateTimer");
380     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
381         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
382         return E_TIME_NOT_SYSTEM_APP;
383     }
384     std::shared_ptr<SimpleTimerInfo> timerInfo = std::make_shared<SimpleTimerInfo>(name, type, repeat, disposable,
385         autoRestore, interval, std::make_shared<OHOS::AbilityRuntime::WantAgent::WantAgent>(wantAgent));
386     auto ret = CreateTimer(timerInfo, timerCallback, timerId);
387     if (ret != E_TIME_OK) {
388         return E_TIME_DEAL_FAILED;
389     }
390     return E_TIME_OK;
391 }
392 
CreateTimerWithoutWA(const std::string & name,int type,bool repeat,bool disposable,bool autoRestore,uint64_t interval,const sptr<IRemoteObject> & timerCallback,uint64_t & timerId)393 int32_t TimeSystemAbility::CreateTimerWithoutWA(const std::string &name, int type, bool repeat, bool disposable,
394     bool autoRestore, uint64_t interval,
395     const sptr<IRemoteObject> &timerCallback, uint64_t &timerId)
396 {
397     TimeXCollie timeXCollie("TimeService::CreateTimer");
398     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
399         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
400         return E_TIME_NOT_SYSTEM_APP;
401     }
402     std::shared_ptr<SimpleTimerInfo> timerInfo = std::make_shared<SimpleTimerInfo>(name, type, repeat, disposable,
403     autoRestore, interval, nullptr);
404     auto ret = CreateTimer(timerInfo, timerCallback, timerId);
405     if (ret != E_TIME_OK) {
406         return E_TIME_DEAL_FAILED;
407     }
408     return E_TIME_OK;
409 }
410 
CreateTimer(const std::shared_ptr<ITimerInfo> & timerOptions,const sptr<IRemoteObject> & obj,uint64_t & timerId)411 int32_t TimeSystemAbility::CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, const sptr<IRemoteObject> &obj,
412     uint64_t &timerId)
413 {
414     if (obj == nullptr) {
415         TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr");
416         return E_TIME_NULLPTR;
417     }
418     sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
419     if (timerCallback == nullptr) {
420         TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr");
421         return E_TIME_NULLPTR;
422     }
423     auto type = DatabaseType::NOT_STORE;
424     if (timerOptions->wantAgent != nullptr) {
425         type = DatabaseType::STORE;
426     }
427     int uid = IPCSkeleton::GetCallingUid();
428     int pid = IPCSkeleton::GetCallingPid();
429     struct TimerPara paras {};
430     ParseTimerPara(timerOptions, paras);
431     int32_t res = CheckTimerPara(type, paras);
432     if (res != E_TIME_OK) {
433         TIME_HILOGE(TIME_MODULE_SERVICE, "check para err:%{public}d,uid:%{public}d", res, uid);
434         return res;
435     }
436     auto timerManager = TimerManager::GetInstance();
437     if (timerManager == nullptr) {
438         return E_TIME_NULLPTR;
439     }
440     auto callbackFunc = [timerCallback](uint64_t id) -> int32_t {
441         return timerCallback->NotifyTimer(id);
442     };
443     if ((paras.flag & ITimerManager::TimerFlag::IDLE_UNTIL) > 0 &&
444         !TimePermission::CheckProxyCallingPermission()) {
445         TIME_HILOGW(TIME_MODULE_SERVICE, "App not support create idle timer");
446         paras.flag &= ~ITimerManager::TimerFlag::IDLE_UNTIL;
447     }
448     return timerManager->CreateTimer(paras, callbackFunc, timerOptions->wantAgent,
449                                      uid, pid, timerId, type);
450 }
451 
CreateTimer(TimerPara & paras,std::function<int32_t (const uint64_t)> callback,uint64_t & timerId)452 int32_t TimeSystemAbility::CreateTimer(TimerPara &paras, std::function<int32_t (const uint64_t)> callback,
453     uint64_t &timerId)
454 {
455     auto timerManager = TimerManager::GetInstance();
456     if (timerManager == nullptr) {
457         return E_TIME_NULLPTR;
458     }
459     return timerManager->CreateTimer(paras, std::move(callback), nullptr, 0, 0, timerId, NOT_STORE);
460 }
461 
StartTimer(uint64_t timerId,uint64_t triggerTime)462 int32_t TimeSystemAbility::StartTimer(uint64_t timerId, uint64_t triggerTime)
463 {
464     TimeXCollie timeXCollie("TimeService::StartTimer");
465     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
466         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
467         return E_TIME_NOT_SYSTEM_APP;
468     }
469     auto timerManager = TimerManager::GetInstance();
470     if (timerManager == nullptr) {
471         return E_TIME_NULLPTR;
472     }
473     auto ret = timerManager->StartTimer(timerId, triggerTime);
474     if (ret != E_TIME_OK) {
475         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to start timer");
476         return E_TIME_DEAL_FAILED;
477     }
478     return ret;
479 }
480 
StopTimer(uint64_t timerId)481 int32_t TimeSystemAbility::StopTimer(uint64_t timerId)
482 {
483     TimeXCollie timeXCollie("TimeService::StopTimer");
484     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
485         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
486         return E_TIME_NOT_SYSTEM_APP;
487     }
488     auto timerManager = TimerManager::GetInstance();
489     if (timerManager == nullptr) {
490         return E_TIME_NULLPTR;
491     }
492     auto ret = timerManager->StopTimer(timerId);
493     if (ret != E_TIME_OK) {
494         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to stop timer");
495         return E_TIME_DEAL_FAILED;
496     }
497     return ret;
498 }
499 
DestroyTimer(uint64_t timerId)500 int32_t TimeSystemAbility::DestroyTimer(uint64_t timerId)
501 {
502     TimeXCollie timeXCollie("TimeService::DestroyTimer");
503     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
504         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
505         return E_TIME_NOT_SYSTEM_APP;
506     }
507     auto timerManager = TimerManager::GetInstance();
508     if (timerManager == nullptr) {
509         return E_TIME_NULLPTR;
510     }
511     auto ret = timerManager->DestroyTimer(timerId);
512     if (ret != E_TIME_OK) {
513         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed to destory timer");
514         return E_TIME_DEAL_FAILED;
515     }
516     return ret;
517 }
518 
DestroyTimerAsync(uint64_t timerId)519 int32_t TimeSystemAbility::DestroyTimerAsync(uint64_t timerId)
520 {
521     return DestroyTimer(timerId);
522 }
523 
IsValidTime(int64_t time)524 bool TimeSystemAbility::IsValidTime(int64_t time)
525 {
526 #if __SIZEOF_POINTER__ == 4
527     if (time / MILLI_TO_BASE > LONG_MAX) {
528         return false;
529     }
530 #endif
531     return true;
532 }
533 
SetRealTime(int64_t time)534 bool TimeSystemAbility::SetRealTime(int64_t time)
535 {
536     if (!IsValidTime(time)) {
537         TIME_HILOGE(TIME_MODULE_SERVICE, "time is invalid: %{public}s", std::to_string(time).c_str());
538         return false;
539     }
540     sptr<TimeSystemAbility> instance = TimeSystemAbility::GetInstance();
541     int64_t beforeTime = 0;
542     TimeUtils::GetWallTimeMs(beforeTime);
543     int64_t bootTime = 0;
544     TimeUtils::GetBootTimeMs(bootTime);
545     TIME_HILOGW(TIME_MODULE_SERVICE,
546         "Before Current Time: %{public}s"
547         " Set time: %{public}s"
548         " Difference: %{public}s"
549         " uid:%{public}d pid:%{public}d ",
550         std::to_string(beforeTime).c_str(), std::to_string(time).c_str(), std::to_string(time - bootTime).c_str(),
551         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
552     if (time < 0) {
553         TIME_HILOGE(TIME_MODULE_SERVICE, "input param error %{public}" PRId64 "", time);
554         return false;
555     }
556     int64_t currentTime = 0;
557     if (TimeUtils::GetWallTimeMs(currentTime) != ERR_OK) {
558         TIME_HILOGE(TIME_MODULE_SERVICE, "currentTime get failed");
559         return false;
560     }
561     struct timeval tv {};
562     tv.tv_sec = (time_t)(time / MILLI_TO_BASE);
563     tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR);
564     int result = settimeofday(&tv, nullptr);
565     if (result < 0) {
566         TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday time fail: %{public}d. error: %{public}s", result,
567             strerror(errno));
568         return false;
569     }
570     auto ret = SetRtcTime(tv.tv_sec);
571     if (ret == E_TIME_SET_RTC_FAILED) {
572         TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d", ret);
573         return false;
574     }
575     TIME_HILOGD(TIME_MODULE_SERVICE, "getting currentTime to milliseconds: %{public}" PRId64 "", currentTime);
576     if (currentTime < (time - ONE_MILLI) || currentTime > (time + ONE_MILLI)) {
577         TimeServiceNotify::GetInstance().PublishTimeChangeEvents(currentTime);
578     }
579     TimeTickNotify::GetInstance().Callback();
580     int64_t curtime = NtpTrustedTime::GetInstance().CurrentTimeMillis();
581     TimeBehaviorReport(ReportEventCode::SET_TIME, std::to_string(beforeTime), std::to_string(time), curtime);
582     return true;
583 }
584 
SetTime(int64_t time,int8_t apiVersion)585 int32_t TimeSystemAbility::SetTime(int64_t time, int8_t apiVersion)
586 {
587     TimeXCollie timeXCollie("TimeService::SetTime");
588     if (apiVersion == APIVersion::API_VERSION_9) {
589         if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
590             TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
591             return E_TIME_NOT_SYSTEM_APP;
592         }
593     }
594     if (!TimePermission::CheckCallingPermission(TimePermission::setTime)) {
595         TIME_HILOGE(TIME_MODULE_SERVICE, "permission check setTime failed");
596         return E_TIME_NO_PERMISSION;
597     }
598     return SetTimeInner(time, apiVersion);
599 }
600 
SetTimeInner(int64_t time,int8_t apiVersion)601 int32_t TimeSystemAbility::SetTimeInner(int64_t time, int8_t apiVersion)
602 {
603     if (!SetRealTime(time)) {
604         return E_TIME_DEAL_FAILED;
605     }
606     return E_TIME_OK;
607 }
608 
609 #ifdef HIDUMPER_ENABLE
Dump(int fd,const std::vector<std::u16string> & args)610 int TimeSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
611 {
612     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
613     const int maxUid = 10000;
614     if (uid > maxUid) {
615         return E_TIME_DEAL_FAILED;
616     }
617 
618     std::vector<std::string> argsStr;
619     for (auto &item : args) {
620         argsStr.emplace_back(Str16ToStr8(item));
621     }
622 
623     TimeCmdDispatcher::GetInstance().Dispatch(fd, argsStr);
624     return ERR_OK;
625 }
626 
DumpAllTimeInfo(int fd,const std::vector<std::string> & input)627 void TimeSystemAbility::DumpAllTimeInfo(int fd, const std::vector<std::string> &input)
628 {
629     dprintf(fd, "\n - dump all time info :\n");
630     struct timespec ts{};
631     struct tm timestr{};
632     char date_time[64];
633     if (GetTimeByClockId(CLOCK_BOOTTIME, ts)) {
634         auto localTime = localtime_r(&ts.tv_sec, &timestr);
635         if (localTime == nullptr) {
636             return;
637         }
638         strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localTime);
639         dprintf(fd, " * date time = %s\n", date_time);
640     } else {
641         dprintf(fd, " * dump date time error.\n");
642     }
643     dprintf(fd, " - dump the time Zone:\n");
644     std::string timeZone;
645     int32_t bRet = GetTimeZone(timeZone);
646     if (bRet == ERR_OK) {
647         dprintf(fd, " * time zone = %s\n", timeZone.c_str());
648     } else {
649         dprintf(fd, " * dump time zone error,is %s\n", timeZone.c_str());
650     }
651 }
652 
DumpTimerInfo(int fd,const std::vector<std::string> & input)653 void TimeSystemAbility::DumpTimerInfo(int fd, const std::vector<std::string> &input)
654 {
655     dprintf(fd, "\n - dump all timer info :\n");
656     auto timerManager = TimerManager::GetInstance();
657     if (timerManager == nullptr) {
658         return;
659     }
660     timerManager->ShowTimerEntryMap(fd);
661 }
662 
DumpTimerInfoById(int fd,const std::vector<std::string> & input)663 void TimeSystemAbility::DumpTimerInfoById(int fd, const std::vector<std::string> &input)
664 {
665     dprintf(fd, "\n - dump the timer info with timer id:\n");
666     int paramNumPos = 2;
667     auto timerManager = TimerManager::GetInstance();
668     if (timerManager == nullptr) {
669         return;
670     }
671     timerManager->ShowTimerEntryById(fd, std::atoi(input.at(paramNumPos).c_str()));
672 }
673 
DumpTimerTriggerById(int fd,const std::vector<std::string> & input)674 void TimeSystemAbility::DumpTimerTriggerById(int fd, const std::vector<std::string> &input)
675 {
676     dprintf(fd, "\n - dump timer trigger statics with timer id:\n");
677     int paramNumPos = 2;
678     auto timerManager = TimerManager::GetInstance();
679     if (timerManager == nullptr) {
680         return;
681     }
682     timerManager->ShowTimerTriggerById(fd, std::atoi(input.at(paramNumPos).c_str()));
683 }
684 
DumpIdleTimerInfo(int fd,const std::vector<std::string> & input)685 void TimeSystemAbility::DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)
686 {
687     dprintf(fd, "\n - dump idle timer info :\n");
688     auto timerManager = TimerManager::GetInstance();
689     if (timerManager == nullptr) {
690         return;
691     }
692     timerManager->ShowIdleTimerInfo(fd);
693 }
694 
DumpProxyTimerInfo(int fd,const std::vector<std::string> & input)695 void TimeSystemAbility::DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)
696 {
697     dprintf(fd, "\n - dump proxy map:\n");
698     int64_t times;
699     TimeUtils::GetBootTimeNs(times);
700     TimerProxy::GetInstance().ShowProxyTimerInfo(fd, times);
701 }
702 
DumpUidTimerMapInfo(int fd,const std::vector<std::string> & input)703 void TimeSystemAbility::DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)
704 {
705     dprintf(fd, "\n - dump uid timer map:\n");
706     int64_t times;
707     TimeUtils::GetBootTimeNs(times);
708     TimerProxy::GetInstance().ShowUidTimerMapInfo(fd, times);
709 }
710 
DumpProxyDelayTime(int fd,const std::vector<std::string> & input)711 void TimeSystemAbility::DumpProxyDelayTime(int fd, const std::vector<std::string> &input)
712 {
713     dprintf(fd, "\n - dump proxy delay time:\n");
714     TimerProxy::GetInstance().ShowProxyDelayTime(fd);
715 }
716 
DumpAdjustTime(int fd,const std::vector<std::string> & input)717 void TimeSystemAbility::DumpAdjustTime(int fd, const std::vector<std::string> &input)
718 {
719     dprintf(fd, "\n - dump adjust timer info:\n");
720     TimerProxy::GetInstance().ShowAdjustTimerInfo(fd);
721 }
722 #endif
723 
SetRtcTime(time_t sec)724 int TimeSystemAbility::SetRtcTime(time_t sec)
725 {
726     struct rtc_time rtc {};
727     struct tm tm {};
728     struct tm *gmtime_res = nullptr;
729     FILE* fd = nullptr;
730     int res;
731     if (rtcId < 0) {
732         TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
733         return E_TIME_SET_RTC_FAILED;
734     }
735     std::stringstream strs;
736     strs << "/dev/rtc" << rtcId;
737     auto rtcDev = strs.str();
738     TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtcDev.data());
739     auto rtcData = rtcDev.data();
740     fd = fopen(rtcData, "r+");
741     if (fd == NULL) {
742         TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtcDev.data(), strerror(errno));
743         return E_TIME_SET_RTC_FAILED;
744     }
745     gmtime_res = gmtime_r(&sec, &tm);
746     if (gmtime_res) {
747         rtc.tm_sec = tm.tm_sec;
748         rtc.tm_min = tm.tm_min;
749         rtc.tm_hour = tm.tm_hour;
750         rtc.tm_mday = tm.tm_mday;
751         rtc.tm_mon = tm.tm_mon;
752         rtc.tm_year = tm.tm_year;
753         rtc.tm_wday = tm.tm_wday;
754         rtc.tm_yday = tm.tm_yday;
755         rtc.tm_isdst = tm.tm_isdst;
756         int fd_int = fileno(fd);
757         res = ioctl(fd_int, RTC_SET_TIME, &rtc);
758         if (res < 0) {
759             TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed,errno: %{public}s, res: %{public}d",
760                 strerror(errno), res);
761         }
762     } else {
763         TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
764         res = E_TIME_SET_RTC_FAILED;
765     }
766     int result = fclose(fd);
767     if (result != 0) {
768         TIME_HILOGE(TIME_MODULE_SERVICE, "file close failed: %{public}d", result);
769     }
770     return res;
771 }
772 
CheckRtc(const std::string & rtcPath,uint64_t rtcId)773 bool TimeSystemAbility::CheckRtc(const std::string &rtcPath, uint64_t rtcId)
774 {
775     std::stringstream strs;
776     strs << rtcPath << "/rtc" << rtcId << "/hctosys";
777     auto hctosys_path = strs.str();
778 
779     std::fstream file(hctosys_path.data(), std::ios_base::in);
780     if (file.is_open()) {
781         return true;
782     } else {
783         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
784         return false;
785     }
786 }
787 
GetWallClockRtcId()788 int TimeSystemAbility::GetWallClockRtcId()
789 {
790     std::string rtcPath = "/sys/class/rtc";
791 
792     std::unique_ptr<DIR, int (*)(DIR *)> dir(opendir(rtcPath.c_str()), closedir);
793     if (!dir.get()) {
794         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtcPath.c_str(), strerror(errno));
795         return -1;
796     }
797 
798     struct dirent *dirent;
799     std::string s = "rtc";
800     while (errno = 0, dirent = readdir(dir.get())) {
801         std::string name(dirent->d_name);
802         unsigned long rtcId = 0;
803         auto index = name.find(s);
804         if (index == std::string::npos) {
805             continue;
806         } else {
807             auto rtcIdStr = name.substr(index + s.length());
808             rtcId = std::stoul(rtcIdStr);
809         }
810         if (CheckRtc(rtcPath, rtcId)) {
811             TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}ld", rtcId);
812             return rtcId;
813         }
814     }
815 
816     if (errno == 0) {
817         TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
818     } else {
819         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
820     }
821     return -1;
822 }
823 
SetTimeZone(const std::string & timeZoneId,int8_t apiVersion)824 int32_t TimeSystemAbility::SetTimeZone(const std::string &timeZoneId, int8_t apiVersion)
825 {
826     TimeXCollie timeXCollie("TimeService::SetTimeZone");
827     if (apiVersion == APIVersion::API_VERSION_9) {
828         if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
829             TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
830             return E_TIME_NOT_SYSTEM_APP;
831         }
832     }
833     if (!TimePermission::CheckCallingPermission(TimePermission::setTimeZone)) {
834         TIME_HILOGE(TIME_MODULE_SERVICE, "permission check setTime failed");
835         return E_TIME_NO_PERMISSION;
836     }
837     return SetTimeZoneInner(timeZoneId, apiVersion);
838 }
839 
SetTimeZoneInner(const std::string & timeZoneId,int8_t apiVersion)840 int32_t TimeSystemAbility::SetTimeZoneInner(const std::string &timeZoneId, int8_t apiVersion)
841 {
842     if (!TimeZoneInfo::GetInstance().SetTimezone(timeZoneId)) {
843         TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
844         return E_TIME_DEAL_FAILED;
845     }
846     int64_t currentTime = 0;
847     TimeUtils::GetBootTimeMs(currentTime);
848     TimeServiceNotify::GetInstance().PublishTimeZoneChangeEvents(currentTime);
849     return E_TIME_OK;
850 }
851 
GetTimeZone(std::string & timeZoneId)852 int32_t TimeSystemAbility::GetTimeZone(std::string &timeZoneId)
853 {
854     TimeXCollie timeXCollie("TimeService::GetTimeZone");
855     if (!TimeZoneInfo::GetInstance().GetTimezone(timeZoneId)) {
856         TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed");
857         return E_TIME_DEAL_FAILED;
858     }
859     TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
860     return ERR_OK;
861 }
862 
GetThreadTimeMs(int64_t & time)863 int32_t TimeSystemAbility::GetThreadTimeMs(int64_t &time)
864 {
865     TimeXCollie timeXCollie("TimeService::GetThreadTimeMs");
866     struct timespec tv {};
867     clockid_t cid;
868     int ret = pthread_getcpuclockid(pthread_self(), &cid);
869     if (ret != E_TIME_OK) {
870         return E_TIME_PARAMETERS_INVALID;
871     }
872     if (GetTimeByClockId(cid, tv)) {
873         time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
874         return ERR_OK;
875     }
876     return E_TIME_DEAL_FAILED;
877 }
878 
GetThreadTimeNs(int64_t & time)879 int32_t TimeSystemAbility::GetThreadTimeNs(int64_t &time)
880 {
881     TimeXCollie timeXCollie("TimeService::GetThreadTimeNs");
882     struct timespec tv {};
883     clockid_t cid;
884     int ret = pthread_getcpuclockid(pthread_self(), &cid);
885     if (ret != E_TIME_OK) {
886         return E_TIME_PARAMETERS_INVALID;
887     }
888     if (GetTimeByClockId(cid, tv)) {
889         time = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
890         return ERR_OK;
891     }
892     return E_TIME_DEAL_FAILED;
893 }
894 
GetTimeByClockId(clockid_t clockId,struct timespec & tv)895 bool TimeSystemAbility::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
896 {
897     if (clock_gettime(clockId, &tv) < 0) {
898         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime");
899         return false;
900     }
901     return true;
902 }
903 
AdjustTimer(bool isAdjust,uint32_t interval,uint32_t delta)904 int32_t TimeSystemAbility::AdjustTimer(bool isAdjust, uint32_t interval, uint32_t delta)
905 {
906     TimeXCollie timeXCollie("TimeService::AdjustTimer");
907     if (!TimePermission::CheckProxyCallingPermission()) {
908         TIME_HILOGE(TIME_MODULE_SERVICE, "Adjust Timer permission check failed");
909         return E_TIME_NO_PERMISSION;
910     }
911     if (isAdjust && interval == 0) {
912         TIME_HILOGE(TIME_MODULE_SERVICE, "invalid parameter: interval");
913         return E_TIME_READ_PARCEL_ERROR;
914     }
915     auto timerManager = TimerManager::GetInstance();
916     if (timerManager == nullptr) {
917         return E_TIME_NULLPTR;
918     }
919     if (!timerManager->AdjustTimer(isAdjust, interval, delta)) {
920         TIME_HILOGE(TIME_MODULE_SERVICE, "Error adjust timer");
921         return E_TIME_DEAL_FAILED;
922     }
923     return E_TIME_OK;
924 }
925 
ProxyTimer(int32_t uid,const std::vector<int> & pidList,bool isProxy,bool needRetrigger)926 int32_t TimeSystemAbility::ProxyTimer(int32_t uid, const std::vector<int>& pidList, bool isProxy, bool needRetrigger)
927 {
928     TimeXCollie timeXCollie("TimeService::TimerProxy");
929     if (!TimePermission::CheckProxyCallingPermission()) {
930         TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
931         return E_TIME_NO_PERMISSION;
932     }
933     if (pidList.size() > MAX_PID_LIST_SIZE) {
934         TIME_HILOGE(TIME_MODULE_SERVICE, "Error pid list size");
935         return E_TIME_PARAMETERS_INVALID;
936     }
937     if (pidList.size() == 0) {
938         TIME_HILOGE(TIME_MODULE_SERVICE, "Error pidList");
939         return E_TIME_PARAMETERS_INVALID;
940     }
941     auto timerManager = TimerManager::GetInstance();
942     if (timerManager == nullptr) {
943         return E_TIME_NULLPTR;
944     }
945     std::set<int> pidSet;
946     std::copy(pidList.begin(), pidList.end(), std::insert_iterator<std::set<int>>(pidSet, pidSet.begin()));
947     auto ret = timerManager->ProxyTimer(uid, pidSet, isProxy, needRetrigger);
948     if (!ret) {
949         return E_TIME_DEAL_FAILED;
950     }
951     return ERR_OK;
952 }
953 
SetTimerExemption(const std::vector<std::string> & nameArr,bool isExemption)954 int32_t TimeSystemAbility::SetTimerExemption(const std::vector<std::string> &nameArr, bool isExemption)
955 {
956     TimeXCollie timeXCollie("TimeService::SetTimerExemption");
957     if (!TimePermission::CheckProxyCallingPermission()) {
958         TIME_HILOGE(TIME_MODULE_SERVICE, "Set Timer Exemption permission check failed");
959         return E_TIME_NO_PERMISSION;
960     }
961     if (nameArr.size() > MAX_EXEMPTION_SIZE) {
962         return E_TIME_PARAMETERS_INVALID;
963     }
964     auto timerManager = TimerManager::GetInstance();
965     if (timerManager == nullptr) {
966         return E_TIME_NULLPTR;
967     }
968     std::unordered_set<std::string> nameSet;
969     std::copy(nameArr.begin(), nameArr.end(), std::inserter(nameSet, nameSet.begin()));
970     timerManager->SetTimerExemption(nameSet, isExemption);
971     return E_TIME_OK;
972 }
973 
ResetAllProxy()974 int32_t TimeSystemAbility::ResetAllProxy()
975 {
976     if (!TimePermission::CheckProxyCallingPermission()) {
977         TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy permission check failed");
978         return E_TIME_NO_PERMISSION;
979     }
980     TIME_HILOGD(TIME_MODULE_SERVICE, "ResetAllProxy service");
981     auto timerManager = TimerManager::GetInstance();
982     if (timerManager == nullptr) {
983         return E_TIME_NULLPTR;
984     }
985     if (!timerManager->ResetAllProxy()) {
986         return E_TIME_DEAL_FAILED;
987     }
988     return E_TIME_OK;
989 }
990 
GetNtpTimeMs(int64_t & time)991 int32_t TimeSystemAbility::GetNtpTimeMs(int64_t &time)
992 {
993     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
994         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
995         return E_TIME_NOT_SYSTEM_APP;
996     }
997     auto ret = NtpUpdateTime::GetInstance().GetNtpTime(time);
998     if (!ret) {
999         TIME_HILOGE(TIME_MODULE_SERVICE, "GetNtpTimeMs failed");
1000         return E_TIME_NTP_UPDATE_FAILED;
1001     }
1002     return E_TIME_OK;
1003 }
1004 
GetRealTimeMs(int64_t & time)1005 int32_t TimeSystemAbility::GetRealTimeMs(int64_t &time)
1006 {
1007     if (!TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
1008         TIME_HILOGE(TIME_MODULE_SERVICE, "not system applications");
1009         return E_TIME_NOT_SYSTEM_APP;
1010     }
1011     auto ret = NtpUpdateTime::GetInstance().GetRealTime(time);
1012     if (!ret) {
1013         TIME_HILOGE(TIME_MODULE_SERVICE, "GetRealTimeMs failed");
1014         return E_TIME_NTP_NOT_UPDATE;
1015     }
1016     return E_TIME_OK;
1017 }
1018 
OnRemoteDied(const wptr<IRemoteObject> & object)1019 void TimeSystemAbility::RSSSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
1020 {
1021     auto timerManager = TimerManager::GetInstance();
1022     if (timerManager == nullptr) {
1023         return;
1024     }
1025     timerManager->HandleRSSDeath();
1026 }
1027 
RegisterRSSDeathCallback()1028 void TimeSystemAbility::RegisterRSSDeathCallback()
1029 {
1030     TIME_HILOGD(TIME_MODULE_SERVICE, "register rss death callback");
1031     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1032     if (systemAbilityManager == nullptr) {
1033         TIME_HILOGE(TIME_MODULE_CLIENT, "Getting SystemAbilityManager failed");
1034         return;
1035     }
1036 
1037     auto systemAbility = systemAbilityManager->GetSystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
1038     if (systemAbility == nullptr) {
1039         TIME_HILOGE(TIME_MODULE_CLIENT, "Get SystemAbility failed");
1040         return;
1041     }
1042 
1043     if (deathRecipient_ == nullptr) {
1044         deathRecipient_ = new (std::nothrow) RSSSaDeathRecipient();
1045         if (deathRecipient_ == nullptr) {
1046             return;
1047         }
1048     }
1049 
1050     systemAbility->AddDeathRecipient(deathRecipient_);
1051 }
1052 
1053 #ifdef SET_AUTO_REBOOT_ENABLE
OnSyncShutdown()1054 void TimeSystemAbility::TimePowerStateListener::OnSyncShutdown()
1055 {
1056     // Clears `drop_on_reboot` table.
1057     TIME_HILOGI(TIME_MODULE_SERVICE, "OnSyncShutdown");
1058     TimeSystemAbility::GetInstance()->SetAutoReboot();
1059     #ifdef RDB_ENABLE
1060     TimeDatabase::GetInstance().ClearDropOnReboot();
1061     TimeDatabase::GetInstance().ClearInvaildDataInHoldOnReboot();
1062     #else
1063     CjsonHelper::GetInstance().Clear(DROP_ON_REBOOT);
1064     CjsonHelper::GetInstance().ClearInvaildDataInHoldOnReboot();
1065     #endif
1066 }
1067 
RegisterPowerStateListener()1068 void TimeSystemAbility::RegisterPowerStateListener()
1069 {
1070     TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener");
1071     auto& powerManagerClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
1072     sptr<OHOS::PowerMgr::ISyncShutdownCallback> syncShutdownCallback = new (std::nothrow) TimePowerStateListener();
1073     if (!syncShutdownCallback) {
1074         TIME_HILOGE(TIME_MODULE_SERVICE, "Get TimePowerStateListener failed");
1075         return;
1076     }
1077     powerManagerClient.RegisterShutdownCallback(syncShutdownCallback, PowerMgr::ShutdownPriority::HIGH);
1078     TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener end");
1079 }
1080 #endif
1081 
RecoverTimerCjson(std::string tableName)1082 void TimeSystemAbility::RecoverTimerCjson(std::string tableName)
1083 {
1084     cJSON* db = NULL;
1085     auto result = CjsonHelper::GetInstance().QueryTable(tableName, &db);
1086     if (result == NULL) {
1087         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}s get table failed", tableName.c_str());
1088     } else {
1089         int count = cJSON_GetArraySize(result);
1090         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}s result rows count: %{public}d", tableName.c_str(), count);
1091         #ifdef RDB_ENABLE
1092         CjsonIntoDatabase(result, true, tableName);
1093         #else
1094         RecoverTimerInnerCjson(result, true, tableName);
1095         #endif
1096     }
1097     cJSON_Delete(db);
1098 }
1099 
RecoverTimer()1100 bool TimeSystemAbility::RecoverTimer()
1101 {
1102     RecoverTimerCjson(HOLD_ON_REBOOT);
1103     RecoverTimerCjson(DROP_ON_REBOOT);
1104 
1105     #ifdef RDB_ENABLE
1106     auto database = TimeDatabase::GetInstance();
1107     OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
1108     auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
1109     if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
1110         TIME_HILOGI(TIME_MODULE_SERVICE, "hold result set is nullptr or go to first row failed");
1111     } else {
1112         int count;
1113         holdResultSet->GetRowCount(count);
1114         TIME_HILOGI(TIME_MODULE_SERVICE, "hold result rows count: %{public}d", count);
1115         RecoverTimerInner(holdResultSet, true);
1116     }
1117     if (holdResultSet != nullptr) {
1118         holdResultSet->Close();
1119     }
1120 
1121     OHOS::NativeRdb::RdbPredicates dropRdbPredicates(DROP_ON_REBOOT);
1122     auto dropResultSet = database.Query(dropRdbPredicates, ALL_DATA);
1123     if (dropResultSet == nullptr || dropResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
1124         TIME_HILOGI(TIME_MODULE_SERVICE, "drop result set is nullptr or go to first row failed");
1125     } else {
1126         int count;
1127         dropResultSet->GetRowCount(count);
1128         TIME_HILOGI(TIME_MODULE_SERVICE, "drop result rows count: %{public}d", count);
1129         RecoverTimerInner(dropResultSet, false);
1130     }
1131     if (dropResultSet != nullptr) {
1132         dropResultSet->Close();
1133     }
1134     #endif
1135     return true;
1136 }
1137 
GetEntry(cJSON * obj,bool autoRestore)1138 std::shared_ptr<TimerEntry> TimeSystemAbility::GetEntry(cJSON* obj, bool autoRestore)
1139 {
1140     auto cjson = CjsonHelper::GetInstance();
1141     auto item = cJSON_GetObjectItem(obj, "name");
1142     if (!cjson.IsString(item)) return nullptr;
1143     auto name = item->valuestring;
1144     item = cJSON_GetObjectItem(obj, "timerId");
1145     if (!cjson.IsString(item)) return nullptr;
1146     int64_t tmp;
1147     if (!cjson.StrToI64(item->valuestring, tmp)) return nullptr;
1148     auto timerId = static_cast<uint64_t>(tmp);
1149     item = cJSON_GetObjectItem(obj, "type");
1150     if (!cjson.IsNumber(item)) return nullptr;
1151     int type = item->valueint;
1152     item = cJSON_GetObjectItem(obj, "windowLength");
1153     if (!cjson.IsNumber(item)) return nullptr;
1154     uint64_t windowLength = static_cast<uint64_t>(item->valueint);
1155     item = cJSON_GetObjectItem(obj, "interval");
1156     if (!cjson.IsNumber(item)) return nullptr;
1157     uint64_t interval = static_cast<uint64_t>(item->valueint);
1158     item = cJSON_GetObjectItem(obj, "flag");
1159     if (!cjson.IsNumber(item)) return nullptr;
1160     uint32_t flag = static_cast<uint32_t>(item->valueint);
1161     item = cJSON_GetObjectItem(obj, "wantAgent");
1162     if (!cjson.IsString(item)) return nullptr;
1163     auto wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(item->valuestring);
1164     item = cJSON_GetObjectItem(obj, "uid");
1165     if (!cjson.IsNumber(item)) return nullptr;
1166     int uid = item->valueint;
1167     item = cJSON_GetObjectItem(obj, "pid");
1168     if (!cjson.IsNumber(item)) return nullptr;
1169     int pid = item->valueint;
1170     item = cJSON_GetObjectItem(obj, "bundleName");
1171     if (!cjson.IsString(item)) return nullptr;
1172     auto bundleName = item->valuestring;
1173     return std::make_shared<TimerEntry>(TimerEntry {name, timerId, type, windowLength, interval, flag, autoRestore,
1174                                                     nullptr, wantAgent, uid, pid, bundleName});
1175 }
1176 
1177 #ifdef RDB_ENABLE
CjsonIntoDatabase(cJSON * resultSet,bool autoRestore,const std::string & table)1178 void TimeSystemAbility::CjsonIntoDatabase(cJSON* resultSet, bool autoRestore, const std::string &table)
1179 {
1180     int size = cJSON_GetArraySize(resultSet);
1181     for (int i = 0; i < size; ++i) {
1182         // Get data row
1183         cJSON* obj = cJSON_GetArrayItem(resultSet, i);
1184         auto timerInfo = GetEntry(obj, autoRestore);
1185         if (timerInfo == nullptr) {
1186             continue;
1187         }
1188         if (timerInfo->wantAgent == nullptr) {
1189             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1190                 timerInfo->uid, timerInfo->id);
1191             continue;
1192         }
1193         auto item = cJSON_GetObjectItem(obj, "state");
1194         if (!CjsonHelper::GetInstance().IsNumber(item)) {
1195             continue;
1196         };
1197         auto state = item->valueint;
1198         item = cJSON_GetObjectItem(obj, "triggerTime");
1199         if (!CjsonHelper::GetInstance().IsString(item)) {
1200             continue;
1201         }
1202         int64_t triggerTime;
1203         if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, triggerTime)) {
1204             continue;
1205         }
1206         OHOS::NativeRdb::ValuesBucket insertValues;
1207         insertValues.PutLong("timerId", timerInfo->id);
1208         insertValues.PutInt("type", timerInfo->type);
1209         insertValues.PutInt("flag", timerInfo->flag);
1210         insertValues.PutLong("windowLength", timerInfo->windowLength);
1211         insertValues.PutLong("interval", timerInfo->interval);
1212         insertValues.PutInt("uid", timerInfo->uid);
1213         insertValues.PutString("bundleName", timerInfo->bundleName);
1214         insertValues.PutString("wantAgent",
1215             OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(timerInfo->wantAgent));
1216         insertValues.PutInt("state", state);
1217         insertValues.PutLong("triggerTime", triggerTime);
1218         insertValues.PutInt("pid", timerInfo->pid);
1219         insertValues.PutString("name", timerInfo->name);
1220         TimeDatabase::GetInstance().Insert(table, insertValues);
1221     }
1222     CjsonHelper::GetInstance().Clear(std::string(table));
1223 }
1224 
RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet,bool autoRestore)1225 void TimeSystemAbility::RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet, bool autoRestore)
1226 {
1227     auto timerManager = TimerManager::GetInstance();
1228     if (timerManager == nullptr) {
1229         return;
1230     }
1231     do {
1232         auto timerId = static_cast<uint64_t>(GetLong(resultSet, 0));
1233         auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
1234             // line 11 is 'name'
1235             GetString(resultSet, 11),
1236             // Line 0 is 'timerId'
1237             timerId,
1238             // Line 1 is 'type'
1239             GetInt(resultSet, 1),
1240             // Line 3 is 'windowLength'
1241             static_cast<uint64_t>(GetLong(resultSet, 3)),
1242             // Line 4 is 'interval'
1243             static_cast<uint64_t>(GetLong(resultSet, 4)),
1244             // Line 2 is 'flag'
1245             GetInt(resultSet, 2),
1246             // autoRestore depends on the table type
1247             autoRestore,
1248             // Callback can't recover.
1249             nullptr,
1250             // Line 7 is 'wantAgent'
1251             OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(resultSet, 7)),
1252             // Line 5 is 'uid'
1253             GetInt(resultSet, 5),
1254             // Line 10 is 'pid'
1255             GetInt(resultSet, 10),
1256             // Line 6 is 'bundleName'
1257             GetString(resultSet, 6)
1258         });
1259         if (timerInfo->wantAgent == nullptr) {
1260             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1261                 timerInfo->uid, timerInfo->id);
1262             continue;
1263         }
1264         timerManager->ReCreateTimer(timerId, timerInfo);
1265         // Line 8 is 'state'
1266         auto state = static_cast<uint8_t>(GetInt(resultSet, 8));
1267         if (state == 1) {
1268             // Line 9 is 'triggerTime'
1269             auto triggerTime = static_cast<uint64_t>(GetLong(resultSet, 9));
1270             timerManager->StartTimer(timerId, triggerTime);
1271         }
1272     } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1273 }
1274 
1275 #else
RecoverTimerInnerCjson(cJSON * resultSet,bool autoRestore,std::string tableName)1276 void TimeSystemAbility::RecoverTimerInnerCjson(cJSON* resultSet, bool autoRestore, std::string tableName)
1277 {
1278     auto timerManager = TimerManager::GetInstance();
1279     if (timerManager == nullptr) {
1280         return;
1281     }
1282     std::vector<std::pair<uint64_t, uint64_t>> timerVec;
1283     int size = cJSON_GetArraySize(resultSet);
1284     for (int i = 0; i < size; ++i) {
1285         // Get data row
1286         cJSON* obj = cJSON_GetArrayItem(resultSet, i);
1287         auto timerInfo = GetEntry(obj, autoRestore);
1288         if (timerInfo == nullptr) {
1289             return;
1290         }
1291         if (timerInfo->wantAgent == nullptr) {
1292             TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
1293                 timerInfo->uid, timerInfo->id);
1294             continue;
1295         }
1296         timerManager->ReCreateTimer(timerInfo->id, timerInfo);
1297         // 'state'
1298         auto item = cJSON_GetObjectItem(obj, "state");
1299         if (!CjsonHelper::GetInstance().IsNumber(item)) {
1300             continue;
1301         }
1302         auto state = static_cast<uint8_t>(item->valueint);
1303         if (state == 1) {
1304             // 'triggerTime'
1305             item = cJSON_GetObjectItem(obj, "triggerTime");
1306             if (!CjsonHelper::GetInstance().IsString(item)) {
1307                 continue;
1308             }
1309             int64_t triggerTime;
1310             if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, triggerTime)) {
1311                 continue;
1312             }
1313             timerVec.push_back(std::make_pair(timerInfo->id, static_cast<uint64_t>(triggerTime)));
1314         }
1315     }
1316     timerManager->StartTimerGroup(timerVec, tableName);
1317 }
1318 #endif
1319 
1320 #ifdef SET_AUTO_REBOOT_ENABLE
SetAutoReboot()1321 void TimeSystemAbility::SetAutoReboot()
1322 {
1323     auto database = TimeDatabase::GetInstance();
1324     OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
1325     holdRdbPredicates.EqualTo("state", 1)->OrderByAsc("triggerTime");
1326     auto resultSet = database.Query(holdRdbPredicates, { "bundleName", "triggerTime", "name" });
1327     if (resultSet == nullptr) {
1328         TIME_HILOGI(TIME_MODULE_SERVICE, "no need to set RTC");
1329         return;
1330     }
1331     int64_t currentTime = 0;
1332     TimeUtils::GetWallTimeMs(currentTime);
1333     auto bundleList = TimeFileUtils::GetParameterList(SCHEDULED_POWER_ON_APPS);
1334     do {
1335         uint64_t triggerTime = static_cast<uint64_t>(GetLong(resultSet, 1));
1336         if (triggerTime < static_cast<uint64_t>(currentTime)) {
1337             TIME_HILOGI(TIME_MODULE_SERVICE,
1338                         "triggerTime: %{public}" PRIu64" currentTime: %{public}" PRId64"", triggerTime, currentTime);
1339             continue;
1340         }
1341         if (std::find(bundleList.begin(), bundleList.end(), GetString(resultSet, 0)) != bundleList.end() ||
1342             std::find(bundleList.begin(), bundleList.end(), GetString(resultSet, INDEX_TWO)) != bundleList.end()) {
1343             int tmfd = timerfd_create(CLOCK_POWEROFF_ALARM, TFD_NONBLOCK);
1344             if (tmfd < 0) {
1345                 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create error: %{public}s", strerror(errno));
1346                 resultSet->Close();
1347                 return;
1348             }
1349             if (static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI > triggerTime) {
1350                 TIME_HILOGI(TIME_MODULE_SERVICE, "interval less than 2min");
1351                 triggerTime = static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI;
1352             }
1353             struct itimerspec new_value;
1354             std::chrono::nanoseconds nsec(triggerTime * MILLISECOND_TO_NANO);
1355             auto second = std::chrono::duration_cast<std::chrono::seconds>(nsec);
1356             new_value.it_value.tv_sec = second.count();
1357             new_value.it_value.tv_nsec = (nsec - second).count();
1358             TIME_HILOGI(TIME_MODULE_SERVICE, "currentTime:%{public}" PRId64 ", second:%{public}" PRId64 ","
1359                         "nanosecond:%{public}" PRId64"", currentTime, static_cast<int64_t>(new_value.it_value.tv_sec),
1360                         static_cast<int64_t>(new_value.it_value.tv_nsec));
1361             int ret = timerfd_settime(tmfd, TFD_TIMER_ABSTIME, &new_value, nullptr);
1362             if (ret < 0) {
1363                 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime error: %{public}s", strerror(errno));
1364                 close(tmfd);
1365             }
1366             resultSet->Close();
1367             return;
1368         }
1369     } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1370     resultSet->Close();
1371 }
1372 #endif
1373 } // namespace MiscServices
1374 } // namespace OHOS