-
Notifications
You must be signed in to change notification settings - Fork 6
/
TimePrefsHandler.cpp
executable file
·4873 lines (4063 loc) · 140 KB
/
TimePrefsHandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2010-2024 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "TimePrefsHandler.h"
#include <glib.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <memory.h>
#include <set>
#include <sys/sysinfo.h>
#if defined(HAVE_LUNA_PREFS)
#include <lunaprefs.h>
#endif
#include <pbnjson.hpp>
#include <luna-service2++/error.hpp>
#include <webosi18n.h>
#include "Mainloop.h"
#include "NetworkConnectionListener.h"
#include "PrefsDb.h"
#include "PrefsFactory.h"
#include "ClockHandler.h"
#include "Logging.h"
#include "Utils.h"
#include "JSONUtils.h"
#include "TimeZoneService.h"
using namespace pbnjson;
static const char* s_tzFile = WEBOS_INSTALL_WEBOS_PREFIX "/ext-timezones.json";
static const char* s_tzFilePath = WEBOS_INSTALL_SYSMGR_LOCALSTATEDIR "/preferences/localtime";
static const char* s_zoneInfoFolder = "/usr/share/zoneinfo/";
static const int s_sysTimeNotificationThreshold = 3000; // 5 mins
static const char* s_logChannel = "TimePrefsHandler";
static const char* s_factoryTimeSource = "factory";
static std::string s_localeStr = "en-US";
static const std::string s_file = "cppstrings.json";
static const std::string s_resources_path = "/usr/share/localization/luna-sysservice";
#define ORIGIN_NITZ "nitz"
#define HOURFORMAT_12 "HH12"
#define HOURFORMAT_24 "HH24"
#define NITZVALIDITY_STATE_NITZVALID "NITZVALID"
#define NITZVALIDITY_STATE_NITZINVALIDUSERNOTSET "NITZINVALID_USERNOTSET"
#define NITZVALIDITY_STATE_NITZINVALIDUSERSET "NITZINVALID_USERSET"
#define DEBUG_TIMEPREFS 1
#define ABSV(x) ((x) < 0 ? (x*-1) : (x))
#define DIFFTIME(x,y) ((x) > (y) ? ((x)-(y)) : ((y)-(x)))
#undef LSREPORT
//#define LSREPORT(lse) g_critical( "in %s: %s => %s", __func__, (lse).func, (lse).message )
#define LSREPORT(lse) qCritical( "in %s: %s => %s", __func__, (lse).func, (lse).message )
#define TIMEOUT_INTERVAL_SEC 5
namespace {
// when no time source used for system time
const int lowestTimeSourcePriority = INT_MIN; // mark for overriding
} // anonymous namespace
JValue TimePrefsHandler::s_timeZonesJson {};
TimePrefsHandler * TimePrefsHandler::s_inst = NULL;
extern char *strptime (__const char *__restrict __s,
__const char *__restrict __fmt, struct tm *__tp);
namespace {
bool convert(const JValue &value, time_t &timeValue)
{
if (!value.isNumber()) return false;
// this check will be compiled-out due to static condition
if (sizeof(time_t) <= sizeof(int32_t))
{
timeValue = value.asNumber<int32_t>();
}
else
{
timeValue = value.asNumber<int64_t>();
}
return true;
}
bool convertUnique(const char *function, const char *value, std::vector<std::string> &unique)
{
JsonMessageParser parser( value,
"{\"type\":\"array\",\"items\": {\"type\":\"string\"},\"uniqueItems\":true}"
);
if (!parser.parse(function)) return false;
JValue array = parser.get();
unique.clear();
unique.reserve(array.arraySize());
for (ssize_t i = 0; i < array.arraySize(); ++i)
{
unique.push_back(array[i].asString());
}
return true;
}
// return moment of bootStart in current system time (i.e. always valid
// even if time were changed since boot)
time_t bootStart()
{
timespec ts_epoch, ts_boot;
bool haveTimes = (clock_gettime(CLOCK_REALTIME, &ts_epoch) == 0) &&
(clock_gettime(CLOCK_BOOTTIME, &ts_boot) == 0);
// Note: we use beginning of epoch as a fake boot time if no way to get
// one of required clocks
return haveTimes ? (ts_epoch.tv_sec - ts_boot.tv_sec) : (time_t)0;
}
} // anonymous namespace
static void
print_tzvars (void)
{
qDebug ("tzname[0]='%s' tzname[1]='%s' daylight='%d' timezone='%ld'", tzname[0], tzname[1], daylight, timezone);
}
static void
set_tz(const char * tz) {
static gchar * env = NULL;
g_free(env);
env = g_strdup_printf("TZ=%s", tz);
putenv(env);
tzset();
qDebug("%s: tz set to %s", __func__, tz);
print_tzvars();
}
static bool
tz_exists(const char* tz_name) {
#define ZONEINFO_PATH_PREFIX "/usr/share/zoneinfo/"
g_return_val_if_fail(tz_name != NULL, false);
g_return_val_if_fail(strlen(tz_name) > 1, false);
g_return_val_if_fail(tz_name[0] != '/', false);
g_return_val_if_fail(tz_name[0] != '.', false);
g_return_val_if_fail(strstr(tz_name, "..") == NULL, false);
char *path = g_build_filename(ZONEINFO_PATH_PREFIX, tz_name, NULL);
bool ret = g_file_test(path, G_FILE_TEST_IS_REGULAR);
g_free(path);
return ret;
}
struct TimeZoneInfo
{
bool operator==(const struct TimeZoneInfo& c) const {
return (name == c.name) && (city== c.city);
}
std::string name;
std::string city;
std::string description;
std::string country;
std::string countryCode;
std::string jsonStringValue;
int dstSupported;
int offsetToUTC;
bool preferred; //if set to true, then pick this TZ is searching by offset vs any others
int howManyZonesForCountry; //how many offsets (incl. this one) does this country (based on countryCode) span? e.g. USA = 9
};
namespace {
TimeZoneInfo buildFailsafeDefaultZone()
{
TimeZoneInfo tz;
tz.name = "Etc/GMT-0";
tz.countryCode = "";
tz.jsonStringValue = "{"
"\"Country\":\"\",\"CountryCode\":\"\","
"\"ZoneID\":\"Etc/GMT-0\",\"City\":\"\","
"\"Description\":\"GMT\",\"offsetFromUTC\": 0,"
"\"supportsDST\":0"
"}";
tz.dstSupported = 0;
tz.offsetToUTC = 0;
tz.preferred = false;
tz.howManyZonesForCountry = 0;
return tz;
}
} // anonymous namespace
const TimeZoneInfo TimePrefsHandler::s_failsafeDefaultZone = buildFailsafeDefaultZone();
struct TZJsonHelper
{
public:
static bool extract(const JValue& root, TimeZoneInfo* timeZoneInfo)
{
if (!root.isObject()) {
return false;
}
reset(timeZoneInfo);
JValue label = root["Description"];
if (label.isString()) {
timeZoneInfo->description = label.asString();
}
label = root["City"];
if (label.isString()) {
timeZoneInfo->city = label.asString();
}
label = root["Country"];
if (label.isString()) {
timeZoneInfo->country = label.asString();
}
label = root["supportDST"];
if (label.isNumber()) {
timeZoneInfo->dstSupported = label.asNumber<int>();
}
label = root["offsetFromUTC"];
if (label.isNumber()) {
timeZoneInfo->offsetToUTC = label.asNumber<int>();
}
label = root["ZoneID"];
if (label.isString()) {
timeZoneInfo->name = label.asString();
}
label = root["CountryCode"];
if (label.isString()) {
timeZoneInfo->countryCode = label.asString();
}
label = root["preferred"];
if (label.isBoolean()) {
timeZoneInfo->preferred = label.asBool();
}
return true;
}
static JValue pack(const TimeZoneInfo* timeZoneInfo)
{
JValue timeZoneObj = pbnjson::Object();
if(!timeZoneInfo->description.empty()) {
timeZoneObj.put("Description", timeZoneInfo->description);
}
if(!timeZoneInfo->city.empty()) {
timeZoneObj.put("City", timeZoneInfo->city);
}
if(!timeZoneInfo->country.empty()) {
timeZoneObj.put("Country", timeZoneInfo->country);
}
timeZoneObj.put("supportDST", timeZoneInfo->dstSupported);
timeZoneObj.put("offsetFromUTC", timeZoneInfo->offsetToUTC);
if (!timeZoneInfo->name.empty()) {
timeZoneObj.put("ZoneID", timeZoneInfo->name);
}
if (!timeZoneInfo->countryCode.empty()) {
timeZoneObj.put("CountryCode", timeZoneInfo->countryCode);
}
if (timeZoneInfo->preferred)
{
timeZoneObj.put("preferred", timeZoneInfo->preferred);
}
return timeZoneObj;
}
private:
static void reset(TimeZoneInfo* timeZoneInfo)
{
timeZoneInfo->name = "";
timeZoneInfo->city = "";
timeZoneInfo->description = "";
timeZoneInfo->country = "";
timeZoneInfo->countryCode = "";
timeZoneInfo->jsonStringValue = "";
timeZoneInfo->dstSupported = 0;
timeZoneInfo->offsetToUTC = 0;
timeZoneInfo->preferred = false;
timeZoneInfo->howManyZonesForCountry = 0;
}
};
///just a simple container
struct PreferredZones
{
PreferredZones() : dstPref(NULL), nonDstPref(NULL), dstFallback(NULL), nonDstFallback(NULL) {}
/* PreferredZones(const PreferredZones& c) = default; */
/* PreferredZones& operator=(const PreferredZones& c) = default; */
int offset;
TimeZoneInfo * dstPref;
TimeZoneInfo * nonDstPref;
TimeZoneInfo * dstFallback;
TimeZoneInfo * nonDstFallback;
};
NitzParameters::NitzParameters()
: _offset(-1000)
, _dst(0)
, _mcc(0)
, _mnc(0)
, _timevalid(false)
, _tzvalid(false)
, _dstvalid(false)
, _localtimeStamp(0)
{
memset(&_timeStruct,0,sizeof(_timeStruct));
}
NitzParameters::NitzParameters(struct tm& timeStruct,int offset,int dst,int mcc,int mnc,
bool timevalid,bool tzvalid,bool dstvalid,uint32_t remotetimeStamp)
: _offset(offset)
, _dst(dst)
, _mcc(mcc)
, _mnc(mnc)
, _timevalid(timevalid)
, _tzvalid(tzvalid)
, _dstvalid(dstvalid)
, _localtimeStamp(remotetimeStamp)
{
memcpy(&_timeStruct,&timeStruct,sizeof(timeStruct));
_localtimeStamp = time(NULL);
}
void NitzParameters::stampTime()
{
_localtimeStamp = time(NULL);
}
bool NitzParameters::valid(uint32_t threshold)
{
/// not using timestamps anymore since the TIL sets the time directly
// uint32_t lt = time(NULL);
// uint32_t difft = (uint32_t)(DIFFTIME(_localtimeStamp,(uint32_t)time(NULL)));
// qDebug("%s: object(%u) ? (%u) current time = diff: %u , threshold: %u",__FUNCTION__,_localtimeStamp,lt,difft,threshold);
// if (difft > threshold)
// return false;
return true;
}
static JValue valuesFor_useNetworkTime( TimePrefsHandler * pTimePrefsHandler);
static bool validateFor_useNetworkTime( TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static JValue valuesFor_useNetworkTimeZone( TimePrefsHandler * pTimePrefsHandler);
static bool validateFor_useNetworkTimeZone( TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static JValue valuesFor_timeZone( TimePrefsHandler * pTimePrefsHandler);
static bool validateFor_timeZone( TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static JValue valuesFor_timeFormat( TimePrefsHandler * pTimePrefsHandler);
static bool validateFor_timeFormat( TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static JValue valuesFor_timeChangeLaunch( TimePrefsHandler * pTimePrefsHandler);
static bool validateFor_timeChangeLaunch( TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static bool validateFor_timeDriftPeriodHr(TimePrefsHandler * pTimePrefsHandler, const JValue &pValue);
static void tzsetWorkaround(const char * newTZ) __attribute__((unused));
/*!
* \page com_palm_systemservice_time Service API com.webos.service.systemservice/time/
* Public methods:
* - \ref com_palm_systemservice_time_set_system_time
* - \ref com_palm_systemservice_time_set_system_network_time
* - \ref com_palm_systemservice_time_get_system_time
* - \ref com_palm_systemservice_time_get_system_timezone_file
* - \ref com_palm_systemservice_time_set_time_change_launch
* - \ref com_palm_systemservice_time_launch_time_change_apps
* - \ref com_palm_systemservice_time_get_ntp_time
* - \ref com_palm_systemservice_time_set_time_with_ntp
* - \ref com_palm_systemservice_time_convert_date
*/
static LSMethod s_methods[] = {
{ "getSystemTime", TimePrefsHandler::cbGetSystemTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "getSystemTimezoneFile", TimePrefsHandler::cbGetSystemTimezoneFile, LUNA_METHOD_FLAG_DEPRECATED},
{ "getBroadcastTime", TimePrefsHandler::cbGetBroadcastTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "getEffectiveBroadcastTime", TimePrefsHandler::cbGetEffectiveBroadcastTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "setTimeChangeLaunch", TimePrefsHandler::cbSetTimeChangeLaunch, LUNA_METHOD_FLAG_DEPRECATED},
{ "launchTimeChangeApps", TimePrefsHandler::cbLaunchTimeChangeApps, LUNA_METHOD_FLAG_DEPRECATED},
{ "getNTPTime", TimePrefsHandler::cbGetNTPTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "convertDate", TimePrefsHandler::cbConvertDate, LUNA_METHOD_FLAG_DEPRECATED},
{ "getSystemUptime", TimePrefsHandler::getSystemUptime, LUNA_METHOD_FLAG_DEPRECATED},
{ "getCurrentTimeZoneByLocale", TimePrefsHandler::cbTimeZoneByLocale, LUNA_METHOD_FLAG_DEPRECATED},
{ "setSystemTime", TimePrefsHandler::cbSetSystemTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "setSystemNetworkTime", TimePrefsHandler::cbSetSystemNetworkTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "setBroadcastTime", TimePrefsHandler::cbSetBroadcastTime, LUNA_METHOD_FLAG_DEPRECATED},
{ "setTimeWithNTP", TimePrefsHandler::cbSetTimeWithNTP, LUNA_METHOD_FLAG_DEPRECATED},
{ 0, 0 },
};
typedef JValue (*valuesForKeyFnPtr)(TimePrefsHandler * pTimePrefsHandler);
typedef bool (*validateForKeyFnPtr)(TimePrefsHandler * pTimePrefsHandler, const pbnjson::JValue & pValue);
typedef struct timePrefKey_s {
const char * keyName;
valuesForKeyFnPtr valuesFn;
validateForKeyFnPtr validateFn;
} TimePrefKey;
static const TimePrefKey timePrefKeys[] = {
{"useNetworkTime" , valuesFor_useNetworkTime , validateFor_useNetworkTime},
{"useNetworkTimeZone" , valuesFor_useNetworkTimeZone , validateFor_useNetworkTimeZone},
{"timeZone", valuesFor_timeZone , validateFor_timeZone},
{"timeFormat", valuesFor_timeFormat , validateFor_timeFormat},
{"timeChangeLaunch", valuesFor_timeChangeLaunch, validateFor_timeChangeLaunch},
{"timeDriftPeriodHr", NULL, validateFor_timeDriftPeriodHr},
{"nitzValidity",NULL,NULL}
};
const time_t TimePrefsHandler::m_driftPeriodDefault = (4*60*60);
const time_t TimePrefsHandler::m_driftPeriodDisabled = -1;
static inline bool isSpaceOrNull(char v) {
return (v == 0 || isspace(v));
}
void convertString(const char* str, std::string& convertedStr)
{
if(str)
{
if(Settings::instance()->useLocalizedTZ) {
ResBundle* resBundle = NULL;
resBundle = new ResBundle(s_localeStr, s_file, s_resources_path);
if (resBundle)
{
convertedStr = resBundle->getLocString(str);
delete resBundle;
resBundle = NULL;
}
} else {
convertedStr = std::string(str);
}
}
}
time_t TimePrefsHandler::currentStamp()
{
#if !defined(DESKTOP)
// FIXME: CLOCK_UPTIME doesn't work
struct timespec currTime;
::clock_gettime(CLOCK_MONOTONIC, &currTime);
return currTime.tv_sec;
#else
struct timespec currTime;
::clock_gettime(CLOCK_MONOTONIC, &currTime);
return currTime.tv_sec;
#endif
}
TimePrefsHandler::TimePrefsHandler(LSHandle* serviceHandle)
: PrefsHandler(serviceHandle)
, m_cpCurrentTimeZone(nullptr)
, m_pDefaultTimeZone(nullptr)
, m_pManualTimeZone(nullptr)
, m_nitzSetting(TimePrefsHandler::NITZ_TimeEnable | TimePrefsHandler::NITZ_TZEnable)
, m_lastNitzValidity(TimePrefsHandler::NITZ_Unknown)
, m_immNitzTimeValid(false)
, m_immNitzZoneValid(false)
, m_p_lastNitzParameter(nullptr)
, m_lastNitzFlags(0)
, m_gsource_periodic(nullptr)
, m_gsource_periodic_id(0)
, m_timeoutCycleCount(0)
, m_sendWakeupSetToAlarmD(true)
, m_lastNtpUpdate(0)
, m_nitzTimeZoneAvailable(true)
, m_currentTimeSourcePriority(lowestTimeSourcePriority)
, m_nextSyncTime(0)
, m_systemTimeSourceTag(s_factoryTimeSource)
, m_micomTimeStamp((time_t)-1)
, m_ntpClock(*this)
, m_driftPeriod(m_driftPeriodDefault)
, m_gsource_tzTrans(nullptr)
, m_gsource_tzTrans_id(0)
, m_nextTzTrans(-1)
, m_micomAvailable(true)
, m_altFactorySrcPriority(0)
, m_altFactorySrcLastUpdate(0)
, m_altFactorySrcSystemOffset(0)
, m_altFactorySrcValid(false)
{
if (!s_inst)
s_inst=this;
init();
}
TimePrefsHandler::~TimePrefsHandler()
{
NetworkConnectionListener::instance()->shutdown();
delete m_p_lastNitzParameter;
m_p_lastNitzParameter = nullptr;
delete m_pManualTimeZone;
m_pManualTimeZone = nullptr;
delete m_pDefaultTimeZone;
m_pDefaultTimeZone = nullptr;
TimeZoneInfoList::iterator it = m_zoneList.begin();
for (; it != m_zoneList.end();++it)
{
delete *it;
*it = nullptr;
}
m_zoneList.clear();
it = m_syszoneList.begin();
for (; it != m_syszoneList.end();++it)
{
delete *it;
*it = nullptr;
}
m_syszoneList.clear();
}
std::list<std::string> TimePrefsHandler::keys() const
{
return m_keyList;
}
bool TimePrefsHandler::validate(const std::string& key, const pbnjson::JValue &value)
{
if (!value.isValid())
return false;
for (size_t i = 0; i < sizeof(timePrefKeys) / sizeof(TimePrefKey); i++) {
auto tmpKey = timePrefKeys[i].keyName;
if (tmpKey) {
if (key == tmpKey) {
if (timePrefKeys[i].validateFn != NULL)
return ((*(timePrefKeys[i].validateFn))(this, value));
else
return false;
}
}
}
return false;
}
void TimePrefsHandler::updateTimeZoneInfo()
{
if ((m_p_lastNitzParameter != NULL)
&& (true == m_p_lastNitzParameter->_tzvalid)) {
const TimeZoneInfo *nitzTz = timeZone_ZoneFromOffset(
m_p_lastNitzParameter->_offset, m_p_lastNitzParameter->_dst,
m_p_lastNitzParameter->_mcc);
if (nitzTz) {
bool valid_tz = isValidTimeZoneName(nitzTz->name);
if (valid_tz) {
JValue root = JDomParser::fromString(nitzTz->jsonStringValue);
TimeZoneInfo tzInfo;
if (TZJsonHelper::extract(root, &tzInfo)) {
if (Settings::instance()->useLocalizedTZ) {
std::unique_ptr < ResBundle > resBundle =
std::unique_ptr < ResBundle
> (new ResBundle(s_localeStr, s_file,
s_resources_path));
tzInfo.city = resBundle->getLocString(tzInfo.city);
tzInfo.description = resBundle->getLocString(
tzInfo.description);
tzInfo.country = resBundle->getLocString(
tzInfo.country);
}
JValue tzInfoJValue = pbnjson::Object();
tzInfoJValue.put("timeZone", TZJsonHelper::pack(&tzInfo));
std::string reply = tzInfoJValue.stringify();
LSError error;
LSErrorInit(&error);
if (!(LSCall(getServiceHandle(),
"luna://com.webos.service.systemservice/setPreferences",
reply.c_str(), nullptr, this, nullptr, &error))) {
LSErrorFree(&error);
} else {
PmLogDebug(sysServiceLogContext(),
"set Network TimeZone successfull");
}
}
}
}
}
}
void TimePrefsHandler::switchTimeZone(bool b_recover)
{
if (b_recover)
{
JValue jArgs = pbnjson::JObject();
std::string lastTzName =
PrefsDb::instance()->getPref("lastTimeZone");
if (lastTzName == "") {
lastTzName = s_failsafeDefaultZone.name;
PrefsDb::instance()->setPref("lastTimeZone",lastTzName.c_str());
}
qDebug("set TimeZone to [%s]",lastTzName.c_str());
jArgs.put("ZoneID", lastTzName);
valueChanged("timeZone", jArgs);
}
else
{
PrefsDb::instance()->setPref("lastTimeZone",
m_cpCurrentTimeZone->name);
qDebug("set TimeZone to [%s]",m_cpCurrentTimeZone->name.c_str());
TimeZoneService::instance()->createTimeZoneFromEasData(getServiceHandle());
JValue jArgs = JObject();
jArgs.put("ZoneID", MANUAL_TZ_NAME);
valueChanged("timeZone", jArgs);
}
// while respond if timeZone preference is set using setPreferencs directly
// (@see. cbSetPreferences & postPrefChangeValueIsCompleteString),
// when useNetworkTime is changed, does not notify timeZone change(manual<->auto).
// so, it need to notify timezone change to subscribers.
std::string timeZone = PrefsDb::instance()->getPref("timeZone");
PrefsFactory::instance()->postPrefChange("timeZone", timeZone);
}
void TimePrefsHandler::valueChanged(const std::string& key, const JValue &value)
{
bool bval;
std::string strval;
if (key == "useNetworkTime") {
if (value.isBoolean()) {
bval = value.asBool();
}
else {
bval = true;
}
if(isManualTimeUsed() == !bval)
{
qWarning("value userNetworkTime isn't changed (ignoring)");
return;
}
if(enableNetworkTimeSync(bval) == -1)
qWarning("valueChanged: enableNetworkTimeSync failed");
setNITZTimeEnable(bval);
if(Settings::instance()->switchTimezoneOnManualTime)
{
// manual timezone will be also set
switchTimeZone(bval);
}
postBroadcastEffectiveTimeChange();
if (bval)
{
//kick off an update cycle right now (* see the function for restrictions; It won't do anything in some cases)
startBootstrapCycle(3);
}
else
{
// on switching from auto-time update manual time right away as if
// user set it
systemSetTime(0, ClockHandler::manual);
}
}
else if (key == "useNetworkTimeZone") {
if (value.isBoolean()) {
bval = value.asBool();
}
else {
bval = true;
}
if(bval){
updateTimeZoneInfo();
}
setNITZTZEnable(bval);
}
else if (key == "timeZone") {
//TODO: change tz
if (value) {
strval = TimePrefsHandler::tzNameFromJsonValue(value);
std::string substrval = TimePrefsHandler::tzCityNameFromJsonValue(value);
__qMessage("attempted change of timeZone to [%s:%s]",
strval.c_str(), substrval.c_str());
const TimeZoneInfo * new_mcTZ = timeZone_ZoneFromName(strval, substrval);
if (new_mcTZ) {
if (*new_mcTZ == *m_cpCurrentTimeZone) {
qDebug("new and old timezones are the same...skipping the rest of the change procedure");
return;
}
m_cpCurrentTimeZone = new_mcTZ;
}
if (m_cpCurrentTimeZone) {
qDebug("%s: successfully mapped to zone [%s]", __func__, m_cpCurrentTimeZone->name.c_str());
setTimeZone(m_cpCurrentTimeZone);
}
else {
int currOffsetToUTC = offsetToUtcSecs()/60;
//last chance to get a valid timezone given the offset
m_cpCurrentTimeZone = timeZone_ZoneFromOffset(currOffsetToUTC);
if (m_cpCurrentTimeZone == NULL)
{
qWarning() << "Couldn't pick timezone from offset" << currOffsetToUTC << "... picking a generic zone based on offset";
//STILL NULL! pick a generic zone
m_cpCurrentTimeZone = timeZone_GenericZoneFromOffset(currOffsetToUTC);
if (m_cpCurrentTimeZone == NULL)
{
qWarning() << "Couldn't pick GENERIC timezone from offset" << currOffsetToUTC << "... last resort: go to default zone";
//This should never happen unless the syszone list is corrupt. But if it is, pick the failsafe default
m_cpCurrentTimeZone = &s_failsafeDefaultZone;
}
}
setTimeZone(m_cpCurrentTimeZone);
}
transitionNITZValidState((this->getLastNITZValidity() == TimePrefsHandler::NITZ_Valid),true);
// TODO: consider moving to systemSetTimeZone
postSystemTimeChange();
postBroadcastEffectiveTimeChange();
//launch any apps that wanted to be launched when the time/zone changed
launchAppsOnTimeChange();
tzTransTimer();
}
else {
qWarning("attempted change of timeZone but no value provided");
}
}
else if (key == "timeFormat") {
//TODO: change tformat
if (value.isString()) {
strval = value.asString();
__qMessage("attempted change of timeFormat to [%s]",strval.c_str());
}
else {
qWarning() << "attempted change of timeFormat but no string value provided";
}
}
else if (key == "timeDriftPeriodHr") {
if (value.isString()) {
strval = value.asString();
__qMessage("attempted change of timeDriftpPeriodHr to [%s]",strval.c_str());
updateDriftPeriod(strval);
}
else {
qWarning() << "attempted change of timeDriftPeriodHr but no string value provided";
}
}
qWarning("valueChanged: useNetworkTime is [%s] , useNetworkTimeZone is [%s]",
(this->isNITZTimeEnabled() ? "true" : "false"),(this->isNITZTZEnabled() ? "true" : "false"));
}
JValue TimePrefsHandler::valuesForKey(const std::string& key)
{
JValue result;
for (size_t i = 0; i < sizeof(timePrefKeys) / sizeof(TimePrefKey); i++) {
if (timePrefKeys[i].keyName) {
if ((key == timePrefKeys[i].keyName)
&& (timePrefKeys[i].valuesFn != NULL)) {
result = ((*(timePrefKeys[i].valuesFn))(this));
break;
} else if ((key == timePrefKeys[i].keyName)
&& (timePrefKeys[i].valuesFn == NULL))
break;
}
}
if (result.isValid()) {
return result;
}
//else, a default return object is returned
return JObject();
}
bool TimePrefsHandler::cbLocaleHandler(LSHandle* sh, LSMessage* message, void* data)
{
do {
const char* str = LSMessageGetPayload(message);
if(!str) break;
JValue root = JDomParser::fromString(str);
if (!root.isObject()) break;
JValue settings = root["settings"];
if (!settings.isObject()) break;
JValue localeInfo = settings["localeInfo"];
if (!localeInfo.isObject()) break;
JValue locales = localeInfo["locales"];
if (!locales.isObject()) break;
JValue UI = locales["UI"];
if (!UI.isString()) break;
s_localeStr = UI.asString();
return true;
} while(false);
return false;
}
JValue TimePrefsHandler::timeZoneListAsJson()
{
return TimePrefsHandler::s_timeZonesJson; //"copy" it!
}
JValue TimePrefsHandler::timeZoneListAsJson(const std::string& countryCode, const std::string& locale)
{
do {
JValue timeZones = TimePrefsHandler::s_timeZonesJson["timeZone"];
if (!timeZones.isArray()) {
qWarning() << "Failed to parse timeZone details";
break;
}
JValue sysZones = TimePrefsHandler::s_timeZonesJson["syszones"];
if (!sysZones.isArray()) {
qWarning() << "Failed to parse syszones details";
break;
}
JValue mmcInfoObj = TimePrefsHandler::s_timeZonesJson["mmcInfo"];
if (!mmcInfoObj.isObject()) {
qWarning() << "Failed to parse mmcInfo details";
break;
}
std::unique_ptr<ResBundle> resBundle(nullptr);
if (!locale.empty())
{
resBundle.reset(new ResBundle(locale, s_file, s_resources_path));
}
else
{
resBundle.reset(new ResBundle(s_localeStr, s_file, s_resources_path));
}
std::string locCountryCode("");
JValue label;
JValue timeZoneArray = pbnjson::Array();
TimeZoneInfo tzInfo;
for (const JValue key: timeZones.items()) {
label = key["CountryCode"];
if (!label.isString()) continue;
locCountryCode = label.asString();
if (countryCode.empty() || (countryCode == locCountryCode)) {
if (TZJsonHelper::extract(key, &tzInfo)) {
if(Settings::instance()->useLocalizedTZ) {
tzInfo.description = resBundle->getLocString(tzInfo.description);
tzInfo.city = resBundle->getLocString(tzInfo.city);
tzInfo.country = resBundle->getLocString(tzInfo.country);
}
timeZoneArray.append(TZJsonHelper::pack(&tzInfo));
}
}
}
JValue timeZonesListObj = pbnjson::Object();
timeZonesListObj.put("timeZone", timeZoneArray);
if (countryCode.empty()) {
timeZonesListObj.put("syszones", sysZones);
timeZonesListObj.put("mmcInfo", mmcInfoObj);
}
if (!timeZonesListObj.isNull()) {
return timeZonesListObj;
}
} while(false);
return TimePrefsHandler::s_timeZonesJson;
}
bool TimePrefsHandler::isValidTimeZoneName(const std::string& tzName)
{
if (!TimePrefsHandler::s_timeZonesJson.isValid())
return false;
if(!tzName.compare(MANUAL_TZ_NAME)) return true;
JValue label = TimePrefsHandler::s_timeZonesJson["timeZone"];
if (!label.isArray()) {
return false;
}
for (const JValue& timezone: label.items()) {
if (!timezone.isObject()) continue;
//parse out the TZ name
JValue zone_id = timezone["ZoneID"];
if (!zone_id.isString()) {
continue;
}
if (tzName == zone_id.asString())
return true;
}
label = TimePrefsHandler::s_timeZonesJson["syszones"];
if (!label.isArray()) {
return false;
}
for (const JValue timezone: label.items()) {
if (!timezone.isObject()) continue;
//parse out the TZ name
JValue zone_id = timezone["ZoneID"];
if (!zone_id.isString()) {
continue;
}
if (tzName == zone_id.asString())
return true;
}
return false;
}
static JValue valuesFor_useNetworkTime(TimePrefsHandler *)
{
return JObject {{"useNetworkTime", JArray {true, false}}};
}
static bool validateFor_useNetworkTime(TimePrefsHandler *, const JValue &pValue)
{
return pValue.isBoolean();
}
static JValue valuesFor_useNetworkTimeZone(TimePrefsHandler *)
{
return JObject {{"useNetworkTimeZone", JArray {true, false}}};
}
static bool validateFor_useNetworkTimeZone(TimePrefsHandler * pTimePrefsHandler, const JValue &pValue)
{
return pValue.isBoolean();
}
static JValue valuesFor_timeZone(TimePrefsHandler * pTimePrefsHandler)
{
if (pTimePrefsHandler == NULL)
return JObject();