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