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
|
/*
This file is part of the KDE libraries
Copyright (c) 2005 S.R.Haque <[email protected]>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <ktimezones.h>
#include <kdebug.h>
#include <kmdcodec.h>
#include <kprocess.h>
#include <kstringhandler.h>
#include <tdetempfile.h>
#include <tqdatetime.h>
#include <tqfile.h>
#include <tqregexp.h>
#include <tqstringlist.h>
#include <tqtextstream.h>
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <ctime>
#define UTC_ZONE "UTC"
/**
* Find out if the given standard (e.g. "GMT") and daylight savings time
* (e.g. "BST", but which may be empty) abbreviated timezone names match
* this timezone.
*
* Thus, this class can be used as a heuristic when trying to lookup the
* real timezone from the abbreviated zone names.
*/
class AbbreviationsMatch :
public KTimezoneDetails
{
public:
AbbreviationsMatch(const TQString &stdZone, const TQString &dstZone = "")
{
m_stdZone = stdZone;
m_dstZone = dstZone;
}
void parseStarted()
{
m_foundStd = false;
m_foundDst = m_dstZone.isEmpty();
}
bool test()
{
return (m_foundStd && m_foundDst);
}
private:
bool m_foundStd;
bool m_foundDst;
TQString m_stdZone;
TQString m_dstZone;
virtual void gotAbbreviation(int /*index*/, const TQString &value)
{
if (m_stdZone == value)
{
m_foundStd = true;
}
if (m_dstZone == value)
{
m_foundDst = true;
}
}
};
/**
* Internal dummy source for UTC timezone.
*/
class DummySource :
public KTimezoneSource
{
public:
DummySource() :
KTimezoneSource("")
{
}
virtual bool parse(const TQString &/*zone*/, KTimezoneDetails &/*dataReceiver*/) const
{
return true;
}
};
/**
* Find offset at a particular point in time.
*/
class OffsetFind :
public KTimezoneDetails
{
public:
OffsetFind(unsigned dateTime)
{
m_dateTime = dateTime;
}
void parseStarted()
{
m_transitionTimeIndex = 0;
m_localTimeIndex = -1;
m_abbrIndex = -1;
m_offset = 0;
m_isDst = false;
m_abbr = UTC_ZONE;
}
int offset()
{
return m_offset;
}
bool isDst()
{
return m_isDst;
}
TQString abbreviation()
{
return m_abbr;
}
private:
unsigned m_dateTime;
int m_transitionTimeIndex;
int m_localTimeIndex;
int m_abbrIndex;
int m_offset;
bool m_isDst;
TQString m_abbr;
virtual void gotTransitionTime(int index, unsigned transitionTime)
{
if (transitionTime <= m_dateTime)
{
// Remember the index of the transition time that relates to dateTime.
m_transitionTimeIndex = index;
}
}
virtual void gotLocalTimeIndex(int index, unsigned localTimeIndex)
{
if (index == m_transitionTimeIndex)
{
// Remember the index of the local time that relates to dateTime.
m_localTimeIndex = localTimeIndex;
}
}
virtual void gotLocalTime(int index, int gmtOff, bool isDst, unsigned abbrInd)
{
if (index == m_localTimeIndex)
{
// Remember the results that relate to gmtOffset.
m_offset = gmtOff;
m_isDst = isDst;
m_abbrIndex = abbrInd;
}
}
virtual void gotAbbreviation(int index, const TQString &value)
{
if (index == m_abbrIndex)
{
m_abbr = value;
}
}
};
const float KTimezone::UNKNOWN = 1000.0;
bool KTimezone::isValidLatitude(float latitude)
{
return (latitude >= -90.0) && (latitude <= 90.0);
}
bool KTimezone::isValidLongitude(float longitude)
{
return (longitude >= -180.0) && (longitude <= 180.0);
}
KTimezone::KTimezone(
TDESharedPtr<KTimezoneSource> db, const TQString& name,
const TQString &countryCode, float latitude, float longitude,
const TQString &comment) :
m_db(db),
m_name(name),
m_countryCode(countryCode),
m_latitude(latitude),
m_longitude(longitude),
m_comment(comment),
d(0)
{
// Detect duff values.
if (m_latitude * m_latitude > 90 * 90)
m_latitude = UNKNOWN;
if (m_longitude * m_longitude > 180 * 180)
m_longitude = UNKNOWN;
}
KTimezone::~KTimezone()
{
// FIXME when needed:
// delete d;
}
TQString KTimezone::comment() const
{
return m_comment;
}
TQDateTime KTimezone::convert(const KTimezone *newZone, const TQDateTime &dateTime) const
{
char *originalZone = ::getenv("TZ");
// Convert the given localtime to UTC.
::setenv("TZ", m_name.utf8(), 1);
tzset();
unsigned utc = dateTime.toTime_t();
// Set the timezone and convert UTC to localtime.
::setenv("TZ", newZone->name().utf8(), 1);
tzset();
TQDateTime remoteTime;
remoteTime.setTime_t(utc, TQt::LocalTime);
// Now restore things
if (!originalZone)
{
::unsetenv("TZ");
}
else
{
::setenv("TZ", originalZone, 1);
}
tzset();
return remoteTime;
}
TQString KTimezone::countryCode() const
{
return m_countryCode;
}
float KTimezone::latitude() const
{
return m_latitude;
}
float KTimezone::longitude() const
{
return m_longitude;
}
TQString KTimezone::name() const
{
return m_name;
}
int KTimezone::offset(TQt::TimeSpec basisSpec) const
{
char *originalZone = ::getenv("TZ");
// Get the time in the current timezone.
TQDateTime basisTime = TQDateTime::currentDateTime(basisSpec);
// Set the timezone and find out what time it is there compared to the basis.
::setenv("TZ", m_name.utf8(), 1);
tzset();
TQDateTime remoteTime = TQDateTime::currentDateTime(TQt::LocalTime);
int offset = remoteTime.secsTo(basisTime);
// Now restore things
if (!originalZone)
{
::unsetenv("TZ");
}
else
{
::setenv("TZ", originalZone, 1);
}
tzset();
return offset;
}
int KTimezone::offset(const TQDateTime &dateTime) const
{
OffsetFind finder(dateTime.toTime_t());
int result = 0;
if (parse(finder))
{
result = finder.offset();
}
return result;
}
bool KTimezone::parse(KTimezoneDetails &dataReceiver) const
{
dataReceiver.parseStarted();
bool result = m_db->parse(m_name, dataReceiver);
dataReceiver.parseEnded();
return result;
}
KTimezones::KTimezones() :
m_zoneinfoDir(),
m_zones(0),
d(0)
{
// Create the database (and resolve m_zoneinfoDir!).
allZones();
m_UTC = new KTimezone(new DummySource(), UTC_ZONE);
add(m_UTC);
}
KTimezones::~KTimezones()
{
// FIXME when needed:
// delete d;
// Autodelete behavior.
if (m_zones)
{
for (ZoneMap::ConstIterator it = m_zones->begin(); it != m_zones->end(); ++it)
{
delete it.data();
}
}
delete m_zones;
}
void KTimezones::add(KTimezone *zone)
{
m_zones->insert(zone->name(), zone);
}
const KTimezones::ZoneMap KTimezones::allZones()
{
// Have we already done all the hard work? If not, create the cache.
if (m_zones)
return *m_zones;
m_zones = new ZoneMap();
// Go read the database.
//
// On Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
// is the place to look. The TZI binary value is the TIME_ZONE_INFORMATION structure.
//
// For Unix its all easy except knowing where to look. Try the LSB location first.
TQFile f;
m_zoneinfoDir = "/usr/share/zoneinfo";
f.setName(m_zoneinfoDir + "/zone.tab");
if (!f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
m_zoneinfoDir = "/usr/lib/zoneinfo";
f.setName(m_zoneinfoDir + "/zone.tab");
if (!f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
m_zoneinfoDir = ::getenv("TZDIR");
f.setName(m_zoneinfoDir + "/zone.tab");
if (m_zoneinfoDir.isEmpty() || !f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
// Solaris support. Synthesise something that looks like a zone.tab.
//
// /bin/grep -h ^Zone /usr/share/lib/zoneinfo/src/* | /bin/awk '{print "??\t+9999+99999\t" $2}'
//
// where the country code is set to "??" and the lattitude/longitude
// values are dummies.
m_zoneinfoDir = "/usr/share/lib/zoneinfo";
KTempFile temp;
KShellProcess reader;
reader << "/bin/grep" << "-h" << "^Zone" << m_zoneinfoDir << "/src/*" << temp.name() << "|" <<
"/bin/awk" << "'{print \"??\\t+9999+99999\\t\" $2}'";
// Note the use of blocking here...it is a trivial amount of data!
temp.close();
reader.start(TDEProcess::Block);
f.setName(temp.name());
if (!temp.status() || !f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
return *m_zones;
}
}
}
}
// Parse the zone.tab.
TQTextStream str(&f);
TQRegExp lineSeparator("[ \t]");
TQRegExp ordinateSeparator("[+-]");
TDESharedPtr<KTimezoneSource> db(new KTimezoneSource(m_zoneinfoDir));
while (!str.atEnd())
{
TQString line = str.readLine();
if (line.isEmpty() || '#' == line[0])
continue;
TQStringList tokens = KStringHandler::perlSplit(lineSeparator, line, 4);
if (tokens.count() < 3)
{
kdError() << "invalid record: " << line << endl;
continue;
}
// Got three tokens. Now check for two ordinates plus first one is "".
TQStringList ordinates = KStringHandler::perlSplit(ordinateSeparator, tokens[1], 2);
if (ordinates.count() < 2)
{
kdError() << "invalid coordinates: " << tokens[1] << endl;
continue;
}
float latitude = convertCoordinate(ordinates[1]);
float longitude = convertCoordinate(ordinates[2]);
// Add entry to list.
if (tokens[0] == "??")
tokens[0] = "";
KTimezone *timezone = new KTimezone(db, tokens[2], tokens[0], latitude, longitude, tokens[3]);
add(timezone);
}
f.close();
return *m_zones;
}
/**
* Convert sHHMM or sHHMMSS to a floating point number of degrees.
*/
float KTimezones::convertCoordinate(const TQString &coordinate)
{
int value = coordinate.toInt();
int degrees = 0;
int minutes = 0;
int seconds = 0;
if (coordinate.length() > 11)
{
degrees = value / 10000;
value -= degrees * 10000;
minutes = value / 100;
value -= minutes * 100;
seconds = value;
}
else
{
degrees = value / 100;
value -= degrees * 100;
minutes = value;
}
value = degrees * 3600 + minutes * 60 + seconds;
return value / 3600.0;
}
const KTimezone *KTimezones::local()
{
const KTimezone *local = 0;
// First try the simplest solution of checking for well-formed TZ setting.
char *envZone = ::getenv("TZ");
if (envZone)
{
if (envZone[0] == '\0')
{
return m_UTC;
}
else
if (envZone[0] == ':')
{
envZone++;
}
local = zone(envZone);
}
if (local)
return local;
// Try to match /etc/localtime against the list of zoneinfo files.
TQFile f;
f.setName("/etc/localtime");
if (f.open(IO_ReadOnly))
{
// Compute the MD5 sum of /etc/localtime.
KMD5 context("");
context.reset();
context.update(f);
TQIODevice::Offset referenceSize = f.size();
TQString referenceMd5Sum = context.hexDigest();
f.close();
if (!m_zoneinfoDir.isEmpty())
{
// Compare it with each zoneinfo file.
for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
{
KTimezone *zone = it.data();
f.setName(m_zoneinfoDir + '/' + zone->name());
if (f.open(IO_ReadOnly))
{
TQIODevice::Offset candidateSize = f.size();
TQString candidateMd5Sum;
if (candidateSize == referenceSize)
{
// Only do the heavy lifting for file sizes which match.
context.reset();
context.update(f);
candidateMd5Sum = context.hexDigest();
}
f.close();
if (candidateMd5Sum == referenceMd5Sum)
{
// kdError() << "local=" << zone->name() << endl;
local = zone;
break;
}
}
}
}
}
if (local)
return local;
// BSD support.
TQString fileZone;
f.setName("/etc/timezone");
if (!f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
// Solaris support using /etc/default/init.
f.setName("/etc/default/init");
if (!f.open(IO_ReadOnly))
{
kdDebug() << "Can't open " << f.name() << endl;
}
else
{
TQTextStream ts(&f);
ts.setEncoding(TQTextStream::Latin1);
// Read the last line starting "TZ=".
while (!ts.atEnd())
{
fileZone = ts.readLine();
if (fileZone.startsWith("TZ="))
{
fileZone = fileZone.mid(3);
// kdError() << "local=" << fileZone << endl;
local = zone(fileZone);
}
}
f.close();
}
}
else
{
TQTextStream ts(&f);
ts.setEncoding(TQTextStream::Latin1);
// Read the first line.
if (!ts.atEnd())
{
fileZone = ts.readLine();
// kdError() << "local=" << fileZone << endl;
local = zone(fileZone);
}
f.close();
}
if (local)
return local;
// None of the deterministic stuff above has worked: try a heuristic. We
// try to find a pair of matching timezone abbreviations...that way, we'll
// likely return a value in the user's own country.
if (!m_zoneinfoDir.isEmpty())
{
tzset();
AbbreviationsMatch matcher(tzname[0], tzname[1]);
int bestOffset = INT_MAX;
for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
{
KTimezone *zone = it.data();
int candidateOffset = QABS(zone->offset(TQt::LocalTime));
if (zone->parse(matcher) && matcher.test() && (candidateOffset < bestOffset))
{
// kdError() << "local=" << zone->name() << endl;
bestOffset = candidateOffset;
local = zone;
}
}
}
if (local)
return local;
return m_UTC;
}
const KTimezone *KTimezones::zone(const TQString &name)
{
if (name.isEmpty())
return m_UTC;
ZoneMap::ConstIterator it = m_zones->find(name);
if (it != m_zones->end())
return it.data();
// Error.
return 0;
}
KTimezoneDetails::KTimezoneDetails()
{
}
KTimezoneDetails::~KTimezoneDetails()
{
}
void KTimezoneDetails::gotAbbreviation(int /*index*/, const TQString &)
{}
void KTimezoneDetails::gotHeader(
unsigned, unsigned, unsigned,
unsigned, unsigned, unsigned)
{}
void KTimezoneDetails::gotLeapAdjustment(int /*index*/, unsigned, unsigned)
{}
void KTimezoneDetails::gotLocalTime(int /*index*/, int, bool, unsigned)
{}
void KTimezoneDetails::gotLocalTimeIndex(int /*index*/, unsigned)
{}
void KTimezoneDetails::gotIsStandard(int /*index*/, bool)
{}
void KTimezoneDetails::gotTransitionTime(int /*index*/, unsigned)
{}
void KTimezoneDetails::gotIsUTC(int /*index*/, bool)
{}
void KTimezoneDetails::parseEnded()
{}
void KTimezoneDetails::parseStarted()
{}
KTimezoneSource::KTimezoneSource(const TQString &db) :
m_db(db)
{
}
KTimezoneSource::~KTimezoneSource()
{
}
TQString KTimezoneSource::db()
{
return m_db;
}
bool KTimezoneSource::parse(const TQString &zone, KTimezoneDetails &dataReceiver) const
{
TQFile f(m_db + '/' + zone);
if (!f.open(IO_ReadOnly))
{
kdError() << "Cannot open " << f.name() << endl;
return false;
}
// Structures that represent the zoneinfo file.
TQ_UINT8 T, z, i_, f_;
struct
{
TQ_UINT32 ttisgmtcnt;
TQ_UINT32 ttisstdcnt;
TQ_UINT32 leapcnt;
TQ_UINT32 timecnt;
TQ_UINT32 typecnt;
TQ_UINT32 charcnt;
} tzh;
TQ_UINT32 transitionTime;
TQ_UINT8 localTimeIndex;
struct
{
TQ_INT32 gmtoff;
TQ_INT8 isdst;
TQ_UINT8 abbrind;
} tt;
TQ_UINT32 leapTime;
TQ_UINT32 leapSeconds;
TQ_UINT8 isStandard;
TQ_UINT8 isUTC;
TQDataStream str(&f);
str >> T >> z >> i_ >> f_;
// kdError() << "signature: " << TQChar(T) << TQChar(z) << TQChar(i_) << TQChar(f_) << endl;
unsigned i;
for (i = 0; i < 4; i++)
str >> tzh.ttisgmtcnt;
str >> tzh.ttisgmtcnt >> tzh.ttisstdcnt >> tzh.leapcnt >> tzh.timecnt >> tzh.typecnt >> tzh.charcnt;
// kdError() << "header: " << tzh.ttisgmtcnt << ", " << tzh.ttisstdcnt << ", " << tzh.leapcnt << ", " <<
// tzh.timecnt << ", " << tzh.typecnt << ", " << tzh.charcnt << endl;
dataReceiver.gotHeader(tzh.ttisgmtcnt, tzh.ttisstdcnt, tzh.leapcnt, tzh.timecnt, tzh.typecnt, tzh.charcnt);
for (i = 0; i < tzh.timecnt; i++)
{
str >> transitionTime;
dataReceiver.gotTransitionTime(i, transitionTime);
}
for (i = 0; i < tzh.timecnt; i++)
{
// NB: these appear to be 1-based, not zero-based!
str >> localTimeIndex;
dataReceiver.gotLocalTimeIndex(i, localTimeIndex);
}
for (i = 0; i < tzh.typecnt; i++)
{
str >> tt.gmtoff >> tt.isdst >> tt.abbrind;
// kdError() << "local type: " << tt.gmtoff << ", " << tt.isdst << ", " << tt.abbrind << endl;
dataReceiver.gotLocalTime(i, tt.gmtoff, (tt.isdst != 0), tt.abbrind);
}
// Make sure we don't run foul of maliciously coded timezone abbreviations.
if (tzh.charcnt > 64)
{
kdError() << "excessive length for timezone abbreviations: " << tzh.charcnt << endl;
return false;
}
TQByteArray array(tzh.charcnt);
str.readRawBytes(array.data(), array.size());
char *abbrs = array.data();
if (abbrs[tzh.charcnt - 1] != 0)
{
// These abbrevations are corrupt!
kdError() << "timezone abbreviations not terminated: " << abbrs[tzh.charcnt - 1] << endl;
return false;
}
char *abbr = abbrs;
while (abbr < abbrs + tzh.charcnt)
{
// kdError() << "abbr: " << abbr << endl;
dataReceiver.gotAbbreviation((abbr - abbrs), abbr);
abbr += strlen(abbr) + 1;
}
for (i = 0; i < tzh.leapcnt; i++)
{
str >> leapTime >> leapSeconds;
// kdError() << "leap entry: " << leapTime << ", " << leapSeconds << endl;
dataReceiver.gotLeapAdjustment(i, leapTime, leapSeconds);
}
for (i = 0; i < tzh.ttisstdcnt; i++)
{
str >> isStandard;
// kdError() << "standard: " << isStandard << endl;
dataReceiver.gotIsStandard(i, (isStandard != 0));
}
for (i = 0; i < tzh.ttisgmtcnt; i++)
{
str >> isUTC;
// kdError() << "UTC: " << isUTC << endl;
dataReceiver.gotIsUTC(i, (isUTC != 0));
}
return true;
}
|