Coverage Report

Created: 2026-11-10 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/timezone/timezone.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Time Zone
4
 *
5
 * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2024 Armin Novak <anovak@thincast.com>
7
 * Copyright 2024 Thincast Technologies GmbH
8
 *
9
 * Licensed under the Apache License, Version 2.0 (the "License");
10
 * you may not use this file except in compliance with the License.
11
 * You may obtain a copy of the License at
12
 *
13
 *     http://www.apache.org/licenses/LICENSE-2.0
14
 *
15
 * Unless required by applicable law or agreed to in writing, software
16
 * distributed under the License is distributed on an "AS IS" BASIS,
17
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
 * See the License for the specific language governing permissions and
19
 * limitations under the License.
20
 */
21
22
#include <winpr/config.h>
23
24
#include <winpr/environment.h>
25
#include <winpr/wtypes.h>
26
#include <winpr/timezone.h>
27
#include <winpr/crt.h>
28
#include <winpr/assert.h>
29
#include <winpr/file.h>
30
#include "../log.h"
31
#include "timezone.h"
32
33
2.33k
#define TAG WINPR_TAG("timezone")
34
35
#include "TimeZoneNameMap.h"
36
#include "TimeZoneIanaAbbrevMap.h"
37
38
#ifndef _WIN32
39
40
#include <time.h>
41
#include <unistd.h>
42
43
#endif
44
45
#if !defined(_WIN32)
46
WINPR_ATTR_MALLOC(free, 1)
47
static char* winpr_read_unix_timezone_identifier_from_file(FILE* fp)
48
2.33k
{
49
2.33k
  const INT CHUNK_SIZE = 32;
50
2.33k
  size_t rc = 0;
51
2.33k
  size_t read = 0;
52
2.33k
  size_t length = CHUNK_SIZE;
53
54
2.33k
  char* tzid = malloc(length);
55
2.33k
  if (!tzid)
56
0
    return nullptr;
57
58
2.33k
  do
59
2.33k
  {
60
2.33k
    rc = fread(tzid + read, 1, length - read - 1UL, fp);
61
2.33k
    if (rc > 0)
62
2.33k
      read += rc;
63
64
2.33k
    if (read < (length - 1UL))
65
2.33k
      break;
66
67
0
    if (read > length - 1UL)
68
0
    {
69
0
      free(tzid);
70
0
      return nullptr;
71
0
    }
72
73
0
    length += CHUNK_SIZE;
74
0
    char* tmp = (char*)realloc(tzid, length);
75
0
    if (!tmp)
76
0
    {
77
0
      free(tzid);
78
0
      return nullptr;
79
0
    }
80
81
0
    tzid = tmp;
82
0
  } while (rc > 0);
83
84
2.33k
  if (ferror(fp))
85
0
  {
86
0
    free(tzid);
87
0
    return nullptr;
88
0
  }
89
90
2.33k
  tzid[read] = '\0';
91
2.33k
  if (read > 0)
92
2.33k
  {
93
2.33k
    if (tzid[read - 1] == '\n')
94
2.33k
      tzid[read - 1] = '\0';
95
2.33k
  }
96
97
2.33k
  return tzid;
98
2.33k
}
99
100
WINPR_ATTR_NODISCARD
101
static const char* winpr_get_zoneinfo_dir(void)
102
4.67k
{
103
  // NOLINTNEXTLINE(concurrency-mt-unsafe)
104
4.67k
  const char* dir = getenv("TZDIR");
105
4.67k
  if (!dir || (dir[0] == '\0'))
106
4.67k
    return "/usr/share/zoneinfo";
107
0
  return dir;
108
4.67k
}
109
110
WINPR_ATTR_NODISCARD
111
static const char* winpr_get_timezone_from_zoneinfo_path(const char* path)
112
2.33k
{
113
2.33k
  char* dir = realpath(winpr_get_zoneinfo_dir(), nullptr);
114
2.33k
  if (!dir)
115
0
    return nullptr;
116
117
2.33k
  const char* name = nullptr;
118
2.33k
  const size_t len = strlen(dir);
119
2.33k
  if ((strncmp(path, dir, len) == 0) && (path[len] == '/'))
120
2.33k
    name = &path[len + 1];
121
2.33k
  free(dir);
122
2.33k
  if (!name)
123
0
    return nullptr;
124
125
  /* these hold variants of the same zones */
126
2.33k
  const char* variants[] = { "posix/", "right/" };
127
7.01k
  for (size_t x = 0; x < ARRAYSIZE(variants); x++)
128
4.67k
  {
129
4.67k
    const size_t vlen = strlen(variants[x]);
130
4.67k
    if (strncmp(name, variants[x], vlen) == 0)
131
0
    {
132
0
      name += vlen;
133
0
      break;
134
0
    }
135
4.67k
  }
136
137
2.33k
  if (name[0] == '\0')
138
0
    return nullptr;
139
2.33k
  return name;
140
2.33k
}
141
142
WINPR_ATTR_MALLOC(free, 1)
143
static char* winpr_get_timezone_from_link(const char* links[], size_t count)
144
2.33k
{
145
2.33k
  const char* _links[] = { "/etc/localtime", "/etc/TZ" };
146
147
2.33k
  if (links == nullptr)
148
0
  {
149
0
    links = _links;
150
0
    count = ARRAYSIZE(_links);
151
0
  }
152
153
  /*
154
   * On linux distros such as Redhat or Archlinux, a symlink at /etc/localtime
155
   * will point to /usr/share/zoneinfo/region/place where region/place could be
156
   * America/Montreal for example.
157
   * Some distributions do have to symlink at /etc/TZ.
158
   */
159
160
2.33k
  for (size_t x = 0; x < count; x++)
161
2.33k
  {
162
2.33k
    char* tzid = nullptr;
163
2.33k
    const char* link = links[x];
164
2.33k
    char* buf = realpath(link, nullptr);
165
166
2.33k
    if (buf)
167
2.33k
    {
168
2.33k
      const char* name = winpr_get_timezone_from_zoneinfo_path(buf);
169
2.33k
      if (name)
170
2.33k
      {
171
2.33k
        tzid = _strdup(name);
172
2.33k
        if (tzid)
173
2.33k
          WLog_DBG(TAG, "tzid: %s", tzid);
174
2.33k
        goto end;
175
2.33k
      }
176
177
0
      size_t sep = 0;
178
0
      size_t alloc = 0;
179
0
      size_t pos = 0;
180
0
      size_t len = pos = strlen(buf);
181
182
      /* find the position of the 2nd to last "/" */
183
0
      for (size_t i = 1; i <= len; i++)
184
0
      {
185
0
        const size_t curpos = len - i;
186
0
        const char cur = buf[curpos];
187
188
0
        if (cur == '/')
189
0
          sep++;
190
0
        if (sep >= 2)
191
0
        {
192
0
          alloc = i;
193
0
          pos = len - i + 1;
194
0
          break;
195
0
        }
196
0
      }
197
198
0
      if ((len == 0) || (sep != 2))
199
0
        goto end;
200
201
0
      tzid = (char*)calloc(alloc + 1, sizeof(char));
202
203
0
      if (!tzid)
204
0
        goto end;
205
206
0
      strncpy(tzid, &buf[pos], alloc);
207
0
      WLog_DBG(TAG, "tzid: %s", tzid);
208
0
      goto end;
209
0
    }
210
211
2.33k
  end:
212
2.33k
    free(buf);
213
2.33k
    if (tzid)
214
2.33k
      return tzid;
215
2.33k
  }
216
217
0
  return nullptr;
218
2.33k
}
219
220
#if defined(ANDROID)
221
#include "../utils/android.h"
222
223
WINPR_ATTR_MALLOC(free, 1)
224
static char* winpr_get_android_timezone_identifier(void)
225
{
226
  char* tzid = nullptr;
227
  JNIEnv* jniEnv;
228
229
  /* Preferred: Try to get identifier from java TimeZone class */
230
  if (jniVm && ((*jniVm)->GetEnv(jniVm, (void**)&jniEnv, JNI_VERSION_1_6) == JNI_OK))
231
  {
232
    const char* raw;
233
    jclass jObjClass;
234
    jobject jObj;
235
    jmethodID jDefaultTimezone;
236
    jmethodID jTimezoneIdentifier;
237
    jstring tzJId;
238
    jboolean attached = (*jniVm)->AttachCurrentThread(jniVm, &jniEnv, nullptr);
239
    jObjClass = (*jniEnv)->FindClass(jniEnv, "java/util/TimeZone");
240
241
    if (!jObjClass)
242
      goto fail;
243
244
    jDefaultTimezone =
245
        (*jniEnv)->GetStaticMethodID(jniEnv, jObjClass, "getDefault", "()Ljava/util/TimeZone;");
246
247
    if (!jDefaultTimezone)
248
      goto fail;
249
250
    jObj = (*jniEnv)->CallStaticObjectMethod(jniEnv, jObjClass, jDefaultTimezone);
251
252
    if (!jObj)
253
      goto fail;
254
255
    jTimezoneIdentifier =
256
        (*jniEnv)->GetMethodID(jniEnv, jObjClass, "getID", "()Ljava/lang/String;");
257
258
    if (!jTimezoneIdentifier)
259
      goto fail;
260
261
    tzJId = (*jniEnv)->CallObjectMethod(jniEnv, jObj, jTimezoneIdentifier);
262
263
    if (!tzJId)
264
      goto fail;
265
266
    raw = (*jniEnv)->GetStringUTFChars(jniEnv, tzJId, 0);
267
268
    if (raw)
269
      tzid = _strdup(raw);
270
271
    (*jniEnv)->ReleaseStringUTFChars(jniEnv, tzJId, raw);
272
  fail:
273
274
    if (attached)
275
      (*jniVm)->DetachCurrentThread(jniVm);
276
  }
277
278
  /* Fall back to property, might not be available. */
279
  if (!tzid)
280
  {
281
    FILE* fp = popen("getprop persist.sys.timezone", "r");
282
283
    if (fp)
284
    {
285
      tzid = winpr_read_unix_timezone_identifier_from_file(fp);
286
      pclose(fp);
287
    }
288
  }
289
290
  return tzid;
291
}
292
#endif
293
294
WINPR_ATTR_MALLOC(free, 1)
295
static char* winpr_get_unix_timezone_identifier_from_file(void)
296
2.33k
{
297
#if defined(ANDROID)
298
  return winpr_get_android_timezone_identifier();
299
#else
300
2.33k
  FILE* fp = nullptr;
301
2.33k
  char* tzid = nullptr;
302
#if !defined(WINPR_TIMEZONE_FILE)
303
#error \
304
    "Please define WINPR_TIMEZONE_FILE with the path to your timezone file (e.g. /etc/timezone or similar)"
305
#else
306
2.33k
  fp = winpr_fopen(WINPR_TIMEZONE_FILE, "r");
307
2.33k
#endif
308
309
2.33k
  if (nullptr == fp)
310
0
    return nullptr;
311
312
2.33k
  tzid = winpr_read_unix_timezone_identifier_from_file(fp);
313
2.33k
  (void)fclose(fp);
314
2.33k
  if (tzid != nullptr)
315
2.33k
    WLog_DBG(TAG, "tzid: %s", tzid);
316
2.33k
  return tzid;
317
2.33k
#endif
318
2.33k
}
319
320
static char* winpr_time_zone_from_env(void)
321
2.33k
{
322
2.33k
  LPCSTR tz = "TZ";
323
2.33k
  char* tzid = nullptr;
324
325
2.33k
  DWORD nSize = GetEnvironmentVariableA(tz, nullptr, 0);
326
2.33k
  if (nSize > 0)
327
0
  {
328
0
    tzid = (char*)calloc(nSize, sizeof(char));
329
0
    if (!tzid)
330
0
      goto fail;
331
0
    if (!GetEnvironmentVariableA(tz, tzid, nSize))
332
0
      goto fail;
333
0
    else if (tzid[0] == ':')
334
0
    {
335
      /* Remove leading colon, see tzset(3) */
336
0
      memmove(tzid, tzid + 1, nSize - sizeof(char));
337
0
    }
338
0
  }
339
340
2.33k
  return tzid;
341
342
0
fail:
343
0
  free(tzid);
344
0
  return nullptr;
345
2.33k
}
346
347
static char* winpr_translate_time_zone(const char* tzid)
348
2.33k
{
349
2.33k
  char* buf = nullptr;
350
2.33k
  const char* links[] = { buf };
351
352
2.33k
  if (!tzid)
353
0
    return nullptr;
354
355
2.33k
  if (tzid[0] == '/')
356
0
  {
357
    /* Full path given in TZ */
358
0
    links[0] = tzid;
359
0
  }
360
2.33k
  else
361
2.33k
  {
362
2.33k
    size_t bsize = 0;
363
2.33k
    winpr_asprintf(&buf, &bsize, "%s/%s", winpr_get_zoneinfo_dir(), tzid);
364
2.33k
    links[0] = buf;
365
2.33k
  }
366
367
2.33k
  char* ntzid = winpr_get_timezone_from_link(links, 1);
368
2.33k
  free(buf);
369
2.33k
  return ntzid;
370
2.33k
}
371
372
#if defined(__EMSCRIPTEN__)
373
/* in timezone_emscripten.js: writes the browser's IANA time zone to buffer, or an empty string */
374
extern void winpr_timezone_js_get(char* buffer, size_t size);
375
376
static char* winpr_get_browser_timezone_identifier(void)
377
{
378
  char tzid[128] = WINPR_C_ARRAY_INIT;
379
380
  winpr_timezone_js_get(tzid, sizeof(tzid));
381
  if (tzid[0] == '\0')
382
    return nullptr;
383
384
  return _strdup(tzid);
385
}
386
#endif
387
388
static char* winpr_guess_time_zone(void)
389
2.33k
{
390
2.33k
  char* tzid = winpr_time_zone_from_env();
391
2.33k
  if (tzid)
392
0
    goto end;
393
#if defined(__EMSCRIPTEN__)
394
  tzid = winpr_get_browser_timezone_identifier();
395
  if (tzid)
396
    goto end;
397
#endif
398
2.33k
  tzid = winpr_get_unix_timezone_identifier_from_file();
399
2.33k
  if (tzid)
400
2.33k
    goto end;
401
0
  tzid = winpr_get_timezone_from_link(nullptr, 0);
402
0
  if (tzid)
403
0
    goto end;
404
405
2.33k
end:
406
2.33k
{
407
2.33k
  char* ntzid = winpr_translate_time_zone(tzid);
408
2.33k
  if (ntzid)
409
2.33k
  {
410
2.33k
    free(tzid);
411
2.33k
    return ntzid;
412
2.33k
  }
413
0
  return tzid;
414
2.33k
}
415
2.33k
}
416
417
static SYSTEMTIME tm2systemtime(const struct tm* t)
418
4.67k
{
419
4.67k
  SYSTEMTIME st = WINPR_C_ARRAY_INIT;
420
421
4.67k
  if (t)
422
0
  {
423
0
    st.wYear = (WORD)(1900 + t->tm_year);
424
0
    st.wMonth = (WORD)t->tm_mon + 1;
425
0
    st.wDay = (WORD)t->tm_mday;
426
0
    st.wDayOfWeek = (WORD)t->tm_wday;
427
0
    st.wHour = (WORD)t->tm_hour;
428
0
    st.wMinute = (WORD)t->tm_min;
429
0
    st.wSecond = (WORD)t->tm_sec;
430
0
    st.wMilliseconds = 0;
431
0
  }
432
4.67k
  return st;
433
4.67k
}
434
435
static struct tm systemtime2tm(const SYSTEMTIME* st)
436
0
{
437
0
  struct tm t = WINPR_C_ARRAY_INIT;
438
0
  if (st)
439
0
  {
440
0
    if (st->wYear >= 1900)
441
0
      t.tm_year = st->wYear - 1900;
442
0
    if (st->wMonth > 0)
443
0
      t.tm_mon = st->wMonth - 1;
444
0
    t.tm_mday = st->wDay;
445
0
    t.tm_wday = st->wDayOfWeek;
446
0
    t.tm_hour = st->wHour;
447
0
    t.tm_min = st->wMinute;
448
0
    t.tm_sec = st->wSecond;
449
0
  }
450
0
  return t;
451
0
}
452
453
static LONG get_gmtoff_min(const struct tm* t)
454
4.67k
{
455
4.67k
  WINPR_ASSERT(t);
456
4.67k
  return -(LONG)(t->tm_gmtoff / 60l);
457
4.67k
}
458
459
static struct tm update_tm(const struct tm* start)
460
2.56M
{
461
2.56M
  WINPR_ASSERT(start);
462
2.56M
  struct tm cur = *start;
463
2.56M
  const time_t t = mktime(&cur);
464
2.56M
  struct tm next = WINPR_C_ARRAY_INIT;
465
2.56M
  (void)localtime_r(&t, &next);
466
2.56M
  return next;
467
2.56M
}
468
469
static struct tm next_day(const struct tm* start)
470
2.56M
{
471
2.56M
  struct tm cur = *start;
472
2.56M
  cur.tm_hour = 0;
473
2.56M
  cur.tm_min = 0;
474
2.56M
  cur.tm_sec = 0;
475
2.56M
  cur.tm_isdst = -1;
476
2.56M
  cur.tm_mday++;
477
2.56M
  return update_tm(&cur);
478
2.56M
}
479
480
static struct tm adjust_time(const struct tm* start, int hour, int minute)
481
0
{
482
0
  struct tm cur = *start;
483
0
  cur.tm_hour = hour;
484
0
  cur.tm_min = minute;
485
0
  cur.tm_sec = 0;
486
0
  cur.tm_isdst = -1;
487
0
  return update_tm(&cur);
488
0
}
489
490
/* [MS-RDPBCGR] 2.2.1.11.1.1.1.1.1  System Time (TS_SYSTEMTIME) */
491
static WORD get_transition_weekday_occurrence(const SYSTEMTIME* st)
492
0
{
493
0
  WORD count = 0;
494
0
  struct tm start = systemtime2tm(st);
495
496
0
  WORD last = 0;
497
0
  struct tm next = start;
498
0
  next.tm_mday = 1;
499
0
  next.tm_isdst = -1;
500
0
  do
501
0
  {
502
503
0
    const time_t t = mktime(&next);
504
0
    next.tm_mday++;
505
506
0
    struct tm cur = WINPR_C_ARRAY_INIT;
507
0
    (void)localtime_r(&t, &cur);
508
509
0
    if (cur.tm_mon + 1 != st->wMonth)
510
0
      break;
511
512
0
    if (cur.tm_wday == st->wDayOfWeek)
513
0
    {
514
0
      if (cur.tm_mday <= st->wDay)
515
0
        count++;
516
0
      last++;
517
0
    }
518
519
0
  } while (TRUE);
520
521
0
  if (count == last)
522
0
    count = 5;
523
524
0
  return count;
525
0
}
526
527
static SYSTEMTIME tm2transitiontime(const struct tm* cur)
528
4.67k
{
529
4.67k
  SYSTEMTIME t = tm2systemtime(cur);
530
4.67k
  if (cur)
531
0
  {
532
0
    t.wDay = get_transition_weekday_occurrence(&t);
533
0
    t.wYear = 0;
534
0
  }
535
536
4.67k
  return t;
537
4.67k
}
538
539
static SYSTEMTIME get_transition_time(const struct tm* start, BOOL toDst)
540
0
{
541
0
  BOOL toggled = FALSE;
542
0
  struct tm first = adjust_time(start, 0, 0);
543
0
  for (int hour = 0; hour < 24; hour++)
544
0
  {
545
0
    struct tm cur = adjust_time(start, hour, 0);
546
0
    if (cur.tm_isdst != first.tm_isdst)
547
0
      toggled = TRUE;
548
549
0
    if (toggled)
550
0
    {
551
0
      if (toDst && (cur.tm_isdst > 0))
552
0
        return tm2transitiontime(&cur);
553
0
      else if (!toDst && (cur.tm_isdst == 0))
554
0
        return tm2transitiontime(&cur);
555
0
    }
556
0
  }
557
0
  return tm2transitiontime(start);
558
0
}
559
560
static BOOL get_transition_date(const struct tm* pstart, BOOL toDst, SYSTEMTIME* pdate)
561
4.67k
{
562
4.67k
  WINPR_ASSERT(pstart);
563
4.67k
  WINPR_ASSERT(pdate);
564
565
4.67k
  *pdate = tm2transitiontime(nullptr);
566
567
4.67k
  struct tm start = update_tm(pstart);
568
4.67k
  if (start.tm_isdst < 0)
569
0
    return FALSE;
570
571
4.67k
  BOOL val = start.tm_isdst > 0; // the year starts with DST or not
572
4.67k
  BOOL toggled = FALSE;
573
4.67k
  struct tm cur = start;
574
4.67k
  struct tm last = cur;
575
1.71M
  for (int day = 1; day <= 365; day++)
576
1.70M
  {
577
1.70M
    last = cur;
578
1.70M
    cur = next_day(&cur);
579
1.70M
    const BOOL curDst = (cur.tm_isdst > 0);
580
1.70M
    if ((val != curDst) && !toggled)
581
0
      toggled = TRUE;
582
583
1.70M
    if (toggled)
584
0
    {
585
0
      if (toDst && curDst)
586
0
      {
587
0
        *pdate = get_transition_time(&last, toDst);
588
0
        return TRUE;
589
0
      }
590
0
      if (!toDst && !curDst)
591
0
      {
592
0
        *pdate = get_transition_time(&last, toDst);
593
0
        return TRUE;
594
0
      }
595
0
    }
596
1.70M
  }
597
4.67k
  return FALSE;
598
4.67k
}
599
600
static LONG get_bias(const struct tm* start, BOOL dstBias)
601
7.01k
{
602
7.01k
  if ((start->tm_isdst > 0) && dstBias)
603
0
    return get_gmtoff_min(start);
604
7.01k
  if ((start->tm_isdst == 0) && !dstBias)
605
4.67k
    return get_gmtoff_min(start);
606
2.33k
  if (start->tm_isdst < 0)
607
0
    return get_gmtoff_min(start);
608
609
2.33k
  struct tm cur = *start;
610
855k
  for (int day = 1; day <= 365; day++)
611
853k
  {
612
853k
    cur = next_day(&cur);
613
853k
    if ((cur.tm_isdst > 0) && dstBias)
614
0
      return get_gmtoff_min(&cur);
615
853k
    else if ((cur.tm_isdst == 0) && !dstBias)
616
0
      return get_gmtoff_min(&cur);
617
853k
  }
618
2.33k
  return 0;
619
2.33k
}
620
621
static BOOL map_iana_id(const char* iana, LPDYNAMIC_TIME_ZONE_INFORMATION tz)
622
2.33k
{
623
2.33k
  const char* winId = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_ID);
624
2.33k
  const char* winStd = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_STANDARD);
625
2.33k
  const char* winDst = TimeZoneIanaToWindows(iana, TIME_ZONE_NAME_DAYLIGHT);
626
627
2.33k
  if (winStd)
628
2.33k
    (void)ConvertUtf8ToWChar(winStd, tz->StandardName, ARRAYSIZE(tz->StandardName));
629
2.33k
  if (winDst)
630
2.33k
    (void)ConvertUtf8ToWChar(winDst, tz->DaylightName, ARRAYSIZE(tz->DaylightName));
631
2.33k
  if (winId)
632
2.33k
    (void)ConvertUtf8ToWChar(winId, tz->TimeZoneKeyName, ARRAYSIZE(tz->TimeZoneKeyName));
633
634
2.33k
  return winId != nullptr;
635
2.33k
}
636
637
static const char* weekday2str(WORD wDayOfWeek)
638
0
{
639
0
  switch (wDayOfWeek)
640
0
  {
641
0
    case 0:
642
0
      return "SUNDAY";
643
0
    case 1:
644
0
      return "MONDAY";
645
0
    case 2:
646
0
      return "TUESDAY";
647
0
    case 3:
648
0
      return "WEDNESDAY";
649
0
    case 4:
650
0
      return "THURSDAY";
651
0
    case 5:
652
0
      return "FRIDAY";
653
0
    case 6:
654
0
      return "SATURDAY";
655
0
    default:
656
0
      return "DAY-OF-MAGIC";
657
0
  }
658
0
}
659
660
static char* systemtime2str(const SYSTEMTIME* t, char* buffer, size_t len)
661
4.67k
{
662
4.67k
  const SYSTEMTIME empty = WINPR_C_ARRAY_INIT;
663
664
4.67k
  if (memcmp(t, &empty, sizeof(SYSTEMTIME)) == 0)
665
4.67k
    (void)_snprintf(buffer, len, "{ not set }");
666
0
  else
667
0
  {
668
0
    (void)_snprintf(buffer, len,
669
0
                    "{ %" PRIu16 "-%" PRIu16 "-%" PRIu16 " [%s] %" PRIu16 ":%" PRIu16
670
0
                    ":%" PRIu16 ".%" PRIu16 "}",
671
0
                    t->wYear, t->wMonth, t->wDay, weekday2str(t->wDayOfWeek), t->wHour,
672
0
                    t->wMinute, t->wSecond, t->wMilliseconds);
673
0
  }
674
4.67k
  return buffer;
675
4.67k
}
676
677
WINPR_ATTR_FORMAT_ARG(6, 7)
678
static void log_print(wLog* log, DWORD level, const char* file, const char* fkt, size_t line,
679
                      WINPR_FORMAT_ARG const char* fmt, ...)
680
28.0k
{
681
28.0k
  if (!WLog_IsLevelActive(log, level))
682
0
    return;
683
684
28.0k
  va_list ap = WINPR_C_ARRAY_INIT;
685
28.0k
  va_start(ap, fmt);
686
28.0k
  WLog_PrintTextMessageVA(log, level, line, file, fkt, fmt, ap);
687
28.0k
  va_end(ap);
688
28.0k
}
689
690
2.33k
#define log_timezone(tzif, result) log_timezone_((tzif), (result), __FILE__, __func__, __LINE__)
691
static void log_timezone_(const DYNAMIC_TIME_ZONE_INFORMATION* tzif, DWORD result, const char* file,
692
                          const char* fkt, size_t line)
693
2.33k
{
694
2.33k
  WINPR_ASSERT(tzif);
695
696
2.33k
  char buffer[130] = WINPR_C_ARRAY_INIT;
697
2.33k
  DWORD level = WLOG_TRACE;
698
2.33k
  wLog* log = WLog_Get(TAG);
699
2.33k
  log_print(log, level, file, fkt, line, "DYNAMIC_TIME_ZONE_INFORMATION {");
700
701
2.33k
  log_print(log, level, file, fkt, line, "  Bias=%" PRId32, tzif->Bias);
702
2.33k
  (void)ConvertWCharNToUtf8(tzif->StandardName, ARRAYSIZE(tzif->StandardName), buffer,
703
2.33k
                            ARRAYSIZE(buffer));
704
2.33k
  log_print(log, level, file, fkt, line, "  StandardName=%s", buffer);
705
2.33k
  log_print(log, level, file, fkt, line, "  StandardDate=%s",
706
2.33k
            systemtime2str(&tzif->StandardDate, buffer, sizeof(buffer)));
707
2.33k
  log_print(log, level, file, fkt, line, "  StandardBias=%" PRId32, tzif->StandardBias);
708
709
2.33k
  (void)ConvertWCharNToUtf8(tzif->DaylightName, ARRAYSIZE(tzif->DaylightName), buffer,
710
2.33k
                            ARRAYSIZE(buffer));
711
2.33k
  log_print(log, level, file, fkt, line, "  DaylightName=%s", buffer);
712
2.33k
  log_print(log, level, file, fkt, line, "  DaylightDate=%s",
713
2.33k
            systemtime2str(&tzif->DaylightDate, buffer, sizeof(buffer)));
714
2.33k
  log_print(log, level, file, fkt, line, "  DaylightBias=%" PRId32, tzif->DaylightBias);
715
2.33k
  (void)ConvertWCharNToUtf8(tzif->TimeZoneKeyName, ARRAYSIZE(tzif->TimeZoneKeyName), buffer,
716
2.33k
                            ARRAYSIZE(buffer));
717
2.33k
  log_print(log, level, file, fkt, line, "  TimeZoneKeyName=%s", buffer);
718
2.33k
  log_print(log, level, file, fkt, line, "  DynamicDaylightTimeDisabled=DST-%s",
719
2.33k
            tzif->DynamicDaylightTimeDisabled ? "disabled" : "enabled");
720
2.33k
  switch (result)
721
2.33k
  {
722
0
    case TIME_ZONE_ID_DAYLIGHT:
723
0
      log_print(log, level, file, fkt, line, "  DaylightDate in use");
724
0
      break;
725
2.33k
    case TIME_ZONE_ID_STANDARD:
726
2.33k
      log_print(log, level, file, fkt, line, "  StandardDate in use");
727
2.33k
      break;
728
0
    default:
729
0
      log_print(log, level, file, fkt, line, "  UnknownDate in use");
730
0
      break;
731
2.33k
  }
732
2.33k
  log_print(log, level, file, fkt, line, "}");
733
2.33k
}
734
735
DWORD GetTimeZoneInformation(LPTIME_ZONE_INFORMATION lpTimeZoneInformation)
736
1.16k
{
737
1.16k
  DYNAMIC_TIME_ZONE_INFORMATION dyn = WINPR_C_ARRAY_INIT;
738
1.16k
  DWORD rc = GetDynamicTimeZoneInformation(&dyn);
739
1.16k
  lpTimeZoneInformation->Bias = dyn.Bias;
740
1.16k
  lpTimeZoneInformation->DaylightBias = dyn.DaylightBias;
741
1.16k
  lpTimeZoneInformation->DaylightDate = dyn.DaylightDate;
742
1.16k
  lpTimeZoneInformation->StandardBias = dyn.StandardBias;
743
1.16k
  lpTimeZoneInformation->StandardDate = dyn.StandardDate;
744
1.16k
  memcpy(lpTimeZoneInformation->StandardName, dyn.StandardName,
745
1.16k
         sizeof(lpTimeZoneInformation->StandardName));
746
1.16k
  memcpy(lpTimeZoneInformation->DaylightName, dyn.DaylightName,
747
1.16k
         sizeof(lpTimeZoneInformation->DaylightName));
748
1.16k
  return rc;
749
1.16k
}
750
751
BOOL SetTimeZoneInformation(const TIME_ZONE_INFORMATION* lpTimeZoneInformation)
752
0
{
753
0
  WINPR_UNUSED(lpTimeZoneInformation);
754
0
  return FALSE;
755
0
}
756
757
BOOL SystemTimeToFileTime(const SYSTEMTIME* lpSystemTime, LPFILETIME lpFileTime)
758
0
{
759
0
  WINPR_UNUSED(lpSystemTime);
760
0
  WINPR_UNUSED(lpFileTime);
761
0
  return FALSE;
762
0
}
763
764
BOOL FileTimeToSystemTime(const FILETIME* lpFileTime, LPSYSTEMTIME lpSystemTime)
765
0
{
766
0
  WINPR_UNUSED(lpFileTime);
767
0
  WINPR_UNUSED(lpSystemTime);
768
0
  return FALSE;
769
0
}
770
771
BOOL SystemTimeToTzSpecificLocalTime(LPTIME_ZONE_INFORMATION lpTimeZone,
772
                                     LPSYSTEMTIME lpUniversalTime, LPSYSTEMTIME lpLocalTime)
773
0
{
774
0
  WINPR_UNUSED(lpTimeZone);
775
0
  WINPR_UNUSED(lpUniversalTime);
776
0
  WINPR_UNUSED(lpLocalTime);
777
0
  return FALSE;
778
0
}
779
780
BOOL TzSpecificLocalTimeToSystemTime(LPTIME_ZONE_INFORMATION lpTimeZoneInformation,
781
                                     LPSYSTEMTIME lpLocalTime, LPSYSTEMTIME lpUniversalTime)
782
0
{
783
0
  WINPR_UNUSED(lpTimeZoneInformation);
784
0
  WINPR_UNUSED(lpLocalTime);
785
0
  WINPR_UNUSED(lpUniversalTime);
786
0
  return FALSE;
787
0
}
788
789
#endif
790
791
/*
792
 * GetDynamicTimeZoneInformation is provided by the SDK if _WIN32_WINNT >= 0x0600 in SDKs above 7.1A
793
 * and incorrectly if _WIN32_WINNT >= 0x0501 in older SDKs
794
 */
795
#if !defined(_WIN32) ||                                                  \
796
    (defined(_WIN32) && (defined(NTDDI_WIN8) && _WIN32_WINNT < 0x0600 || \
797
                         !defined(NTDDI_WIN8) && _WIN32_WINNT < 0x0501)) /* Windows Vista */
798
799
typedef enum
800
{
801
  HAVE_TRANSITION_DATES = 0,
802
  HAVE_NO_STANDARD_TRANSITION_DATE = 1,
803
  HAVE_NO_DAYLIGHT_TRANSITION_DATE = 2
804
} dyn_transition_result;
805
806
static int dynamic_time_zone_from_localtime(const struct tm* local_time,
807
                                            PDYNAMIC_TIME_ZONE_INFORMATION tz)
808
2.33k
{
809
2.33k
  WINPR_ASSERT(local_time);
810
2.33k
  WINPR_ASSERT(tz);
811
2.33k
  int rc = HAVE_TRANSITION_DATES;
812
813
2.33k
  tz->Bias = get_bias(local_time, FALSE);
814
815
  /* If the current time has (or had) DST */
816
2.33k
  if (local_time->tm_isdst >= 0)
817
2.33k
  {
818
    /* DST bias is the difference between standard time and DST in minutes */
819
2.33k
    const LONG d = get_bias(local_time, TRUE);
820
2.33k
    tz->DaylightBias = -1 * (tz->Bias - d);
821
2.33k
    struct tm newyear = *local_time;
822
2.33k
    newyear.tm_mday = 0;
823
2.33k
    newyear.tm_yday = 0;
824
2.33k
    newyear.tm_wday = 0;
825
2.33k
    newyear.tm_min = 0;
826
2.33k
    newyear.tm_sec = 0;
827
2.33k
    newyear.tm_mon = 0;
828
829
    /* Searching for transition dates.
830
     *
831
     * For the current DST setting, search from the local_time, for the other one
832
     * search from beginning of the year.
833
     * We want the dates in the same year, so searching both from local_time might lead to
834
     * issues.
835
     */
836
2.33k
    const struct tm* stdtransition = local_time;
837
2.33k
    const struct tm* dsttransition = &newyear;
838
2.33k
    if (local_time->tm_isdst == 0)
839
2.33k
    {
840
2.33k
      stdtransition = &newyear;
841
2.33k
      dsttransition = local_time;
842
2.33k
    }
843
2.33k
    if (!get_transition_date(stdtransition, FALSE, &tz->StandardDate))
844
2.33k
    {
845
2.33k
      rc |= HAVE_NO_STANDARD_TRANSITION_DATE;
846
2.33k
      tz->StandardBias = 0;
847
2.33k
    }
848
2.33k
    if (!get_transition_date(dsttransition, TRUE, &tz->DaylightDate))
849
2.33k
    {
850
2.33k
      rc |= HAVE_NO_DAYLIGHT_TRANSITION_DATE;
851
2.33k
      tz->DaylightBias = 0;
852
2.33k
    }
853
2.33k
  }
854
2.33k
  return rc;
855
2.33k
}
856
857
DWORD GetDynamicTimeZoneInformation(PDYNAMIC_TIME_ZONE_INFORMATION pTimeZoneInformation)
858
2.33k
{
859
2.33k
  const char** list = nullptr;
860
2.33k
  char* tzid = nullptr;
861
2.33k
  const char* defaultName = "Client Local Time";
862
2.33k
  DWORD res = TIME_ZONE_ID_UNKNOWN;
863
2.33k
  const DYNAMIC_TIME_ZONE_INFORMATION empty = WINPR_C_ARRAY_INIT;
864
865
2.33k
  WINPR_ASSERT(pTimeZoneInformation);
866
867
2.33k
  *pTimeZoneInformation = empty;
868
2.33k
  (void)ConvertUtf8ToWChar(defaultName, pTimeZoneInformation->StandardName,
869
2.33k
                           ARRAYSIZE(pTimeZoneInformation->StandardName));
870
871
2.33k
  const time_t t = time(nullptr);
872
2.33k
  struct tm tres = WINPR_C_ARRAY_INIT;
873
2.33k
  struct tm* local_time = localtime_r(&t, &tres);
874
2.33k
  if (!local_time)
875
0
    goto out_error;
876
877
2.33k
  pTimeZoneInformation->Bias = get_bias(local_time, FALSE);
878
2.33k
  if (local_time->tm_isdst >= 0)
879
2.33k
    dynamic_time_zone_from_localtime(local_time, pTimeZoneInformation);
880
881
2.33k
  tzid = winpr_guess_time_zone();
882
2.33k
  if (!map_iana_id(tzid, pTimeZoneInformation))
883
0
  {
884
0
    const size_t len = TimeZoneIanaAbbrevGet(local_time->tm_zone, nullptr, 0);
885
0
    list = (const char**)calloc(len, sizeof(const char*));
886
0
    if (!list)
887
0
      goto out_error;
888
0
    const size_t size = TimeZoneIanaAbbrevGet(local_time->tm_zone, list, len);
889
0
    for (size_t x = 0; x < size; x++)
890
0
    {
891
0
      const char* id = list[x];
892
0
      if (map_iana_id(id, pTimeZoneInformation))
893
0
      {
894
0
        res = (local_time->tm_isdst) ? TIME_ZONE_ID_DAYLIGHT : TIME_ZONE_ID_STANDARD;
895
0
        break;
896
0
      }
897
0
    }
898
0
  }
899
2.33k
  else
900
2.33k
    res = (local_time->tm_isdst) ? TIME_ZONE_ID_DAYLIGHT : TIME_ZONE_ID_STANDARD;
901
902
2.33k
out_error:
903
2.33k
  free(tzid);
904
2.33k
  free((void*)list);
905
906
2.33k
  log_timezone(pTimeZoneInformation, res);
907
2.33k
  return res;
908
2.33k
}
909
910
BOOL SetDynamicTimeZoneInformation(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation)
911
0
{
912
0
  WINPR_UNUSED(lpTimeZoneInformation);
913
0
  return FALSE;
914
0
}
915
916
BOOL GetTimeZoneInformationForYear(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi,
917
                                   LPTIME_ZONE_INFORMATION ptzi)
918
0
{
919
0
  WINPR_UNUSED(wYear);
920
0
  WINPR_UNUSED(pdtzi);
921
0
  WINPR_UNUSED(ptzi);
922
0
  return FALSE;
923
0
}
924
925
#endif
926
927
#if !defined(_WIN32) || (defined(_WIN32) && (_WIN32_WINNT < 0x0601)) /* Windows 7 */
928
929
BOOL SystemTimeToTzSpecificLocalTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation,
930
                                       const SYSTEMTIME* lpUniversalTime, LPSYSTEMTIME lpLocalTime)
931
0
{
932
0
  WINPR_UNUSED(lpTimeZoneInformation);
933
0
  WINPR_UNUSED(lpUniversalTime);
934
0
  WINPR_UNUSED(lpLocalTime);
935
0
  return FALSE;
936
0
}
937
938
BOOL TzSpecificLocalTimeToSystemTimeEx(const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation,
939
                                       const SYSTEMTIME* lpLocalTime, LPSYSTEMTIME lpUniversalTime)
940
0
{
941
0
  WINPR_UNUSED(lpTimeZoneInformation);
942
0
  WINPR_UNUSED(lpLocalTime);
943
0
  WINPR_UNUSED(lpUniversalTime);
944
0
  return FALSE;
945
0
}
946
947
#endif
948
949
#if !defined(_WIN32)
950
951
DWORD EnumDynamicTimeZoneInformation(DWORD dwIndex,
952
                                     PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation)
953
0
{
954
0
  if (!lpTimeZoneInformation)
955
0
    return ERROR_INVALID_PARAMETER;
956
0
  const DYNAMIC_TIME_ZONE_INFORMATION empty = WINPR_C_ARRAY_INIT;
957
0
  *lpTimeZoneInformation = empty;
958
959
0
  const TimeZoneNameMapEntry* entry = TimeZoneGetAt(dwIndex);
960
0
  if (!entry)
961
0
    return ERROR_NO_MORE_ITEMS;
962
963
0
  if (entry->DaylightName)
964
0
    (void)ConvertUtf8ToWChar(entry->DaylightName, lpTimeZoneInformation->DaylightName,
965
0
                             ARRAYSIZE(lpTimeZoneInformation->DaylightName));
966
0
  if (entry->StandardName)
967
0
    (void)ConvertUtf8ToWChar(entry->StandardName, lpTimeZoneInformation->StandardName,
968
0
                             ARRAYSIZE(lpTimeZoneInformation->StandardName));
969
0
  if (entry->Id)
970
0
    (void)ConvertUtf8ToWChar(entry->Id, lpTimeZoneInformation->TimeZoneKeyName,
971
0
                             ARRAYSIZE(lpTimeZoneInformation->TimeZoneKeyName));
972
973
0
  const time_t t = time(nullptr);
974
0
  struct tm tres = WINPR_C_ARRAY_INIT;
975
976
0
  char* tzcopy = entry->Iana ? setNewAndSaveOldTZ(entry->Iana) : nullptr;
977
978
0
  struct tm* local_time = localtime_r(&t, &tres);
979
980
0
  if (local_time)
981
0
    dynamic_time_zone_from_localtime(local_time, lpTimeZoneInformation);
982
983
0
  if (entry->Iana)
984
0
    restoreSavedTZ(tzcopy);
985
986
0
  return ERROR_SUCCESS;
987
0
}
988
989
// NOLINTBEGIN(readability-non-const-parameter)
990
DWORD GetDynamicTimeZoneInformationEffectiveYears(
991
    const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, LPDWORD FirstYear, LPDWORD LastYear)
992
// NOLINTEND(readability-non-const-parameter)
993
0
{
994
0
  WINPR_UNUSED(lpTimeZoneInformation);
995
0
  WINPR_UNUSED(FirstYear);
996
0
  WINPR_UNUSED(LastYear);
997
0
  return ERROR_FILE_NOT_FOUND;
998
0
}
999
1000
#elif _WIN32_WINNT < 0x0602 /* Windows 8 */
1001
DWORD EnumDynamicTimeZoneInformation(DWORD dwIndex,
1002
                                     PDYNAMIC_TIME_ZONE_INFORMATION lpTimeZoneInformation)
1003
{
1004
  WINPR_UNUSED(dwIndex);
1005
  WINPR_UNUSED(lpTimeZoneInformation);
1006
  return ERROR_NO_MORE_ITEMS;
1007
}
1008
1009
DWORD GetDynamicTimeZoneInformationEffectiveYears(
1010
    const DYNAMIC_TIME_ZONE_INFORMATION* lpTimeZoneInformation, LPDWORD FirstYear, LPDWORD LastYear)
1011
{
1012
  WINPR_UNUSED(lpTimeZoneInformation);
1013
  WINPR_UNUSED(FirstYear);
1014
  WINPR_UNUSED(LastYear);
1015
  return ERROR_FILE_NOT_FOUND;
1016
}
1017
#endif
1018
1019
#if !defined(_WIN32)
1020
char* setNewAndSaveOldTZ(const char* val)
1021
0
{
1022
  // NOLINTBEGIN(concurrency-mt-unsafe)
1023
0
  const char* otz = getenv("TZ");
1024
0
  char* oldtz = nullptr;
1025
0
  if (otz)
1026
0
    oldtz = _strdup(otz);
1027
0
  setenv("TZ", val, 1);
1028
0
  tzset();
1029
  // NOLINTEND(concurrency-mt-unsafe)
1030
0
  return oldtz;
1031
0
}
1032
1033
void restoreSavedTZ(char* saved)
1034
0
{
1035
  // NOLINTBEGIN(concurrency-mt-unsafe)
1036
0
  if (saved)
1037
0
  {
1038
0
    setenv("TZ", saved, 1);
1039
0
    free(saved);
1040
0
  }
1041
0
  else
1042
0
    unsetenv("TZ");
1043
0
  tzset();
1044
  // NOLINTEND(concurrency-mt-unsafe)
1045
0
}
1046
#endif