• 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 <cerrno>
18 #include <chrono>
19 #include <cstdio>
20 #include <cstring>
21 #include <ctime>
22 #include <dirent.h>
23 #include <fcntl.h>
24 #include <fstream>
25 #include <linux/rtc.h>
26 #include <mutex>
27 #include <sstream>
28 #include <string>
29 #include <sys/ioctl.h>
30 #include <sys/socket.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include <climits>
35 
36 #include "iservice_registry.h"
37 #include "ntp_update_time.h"
38 #include "pthread.h"
39 #include "system_ability.h"
40 #include "system_ability_definition.h"
41 #include "time_common.h"
42 #include "time_tick_notify.h"
43 #include "time_zone_info.h"
44 #include "timer_manager_interface.h"
45 #include "timer_proxy.h"
46 
47 using namespace std::chrono;
48 
49 namespace OHOS {
50 namespace MiscServices {
51 namespace {
52 // Unit of measure conversion , BASE: second
53 static const int MILLI_TO_BASE = 1000LL;
54 static const int MICR_TO_BASE = 1000000LL;
55 static const int NANO_TO_BASE = 1000000000LL;
56 static const std::int32_t INIT_INTERVAL = 10000L;
57 static const uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
58 static const uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
59 static const uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
60 static const uint32_t TIMER_TYPE_IDLE_MASK = 1 << 3;
61 static const uint32_t TIMER_TYPE_INEXACT_REMINDER_MASK = 1 << 4;
62 constexpr int32_t MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
63 constexpr int32_t NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
64 constexpr int32_t ONE_MILLI = 1000;
65 } // namespace
66 
67 REGISTER_SYSTEM_ABILITY_BY_ID(TimeSystemAbility, TIME_SERVICE_ID, true);
68 
69 std::mutex TimeSystemAbility::instanceLock_;
70 sptr<TimeSystemAbility> TimeSystemAbility::instance_;
71 std::shared_ptr<AppExecFwk::EventHandler> TimeSystemAbility::serviceHandler_ = nullptr;
72 std::shared_ptr<TimerManager> TimeSystemAbility::timerManagerHandler_ = nullptr;
73 
TimeSystemAbility(int32_t systemAbilityId,bool runOnCreate)74 TimeSystemAbility::TimeSystemAbility(int32_t systemAbilityId, bool runOnCreate)
75     : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
76       rtcId(GetWallClockRtcId())
77 {
78     TIME_HILOGD(TIME_MODULE_SERVICE, " TimeSystemAbility Start.");
79 }
80 
TimeSystemAbility()81 TimeSystemAbility::TimeSystemAbility() : state_(ServiceRunningState::STATE_NOT_START), rtcId(GetWallClockRtcId())
82 {
83 }
84 
~TimeSystemAbility()85 TimeSystemAbility::~TimeSystemAbility(){};
86 
GetInstance()87 sptr<TimeSystemAbility> TimeSystemAbility::GetInstance()
88 {
89     if (instance_ == nullptr) {
90         std::lock_guard<std::mutex> autoLock(instanceLock_);
91         if (instance_ == nullptr) {
92             instance_ = new TimeSystemAbility;
93         }
94     }
95     return instance_;
96 }
97 
InitDumpCmd()98 void TimeSystemAbility::InitDumpCmd()
99 {
100     auto cmdTime = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-time" }),
101         "dump current time info,include localtime,timezone info",
102         [this](int fd, const std::vector<std::string> &input) { DumpAllTimeInfo(fd, input); });
103     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTime);
104 
105     auto cmdTimerAll = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-a" }),
106         "dump all timer info", [this](int fd, const std::vector<std::string> &input) { DumpTimerInfo(fd, input); });
107     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerAll);
108 
109     auto cmdTimerInfo = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-i", "[n]" }),
110         "dump the timer info with timer id",
111         [this](int fd, const std::vector<std::string> &input) { DumpTimerInfoById(fd, input); });
112     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerInfo);
113 
114     auto cmdTimerTrigger = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-s", "[n]" }),
115         "dump current time info,include localtime,timezone info",
116         [this](int fd, const std::vector<std::string> &input) { DumpTimerTriggerById(fd, input); });
117     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerTrigger);
118 
119     auto cmdTimerIdle = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-idle", "-a" }),
120         "dump idle state and timer info, include pending delay timers and delayed info.",
121         [this](int fd, const std::vector<std::string> &input) { DumpIdleTimerInfo(fd, input); });
122     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerIdle);
123 
124     auto cmdProxyTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyTimer", "-l" }),
125         "dump proxy timer info.",
126         [this](int fd, const std::vector<std::string> &input) { DumpProxyTimerInfo(fd, input); });
127     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdProxyTimer);
128 
129     auto cmdUidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-UidTimer", "-l" }),
130         "dump uid timer map.",
131         [this](int fd, const std::vector<std::string> &input) { DumpUidTimerMapInfo(fd, input); });
132     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdUidTimer);
133 
134     auto cmdSetDelayTimer = std::make_shared<TimeCmdParse>(
135         std::vector<std::string>({ "-ProxyDelayTime", "-s", "[n]" }),
136         "set proxy delay time.",
137         [this](int fd, const std::vector<std::string> &input) { SetProxyDelayTime(fd, input); });
138     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdSetDelayTimer);
139 
140     auto cmdShowDelayTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyDelayTime", "-l" }),
141         "dump proxy delay time.",
142         [this](int fd, const std::vector<std::string> &input) { DumpProxyDelayTime(fd, input); });
143     TimeCmdDispatcher::GetInstance().RegisterCommand(cmdShowDelayTimer);
144 }
145 
OnStart()146 void TimeSystemAbility::OnStart()
147 {
148     TIME_HILOGD(TIME_MODULE_SERVICE, "TimeSystemAbility OnStart.");
149     if (state_ == ServiceRunningState::STATE_RUNNING) {
150         TIME_HILOGE(TIME_MODULE_SERVICE, "TimeSystemAbility is already running.");
151         return;
152     }
153     InitServiceHandler();
154     InitTimerHandler();
155     TimeTickNotify::GetInstance().Init();
156     TimeZoneInfo::GetInstance().Init();
157     NtpUpdateTime::GetInstance().Init();
158     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
159     AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
160     InitDumpCmd();
161     TIME_HILOGD(TIME_MODULE_SERVICE, "Start TimeSystemAbility success.");
162     if (Init() != ERR_OK) {
163         auto callback = [this]() { Init(); };
164         serviceHandler_->PostTask(callback, "time_service_init_retry", INIT_INTERVAL);
165         TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later.");
166     }
167 }
168 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)169 void TimeSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
170 {
171     TIME_HILOGD(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
172     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
173         RegisterSubscriber();
174     } else if (systemAbilityId == DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID) {
175         RegisterRSSDeathCallback();
176     } else {
177         TIME_HILOGE(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId is not COMMON_EVENT_SERVICE_ID");
178         return;
179     }
180 }
181 
RegisterSubscriber()182 void TimeSystemAbility::RegisterSubscriber()
183 {
184     TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterSubscriber Started");
185     bool subRes = TimeServiceNotify::GetInstance().RepublishEvents();
186     if (!subRes) {
187         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to RegisterSubscriber");
188         auto callback = [this]() { TimeServiceNotify::GetInstance().RepublishEvents(); };
189         serviceHandler_->PostTask(callback, "time_service_subscriber_retry", INIT_INTERVAL);
190         return;
191     }
192     TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterSubscriber success.");
193 }
194 
Init()195 int32_t TimeSystemAbility::Init()
196 {
197     bool ret = Publish(TimeSystemAbility::GetInstance());
198     if (!ret) {
199         TIME_HILOGE(TIME_MODULE_SERVICE, "Init Failed.");
200         return E_TIME_PUBLISH_FAIL;
201     }
202     TIME_HILOGD(TIME_MODULE_SERVICE, "Init Success.");
203     state_ = ServiceRunningState::STATE_RUNNING;
204     return ERR_OK;
205 }
206 
OnStop()207 void TimeSystemAbility::OnStop()
208 {
209     TIME_HILOGD(TIME_MODULE_SERVICE, "OnStop Started.");
210     if (state_ != ServiceRunningState::STATE_RUNNING) {
211         TIME_HILOGI(TIME_MODULE_SERVICE, "state is running.");
212         return;
213     }
214     serviceHandler_ = nullptr;
215     TimeTickNotify::GetInstance().Stop();
216     state_ = ServiceRunningState::STATE_NOT_START;
217     TIME_HILOGD(TIME_MODULE_SERVICE, "OnStop End.");
218 }
219 
InitServiceHandler()220 void TimeSystemAbility::InitServiceHandler()
221 {
222     TIME_HILOGD(TIME_MODULE_SERVICE, "InitServiceHandler started.");
223     if (serviceHandler_ != nullptr) {
224         TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
225         return;
226     }
227     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create(TIME_SERVICE_NAME);
228     serviceHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
229     TIME_HILOGD(TIME_MODULE_SERVICE, "InitServiceHandler Succeeded.");
230 }
231 
InitTimerHandler()232 void TimeSystemAbility::InitTimerHandler()
233 {
234     TIME_HILOGD(TIME_MODULE_SERVICE, "Init Timer started.");
235     if (timerManagerHandler_ != nullptr) {
236         TIME_HILOGE(TIME_MODULE_SERVICE, " Already init.");
237         return;
238     }
239     timerManagerHandler_ = TimerManager::Create();
240 }
241 
ParseTimerPara(const std::shared_ptr<ITimerInfo> & timerOptions,TimerPara & paras)242 void TimeSystemAbility::ParseTimerPara(const std::shared_ptr<ITimerInfo> &timerOptions, TimerPara &paras)
243 {
244     auto uIntType = static_cast<uint32_t>(timerOptions->type);
245     bool isRealtime = (uIntType & TIMER_TYPE_REALTIME_MASK) > 0;
246     bool isWakeup = (uIntType & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0;
247     paras.windowLength = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 0 : -1;
248     paras.flag = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 1 : 0;
249     if (isRealtime && isWakeup) {
250         paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP;
251     } else if (isRealtime) {
252         paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
253     } else if (isWakeup) {
254         paras.timerType = ITimerManager::TimerType::RTC_WAKEUP;
255     } else {
256         paras.timerType = ITimerManager::TimerType::RTC;
257     }
258     if ((uIntType & TIMER_TYPE_IDLE_MASK) > 0) {
259         paras.flag += ITimerManager::TimerFlag::IDLE_UNTIL;
260     }
261     if ((uIntType & TIMER_TYPE_INEXACT_REMINDER_MASK) > 0) {
262         paras.flag += ITimerManager::TimerFlag::INEXACT_REMINDER;
263     }
264     paras.interval = timerOptions->repeat ? timerOptions->interval : 0;
265 }
266 
CreateTimer(const std::shared_ptr<ITimerInfo> & timerOptions,sptr<IRemoteObject> & obj,uint64_t & timerId)267 int32_t TimeSystemAbility::CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, sptr<IRemoteObject> &obj,
268     uint64_t &timerId)
269 {
270     int uid = IPCSkeleton::GetCallingUid();
271     if (obj == nullptr) {
272         TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr.");
273         return E_TIME_NULLPTR;
274     }
275     struct TimerPara paras {};
276     ParseTimerPara(timerOptions, paras);
277     sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
278     if (timerCallback == nullptr) {
279         TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr.");
280         return E_TIME_NULLPTR;
281     }
282     auto callbackFunc = [timerCallback](uint64_t id) {
283         timerCallback->NotifyTimer(id, nullptr);
284     };
285     int64_t triggerTime = 0;
286     GetWallTimeMs(triggerTime);
287     StatisticReporter(IPCSkeleton::GetCallingPid(), uid, timerOptions->type, triggerTime, timerOptions->interval);
288     if (timerManagerHandler_ == nullptr) {
289         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
290         timerManagerHandler_ = TimerManager::Create();
291         if (timerManagerHandler_ == nullptr) {
292             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
293             return E_TIME_NULLPTR;
294         }
295     }
296     if ((static_cast<uint32_t>(paras.flag) & static_cast<uint32_t>(ITimerManager::TimerFlag::IDLE_UNTIL)) > 0 &&
297         !TimePermission::CheckProxyCallingPermission()) {
298         TIME_HILOGW(TIME_MODULE_SERVICE, "App not support create idle timer.");
299         paras.flag = 0;
300     }
301     return timerManagerHandler_->CreateTimer(paras, callbackFunc, timerOptions->wantAgent, uid, timerId);
302 }
303 
CreateTimer(TimerPara & paras,std::function<void (const uint64_t)> Callback,uint64_t & timerId)304 int32_t TimeSystemAbility::CreateTimer(TimerPara &paras, std::function<void(const uint64_t)> Callback,
305     uint64_t &timerId)
306 {
307     if (timerManagerHandler_ == nullptr) {
308         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
309         timerManagerHandler_ = TimerManager::Create();
310         if (timerManagerHandler_ == nullptr) {
311             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
312             return E_TIME_NULLPTR;
313         }
314     }
315     return timerManagerHandler_->CreateTimer(paras, std::move(Callback), nullptr, 0, timerId);
316 }
317 
StartTimer(uint64_t timerId,uint64_t triggerTime)318 int32_t TimeSystemAbility::StartTimer(uint64_t timerId, uint64_t triggerTime)
319 {
320     if (timerManagerHandler_ == nullptr) {
321         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
322         timerManagerHandler_ = TimerManager::Create();
323         if (timerManagerHandler_ == nullptr) {
324             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
325             return false;
326         }
327     }
328     auto ret = timerManagerHandler_->StartTimer(timerId, triggerTime);
329     if (ret != E_TIME_OK) {
330         TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
331     }
332     return ret;
333 }
334 
StopTimer(uint64_t timerId)335 int32_t TimeSystemAbility::StopTimer(uint64_t timerId)
336 {
337     if (timerManagerHandler_ == nullptr) {
338         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
339         timerManagerHandler_ = TimerManager::Create();
340         if (timerManagerHandler_ == nullptr) {
341             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
342             return false;
343         }
344     }
345     auto ret = timerManagerHandler_->StopTimer(timerId);
346     if (ret != E_TIME_OK) {
347         TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
348     }
349     return ret;
350 }
351 
DestroyTimer(uint64_t timerId)352 int32_t TimeSystemAbility::DestroyTimer(uint64_t timerId)
353 {
354     if (timerManagerHandler_ == nullptr) {
355         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
356         timerManagerHandler_ = TimerManager::Create();
357         if (timerManagerHandler_ == nullptr) {
358             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
359             return false;
360         }
361     }
362     auto ret = timerManagerHandler_->DestroyTimer(timerId);
363     if (ret != E_TIME_OK) {
364         TIME_HILOGE(TIME_MODULE_SERVICE, "TimerId Not found.");
365     }
366     return ret;
367 }
368 
IsValidTime(int64_t time)369 bool TimeSystemAbility::IsValidTime(int64_t time)
370 {
371 #if __SIZEOF_POINTER__ == 4
372     if (time / MILLI_TO_BASE > LONG_MAX) {
373         return false;
374     }
375 #endif
376     return true;
377 }
378 
SetRealTime(int64_t time)379 bool TimeSystemAbility::SetRealTime(int64_t time)
380 {
381     if (!IsValidTime(time)) {
382         TIME_HILOGE(TIME_MODULE_SERVICE, "time is invalid: %{public}s", std::to_string(time).c_str());
383         return false;
384     }
385     sptr<TimeSystemAbility> instance = TimeSystemAbility::GetInstance();
386     int64_t beforeTime = 0;
387     instance->GetWallTimeMs(beforeTime);
388     int64_t bootTime = 0;
389     instance->GetBootTimeMs(bootTime);
390     TIME_HILOGI(TIME_MODULE_SERVICE, "Before Current Time: %{public}" PRId64 ""
391                 " Set time: %{public}" PRId64 ""
392                 " Difference: %{public}" PRId64 ""
393                 " uid:%{public}d pid:%{public}d ",
394                 beforeTime,
395                 time,
396                 time - bootTime,
397                 IPCSkeleton::GetCallingUid(),
398                 IPCSkeleton::GetCallingPid());
399     if (time < 0 || time / 1000LL >= LLONG_MAX) {
400         TIME_HILOGE(TIME_MODULE_SERVICE, "input param error");
401         return false;
402     }
403     int64_t currentTime = 0;
404     if (GetWallTimeMs(currentTime) != ERR_OK) {
405         TIME_HILOGE(TIME_MODULE_SERVICE, "currentTime get failed");
406         return false;
407     }
408     struct timeval tv {};
409     tv.tv_sec = (time_t)(time / MILLI_TO_BASE);
410     tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR);
411     int result = settimeofday(&tv, nullptr);
412     if (result < 0) {
413         TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday time fail: %{public}d. error: %{public}s", result,
414             strerror(errno));
415         return false;
416     }
417     auto ret = SetRtcTime(tv.tv_sec);
418     if (ret == E_TIME_SET_RTC_FAILED) {
419         TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d.", ret);
420         return false;
421     }
422     TIME_HILOGD(TIME_MODULE_SERVICE, "getting currentTime to milliseconds: %{public}" PRId64 "", currentTime);
423     if (currentTime < (time - ONE_MILLI) || currentTime > (time + ONE_MILLI)) {
424         TimeServiceNotify::GetInstance().PublishTimeChangeEvents(currentTime);
425     }
426     return true;
427 }
428 
SetTime(int64_t time,APIVersion apiVersion)429 int32_t TimeSystemAbility::SetTime(int64_t time, APIVersion apiVersion)
430 {
431     if (!SetRealTime(time)) {
432         return E_TIME_DEAL_FAILED;
433     }
434     return ERR_OK;
435 }
436 
Dump(int fd,const std::vector<std::u16string> & args)437 int TimeSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
438 {
439     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
440     const int maxUid = 10000;
441     if (uid > maxUid) {
442         return E_TIME_DEAL_FAILED;
443     }
444 
445     std::vector<std::string> argsStr;
446     for (auto &item : args) {
447         argsStr.emplace_back(Str16ToStr8(item));
448     }
449 
450     TimeCmdDispatcher::GetInstance().Dispatch(fd, argsStr);
451     return ERR_OK;
452 }
453 
DumpAllTimeInfo(int fd,const std::vector<std::string> & input)454 void TimeSystemAbility::DumpAllTimeInfo(int fd, const std::vector<std::string> &input)
455 {
456     dprintf(fd, "\n - dump all time info :\n");
457     struct timespec ts{};
458     struct tm timestr{};
459     char date_time[64];
460     if (GetTimeByClockId(CLOCK_BOOTTIME, ts)) {
461         strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&ts.tv_sec, &timestr));
462         dprintf(fd, " * date time = %s\n", date_time);
463     } else {
464         dprintf(fd, " * dump date time error.\n");
465     }
466     dprintf(fd, " - dump the time Zone:\n");
467     std::string timeZone;
468     int32_t bRet = GetTimeZone(timeZone);
469     if (bRet == ERR_OK) {
470         dprintf(fd, " * time zone = %s\n", timeZone.c_str());
471     } else {
472         dprintf(fd, " * dump time zone error,is %s\n", timeZone.c_str());
473     }
474 }
475 
DumpTimerInfo(int fd,const std::vector<std::string> & input)476 void TimeSystemAbility::DumpTimerInfo(int fd, const std::vector<std::string> &input)
477 {
478     dprintf(fd, "\n - dump all timer info :\n");
479     if (timerManagerHandler_ == nullptr) {
480         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
481         timerManagerHandler_ = TimerManager::Create();
482         if (timerManagerHandler_ == nullptr) {
483             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
484             return;
485         }
486     }
487     timerManagerHandler_->ShowTimerEntryMap(fd);
488 }
489 
DumpTimerInfoById(int fd,const std::vector<std::string> & input)490 void TimeSystemAbility::DumpTimerInfoById(int fd, const std::vector<std::string> &input)
491 {
492     dprintf(fd, "\n - dump the timer info with timer id:\n");
493     if (timerManagerHandler_ == nullptr) {
494         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
495         timerManagerHandler_ = TimerManager::Create();
496         if (timerManagerHandler_ == nullptr) {
497             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
498             return;
499         }
500     }
501     int paramNumPos = 2;
502     timerManagerHandler_->ShowTimerEntryById(fd, std::atoi(input.at(paramNumPos).c_str()));
503 }
504 
DumpTimerTriggerById(int fd,const std::vector<std::string> & input)505 void TimeSystemAbility::DumpTimerTriggerById(int fd, const std::vector<std::string> &input)
506 {
507     dprintf(fd, "\n - dump timer trigger statics with timer id:\n");
508     if (timerManagerHandler_ == nullptr) {
509         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
510         timerManagerHandler_ = TimerManager::Create();
511         if (timerManagerHandler_ == nullptr) {
512             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
513             return;
514         }
515     }
516     int paramNumPos = 2;
517     timerManagerHandler_->ShowTimerTriggerById(fd, std::atoi(input.at(paramNumPos).c_str()));
518 }
519 
DumpIdleTimerInfo(int fd,const std::vector<std::string> & input)520 void TimeSystemAbility::DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)
521 {
522     dprintf(fd, "\n - dump idle timer info :\n");
523     if (timerManagerHandler_ == nullptr) {
524         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer manager nullptr.");
525         timerManagerHandler_ = TimerManager::Create();
526         if (timerManagerHandler_ == nullptr) {
527             TIME_HILOGE(TIME_MODULE_SERVICE, "Redo Timer manager Init Failed.");
528             return;
529         }
530     }
531     timerManagerHandler_->ShowIdleTimerInfo(fd);
532 }
533 
DumpProxyTimerInfo(int fd,const std::vector<std::string> & input)534 void TimeSystemAbility::DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)
535 {
536     dprintf(fd, "\n - dump proxy map:\n");
537     int64_t times;
538     GetBootTimeNs(times);
539     TimerProxy::GetInstance().ShowProxyTimerInfo(fd, times);
540 }
541 
DumpUidTimerMapInfo(int fd,const std::vector<std::string> & input)542 void TimeSystemAbility::DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)
543 {
544     dprintf(fd, "\n - dump uid timer map:\n");
545     int64_t times;
546     GetBootTimeNs(times);
547     TimerProxy::GetInstance().ShowUidTimerMapInfo(fd, times);
548 }
549 
SetProxyDelayTime(int fd,const std::vector<std::string> & input)550 void TimeSystemAbility::SetProxyDelayTime(int fd, const std::vector<std::string> &input)
551 {
552     dprintf(fd, "\n - set proxy delay time:\n");
553     int paramNumPos = 2;
554     TimerProxy::GetInstance().SetProxyDelayTime(fd, std::atoi(input.at(paramNumPos).c_str()));
555 }
556 
DumpProxyDelayTime(int fd,const std::vector<std::string> & input)557 void TimeSystemAbility::DumpProxyDelayTime(int fd, const std::vector<std::string> &input)
558 {
559     dprintf(fd, "\n - dump proxy delay time:\n");
560     TimerProxy::GetInstance().ShowProxyDelayTime(fd);
561 }
562 
SetRtcTime(time_t sec)563 int TimeSystemAbility::SetRtcTime(time_t sec)
564 {
565     struct rtc_time rtc {};
566     struct tm tm {};
567     struct tm *gmtime_res = nullptr;
568     int fd = -1;
569     int res;
570     if (rtcId < 0) {
571         TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
572         return E_TIME_SET_RTC_FAILED;
573     }
574     std::stringstream strs;
575     strs << "/dev/rtc" << rtcId;
576     auto rtcDev = strs.str();
577     TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtcDev.data());
578     auto rtcData = rtcDev.data();
579     fd = open(rtcData, O_RDWR);
580     if (fd < 0) {
581         TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtcDev.data(), strerror(errno));
582         return E_TIME_SET_RTC_FAILED;
583     }
584     gmtime_res = gmtime_r(&sec, &tm);
585     if (gmtime_res) {
586         rtc.tm_sec = tm.tm_sec;
587         rtc.tm_min = tm.tm_min;
588         rtc.tm_hour = tm.tm_hour;
589         rtc.tm_mday = tm.tm_mday;
590         rtc.tm_mon = tm.tm_mon;
591         rtc.tm_year = tm.tm_year;
592         rtc.tm_wday = tm.tm_wday;
593         rtc.tm_yday = tm.tm_yday;
594         rtc.tm_isdst = tm.tm_isdst;
595         res = ioctl(fd, RTC_SET_TIME, &rtc);
596         if (res < 0) {
597             TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed: %{public}s", strerror(errno));
598         }
599     } else {
600         TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
601         res = E_TIME_SET_RTC_FAILED;
602     }
603     close(fd);
604     return res;
605 }
606 
CheckRtc(const std::string & rtcPath,uint64_t rtcId)607 bool TimeSystemAbility::CheckRtc(const std::string &rtcPath, uint64_t rtcId)
608 {
609     std::stringstream strs;
610     strs << rtcPath << "/rtc" << rtcId << "/hctosys";
611     auto hctosys_path = strs.str();
612 
613     std::fstream file(hctosys_path.data(), std::ios_base::in);
614     if (file.is_open()) {
615         return true;
616     } else {
617         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
618         return false;
619     }
620 }
621 
GetWallClockRtcId()622 int TimeSystemAbility::GetWallClockRtcId()
623 {
624     std::string rtcPath = "/sys/class/rtc";
625 
626     std::unique_ptr<DIR, int (*)(DIR *)> dir(opendir(rtcPath.c_str()), closedir);
627     if (!dir.get()) {
628         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtcPath.c_str(), strerror(errno));
629         return -1;
630     }
631 
632     struct dirent *dirent;
633     std::string s = "rtc";
634     while (errno = 0, dirent = readdir(dir.get())) {
635         std::string name(dirent->d_name);
636         unsigned long rtcId = 0;
637         auto index = name.find(s);
638         if (index == std::string::npos) {
639             continue;
640         } else {
641             auto rtcIdStr = name.substr(index + s.length());
642             rtcId = std::stoul(rtcIdStr);
643         }
644         if (CheckRtc(rtcPath, rtcId)) {
645             TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}ld", rtcId);
646             return rtcId;
647         }
648     }
649 
650     if (errno == 0) {
651         TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
652     } else {
653         TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
654     }
655     return -1;
656 }
657 
SetTimeZone(const std::string & timeZoneId,APIVersion apiVersion)658 int32_t TimeSystemAbility::SetTimeZone(const std::string &timeZoneId, APIVersion apiVersion)
659 {
660     if (!TimeZoneInfo::GetInstance().SetTimezone(timeZoneId)) {
661         TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
662         return E_TIME_DEAL_FAILED;
663     }
664     int64_t currentTime = 0;
665     GetBootTimeMs(currentTime);
666     TimeServiceNotify::GetInstance().PublishTimeZoneChangeEvents(currentTime);
667     return ERR_OK;
668 }
669 
GetTimeZone(std::string & timeZoneId)670 int32_t TimeSystemAbility::GetTimeZone(std::string &timeZoneId)
671 {
672     if (!TimeZoneInfo::GetInstance().GetTimezone(timeZoneId)) {
673         TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed.");
674         return E_TIME_DEAL_FAILED;
675     }
676     TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
677     return ERR_OK;
678 }
679 
GetWallTimeMs(int64_t & times)680 int32_t TimeSystemAbility::GetWallTimeMs(int64_t &times)
681 {
682     struct timespec tv {};
683     if (GetTimeByClockId(CLOCK_REALTIME, tv)) {
684         times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
685         return ERR_OK;
686     }
687     return E_TIME_DEAL_FAILED;
688 }
689 
GetWallTimeNs(int64_t & times)690 int32_t TimeSystemAbility::GetWallTimeNs(int64_t &times)
691 {
692     struct timespec tv {};
693     if (GetTimeByClockId(CLOCK_REALTIME, tv)) {
694         times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
695         return ERR_OK;
696     }
697     return E_TIME_DEAL_FAILED;
698 }
699 
GetBootTimeMs(int64_t & times)700 int32_t TimeSystemAbility::GetBootTimeMs(int64_t &times)
701 {
702     struct timespec tv {};
703     if (GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
704         times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
705         return ERR_OK;
706     }
707     return E_TIME_DEAL_FAILED;
708 }
709 
GetBootTimeNs(int64_t & times)710 int32_t TimeSystemAbility::GetBootTimeNs(int64_t &times)
711 {
712     struct timespec tv {};
713     if (GetTimeByClockId(CLOCK_BOOTTIME, tv)) {
714         times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
715         return ERR_OK;
716     }
717     return E_TIME_DEAL_FAILED;
718 }
719 
GetMonotonicTimeMs(int64_t & times)720 int32_t TimeSystemAbility::GetMonotonicTimeMs(int64_t &times)
721 {
722     struct timespec tv {};
723     if (GetTimeByClockId(CLOCK_MONOTONIC, tv)) {
724         times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
725         return ERR_OK;
726     }
727     return E_TIME_DEAL_FAILED;
728 }
729 
GetMonotonicTimeNs(int64_t & times)730 int32_t TimeSystemAbility::GetMonotonicTimeNs(int64_t &times)
731 {
732     struct timespec tv {};
733     if (GetTimeByClockId(CLOCK_MONOTONIC, tv)) {
734         times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
735         return ERR_OK;
736     }
737     return E_TIME_DEAL_FAILED;
738 }
739 
GetThreadTimeMs(int64_t & times)740 int32_t TimeSystemAbility::GetThreadTimeMs(int64_t &times)
741 {
742     struct timespec tv {};
743     int ret;
744     clockid_t cid;
745     ret = pthread_getcpuclockid(pthread_self(), &cid);
746     if (ret != 0) {
747         return E_TIME_PARAMETERS_INVALID;
748     }
749     if (GetTimeByClockId(cid, tv)) {
750         times = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
751         return ERR_OK;
752     }
753     return E_TIME_DEAL_FAILED;
754 }
755 
GetThreadTimeNs(int64_t & times)756 int32_t TimeSystemAbility::GetThreadTimeNs(int64_t &times)
757 {
758     struct timespec tv {};
759     int ret;
760     clockid_t cid;
761     ret = pthread_getcpuclockid(pthread_self(), &cid);
762     if (ret != 0) {
763         return E_TIME_PARAMETERS_INVALID;
764     }
765     if (GetTimeByClockId(cid, tv)) {
766         times = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
767         return ERR_OK;
768     }
769     return E_TIME_DEAL_FAILED;
770 }
771 
GetTimeByClockId(clockid_t clockId,struct timespec & tv)772 bool TimeSystemAbility::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
773 {
774     if (clock_gettime(clockId, &tv) < 0) {
775         TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime.");
776         return false;
777     }
778     return true;
779 }
780 
ProxyTimer(int32_t uid,bool isProxy,bool needRetrigger)781 bool TimeSystemAbility::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
782 {
783     if (!TimePermission::CheckProxyCallingPermission()) {
784         TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
785         return E_TIME_NO_PERMISSION;
786     }
787     TIME_HILOGD(TIME_MODULE_SERVICE, "ProxyTimer service start uid: %{public}d, isProxy: %{public}d", uid, isProxy);
788     if (timerManagerHandler_ == nullptr) {
789         TIME_HILOGI(TIME_MODULE_SERVICE, "ProxyTimer manager nullptr.");
790         timerManagerHandler_ = TimerManager::Create();
791         if (timerManagerHandler_ == nullptr) {
792             TIME_HILOGE(TIME_MODULE_SERVICE, "Proxytimer manager init failed.");
793             return false;
794         }
795     }
796     return timerManagerHandler_->ProxyTimer(uid, isProxy, needRetrigger);
797 }
798 
ResetAllProxy()799 bool TimeSystemAbility::ResetAllProxy()
800 {
801     if (!TimePermission::CheckProxyCallingPermission()) {
802         TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy permission check failed");
803         return E_TIME_NO_PERMISSION;
804     }
805     TIME_HILOGD(TIME_MODULE_SERVICE, "ResetAllProxy service");
806     if (timerManagerHandler_ == nullptr) {
807         timerManagerHandler_ = TimerManager::Create();
808         if (timerManagerHandler_ == nullptr) {
809             TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy timer manager init failed");
810             return false;
811         }
812     }
813     return timerManagerHandler_->ResetAllProxy();
814 }
815 
OnRemoteDied(const wptr<IRemoteObject> & object)816 void TimeSystemAbility::RSSSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
817 {
818     if (timerManagerHandler_ != nullptr) {
819         timerManagerHandler_->HandleRSSDeath();
820     }
821 }
822 
RegisterRSSDeathCallback()823 void TimeSystemAbility::RegisterRSSDeathCallback()
824 {
825     TIME_HILOGD(TIME_MODULE_SERVICE, "register rss death callback");
826     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
827     if (systemAbilityManager == nullptr) {
828         TIME_HILOGE(TIME_MODULE_CLIENT, "Getting SystemAbilityManager failed.");
829         return;
830     }
831 
832     auto systemAbility = systemAbilityManager->GetSystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
833     if (systemAbility == nullptr) {
834         TIME_HILOGE(TIME_MODULE_CLIENT, "Get SystemAbility failed.");
835         return;
836     }
837 
838     if (deathRecipient_ == nullptr) {
839         deathRecipient_ = new RSSSaDeathRecipient();
840     }
841 
842     systemAbility->AddDeathRecipient(deathRecipient_);
843 }
844 } // namespace MiscServices
845 } // namespace OHOS