~ubuntu-branches/ubuntu/karmic/kst/karmic

« back to all changes in this revision

Viewing changes to kst/kst/ksttimezones.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Daniel T Chen
  • Date: 2006-06-30 19:11:30 UTC
  • mfrom: (1.2.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20060630191130-acumuar75bz4puty
Tags: 1.2.1-1ubuntu1
Merge from debian unstable.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
   This file is part of the KDE libraries
 
3
   Copyright (c) 2005 S.R.Haque <srhaque@iee.org>.
 
4
 
 
5
   This library is free software; you can redistribute it and/or
 
6
   modify it under the terms of the GNU Library General Public
 
7
   License version 2 as published by the Free Software Foundation.
 
8
 
 
9
   This library is distributed in the hope that it will be useful,
 
10
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
12
   Library General Public License for more details.
 
13
 
 
14
   You should have received a copy of the GNU Library General Public License
 
15
   along with this library; see the file COPYING.LIB.  If not, write to
 
16
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 
17
   Boston, MA 02110-1301, USA.
 
18
*/
 
19
 
 
20
#include <config.h>
 
21
 
 
22
#include "ksttimezones.h"
 
23
#include <kmdcodec.h>
 
24
#include <kprocess.h>
 
25
#include <kstringhandler.h>
 
26
#include <ktempfile.h>
 
27
 
 
28
#include <qdatetime.h>
 
29
#include <qfile.h>
 
30
#include <qregexp.h>
 
31
#include <qstringlist.h>
 
32
#include <qtextstream.h>
 
33
 
 
34
#include <cerrno>
 
35
#include <climits>
 
36
#include <cstdlib>
 
37
#include <cstring>
 
38
#include <ctime>
 
39
 
 
40
#define UTC_ZONE "UTC"
 
41
 
 
42
#ifndef HAVE_UNSETENV
 
43
#ifdef HAVE_ALLOCA_H
 
44
#include <alloca.h>
 
45
#endif
 
46
 
 
47
#include <string.h>
 
48
#include <stdlib.h>
 
49
#include <errno.h>
 
50
#include <unistd.h>
 
51
 
 
52
#ifndef environ
 
53
extern char ** environ;
 
54
#endif
 
55
 
 
56
void unsetenv(const char *name)
 
57
{
 
58
  size_t len;
 
59
  char **ep;
 
60
 
 
61
  if (name == NULL || *name == '\0' || strchr (name, '=') != NULL) {
 
62
    errno = EINVAL;
 
63
    return;
 
64
  }
 
65
 
 
66
  len = strlen (name);
 
67
  ep = environ;
 
68
  while (*ep != NULL) {
 
69
    if (!strncmp (*ep, name, len) && (*ep)[len] == '=') {
 
70
      /* Found it.  Remove this pointer by moving later ones back.  */
 
71
      char **dp = ep;
 
72
      do {
 
73
        dp[0] = dp[1];
 
74
      } while (*dp++);
 
75
      /* Continue the loop in case NAME appears again.  */
 
76
    } else {
 
77
      ++ep;
 
78
    }
 
79
  }
 
80
}
 
81
 
 
82
#endif /* !HAVE_UNSETENV */
 
83
 
 
84
/**
 
85
 * Find out if the given standard (e.g. "GMT") and daylight savings time
 
86
 * (e.g. "BST", but which may be empty) abbreviated timezone names match
 
87
 * this timezone.
 
88
 *
 
89
 * Thus, this class can be used as a heuristic when trying to lookup the
 
90
 * real timezone from the abbreviated zone names.
 
91
 */
 
92
class AbbreviationsMatch :
 
93
    public KstTimezoneDetails
 
94
{
 
95
public:
 
96
    AbbreviationsMatch(const QString &stdZone, const QString &dstZone = "")
 
97
    {
 
98
        m_stdZone = stdZone;
 
99
        m_dstZone = dstZone;
 
100
    }
 
101
 
 
102
    void parseStarted()
 
103
    {
 
104
        m_foundStd = false;
 
105
        m_foundDst = m_dstZone.isEmpty();
 
106
    }
 
107
 
 
108
    bool test()
 
109
    {
 
110
        return (m_foundStd && m_foundDst);
 
111
    }
 
112
 
 
113
private:
 
114
    bool m_foundStd;
 
115
    bool m_foundDst;
 
116
    QString m_stdZone;
 
117
    QString m_dstZone;
 
118
 
 
119
    virtual void gotAbbreviation(int /*index*/, const QString &value)
 
120
    {
 
121
        if (m_stdZone == value)
 
122
        {
 
123
            m_foundStd = true;
 
124
        }
 
125
        if (m_dstZone == value)
 
126
        {
 
127
            m_foundDst = true;
 
128
        }
 
129
    }
 
130
};
 
131
 
 
132
/**
 
133
 * Internal dummy source for UTC timezone.
 
134
 */
 
135
class DummySource :
 
136
    public KstTimezoneSource
 
137
{
 
138
public:
 
139
    DummySource() :
 
140
        KstTimezoneSource("")
 
141
    {
 
142
    }
 
143
 
 
144
    virtual bool parse(const QString &/*zone*/, KstTimezoneDetails &/*dataReceiver*/) const
 
145
    {
 
146
        return true;
 
147
    }
 
148
};
 
149
 
 
150
/**
 
151
 * Find offset at a particular point in time.
 
152
 */
 
153
class OffsetFind :
 
154
    public KstTimezoneDetails
 
155
{
 
156
public:
 
157
    OffsetFind(unsigned dateTime)
 
158
    {
 
159
        m_dateTime = dateTime;
 
160
    }
 
161
 
 
162
    void parseStarted()
 
163
    {
 
164
        m_transitionTimeIndex = 0;
 
165
        m_localTimeIndex = -1;
 
166
        m_abbrIndex = -1;
 
167
        m_offset = 0;
 
168
        m_isDst = false;
 
169
        m_abbr = UTC_ZONE;
 
170
    }
 
171
 
 
172
    int offset()
 
173
    {
 
174
        return m_offset;
 
175
    }
 
176
 
 
177
    bool isDst()
 
178
    {
 
179
        return m_isDst;
 
180
    }
 
181
 
 
182
    QString abbreviation()
 
183
    {
 
184
        return m_abbr;
 
185
    }
 
186
 
 
187
private:
 
188
    unsigned m_dateTime;
 
189
    int m_transitionTimeIndex;
 
190
    int m_localTimeIndex;
 
191
    int m_abbrIndex;
 
192
    int m_offset;
 
193
    bool m_isDst;
 
194
    QString m_abbr;
 
195
 
 
196
    virtual void gotTransitionTime(int index, unsigned transitionTime)
 
197
    {
 
198
        if (transitionTime <= m_dateTime)
 
199
        {
 
200
            // Remember the index of the transition time that relates to dateTime.
 
201
            m_transitionTimeIndex = index;
 
202
        }
 
203
    }
 
204
 
 
205
    virtual void gotLocalTimeIndex(int index, unsigned localTimeIndex)
 
206
    {
 
207
        if (index == m_transitionTimeIndex)
 
208
        {
 
209
            // Remember the index of the local time that relates to dateTime.
 
210
            m_localTimeIndex = localTimeIndex;
 
211
        }
 
212
    }
 
213
 
 
214
    virtual void gotLocalTime(int index, int gmtOff, bool isDst, unsigned abbrInd)
 
215
    {
 
216
        if (index == m_localTimeIndex)
 
217
        {
 
218
            // Remember the results that relate to gmtOffset.
 
219
            m_offset = gmtOff;
 
220
            m_isDst = isDst;
 
221
            m_abbrIndex = abbrInd;
 
222
        }
 
223
    }
 
224
 
 
225
    virtual void gotAbbreviation(int index, const QString &value)
 
226
    {
 
227
        if (index == m_abbrIndex)
 
228
        {
 
229
            m_abbr = value;
 
230
        }
 
231
    }
 
232
};
 
233
 
 
234
const float KstTimezone::UNKNOWN = 1000.0;
 
235
 
 
236
bool KstTimezone::isValidLatitude(float latitude)
 
237
{
 
238
    return (latitude >= -90.0) && (latitude <= 90.0);
 
239
}
 
240
 
 
241
bool KstTimezone::isValidLongitude(float longitude)
 
242
{
 
243
    return (longitude >= -180.0) && (longitude <= 180.0);
 
244
}
 
245
 
 
246
KstTimezone::KstTimezone(
 
247
    KSharedPtr<KstTimezoneSource> db, const QString& name,
 
248
    const QString &countryCode, float latitude, float longitude,
 
249
    const QString &comment) :
 
250
    m_db(db),
 
251
    m_name(name),
 
252
    m_countryCode(countryCode),
 
253
    m_latitude(latitude),
 
254
    m_longitude(longitude),
 
255
    m_comment(comment),
 
256
    d(0)
 
257
{
 
258
    // Detect duff values.
 
259
    if (m_latitude * m_latitude > 90 * 90)
 
260
        m_latitude = UNKNOWN;
 
261
    if (m_longitude * m_longitude > 180 * 180)
 
262
        m_longitude = UNKNOWN;
 
263
}
 
264
 
 
265
KstTimezone::~KstTimezone()
 
266
{
 
267
    // FIXME when needed:
 
268
    // delete d;
 
269
}
 
270
 
 
271
QString KstTimezone::comment() const
 
272
{
 
273
    return m_comment;
 
274
}
 
275
 
 
276
QDateTime KstTimezone::convert(const KstTimezone *newZone, const QDateTime &dateTime) const
 
277
{
 
278
    char *originalZone = ::getenv("TZ");
 
279
 
 
280
    // Convert the given localtime to UTC.
 
281
    ::putenv(strdup(QString("TZ=:").append(m_name).utf8()));
 
282
    tzset();
 
283
    unsigned utc = dateTime.toTime_t();
 
284
 
 
285
    // Set the timezone and convert UTC to localtime.
 
286
    ::putenv(strdup(QString("TZ=:").append(newZone->name()).utf8()));
 
287
    tzset();
 
288
    QDateTime remoteTime;
 
289
    remoteTime.setTime_t(utc, Qt::LocalTime);
 
290
 
 
291
    // Now restore things
 
292
    if (!originalZone)
 
293
    {
 
294
        ::unsetenv("TZ");
 
295
    }
 
296
    else
 
297
    {
 
298
        ::putenv(strdup(QString("TZ=").append(originalZone).utf8()));
 
299
    }
 
300
    tzset();
 
301
    return remoteTime;
 
302
}
 
303
 
 
304
QString KstTimezone::countryCode() const
 
305
{
 
306
    return m_countryCode;
 
307
}
 
308
 
 
309
float KstTimezone::latitude() const
 
310
{
 
311
    return m_latitude;
 
312
}
 
313
 
 
314
float KstTimezone::longitude() const
 
315
{
 
316
    return m_longitude;
 
317
}
 
318
 
 
319
QString KstTimezone::name() const
 
320
{
 
321
    return m_name;
 
322
}
 
323
 
 
324
int KstTimezone::offset(Qt::TimeSpec basisSpec) const
 
325
{
 
326
    char *originalZone = ::getenv("TZ");
 
327
 
 
328
    // Get the time in the current timezone.
 
329
    QDateTime basisTime = QDateTime::currentDateTime(basisSpec);
 
330
 
 
331
    // Set the timezone and find out what time it is there compared to the basis.
 
332
    ::putenv(strdup(QString("TZ=:").append(m_name).utf8()));
 
333
    tzset();
 
334
    QDateTime remoteTime = QDateTime::currentDateTime(Qt::LocalTime);
 
335
    int offset = remoteTime.secsTo(basisTime);
 
336
 
 
337
    // Now restore things
 
338
    if (!originalZone)
 
339
    {
 
340
        ::unsetenv("TZ");
 
341
    }
 
342
    else
 
343
    {
 
344
        ::putenv(strdup(QString("TZ=").append(originalZone).utf8()));
 
345
    }
 
346
    tzset();
 
347
    return offset;
 
348
}
 
349
 
 
350
int KstTimezone::offset(const QDateTime &dateTime) const
 
351
{
 
352
    OffsetFind finder(dateTime.toTime_t());
 
353
    int result = 0;
 
354
    if (parse(finder))
 
355
    {
 
356
        result = finder.offset();
 
357
    }
 
358
    return result;
 
359
}
 
360
 
 
361
bool KstTimezone::parse(KstTimezoneDetails &dataReceiver) const
 
362
{
 
363
    dataReceiver.parseStarted();
 
364
    bool result = m_db->parse(m_name, dataReceiver);
 
365
    dataReceiver.parseEnded();
 
366
    return result;
 
367
}
 
368
 
 
369
KstTimezones::KstTimezones() :
 
370
    m_zoneinfoDir(),
 
371
    m_zones(0),
 
372
    d(0)
 
373
{
 
374
    // Create the database (and resolve m_zoneinfoDir!).
 
375
    allZones();
 
376
    m_UTC = new KstTimezone(new DummySource(), UTC_ZONE);
 
377
    add(m_UTC);
 
378
}
 
379
 
 
380
KstTimezones::~KstTimezones()
 
381
{
 
382
    // FIXME when needed:
 
383
    // delete d;
 
384
 
 
385
    // Autodelete behavior.
 
386
    if (m_zones)
 
387
    {
 
388
        for (ZoneMap::ConstIterator it = m_zones->begin(); it != m_zones->end(); ++it)
 
389
        {
 
390
            delete it.data();
 
391
        }
 
392
    }
 
393
    delete m_zones;
 
394
}
 
395
 
 
396
void KstTimezones::add(KstTimezone *zone)
 
397
{
 
398
    m_zones->insert(zone->name(), zone);
 
399
}
 
400
 
 
401
const KstTimezones::ZoneMap KstTimezones::allZones()
 
402
{
 
403
    // Have we already done all the hard work? If not, create the cache.
 
404
    if (m_zones)
 
405
        return *m_zones;
 
406
    m_zones = new ZoneMap();
 
407
 
 
408
    // Go read the database.
 
409
    //
 
410
    // On Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
 
411
    // is the place to look. The TZI binary value is the TIME_ZONE_INFORMATION structure.
 
412
    //
 
413
    // For Unix its all easy except knowing where to look. Try the LSB location first.
 
414
    QFile f;
 
415
    m_zoneinfoDir = "/usr/share/zoneinfo";
 
416
    f.setName(m_zoneinfoDir + "/zone.tab");
 
417
    if (!f.open(IO_ReadOnly))
 
418
    {
 
419
        m_zoneinfoDir = "/usr/lib/zoneinfo";
 
420
        f.setName(m_zoneinfoDir + "/zone.tab");
 
421
        if (!f.open(IO_ReadOnly))
 
422
        {
 
423
            m_zoneinfoDir = ::getenv("TZDIR");
 
424
            f.setName(m_zoneinfoDir + "/zone.tab");
 
425
            if (m_zoneinfoDir.isEmpty() || !f.open(IO_ReadOnly))
 
426
            {
 
427
                // Solaris support. Synthesise something that looks like a zone.tab.
 
428
                //
 
429
                // /bin/grep -h ^Zone /usr/share/lib/zoneinfo/src/* | /bin/awk '{print "??\t+9999+99999\t" $2}'
 
430
                //
 
431
                // where the country code is set to "??" and the lattitude/longitude
 
432
                // values are dummies.
 
433
                m_zoneinfoDir = "/usr/share/lib/zoneinfo";
 
434
                KTempFile temp;
 
435
                KShellProcess reader;
 
436
                reader << "/bin/grep" << "-h" << "^Zone" << m_zoneinfoDir << "/src/*" << temp.name() << "|" <<
 
437
                    "/bin/awk" << "'{print \"??\\t+9999+99999\\t\" $2}'";
 
438
                // Note the use of blocking here...it is a trivial amount of data!
 
439
                temp.close();
 
440
                reader.start(KProcess::Block);
 
441
                f.setName(temp.name());
 
442
                if (!temp.status() || !f.open(IO_ReadOnly))
 
443
                {
 
444
                    return *m_zones;
 
445
                }
 
446
            }
 
447
        }
 
448
    }
 
449
 
 
450
    // Parse the zone.tab.
 
451
    QTextStream str(&f);
 
452
    QRegExp lineSeparator("[ \t]");
 
453
    QRegExp ordinateSeparator("[+-]");
 
454
    KSharedPtr<KstTimezoneSource> db(new KstTimezoneSource(m_zoneinfoDir));
 
455
    while (!str.atEnd())
 
456
    {
 
457
        QString line = str.readLine();
 
458
        if (line.isEmpty() || '#' == line[0])
 
459
            continue;
 
460
        QStringList tokens = KStringHandler::perlSplit(lineSeparator, line, 4);
 
461
        if (tokens.count() < 3)
 
462
        {
 
463
            continue;
 
464
        }
 
465
 
 
466
        // Got three tokens. Now check for two ordinates plus first one is "".
 
467
        QStringList ordinates = KStringHandler::perlSplit(ordinateSeparator, tokens[1], 2);
 
468
        if (ordinates.count() < 2)
 
469
        {
 
470
            continue;
 
471
        }
 
472
 
 
473
        float latitude = convertCoordinate(ordinates[1]);
 
474
        float longitude = convertCoordinate(ordinates[2]);
 
475
 
 
476
        // Add entry to list.
 
477
        if (tokens[0] == "??")
 
478
            tokens[0] = "";
 
479
        KstTimezone *timezone = new KstTimezone(db, tokens[2], tokens[0], latitude, longitude, tokens[3]);
 
480
        add(timezone);
 
481
    }
 
482
    f.close();
 
483
    return *m_zones;
 
484
}
 
485
 
 
486
/**
 
487
 * Convert sHHMM or sHHMMSS to a floating point number of degrees.
 
488
 */
 
489
float KstTimezones::convertCoordinate(const QString &coordinate)
 
490
{
 
491
    int value = coordinate.toInt();
 
492
    int degrees = 0;
 
493
    int minutes = 0;
 
494
    int seconds = 0;
 
495
 
 
496
    if (coordinate.length() > 11)
 
497
    {
 
498
        degrees = value / 10000;
 
499
        value -= degrees * 10000;
 
500
        minutes = value / 100;
 
501
        value -= minutes * 100;
 
502
        seconds = value;
 
503
    }
 
504
    else
 
505
    {
 
506
        degrees = value / 100;
 
507
        value -= degrees * 100;
 
508
        minutes = value;
 
509
    }
 
510
    value = degrees * 3600 + minutes * 60 + seconds;
 
511
    return value / 3600.0;
 
512
}
 
513
 
 
514
const KstTimezone *KstTimezones::local()
 
515
{
 
516
    const KstTimezone *local = 0;
 
517
 
 
518
    // First try the simplest solution of checking for well-formed TZ setting.
 
519
    char *envZone = ::getenv("TZ");
 
520
    if (envZone)
 
521
    {
 
522
        if (envZone[0] == '\0')
 
523
        {
 
524
            return m_UTC;
 
525
        }
 
526
        else
 
527
        if (envZone[0] == ':')
 
528
        {
 
529
            envZone++;
 
530
        }
 
531
        local = zone(envZone);
 
532
    }
 
533
    if (local)
 
534
        return local;
 
535
 
 
536
    // Try to match /etc/localtime against the list of zoneinfo files.
 
537
    QFile f;
 
538
    f.setName("/etc/localtime");
 
539
    if (f.open(IO_ReadOnly))
 
540
    {
 
541
        // Compute the MD5 sum of /etc/localtime.
 
542
        KMD5 context("");
 
543
        context.reset();
 
544
        context.update(f);
 
545
        QIODevice::Offset referenceSize = f.size();
 
546
        QString referenceMd5Sum = context.hexDigest();
 
547
        f.close();
 
548
        if (!m_zoneinfoDir.isEmpty())
 
549
        {
 
550
            // Compare it with each zoneinfo file.
 
551
            for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
 
552
            {
 
553
                KstTimezone *zone = it.data();
 
554
                f.setName(m_zoneinfoDir + '/' + zone->name());
 
555
                if (f.open(IO_ReadOnly))
 
556
                {
 
557
                    QIODevice::Offset candidateSize = f.size();
 
558
                    QString candidateMd5Sum;
 
559
                    if (candidateSize == referenceSize)
 
560
                    {
 
561
                        // Only do the heavy lifting for file sizes which match.
 
562
                        context.reset();
 
563
                        context.update(f);
 
564
                        candidateMd5Sum = context.hexDigest();
 
565
                    }
 
566
                    f.close();
 
567
                    if (candidateMd5Sum == referenceMd5Sum)
 
568
                    {
 
569
                        local = zone;
 
570
                        break;
 
571
                    }
 
572
                }
 
573
            }
 
574
        }
 
575
    }
 
576
    if (local)
 
577
        return local;
 
578
 
 
579
    // BSD support.
 
580
    QString fileZone;
 
581
    f.setName("/etc/timezone");
 
582
    if (!f.open(IO_ReadOnly))
 
583
    {
 
584
        // Solaris support using /etc/default/init.
 
585
        f.setName("/etc/default/init");
 
586
        if (f.open(IO_ReadOnly))
 
587
        {
 
588
            QTextStream ts(&f);
 
589
            ts.setEncoding(QTextStream::Latin1);
 
590
 
 
591
            // Read the last line starting "TZ=".
 
592
            while (!ts.atEnd())
 
593
            {
 
594
                fileZone = ts.readLine();
 
595
                if (fileZone.startsWith("TZ="))
 
596
                {
 
597
                    fileZone = fileZone.mid(3);
 
598
 
 
599
                    local = zone(fileZone);
 
600
                }
 
601
            }
 
602
            f.close();
 
603
        }
 
604
    }
 
605
    else
 
606
    {
 
607
        QTextStream ts(&f);
 
608
        ts.setEncoding(QTextStream::Latin1);
 
609
 
 
610
        // Read the first line.
 
611
        if (!ts.atEnd())
 
612
        {
 
613
            fileZone = ts.readLine();
 
614
 
 
615
            local = zone(fileZone);
 
616
        }
 
617
        f.close();
 
618
    }
 
619
    if (local)
 
620
        return local;
 
621
 
 
622
    // None of the deterministic stuff above has worked: try a heuristic. We
 
623
    // try to find a pair of matching timezone abbreviations...that way, we'll
 
624
    // likely return a value in the user's own country.
 
625
    if (!m_zoneinfoDir.isEmpty())
 
626
    {
 
627
        tzset();
 
628
        AbbreviationsMatch matcher(tzname[0], tzname[1]);
 
629
        int bestOffset = INT_MAX;
 
630
        for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
 
631
        {
 
632
            KstTimezone *zone = it.data();
 
633
            int candidateOffset = QABS(zone->offset(Qt::LocalTime));
 
634
            if (zone->parse(matcher) && matcher.test() && (candidateOffset < bestOffset))
 
635
            {
 
636
                bestOffset = candidateOffset;
 
637
                local = zone;
 
638
            }
 
639
        }
 
640
    }
 
641
    if (local)
 
642
        return local;
 
643
    return m_UTC;
 
644
}
 
645
 
 
646
const KstTimezone *KstTimezones::zone(const QString &name)
 
647
{
 
648
    if (name.isEmpty())
 
649
        return m_UTC;
 
650
    ZoneMap::ConstIterator it = m_zones->find(name);
 
651
    if (it != m_zones->end())
 
652
        return it.data();
 
653
 
 
654
    // Error.
 
655
    return 0;
 
656
}
 
657
 
 
658
KstTimezoneDetails::KstTimezoneDetails()
 
659
{
 
660
}
 
661
 
 
662
KstTimezoneDetails::~KstTimezoneDetails()
 
663
{
 
664
}
 
665
 
 
666
void KstTimezoneDetails::gotAbbreviation(int /*index*/, const QString &)
 
667
{}
 
668
 
 
669
void KstTimezoneDetails::gotHeader(
 
670
        unsigned, unsigned, unsigned,
 
671
        unsigned, unsigned, unsigned)
 
672
{}
 
673
 
 
674
void KstTimezoneDetails::gotLeapAdjustment(int /*index*/, unsigned, unsigned)
 
675
{}
 
676
 
 
677
void KstTimezoneDetails::gotLocalTime(int /*index*/, int, bool, unsigned)
 
678
{}
 
679
 
 
680
void KstTimezoneDetails::gotLocalTimeIndex(int /*index*/, unsigned)
 
681
{}
 
682
 
 
683
void KstTimezoneDetails::gotIsStandard(int /*index*/, bool)
 
684
{}
 
685
 
 
686
void KstTimezoneDetails::gotTransitionTime(int /*index*/, unsigned)
 
687
{}
 
688
 
 
689
void KstTimezoneDetails::gotIsUTC(int /*index*/, bool)
 
690
{}
 
691
 
 
692
void KstTimezoneDetails::parseEnded()
 
693
{}
 
694
 
 
695
void KstTimezoneDetails::parseStarted()
 
696
{}
 
697
 
 
698
KstTimezoneSource::KstTimezoneSource(const QString &db) :
 
699
    m_db(db)
 
700
{
 
701
}
 
702
 
 
703
KstTimezoneSource::~KstTimezoneSource()
 
704
{
 
705
}
 
706
 
 
707
QString KstTimezoneSource::db()
 
708
{
 
709
    return m_db;
 
710
}
 
711
 
 
712
bool KstTimezoneSource::parse(const QString &zone, KstTimezoneDetails &dataReceiver) const
 
713
{
 
714
    QFile f(m_db + '/' + zone);
 
715
    if (!f.open(IO_ReadOnly))
 
716
    {
 
717
        return false;
 
718
    }
 
719
 
 
720
    // Structures that represent the zoneinfo file.
 
721
    Q_UINT8 T, z, i_, f_;
 
722
    struct
 
723
    {
 
724
        Q_UINT32 ttisgmtcnt;
 
725
        Q_UINT32 ttisstdcnt;
 
726
        Q_UINT32 leapcnt;
 
727
        Q_UINT32 timecnt;
 
728
        Q_UINT32 typecnt;
 
729
        Q_UINT32 charcnt;
 
730
    } tzh;
 
731
    Q_UINT32 transitionTime;
 
732
    Q_UINT8 localTimeIndex;
 
733
    struct
 
734
    {
 
735
        Q_INT32 gmtoff;
 
736
        Q_INT8 isdst;
 
737
        Q_UINT8 abbrind;
 
738
    } tt;
 
739
    Q_UINT32 leapTime;
 
740
    Q_UINT32 leapSeconds;
 
741
    Q_UINT8 isStandard;
 
742
    Q_UINT8 isUTC;
 
743
 
 
744
    QDataStream str(&f);
 
745
    str >> T >> z >> i_ >> f_;
 
746
    unsigned i;
 
747
    for (i = 0; i < 4; i++)
 
748
        str >> tzh.ttisgmtcnt;
 
749
    str >> tzh.ttisgmtcnt >> tzh.ttisstdcnt >> tzh.leapcnt >> tzh.timecnt >> tzh.typecnt >> tzh.charcnt;
 
750
    dataReceiver.gotHeader(tzh.ttisgmtcnt, tzh.ttisstdcnt, tzh.leapcnt, tzh.timecnt, tzh.typecnt, tzh.charcnt);
 
751
    for (i = 0; i < tzh.timecnt; i++)
 
752
    {
 
753
        str >> transitionTime;
 
754
        dataReceiver.gotTransitionTime(i, transitionTime);
 
755
    }
 
756
    for (i = 0; i < tzh.timecnt; i++)
 
757
    {
 
758
        // NB: these appear to be 1-based, not zero-based!
 
759
        str >> localTimeIndex;
 
760
        dataReceiver.gotLocalTimeIndex(i, localTimeIndex);
 
761
    }
 
762
    for (i = 0; i < tzh.typecnt; i++)
 
763
    {
 
764
        str >> tt.gmtoff >> tt.isdst >> tt.abbrind;
 
765
        dataReceiver.gotLocalTime(i, tt.gmtoff, (tt.isdst != 0), tt.abbrind);
 
766
    }
 
767
 
 
768
    // Make sure we don't run foul of maliciously coded timezone abbreviations.
 
769
    if (tzh.charcnt > 64)
 
770
    {
 
771
        return false;
 
772
    }
 
773
    QByteArray array(tzh.charcnt);
 
774
    str.readRawBytes(array.data(), array.size());
 
775
    char *abbrs = array.data();
 
776
    if (abbrs[tzh.charcnt - 1] != 0)
 
777
    {
 
778
        // These abbrevations are corrupt!
 
779
        return false;
 
780
    }
 
781
    char *abbr = abbrs;
 
782
    while (abbr < abbrs + tzh.charcnt)
 
783
    {
 
784
        dataReceiver.gotAbbreviation((abbr - abbrs), abbr);
 
785
        abbr += strlen(abbr) + 1;
 
786
    }
 
787
    for (i = 0; i < tzh.leapcnt; i++)
 
788
    {
 
789
        str >> leapTime >> leapSeconds;
 
790
        dataReceiver.gotLeapAdjustment(i, leapTime, leapSeconds);
 
791
    }
 
792
    for (i = 0; i < tzh.ttisstdcnt; i++)
 
793
    {
 
794
        str >> isStandard;
 
795
        dataReceiver.gotIsStandard(i, (isStandard != 0));
 
796
    }
 
797
    for (i = 0; i < tzh.ttisgmtcnt; i++)
 
798
    {
 
799
        str >> isUTC;
 
800
        dataReceiver.gotIsUTC(i, (isUTC != 0));
 
801
    }
 
802
    return true;
 
803
}