GnuCash de0bfde+
Loading...
Searching...
No Matches
gnc-timezone.cpp
1/********************************************************************\
2 * gnc-timezone.cpp - Retrieve timezone information from OS. *
3 * Copyright 2014 John Ralls <jralls@ceridwen.us> *
4 * Based on work done with Arnel Borja for GLib's gtimezone in 2012.*
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License as *
7 * published by the Free Software Foundation; either version 2 of *
8 * the License, or (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License*
16 * along with this program; if not, contact: *
17 * *
18 * Free Software Foundation Voice: +1-617-542-5942 *
19 * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
20 * Boston, MA 02110-1301, USA gnu@gnu.org *
21\********************************************************************/
22
23#include "gnc-timezone.hpp"
24
25#include <string>
26#include <cstdint>
27#include <iostream>
28#include <algorithm>
29#include <boost/date_time/gregorian/gregorian.hpp>
30#if PLATFORM(WINDOWS)
31//We'd prefer to use std::codecvt, but it's not supported by gcc until 5.0.
32#include <boost/locale/encoding_utf.hpp>
33#include <cwchar>
34#endif
35#include "qoflog.h"
36static const QofLogModule log_module = "gnc-timezone";
37
38using namespace gnc::date;
39
40using duration = boost::posix_time::time_duration;
41using time_zone = boost::local_time::custom_time_zone;
42using dst_offsets = boost::local_time::dst_adjustment_offsets;
43using calc_rule_ptr = boost::local_time::dst_calc_rule_ptr;
44using PTZ = boost::local_time::posix_time_zone;
45
46const unsigned int TimeZoneProvider::min_year = 1400;
47const unsigned int TimeZoneProvider::max_year = 9999;
48
49template<typename T>
50T*
51endian_swap(T* t)
52{
53#ifndef WORDS_BIGENDIAN
54 auto memp = reinterpret_cast<unsigned char*>(t);
55 std::reverse(memp, memp + sizeof(T));
56#endif
57 return t;
58}
59
60#if PLATFORM(WINDOWS)
61/* libstdc++ to_string is broken on MinGW with no real interest in fixing it.
62 * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52015
63 */
64#if ! COMPILER(MINGW)
65using std::to_string;
66#else
67template<typename T> inline std::string to_string(T num);
68
69template<>
70inline std::string
71to_string<unsigned int>(unsigned int num)
72{
73 constexpr unsigned int numchars = sizeof num * 3 + 1;
74 char buf [numchars] {};
75 snprintf (buf, numchars, "%u", num);
76 return std::string(buf);
77}
78
79template<>
80inline std::string
81to_string<int>(int num)
82{
83 constexpr unsigned int numchars = sizeof num * 3 + 1;
84 char buf [numchars];
85 snprintf (buf, numchars, "%d", num);
86 return std::string(buf);
87}
88#endif
89
90/* Read a REG_SZ registry value and return it as UTF-8 using
91 * wide-character registry functions and doing the UTF8 recoding
92 * ourselves to avoid code page flakiness in Microsoft's libraries.
93 */
94static bool
95windows_reg_string (HKEY key, const wchar_t* subkey,
96 const wchar_t* value_name, std::string& value)
97{
98 DWORD size {0};
99 if (RegGetValueW (key, subkey, value_name, RRF_RT_REG_SZ, nullptr,
100 nullptr, &size) != ERROR_SUCCESS)
101 return false;
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)
106 return false;
107 buf.resize (wcslen (buf.c_str ()));
108 value = boost::locale::conv::utf_to_utf<char> (buf);
109 return true;
110}
111
112static std::string
113windows_default_tzname (void)
114{
115 std::string key_name;
116 windows_reg_string (HKEY_LOCAL_MACHINE,
117 L"SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation",
118 L"TimeZoneKeyName", key_name);
119 return key_name;
120}
121
122typedef struct
123{
124 LONG Bias;
125 LONG StandardBias;
126 LONG DaylightBias;
127 SYSTEMTIME StandardDate;
128 SYSTEMTIME DaylightDate;
129} RegTZI;
130
131static time_zone_names
132windows_tz_names (HKEY key)
133{
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.");
137
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.");
141
142 return time_zone_names (std_name, std_name, dlt_name, dlt_name);
143}
144
145#define make_week_num(x) static_cast<boost::date_time::nth_kday_of_month<boost::gregorian::date>::week_num>(x)
146
147static TZ_Ptr
148zone_from_regtzi (const RegTZI& regtzi, time_zone_names names)
149{
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;
152 /* Note that Windows runs its biases backwards from POSIX and
153 * boost::date_time: It's the value added to the local time to get
154 * GMT rather than the value added to GMT to get local time; for
155 * the same reason the DaylightBias is negative as one generally
156 * adds an hour less to the local time to get GMT. Biases are in
157 * minutes.
158 */
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);
168 calc_rule_ptr dates;
169 if (regtzi.StandardDate.wMonth != 0)
170 {
171 try
172 {
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));
178 }
179 catch (boost::gregorian::bad_month& err)
180 {
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);
185 }
186 }
187 return TZ_Ptr(new time_zone(names, std_off, offsets, dates));
188}
189
190void
191TimeZoneProvider::load_windows_dynamic_tz (HKEY key, time_zone_names names)
192{
193 DWORD first, last;
194
195 try
196 {
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.");
201
202 size = sizeof last;
203 if (RegQueryValueExW (key, L"LastEntry", NULL, NULL,
204 (LPBYTE) &last, &size) != ERROR_SUCCESS)
205 throw std::invalid_argument ("No last entry.");
206
207 TZ_Ptr tz {};
208 for (unsigned int year = first; year <= last; year++)
209 {
210 auto s = to_string(year);
211 std::wstring ystr (s.begin(), s.end());
212 RegTZI regtzi {};
213 size = sizeof regtzi;
214 auto err_val = RegQueryValueExW (key, ystr.c_str(), NULL, NULL,
215 (LPBYTE) &regtzi, &size);
216 if (err_val != ERROR_SUCCESS)
217 {
218 break;
219 }
220 tz = zone_from_regtzi (regtzi, names);
221 if (year == first)
222 m_zone_vector.push_back (std::make_pair(0, tz));
223 m_zone_vector.push_back (std::make_pair(year, tz));
224 }
225 m_zone_vector.push_back (std::make_pair(max_year, tz));
226 }
227 catch (const std::invalid_argument& err)
228 {
229 RegCloseKey (key);
230 throw;
231 }
232 catch (const std::bad_alloc& err)
233 {
234 RegCloseKey (key);
235 throw;
236 }
237 RegCloseKey (key);
238}
239
240void
241TimeZoneProvider::load_windows_classic_tz (HKEY key, time_zone_names names)
242{
243 RegTZI regtzi {};
244 unsigned long size = sizeof regtzi;
245 try
246 {
247 if (RegQueryValueExW (key, L"TZI", NULL, NULL,
248 (LPBYTE) &regtzi, &size) == ERROR_SUCCESS)
249 {
250 m_zone_vector.push_back(
251 std::make_pair(max_year, zone_from_regtzi (regtzi, names)));
252 }
253 }
254 catch (const std::bad_alloc& err)
255 {
256 RegCloseKey (key);
257 throw;
258 }
259 RegCloseKey (key);
260}
261
262void
263TimeZoneProvider::load_windows_default_tz()
264{
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)));
276}
277
278TimeZoneProvider::TimeZoneProvider (const std::string& identifier) :
279 m_zone_vector ()
280{
281 HKEY key;
282 const std::string reg_key =
283 "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\";
284
285 auto key_name = (identifier.empty() ? windows_default_tzname () :
286 identifier);
287
288 if (key_name.empty())
289 {
290 load_windows_default_tz();
291 return;
292 }
293 std::string subkey = reg_key + key_name;
294// Time Zone names are always ASCII so narrow-char access is safe.
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);
298
299 time_zone_names names {windows_tz_names (key)};
300 RegCloseKey (key);
301
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);
309 else
310 throw std::invalid_argument ("No data for TZ " + key_name);
311}
312#elif PLATFORM(POSIX)
313using std::to_string;
314#include <istream>
315#include <cstdlib>
316
317using boost::posix_time::ptime;
318//To enable using Transition with different meanings for IANA files
319//and for DSTRules.
320namespace IANAParser
321{
322 struct TZHead
323 {
324 char magic[4];
325 char version;
326 uint8_t reserved[15];
327 uint8_t ttisgmtcnt[4];
328 uint8_t ttisstdcnt[4];
329 uint8_t leapcnt[4];
330 uint8_t timecnt[4];
331 uint8_t typecnt[4];
332 uint8_t charcnt[4];
333 };
334
335 struct TTInfo
336 {
337 int32_t gmtoff;
338 uint8_t isdst;
339 uint8_t abbrind;
340 };
341
342 struct TZInfo
343 {
344 TTInfo info;
345 std::string name;
346 bool isstd;
347 bool isgmt;
348 };
349
350 struct Transition
351 {
352 int64_t timestamp;
353 uint8_t index;
354 };
355
356 static std::unique_ptr<char[]>
357 find_tz_file(const std::string& name)
358 {
359 std::ifstream ifs;
360 auto tzname = name;
361 if (tzname.empty())
362 if (auto tzenv = std::getenv("TZ"))
363 tzname = std::string(tzenv);
364 //std::cout << "Testing tzname " << tzname << "\n";
365 if (!tzname.empty())
366 {
367//POSIX specifies that that identifier should begin with ':', but we
368//should be liberal. If it's there, it's not part of the filename.
369 if (tzname[0] == ':')
370 tzname.erase(tzname.begin());
371 if (tzname[0] == '/') //Absolute filename
372 {
373 ifs.open(tzname, std::ios::in|std::ios::binary|std::ios::ate);
374 }
375 else
376 {
377 const char* tzdir_c = std::getenv("TZDIR");
378 std::string tzdir = tzdir_c ? tzdir_c : "/usr/share/zoneinfo";
379//Note that we're not checking the filename.
380 ifs.open(std::move(tzdir + "/" + tzname),
381 std::ios::in|std::ios::binary|std::ios::ate);
382 }
383 }
384
385 if (! ifs.is_open())
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);
391 ifs.close();
392 return fileblock;
393 }
394
395 using TZInfoVec = std::vector<TZInfo>;
396 using TZInfoIter = TZInfoVec::iterator;
397
398 struct IANAParser
399 {
400 IANAParser(const std::string& name) : IANAParser(find_tz_file(name)) {}
401 IANAParser(std::unique_ptr<char[]>);
402 std::vector<Transition>transitions;
403 TZInfoVec tzinfo;
404 int last_year;
405 };
406
407 IANAParser::IANAParser(std::unique_ptr<char[]>fileblock)
408 {
409 unsigned int fb_index = 0;
410 TZHead tzh = *reinterpret_cast<TZHead*>(&fileblock[fb_index]);
411 static constexpr int ttinfo_size = 6; //struct TTInfo gets padded
412 last_year = 2037; //Constrained by 32-bit time_t.
413 int transition_size = 4; // length of a transition time in the file
414
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'))
422 {
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);
430
431 //This might change at some point in the probably very
432 //distant future.
433 tzh = *reinterpret_cast<TZHead*>(&fileblock[fb_index]);
434 last_year = 2499;
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)));
438 transition_size = 8;
439 }
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)
444 {
445 fb_index = start_index + index * transition_size;
446 auto info_index = info_index_zero + index;
447 if (transition_size == 4)
448 {
449 int32_t transition_time;
450 // Ensure correct alignment for ARM.
451 memcpy(&transition_time,
452 endian_swap(reinterpret_cast<int32_t*>(&fileblock[fb_index])),
453 sizeof(int32_t));
454 auto info = static_cast<uint8_t>(fileblock[info_index]);
455 transitions.push_back({transition_time, info});
456 }
457 else
458 {
459 int64_t transition_time;
460 // Ensure correct alignment for ARM.
461 memcpy(&transition_time, &fileblock[fb_index],
462 sizeof(int64_t));
463 transition_time = *(endian_swap(&transition_time));
464 auto info = static_cast<uint8_t>(fileblock[info_index]);
465 transitions.push_back({transition_time, info});
466 }
467 }
468
469 //Add in the tzinfo indexes consumed in the previous loop
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)
475 {
476 fb_index = start_index + index * ttinfo_size;
477 /* Use memcpy instead of static_cast to avoid memory alignment issues with chars */
478 TTInfo info{};
479 memcpy(&info, &fileblock[fb_index], ttinfo_size);
480 endian_swap(&info.gmtoff);
481 tzinfo.push_back(
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)});
485 }
486
487 }
488}
489
490namespace DSTRule
491{
492 using gregorian_date = boost::gregorian::date;
493 using IANAParser::TZInfoIter;
494 using ndate = boost::gregorian::nth_day_of_the_week_in_month;
495 using week_num =
496 boost::date_time::nth_kday_of_month<boost::gregorian::date>::week_num;
497
498 struct Transition
499 {
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;
503 ndate get();
504 boost::gregorian::greg_month month;
505 boost::gregorian::greg_weekday dow;
506 week_num week;
507 };
508
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))
512 {}
513
514 bool
515 Transition::operator==(const Transition& rhs) const noexcept
516 {
517 return (month == rhs.month && dow == rhs.dow && week == rhs.week);
518 }
519
520 ndate
521 Transition::get()
522 {
523 return ndate(week, dow, month);
524 }
525
526 struct DSTRule
527 {
528 DSTRule();
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;
533 Transition to_std;
534 Transition to_dst;
535 duration to_std_time;
536 duration to_dst_time;
537 TZInfoIter std_info;
538 TZInfoIter dst_info;
539 };
540
541 DSTRule::DSTRule() : to_std(), to_dst(), to_std_time {}, to_dst_time {},
542 std_info (), dst_info () {};
543
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)
551 {
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)
555 {
556 std::swap(to_std, to_dst);
557 std::swap(to_std_time, to_dst_time);
558 std::swap(std_info, dst_info);
559 }
560
561 /* Documentation notwithstanding, the date-time rules are
562 * looking for local time (wall clock to use the RFC 8538
563 * definition) values.
564 *
565 * The TZ Info contains two fields, isstd and isgmt (renamed
566 * to isut in newer versions of tzinfo). In theory if both are
567 * 0 the transition times represent wall-clock times,
568 * i.e. time stamps in the respective time zone's local time
569 * at the moment of the transition. If isstd is 1 then the
570 * representation is always in standard time instead of
571 * daylight time; this is significant for dst->std
572 * transitions. If isgmt/isut is one then isstd must also be
573 * set and the transition time is in UTC.
574 *
575 * In practice it seems that the timestamps are always in UTC
576 * so the isgmt/isut flag isn't meaningful. The times always
577 * need to have the utc offset added to them to make the
578 * transition occur at the right time; the isstd flag
579 * determines whether that should be the standard offset or
580 * the daylight offset for the daylight->standard transition.
581 *
582 * The rules are also built from the transition's wall-clock
583 * date, not its UTC date: in zones east of UTC a transition
584 * early on a Sunday morning local time is still Saturday in
585 * UTC, and a rule built from the UTC date picks the wrong
586 * Sunday in other years. date1 and date2 are the UTC times at
587 * which info1 and info2 take effect, so each is converted
588 * with the other info's offset, the one in force until then.
589 */
590
591 if (std_info->isstd) //if isstd always use standard time
592 to_std_time += boost::posix_time::seconds(std_info->info.gmtoff -
593 dst_info->info.gmtoff);
594 }
595
596 bool
597 DSTRule::operator==(const DSTRule& rhs) const noexcept
598 {
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);
605 }
606
607 bool
608 DSTRule::operator!=(const DSTRule& rhs) const noexcept
609 {
610 return ! operator==(rhs);
611 }
612}
613
614static TZ_Entry
615zone_no_dst(int year, IANAParser::TZInfoIter std_info)
616{
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);
623}
624
625static TZ_Entry
626zone_from_rule(int year, DSTRule::DSTRule rule)
627{
628 using boost::gregorian::partial_date;
629 using boost::local_time::partial_date_dst_rule;
630 using nth_day_rule =
631 boost::local_time::nth_day_of_the_week_in_month_dst_rule;
632
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);
642}
643
644void
645TimeZoneProvider::parse_file(const std::string& tzname)
646{
647 IANAParser::IANAParser parser(tzname);
648 using boost::posix_time::hours;
649 const auto one_year = hours(366 * 24); //Might be a leap year.
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)
660 {
661 auto this_info = parser.tzinfo.begin() + txi->index;
662//Can't use boost::posix_date::from_time_t() constructor because it
663//silently casts the time_t to an int32_t.
664 auto this_time = ptime(date(1970, 1, 1),
665 time_duration(txi->timestamp / 3600, 0,
666 txi->timestamp % 3600));
667 /* Note: The "get" function retrieves the last zone with a
668 * year *earlier* than the requested year: Zone periods run
669 * from the saved year to the beginning year of the next zone.
670 */
671 try
672 {
673 auto this_year = this_time.date().year();
674 //Initial case
675 if (last_time.is_not_a_date_time())
676 {
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));
679 }
680 // No change in is_dst means a permanent zone change.
681 else if (last_info->info.isdst == this_info->info.isdst)
682 {
683 m_zone_vector.push_back(zone_no_dst(this_year, this_info));
684 }
685 /* If there have been no transitions in at least a year
686 * then we need to create a no-DST rule with last_info to
687 * reflect the frozen timezone.
688 */
689 else if (this_time - last_time > one_year)
690 {
691 auto year = last_time.date().year();
692 if (m_zone_vector.back().first == year)
693 year = year + 1; // no operator ++ or +=, sigh.
694 m_zone_vector.push_back(zone_no_dst(year, last_info));
695 }
696 /* It's been less than a year, so it's probably a DST
697 * cycle. This consumes two transitions so we want only
698 * the return-to-standard-time one to make a DST rule.
699 */
700 else if (!this_info->info.isdst)
701 {
702 DSTRule::DSTRule new_rule(last_info, this_info,
703 last_time, this_time);
704 if (new_rule != last_rule)
705 {
706 last_rule = new_rule;
707 auto year = last_time.date().year();
708 m_zone_vector.push_back(zone_from_rule(year, new_rule));
709 }
710 }
711 }
712 catch(const boost::gregorian::bad_year& err)
713 {
714 continue;
715 } catch (std::out_of_range &)
716 {
717 continue;
718 }
719 last_time = this_time;
720 last_info = this_info;
721 }
722/* if the transitions end before the end of the zoneinfo coverage
723 * period then the zone rescinded DST and we need a final no-dstzone.
724 */
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));
729}
730
731bool
732TimeZoneProvider::construct(const std::string& tzname)
733{
734 try
735 {
736 parse_file(tzname);
737 }
738 catch(const std::invalid_argument& err)
739 {
740 try
741 {
742 TZ_Ptr zone(new PTZ(tzname));
743 m_zone_vector.push_back(std::make_pair(max_year, zone));
744 }
745 catch(std::exception& err)
746 {
747 return false;
748 }
749 }
750 return true;
751}
752
753TimeZoneProvider::TimeZoneProvider(const std::string& tzname) : m_zone_vector {}
754{
755 if(construct(tzname))
756 return;
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))
760 return;
761 DEBUG("No valid $TZ, resorting to /etc/localtime.\n");
762 try
763 {
764 parse_file("/etc/localtime");
765 }
766 catch(const std::invalid_argument& env)
767 {
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));
771 }
772}
773#endif
774
775
776TZ_Ptr
777TimeZoneProvider::get(int year) const noexcept
778{
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;
785 return iter->second;
786}
787
788void
789TimeZoneProvider::dump() const noexcept
790{
791 for (const auto& zone : m_zone_vector)
792 std::cout << zone.first << ": " << zone.second->to_posix_string() << "\n";
793}
#define DEBUG(format, args...)
Print a debugging message.
Definition qoflog.h:264
#define PWARN(format, args...)
Log a warning.
Definition qoflog.h:250