23 #include "gnc-timezone.hpp" 29 #include <boost/date_time/gregorian/gregorian.hpp> 32 #include <boost/locale/encoding_utf.hpp> 36 static const QofLogModule log_module =
"gnc-timezone";
40 using duration = boost::posix_time::time_duration;
41 using time_zone = boost::local_time::custom_time_zone;
42 using dst_offsets = boost::local_time::dst_adjustment_offsets;
43 using calc_rule_ptr = boost::local_time::dst_calc_rule_ptr;
44 using PTZ = boost::local_time::posix_time_zone;
46 const unsigned int TimeZoneProvider::min_year = 1400;
47 const unsigned int TimeZoneProvider::max_year = 9999;
53 #ifndef WORDS_BIGENDIAN 54 auto memp =
reinterpret_cast<unsigned char*
>(t);
55 std::reverse(memp, memp +
sizeof(T));
67 template<
typename T>
inline std::string to_string(T num);
71 to_string<unsigned int>(
unsigned int num)
73 constexpr
unsigned int numchars =
sizeof num * 3 + 1;
74 char buf [numchars] {};
75 snprintf (buf, numchars,
"%u", num);
76 return std::string(buf);
81 to_string<int>(
int num)
83 constexpr
unsigned int numchars =
sizeof num * 3 + 1;
85 snprintf (buf, numchars,
"%d", num);
86 return std::string(buf);
95 windows_reg_string (HKEY key,
const wchar_t* subkey,
96 const wchar_t* value_name, std::string& value)
99 if (RegGetValueW (key, subkey, value_name, RRF_RT_REG_SZ,
nullptr,
100 nullptr, &size) != ERROR_SUCCESS)
102 std::wstring buf (size /
sizeof (
wchar_t) + 1, L
'\0');
103 size =
static_cast<DWORD
>(buf.size () *
sizeof (wchar_t));
104 if (RegGetValueW (key, subkey, value_name, RRF_RT_REG_SZ,
nullptr,
105 &buf[0], &size) != ERROR_SUCCESS)
107 buf.resize (wcslen (buf.c_str ()));
108 value = boost::locale::conv::utf_to_utf<char> (buf);
113 windows_default_tzname (
void)
115 std::string key_name;
116 windows_reg_string (HKEY_LOCAL_MACHINE,
117 L
"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation",
118 L
"TimeZoneKeyName", key_name);
127 SYSTEMTIME StandardDate;
128 SYSTEMTIME DaylightDate;
131 static time_zone_names
132 windows_tz_names (HKEY key)
134 std::string std_name;
135 if (!windows_reg_string (key,
nullptr, L
"Std", std_name))
136 throw std::invalid_argument (
"Registry contains no standard name.");
138 std::string dlt_name;
139 if (!windows_reg_string (key,
nullptr, L
"Dlt", dlt_name))
140 throw std::invalid_argument (
"Registry contains no daylight name.");
142 return time_zone_names (std_name, std_name, dlt_name, dlt_name);
145 #define make_week_num(x) static_cast<boost::date_time::nth_kday_of_month<boost::gregorian::date>::week_num>(x) 148 zone_from_regtzi (
const RegTZI& regtzi, time_zone_names names)
150 using ndate = boost::gregorian::nth_day_of_the_week_in_month;
151 using nth_day_rule = boost::local_time::nth_day_of_the_week_in_month_dst_rule;
159 duration std_off (0, regtzi.StandardBias - regtzi.Bias, 0);
160 duration dlt_off (0, -regtzi.DaylightBias, 0);
161 duration start_time (regtzi.StandardDate.wHour, regtzi.StandardDate.wMinute,
162 regtzi.StandardDate.wSecond);
163 duration end_time (regtzi.DaylightDate.wHour, regtzi.DaylightDate.wMinute,
164 regtzi.DaylightDate.wSecond);
165 dst_offsets offsets (dlt_off, start_time, end_time);
166 auto std_week_num = make_week_num(regtzi.StandardDate.wDay);
167 auto dlt_week_num = make_week_num(regtzi.DaylightDate.wDay);
169 if (regtzi.StandardDate.wMonth != 0)
173 ndate start (dlt_week_num, regtzi.DaylightDate.wDayOfWeek,
174 regtzi.DaylightDate.wMonth);
175 ndate end(std_week_num, regtzi.StandardDate.wDayOfWeek,
176 regtzi.StandardDate.wMonth);
177 dates.reset(
new nth_day_rule (start, end));
179 catch (boost::gregorian::bad_month& err)
181 PWARN(
"Caught Bad Month Exception. Daylight Bias: %ld " 182 "Standard Month : %d Daylight Month: %d",
183 regtzi.DaylightBias, regtzi.StandardDate.wMonth,
184 regtzi.DaylightDate.wMonth);
187 return TZ_Ptr(
new time_zone(names, std_off, offsets, dates));
191 TimeZoneProvider::load_windows_dynamic_tz (HKEY key, time_zone_names names)
197 unsigned long size =
sizeof first;
198 if (RegQueryValueExW (key, L
"FirstEntry", NULL, NULL,
199 (LPBYTE) &first, &size) != ERROR_SUCCESS)
200 throw std::invalid_argument (
"No first entry.");
203 if (RegQueryValueExW (key, L
"LastEntry", NULL, NULL,
204 (LPBYTE) &last, &size) != ERROR_SUCCESS)
205 throw std::invalid_argument (
"No last entry.");
208 for (
unsigned int year = first; year <= last; year++)
210 auto s = to_string(year);
211 std::wstring ystr (s.begin(), s.end());
213 size =
sizeof regtzi;
214 auto err_val = RegQueryValueExW (key, ystr.c_str(), NULL, NULL,
215 (LPBYTE) ®tzi, &size);
216 if (err_val != ERROR_SUCCESS)
220 tz = zone_from_regtzi (regtzi, names);
222 m_zone_vector.push_back (std::make_pair(0, tz));
223 m_zone_vector.push_back (std::make_pair(year, tz));
225 m_zone_vector.push_back (std::make_pair(max_year, tz));
227 catch (
const std::invalid_argument& err)
232 catch (
const std::bad_alloc& err)
241 TimeZoneProvider::load_windows_classic_tz (HKEY key, time_zone_names names)
244 unsigned long size =
sizeof regtzi;
247 if (RegQueryValueExW (key, L
"TZI", NULL, NULL,
248 (LPBYTE) ®tzi, &size) == ERROR_SUCCESS)
250 m_zone_vector.push_back(
251 std::make_pair(max_year, zone_from_regtzi (regtzi, names)));
254 catch (
const std::bad_alloc& err)
263 TimeZoneProvider::load_windows_default_tz()
265 TIME_ZONE_INFORMATION tzi {};
266 GetTimeZoneInformation (&tzi);
267 RegTZI regtzi { tzi.Bias, tzi.StandardBias, tzi.DaylightBias,
268 tzi.StandardDate, tzi.DaylightDate };
269 using boost::locale::conv::utf_to_utf;
270 auto std_name = utf_to_utf<char>(tzi.StandardName,
271 tzi.StandardName +
sizeof(tzi.StandardName));
272 auto dlt_name = utf_to_utf<char>(tzi.DaylightName,
273 tzi.DaylightName +
sizeof(tzi.DaylightName));
274 time_zone_names names (std_name, std_name, dlt_name, dlt_name);
275 m_zone_vector.push_back(std::make_pair(max_year, zone_from_regtzi(regtzi, names)));
278 TimeZoneProvider::TimeZoneProvider (
const std::string& identifier) :
282 const std::string reg_key =
283 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
285 auto key_name = (identifier.empty() ? windows_default_tzname () :
288 if (key_name.empty())
290 load_windows_default_tz();
293 std::string subkey = reg_key + key_name;
295 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey.c_str(), 0,
296 KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
297 throw std::invalid_argument (
"No TZ in registry named " + key_name);
299 time_zone_names names {windows_tz_names (key)};
302 std::string subkey_dynamic = subkey +
"\\Dynamic DST";
303 if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey_dynamic.c_str(), 0,
304 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
305 this->load_windows_dynamic_tz (key, names);
306 else if (RegOpenKeyExA (HKEY_LOCAL_MACHINE, subkey.c_str(), 0,
307 KEY_QUERY_VALUE, &key) == ERROR_SUCCESS)
308 this->load_windows_classic_tz (key, names);
310 throw std::invalid_argument (
"No data for TZ " + key_name);
312 #elif PLATFORM(POSIX) 313 using std::to_string;
317 using boost::posix_time::ptime;
326 uint8_t reserved[15];
327 uint8_t ttisgmtcnt[4];
328 uint8_t ttisstdcnt[4];
356 static std::unique_ptr<char[]>
357 find_tz_file(
const std::string& name)
362 if (
auto tzenv = std::getenv(
"TZ"))
363 tzname = std::string(tzenv);
369 if (tzname[0] ==
':')
370 tzname.erase(tzname.begin());
371 if (tzname[0] ==
'/')
373 ifs.open(tzname, std::ios::in|std::ios::binary|std::ios::ate);
377 const char* tzdir_c = std::getenv(
"TZDIR");
378 std::string tzdir = tzdir_c ? tzdir_c :
"/usr/share/zoneinfo";
380 ifs.open(std::move(tzdir +
"/" + tzname),
381 std::ios::in|std::ios::binary|std::ios::ate);
386 throw std::invalid_argument(
"The timezone string failed to resolve to a valid filename");
387 std::streampos filesize = ifs.tellg();
388 std::unique_ptr<char[]>fileblock(
new char[filesize]);
389 ifs.seekg(0, std::ios::beg);
390 ifs.read(fileblock.get(), filesize);
395 using TZInfoVec = std::vector<TZInfo>;
396 using TZInfoIter = TZInfoVec::iterator;
400 IANAParser(
const std::string& name) : IANAParser(find_tz_file(name)) {}
401 IANAParser(std::unique_ptr<
char[]>);
402 std::vector<Transition>transitions;
407 IANAParser::IANAParser(std::unique_ptr<
char[]>fileblock)
409 unsigned int fb_index = 0;
410 TZHead tzh = *
reinterpret_cast<TZHead*
>(&fileblock[fb_index]);
411 static constexpr
int ttinfo_size = 6;
413 int transition_size = 4;
415 auto time_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.timecnt)));
416 auto type_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.typecnt)));
417 auto char_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.charcnt)));
418 auto isgmt_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisgmtcnt)));
419 auto isstd_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.ttisstdcnt)));
420 auto leap_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.leapcnt)));
421 if ((tzh.version ==
'2' || tzh.version ==
'3'))
423 fb_index = (
sizeof(tzh) +
424 (
sizeof(uint32_t) +
sizeof(uint8_t)) * time_count +
425 ttinfo_size * type_count +
426 sizeof(char) * char_count +
427 sizeof(uint8_t) * isgmt_count +
428 sizeof(uint8_t) * isstd_count +
429 2 *
sizeof(uint32_t) * leap_count);
433 tzh = *
reinterpret_cast<TZHead*
>(&fileblock[fb_index]);
435 time_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.timecnt)));
436 type_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.typecnt)));
437 char_count = *(endian_swap(reinterpret_cast<uint32_t*>(tzh.charcnt)));
440 fb_index +=
sizeof(tzh);
441 auto start_index = fb_index;
442 auto info_index_zero = start_index + time_count * transition_size;
443 for(uint32_t index = 0; index < time_count; ++index)
445 fb_index = start_index + index * transition_size;
446 auto info_index = info_index_zero + index;
447 if (transition_size == 4)
449 int32_t transition_time;
451 memcpy(&transition_time,
452 endian_swap(reinterpret_cast<int32_t*>(&fileblock[fb_index])),
454 auto info =
static_cast<uint8_t
>(fileblock[info_index]);
455 transitions.push_back({transition_time, info});
459 int64_t transition_time;
461 memcpy(&transition_time, &fileblock[fb_index],
463 transition_time = *(endian_swap(&transition_time));
464 auto info =
static_cast<uint8_t
>(fileblock[info_index]);
465 transitions.push_back({transition_time, info});
470 start_index = info_index_zero + time_count;
471 auto abbrev = start_index + type_count * ttinfo_size;
472 auto std_dist = abbrev + char_count;
473 auto gmt_dist = std_dist + type_count;
474 for(uint32_t index = 0; index < type_count; ++index)
476 fb_index = start_index + index * ttinfo_size;
479 memcpy(&info, &fileblock[fb_index], ttinfo_size);
480 endian_swap(&info.gmtoff);
482 {info, &fileblock[abbrev + info.abbrind],
483 (index < isstd_count ? fileblock[std_dist + index] !=
'\0' :
true),
484 (index < isgmt_count ? fileblock[gmt_dist + index] !=
'\0' :
false)});
492 using gregorian_date = boost::gregorian::date;
493 using IANAParser::TZInfoIter;
494 using ndate = boost::gregorian::nth_day_of_the_week_in_month;
496 boost::date_time::nth_kday_of_month<boost::gregorian::date>::week_num;
500 Transition() : month(1), dow(0), week(static_cast<week_num>(0)) {}
501 Transition(gregorian_date date);
502 bool operator==(
const Transition& rhs)
const noexcept;
504 boost::gregorian::greg_month month;
505 boost::gregorian::greg_weekday dow;
509 Transition::Transition(gregorian_date date) :
510 month(date.month()), dow(date.day_of_week()),
511 week(static_cast<week_num>((6 + date.day()) / 7))
515 Transition::operator==(
const Transition& rhs)
const noexcept
517 return (month == rhs.month && dow == rhs.dow && week == rhs.week);
523 return ndate(week, dow, month);
529 DSTRule(TZInfoIter info1, TZInfoIter info2,
530 ptime date1, ptime date2);
531 bool operator==(
const DSTRule& rhs)
const noexcept;
532 bool operator!=(
const DSTRule& rhs)
const noexcept;
535 duration to_std_time;
536 duration to_dst_time;
541 DSTRule::DSTRule() : to_std(), to_dst(), to_std_time {}, to_dst_time {},
542 std_info (), dst_info () {};
544 DSTRule::DSTRule (TZInfoIter info1, TZInfoIter info2,
545 ptime date1, ptime date2) :
546 to_std((date1 + boost::posix_time::seconds(info2->info.gmtoff)).date()),
547 to_dst((date2 + boost::posix_time::seconds(info1->info.gmtoff)).date()),
548 to_std_time((date1 + boost::posix_time::seconds(info2->info.gmtoff)).time_of_day()),
549 to_dst_time((date2 + boost::posix_time::seconds(info1->info.gmtoff)).time_of_day()),
550 std_info(info1), dst_info(info2)
552 if (info1->info.isdst == info2->info.isdst)
553 throw(std::invalid_argument(
"Both infos have the same dst value."));
554 if (info1->info.isdst && !info2->info.isdst)
556 std::swap(to_std, to_dst);
557 std::swap(to_std_time, to_dst_time);
558 std::swap(std_info, dst_info);
592 to_std_time += boost::posix_time::seconds(std_info->info.gmtoff -
593 dst_info->info.gmtoff);
597 DSTRule::operator==(
const DSTRule& rhs)
const noexcept
599 return (to_std == rhs.to_std &&
600 to_dst == rhs.to_dst &&
601 to_std_time == rhs.to_std_time &&
602 to_dst_time == rhs.to_dst_time &&
603 std_info == rhs.std_info &&
604 dst_info == rhs.dst_info);
608 DSTRule::operator!=(
const DSTRule& rhs)
const noexcept
610 return ! operator==(rhs);
615 zone_no_dst(
int year, IANAParser::TZInfoIter std_info)
617 time_zone_names names(std_info->name, std_info->name,
"",
"");
618 duration std_off(0, 0, std_info->info.gmtoff);
619 dst_offsets offsets({0, 0, 0}, {0, 0, 0}, {0, 0, 0});
620 boost::local_time::dst_calc_rule_ptr calc_rule(
nullptr);
621 TZ_Ptr tz(
new time_zone(names, std_off, offsets, calc_rule));
622 return std::make_pair(year, tz);
626 zone_from_rule(
int year, DSTRule::DSTRule rule)
628 using boost::gregorian::partial_date;
629 using boost::local_time::partial_date_dst_rule;
631 boost::local_time::nth_day_of_the_week_in_month_dst_rule;
633 time_zone_names names(rule.std_info->name, rule.std_info->name,
634 rule.dst_info->name, rule.dst_info->name);
635 duration std_off(0, 0, rule.std_info->info.gmtoff);
636 duration dlt_off(0, 0,
637 rule.dst_info->info.gmtoff - rule.std_info->info.gmtoff);
638 dst_offsets offsets(dlt_off, rule.to_dst_time, rule.to_std_time);
639 calc_rule_ptr dates(
new nth_day_rule(rule.to_dst.get(), rule.to_std.get()));
640 TZ_Ptr tz(
new time_zone(names, std_off, offsets, dates));
641 return std::make_pair(year, tz);
645 TimeZoneProvider::parse_file(
const std::string& tzname)
647 IANAParser::IANAParser parser(tzname);
648 using boost::posix_time::hours;
649 const auto one_year = hours(366 * 24);
650 auto last_info = std::find_if(parser.tzinfo.begin(), parser.tzinfo.end(),
651 [](IANAParser::TZInfo tz)
652 {
return !tz.info.isdst;});
653 auto last_time = ptime();
654 DSTRule::DSTRule last_rule;
655 using boost::gregorian::date;
656 using boost::posix_time::ptime;
657 using boost::posix_time::time_duration;
658 for (
auto txi = parser.transitions.begin();
659 txi != parser.transitions.end(); ++txi)
661 auto this_info = parser.tzinfo.begin() + txi->index;
664 auto this_time = ptime(date(1970, 1, 1),
665 time_duration(txi->timestamp / 3600, 0,
666 txi->timestamp % 3600));
673 auto this_year = this_time.date().year();
675 if (last_time.is_not_a_date_time())
677 m_zone_vector.push_back(zone_no_dst(this_year - 1, last_info));
678 m_zone_vector.push_back(zone_no_dst(this_year, this_info));
681 else if (last_info->info.isdst == this_info->info.isdst)
683 m_zone_vector.push_back(zone_no_dst(this_year, this_info));
689 else if (this_time - last_time > one_year)
691 auto year = last_time.date().year();
692 if (m_zone_vector.back().first == year)
694 m_zone_vector.push_back(zone_no_dst(year, last_info));
700 else if (!this_info->info.isdst)
702 DSTRule::DSTRule new_rule(last_info, this_info,
703 last_time, this_time);
704 if (new_rule != last_rule)
706 last_rule = new_rule;
707 auto year = last_time.date().year();
708 m_zone_vector.push_back(zone_from_rule(year, new_rule));
712 catch(
const boost::gregorian::bad_year& err)
715 }
catch (std::out_of_range &)
719 last_time = this_time;
720 last_info = this_info;
725 if (last_time.is_not_a_date_time())
726 m_zone_vector.push_back(zone_no_dst(max_year, last_info));
727 else if (last_time.date().year() < parser.last_year)
728 m_zone_vector.push_back(zone_no_dst(last_time.date().year(), last_info));
732 TimeZoneProvider::construct(
const std::string& tzname)
738 catch(
const std::invalid_argument& err)
742 TZ_Ptr zone(
new PTZ(tzname));
743 m_zone_vector.push_back(std::make_pair(max_year, zone));
745 catch(std::exception& err)
753 TimeZoneProvider::TimeZoneProvider(
const std::string& tzname) : m_zone_vector {}
755 if(construct(tzname))
757 DEBUG(
"%s invalid, trying TZ environment variable.\n", tzname.c_str());
758 const char* tz_env = getenv(
"TZ");
759 if(tz_env && construct(tz_env))
761 DEBUG(
"No valid $TZ, resorting to /etc/localtime.\n");
764 parse_file(
"/etc/localtime");
766 catch(
const std::invalid_argument& env)
768 DEBUG(
"/etc/localtime invalid, resorting to GMT.");
769 TZ_Ptr zone(
new PTZ(
"UTC0"));
770 m_zone_vector.push_back(std::make_pair(max_year, zone));
777 TimeZoneProvider::get(
int year)
const noexcept
779 if (m_zone_vector.empty())
780 return TZ_Ptr(
new PTZ(
"UTC0"));
781 auto iter = find_if(m_zone_vector.rbegin(), m_zone_vector.rend(),
782 [=](TZ_Entry e) {
return e.first <= year; });
783 if (iter == m_zone_vector.rend())
784 return m_zone_vector.front().second;
789 TimeZoneProvider::dump() const noexcept
791 for (
const auto& zone : m_zone_vector)
792 std::cout << zone.first <<
": " << zone.second->to_posix_string() <<
"\n";
#define DEBUG(format, args...)
Print a debugging message.
#define PWARN(format, args...)
Log a warning.