-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathlocaltime.c
More file actions
3153 lines (2864 loc) · 81.1 KB
/
localtime.c
File metadata and controls
3153 lines (2864 loc) · 81.1 KB
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Convert timestamp from time_t to struct tm. */
/*
** This file is in the public domain, so clarified as of
** 1996-06-05 by Arthur David Olson.
*/
/*
** Leap second handling from Bradley White.
** POSIX.1-1988 style TZ environment variable handling from Guy Harris.
*/
/*LINTLIBRARY*/
#define LOCALTIME_IMPLEMENTATION
#include "private.h"
#include "tzdir.h"
#include "tzfile.h"
#include <fcntl.h>
#if HAVE_SYS_STAT_H
# include <sys/stat.h>
# ifndef S_ISREG
# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) /* Ancient UNIX. */
# endif
#else
struct stat { char st_ctime, st_dev, st_ino; };
# define dev_t char
# define ino_t char
# define fstat(fd, st) (memset(st, 0, sizeof *(st)), 0)
# define stat(name, st) fstat(0, st)
# define S_ISREG(mode) 1
#endif
#ifndef HAVE_STRUCT_STAT_ST_CTIM
# define HAVE_STRUCT_STAT_ST_CTIM 1
#endif
#if !defined st_ctim && defined __APPLE__ && defined __MACH__
# define st_ctim st_ctimespec
#endif
#ifndef THREAD_SAFE
# define THREAD_SAFE 0
#endif
#ifndef THREAD_RWLOCK
# define THREAD_RWLOCK 0
#endif
#ifndef THREAD_TM_MULTI
# define THREAD_TM_MULTI 0
#endif
#ifndef USE_TIMEX_T
# define USE_TIMEX_T false
#endif
#if THREAD_SAFE
# include <pthread.h>
# ifndef THREAD_PREFER_SINGLE
# define THREAD_PREFER_SINGLE 0
# endif
# if THREAD_PREFER_SINGLE
# ifndef HAVE___ISTHREADED
# if defined __FreeBSD__ || defined __OpenBSD__
# define HAVE___ISTHREADED 1
# else
# define HAVE___ISTHREADED 0
# endif
# endif
# if HAVE___ISTHREADED
extern int __isthreaded;
# else
# if !defined HAVE_SYS_SINGLE_THREADED_H && defined __has_include
# if __has_include(<sys/single_threaded.h>)
# define HAVE_SYS_SINGLE_THREADED_H 1
# else
# define HAVE_SYS_SINGLE_THREADED_H 0
# endif
# endif
# ifndef HAVE_SYS_SINGLE_THREADED_H
# if defined __GLIBC__ && 2 < __GLIBC__ + (32 <= __GLIBC_MINOR__)
# define HAVE_SYS_SINGLE_THREADED_H 1
# else
# define HAVE_SYS_SINGLE_THREADED_H 0
# endif
# endif
# if HAVE_SYS_SINGLE_THREADED_H
# include <sys/single_threaded.h>
# endif
# endif
# endif
#endif
#if !defined TM_GMTOFF || !USE_TIMEX_T
# if THREAD_SAFE
/* True if the current process might be multi-threaded,
false if it is definitely single-threaded.
If false, it will be false the next time it is called
unless the caller creates a thread in the meantime.
If true, it might become false the next time it is called
if all other threads exit in the meantime. */
static bool
is_threaded(void)
{
# if THREAD_PREFER_SINGLE && HAVE___ISTHREADED
return !!__isthreaded;
# elif THREAD_PREFER_SINGLE && HAVE_SYS_SINGLE_THREADED_H
return !__libc_single_threaded;
# else
return true;
# endif
}
# if THREAD_RWLOCK
static pthread_rwlock_t locallock = PTHREAD_RWLOCK_INITIALIZER;
static int dolock(void) { return pthread_rwlock_rdlock(&locallock); }
static void dounlock(void) { pthread_rwlock_unlock(&locallock); }
# else
static pthread_mutex_t locallock = PTHREAD_MUTEX_INITIALIZER;
static int dolock(void) { return pthread_mutex_lock(&locallock); }
static void dounlock(void) { pthread_mutex_unlock(&locallock); }
# endif
/* Get a lock. Return 0 on success, a positive errno value on failure,
negative if known to be single-threaded so no lock is needed. */
static int
lock(void)
{
if (!is_threaded())
return -1;
return dolock();
}
static void
unlock(bool threaded)
{
if (threaded)
dounlock();
}
# else
static int lock(void) { return -1; }
static void unlock(ATTRIBUTE_MAYBE_UNUSED bool threaded) { }
# endif
#endif
#if THREAD_SAFE
typedef pthread_once_t once_t;
# define ONCE_INIT PTHREAD_ONCE_INIT
#else
typedef bool once_t;
# define ONCE_INIT false
#endif
static void
once(once_t *once_control, void init_routine(void))
{
#if THREAD_SAFE
pthread_once(once_control, init_routine);
#else
if (!*once_control) {
*once_control = true;
init_routine();
}
#endif
}
enum tm_multi { LOCALTIME_TM_MULTI, GMTIME_TM_MULTI, OFFTIME_TM_MULTI };
#if THREAD_SAFE && THREAD_TM_MULTI
enum { N_TM_MULTI = OFFTIME_TM_MULTI + 1 };
static pthread_key_t tm_multi_key;
static int tm_multi_key_err;
static void
tm_multi_key_init(void)
{
tm_multi_key_err = pthread_key_create(&tm_multi_key, free);
}
#endif
/* Unless intptr_t is missing, pacify gcc -Wcast-qual on char const * exprs.
Use this carefully, as the casts disable type checking.
This is a macro so that it can be used in static initializers. */
#ifdef INTPTR_MAX
# define UNCONST(a) ((char *) (intptr_t) (a))
#else
# define UNCONST(a) ((char *) (a))
#endif
/* A signed type wider than int, so that we can add 1900 + tm_mon/12 to tm_year
without overflow. The static_assert checks that it is indeed wider
than int; if this fails on your platform please let us know. */
#if INT_MAX < LONG_MAX
typedef long iinntt;
# define IINNTT_MIN LONG_MIN
# define IINNTT_MAX LONG_MAX
#elif INT_MAX < LLONG_MAX
typedef long long iinntt;
# define IINNTT_MIN LLONG_MIN
# define IINNTT_MAX LLONG_MAX
#else
typedef intmax_t iinntt;
# define IINNTT_MIN INTMAX_MIN
# define IINNTT_MAX INTMAX_MAX
#endif
static_assert(IINNTT_MIN < INT_MIN && INT_MAX < IINNTT_MAX);
#ifndef HAVE_STRUCT_TIMESPEC
# define HAVE_STRUCT_TIMESPEC 1
#endif
#if !HAVE_STRUCT_TIMESPEC
struct timespec { time_t tv_sec; long tv_nsec; };
#endif
#if !defined CLOCK_MONOTONIC_COARSE && defined CLOCK_MONOTONIC
# define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
#endif
#ifndef CLOCK_MONOTONIC_COARSE
# undef clock_gettime
# define clock_gettime(id, t) ((t)->tv_sec = time(NULL), (t)->tv_nsec = 0, 0)
#endif
/* How many seconds to wait before checking the default TZif file again.
Negative means no checking. Default to 61 if DETECT_TZ_CHANGES
(as circa 2025 FreeBSD builds its localtime.c with -DDETECT_TZ_CHANGES),
and to -1 otherwise. */
#ifndef TZ_CHANGE_INTERVAL
# ifdef DETECT_TZ_CHANGES
# define TZ_CHANGE_INTERVAL 61
# else
# define TZ_CHANGE_INTERVAL (-1)
# endif
#endif
static_assert(TZ_CHANGE_INTERVAL < 0 || HAVE_SYS_STAT_H);
/* The change detection interval. */
#if TZ_CHANGE_INTERVAL < 0 || !defined __FreeBSD__
enum { tz_change_interval = TZ_CHANGE_INTERVAL };
#else
/* FreeBSD uses this private-but-extern var in its internal test suite. */
int __tz_change_interval = TZ_CHANGE_INTERVAL;
# define tz_change_interval __tz_change_interval
#endif
/* The type of monotonic times.
This is the system time_t, even if USE_TIMEX_T #defines time_t below. */
typedef time_t monotime_t;
/* On platforms where offtime or mktime might overflow,
strftime.c defines USE_TIMEX_T to be true and includes us.
This tells us to #define time_t to an internal type timex_t that is
wide enough so that strftime %s never suffers from integer overflow,
and to #define offtime (if TM_GMTOFF is defined) or mktime (otherwise)
to a static function that returns the redefined time_t.
It also tells us to define only data and code needed
to support the offtime or mktime variant. */
#if USE_TIMEX_T
# undef TIME_T_MIN
# undef TIME_T_MAX
# undef time_t
# define time_t timex_t
# if MKTIME_FITS_IN(LONG_MIN, LONG_MAX)
typedef long timex_t;
# define TIME_T_MIN LONG_MIN
# define TIME_T_MAX LONG_MAX
# elif MKTIME_FITS_IN(LLONG_MIN, LLONG_MAX)
typedef long long timex_t;
# define TIME_T_MIN LLONG_MIN
# define TIME_T_MAX LLONG_MAX
# else
typedef intmax_t timex_t;
# define TIME_T_MIN INTMAX_MIN
# define TIME_T_MAX INTMAX_MAX
# endif
# ifdef TM_GMTOFF
# undef timeoff
# define timeoff timex_timeoff
# undef EXTERN_TIMEOFF
# else
# undef mktime
# define mktime timex_mktime
# endif
#endif
/* Placeholders for platforms lacking openat. */
#ifndef AT_FDCWD
# define AT_FDCWD (-1) /* any negative value will do */
static int openat(int dd, char const *path, int oflag) { unreachable (); }
#endif
/* Port to platforms that lack some O_* flags. Unless otherwise
specified, the flags are standardized by POSIX. */
#ifndef O_BINARY
# define O_BINARY 0 /* MS-Windows */
#endif
#ifndef O_CLOEXEC
# define O_CLOEXEC 0
#endif
#ifndef O_CLOFORK
# define O_CLOFORK 0
#endif
#ifndef O_DIRECTORY
# define O_DIRECTORY 0
#endif
#ifndef O_IGNORE_CTTY
# define O_IGNORE_CTTY 0 /* GNU/Hurd */
#endif
#ifndef O_NOCTTY
# define O_NOCTTY 0
#endif
#ifndef O_PATH
# define O_PATH 0
#endif
#ifndef O_REGULAR
# define O_REGULAR 0
#endif
#ifndef O_RESOLVE_BENEATH
# define O_RESOLVE_BENEATH 0
#endif
#ifndef O_SEARCH
# define O_SEARCH 0
#endif
#if !HAVE_ISSETUGID
# if !defined HAVE_SYS_AUXV_H && defined __has_include
# if __has_include(<sys/auxv.h>)
# define HAVE_SYS_AUXV_H 1
# endif
# endif
# ifndef HAVE_SYS_AUXV_H
# if defined __GLIBC__ && 2 < __GLIBC__ + (19 <= __GLIBC_MINOR__)
# define HAVE_SYS_AUXV_H 1
# else
# define HAVE_SYS_AUXV_H 0
# endif
# endif
# if HAVE_SYS_AUXV_H
# include <sys/auxv.h>
# endif
/* Return 1 if the process is privileged, 0 otherwise. */
static int
issetugid(void)
{
# if HAVE_SYS_AUXV_H && defined AT_SECURE
unsigned long val;
errno = 0;
val = getauxval(AT_SECURE);
if (val || errno != ENOENT)
return !!val;
# endif
# if HAVE_GETRESUID
{
uid_t ruid, euid, suid;
gid_t rgid, egid, sgid;
if (0 <= getresuid (&ruid, &euid, &suid)) {
if ((ruid ^ euid) | (ruid ^ suid))
return 1;
if (0 <= getresgid (&rgid, &egid, &sgid))
return !!((rgid ^ egid) | (rgid ^ sgid));
}
}
# endif
# if HAVE_GETEUID
return geteuid() != getuid() || getegid() != getgid();
# else
return 0;
# endif
}
#endif
#ifndef WILDABBR
/*
** Someone might make incorrect use of a time zone abbreviation:
** 1. They might reference tzname[0] before calling tzset (explicitly
** or implicitly).
** 2. They might reference tzname[1] before calling tzset (explicitly
** or implicitly).
** 3. They might reference tzname[1] after setting to a time zone
** in which Daylight Saving Time is never observed.
** 4. They might reference tzname[0] after setting to a time zone
** in which Standard Time is never observed.
** 5. They might reference tm.TM_ZONE after calling offtime.
** What's best to do in the above cases is open to debate;
** for now, we just set things up so that in any of the five cases
** WILDABBR is used. Another possibility: initialize tzname[0] to the
** string "tzname[0] used before set", and similarly for the other cases.
** And another: initialize tzname[0] to "ERA", with an explanation in the
** manual page of what this "time zone abbreviation" means (doing this so
** that tzname[0] has the "normal" length of three characters).
*/
# define WILDABBR " "
#endif /* !defined WILDABBR */
static const char wildabbr[] = WILDABBR;
static char const etc_utc[] = "Etc/UTC";
#if !USE_TIMEX_T || defined TM_ZONE || !defined TM_GMTOFF
static char const *utc = etc_utc + sizeof "Etc/" - 1;
#endif
/*
** The DST rules to use if TZ has no rules.
** Default to US rules as of 2017-05-07.
** POSIX does not specify the default DST rules;
** for historical reasons, US rules are a common default.
*/
#ifndef TZDEFRULESTRING
# define TZDEFRULESTRING ",M3.2.0,M11.1.0"
#endif
/* If compiled with -DOPENAT_TZDIR, then when accessing a relative
name like "America/Los_Angeles", first open TZDIR (default
"/usr/share/zoneinfo") as a directory and then use the result in
openat with "America/Los_Angeles", rather than the traditional
approach of opening "/usr/share/zoneinfo/America/Los_Angeles".
Although the OPENAT_TZDIR approach is less efficient, suffers from
spurious EMFILE and ENFILE failures, and is no more secure in practice,
it is how bleeding edge FreeBSD did things from August 2025
through at least September 2025. */
#ifndef OPENAT_TZDIR
# define OPENAT_TZDIR 0
#endif
/* If compiled with -DSUPPRESS_TZDIR, do not prepend TZDIR to relative TZ.
This is intended for specialized applications only, due to its
security implications. */
#ifndef SUPPRESS_TZDIR
# define SUPPRESS_TZDIR 0
#endif
/* Limit to time zone abbreviation length in proleptic TZ strings.
This is distinct from TZ_MAX_CHARS, which limits TZif file contents.
It defaults to 254, not 255, so that desigidx_type can be an unsigned char.
unsigned char suffices for TZif files, so the only reason to increase
TZNAME_MAXIMUM is to support TZ strings specifying abbreviations
longer than 254 bytes. There is little reason to do that, though,
as strings that long are hardly "abbreviations". */
#ifndef TZNAME_MAXIMUM
# define TZNAME_MAXIMUM 254
#endif
#if TZNAME_MAXIMUM < UCHAR_MAX
typedef unsigned char desigidx_type;
#elif TZNAME_MAXIMUM < INT_MAX
typedef int desigidx_type;
#elif TZNAME_MAXIMUM < PTRDIFF_MAX
typedef ptrdiff_t desigidx_type;
#else
# error "TZNAME_MAXIMUM too large"
#endif
/* A type that can represent any 32-bit two's complement integer,
i.e., any integer in the range -2**31 .. 2**31 - 1.
Ordinarily this is int_fast32_t, but on non-C23 hosts
that are not two's complement it is int_fast64_t. */
#if INT_FAST32_MIN < -TWO_31_MINUS_1
typedef int_fast32_t int_fast32_2s;
#else
typedef int_fast64_t int_fast32_2s;
#endif
struct ttinfo { /* time type information */
int_least32_t tt_utoff; /* UT offset in seconds; in the range
-2**31 + 1 .. 2**31 - 1 */
desigidx_type tt_desigidx; /* abbreviation list index */
bool tt_isdst; /* used to set tm_isdst */
bool tt_ttisstd; /* transition is std time */
bool tt_ttisut; /* transition is UT */
};
struct lsinfo { /* leap second information */
time_t ls_trans; /* transition time (positive) */
int_fast32_2s ls_corr; /* correction to apply */
};
/* This abbreviation means local time is unspecified. */
static char const UNSPEC[] = "-00";
/* How many extra bytes are needed at the end of struct state's chars array.
This needs to be at least 1 for null termination in case the input
data isn't properly terminated, and it also needs to be big enough
for ttunspecified to work without crashing. */
enum { CHARS_EXTRA = max(sizeof UNSPEC, 2) - 1 };
/* A representation of the contents of a TZif file. Ideally this
would have no size limits; the following sizes should suffice for
practical use. This struct should not be too large, as instances
are put on the stack and stacks are relatively small on some platforms.
See tzfile.h for more about the sizes. */
struct state {
#if TZ_RUNTIME_LEAPS
int leapcnt;
#endif
int timecnt;
int typecnt;
int charcnt;
bool goback;
bool goahead;
time_t ats[TZ_MAX_TIMES];
unsigned char types[TZ_MAX_TIMES];
struct ttinfo ttis[TZ_MAX_TYPES];
char chars[max(max(TZ_MAX_CHARS + CHARS_EXTRA, sizeof "UTC"),
2 * (TZNAME_MAXIMUM + 1))];
#if TZ_RUNTIME_LEAPS
struct lsinfo lsis[TZ_MAX_LEAPS];
#endif
};
static int
leapcount(ATTRIBUTE_MAYBE_UNUSED struct state const *sp)
{
#if TZ_RUNTIME_LEAPS
return sp->leapcnt;
#else
return 0;
#endif
}
static void
set_leapcount(ATTRIBUTE_MAYBE_UNUSED struct state *sp,
ATTRIBUTE_MAYBE_UNUSED int leapcnt)
{
#if TZ_RUNTIME_LEAPS
sp->leapcnt = leapcnt;
#endif
}
static struct lsinfo
lsinfo(ATTRIBUTE_MAYBE_UNUSED struct state const *sp,
ATTRIBUTE_MAYBE_UNUSED int i)
{
#if TZ_RUNTIME_LEAPS
return sp->lsis[i];
#else
unreachable();
#endif
}
static void
set_lsinfo(ATTRIBUTE_MAYBE_UNUSED struct state *sp,
ATTRIBUTE_MAYBE_UNUSED int i,
ATTRIBUTE_MAYBE_UNUSED struct lsinfo lsinfo)
{
#if TZ_RUNTIME_LEAPS
sp->lsis[i] = lsinfo;
#endif
}
enum r_type {
JULIAN_DAY, /* Jn = Julian day */
DAY_OF_YEAR, /* n = day of year */
MONTH_NTH_DAY_OF_WEEK /* Mm.n.d = month, week, day of week */
};
struct rule {
enum r_type r_type; /* type of rule */
int r_day; /* day number of rule */
int r_week; /* week number of rule */
int r_mon; /* month number of rule */
int_fast32_t r_time; /* transition time of rule */
};
static struct tm *gmtsub(struct state const *, time_t const *, int_fast32_t,
struct tm *);
static bool increment_overflow(int *, int);
static bool increment_overflow_time(time_t *, int_fast32_2s);
static int_fast32_2s leapcorr(struct state const *, time_t);
static struct tm *timesub(time_t const *, int_fast32_t, struct state const *,
struct tm *);
static bool tzparse(char const *, struct state *, struct state const *);
#ifndef ALL_STATE
# define ALL_STATE 0
#endif
#if ALL_STATE
static struct state * lclptr;
static struct state * gmtptr;
#else
static struct state lclmem;
static struct state gmtmem;
static struct state *const lclptr = &lclmem;
static struct state *const gmtptr = &gmtmem;
#endif /* State Farm */
/* Maximum number of bytes in an efficiently-handled TZ string.
Longer strings work, albeit less efficiently. */
#ifndef TZ_STRLEN_MAX
# define TZ_STRLEN_MAX 255
#endif /* !defined TZ_STRLEN_MAX */
#if !USE_TIMEX_T || !defined TM_GMTOFF
static char lcl_TZname[TZ_STRLEN_MAX + 1];
static int lcl_is_set;
#endif
/*
** Section 4.12.3 of X3.159-1989 requires that
** Except for the strftime function, these functions [asctime,
** ctime, gmtime, localtime] return values in one of two static
** objects: a broken-down time structure and an array of char.
** Thanks to Paul Eggert for noting this.
**
** Although this requirement was removed in C99 it is still present in POSIX.
** Follow the requirement if SUPPORT_C89, even though this is more likely to
** trigger latent bugs in programs.
*/
#if !USE_TIMEX_T
# if SUPPORT_C89
static struct tm tm;
# endif
# if 2 <= HAVE_TZNAME + TZ_TIME_T
char *tzname[2] = { UNCONST(wildabbr), UNCONST(wildabbr) };
# endif
# if 2 <= USG_COMPAT + TZ_TIME_T
long timezone;
int daylight;
# endif
# if 2 <= ALTZONE + TZ_TIME_T
long altzone;
# endif
#endif
/* Initialize *S to a value based on UTOFF, ISDST, and DESIGIDX. */
static void
init_ttinfo(struct ttinfo *s, int_fast32_t utoff, bool isdst,
desigidx_type desigidx)
{
s->tt_utoff = utoff;
s->tt_isdst = isdst;
s->tt_desigidx = desigidx;
s->tt_ttisstd = false;
s->tt_ttisut = false;
}
/* Return true if SP's time type I does not specify local time. */
static bool
ttunspecified(struct state const *sp, int i)
{
char const *abbr = &sp->chars[sp->ttis[i].tt_desigidx];
/* memcmp is likely faster than strcmp, and is safe due to CHARS_EXTRA. */
return memcmp(abbr, UNSPEC, sizeof UNSPEC) == 0;
}
static int_fast32_2s
detzcode(const char *const codep)
{
register int i;
int_fast32_2s
maxval = TWO_31_MINUS_1,
minval = -1 - maxval,
result;
result = codep[0] & 0x7f;
for (i = 1; i < 4; ++i)
result = (result << 8) | (codep[i] & 0xff);
if (codep[0] & 0x80) {
/* Do two's-complement negation even on non-two's-complement machines.
This cannot overflow, as int_fast32_2s is wide enough. */
result += minval;
}
return result;
}
static int_fast64_t
detzcode64(const char *const codep)
{
register int_fast64_t result;
register int i;
int_fast64_t one = 1;
int_fast64_t halfmaxval = one << (64 - 2);
int_fast64_t maxval = halfmaxval - 1 + halfmaxval;
int_fast64_t minval = -TWOS_COMPLEMENT(int_fast64_t) - maxval;
result = codep[0] & 0x7f;
for (i = 1; i < 8; ++i)
result = (result << 8) | (codep[i] & 0xff);
if (codep[0] & 0x80) {
/* Do two's-complement negation even on non-two's-complement machines.
If the result would be minval - 1, return minval. */
result -= !TWOS_COMPLEMENT(int_fast64_t) && result != 0;
result += minval;
}
return result;
}
#if !USE_TIMEX_T || !defined TM_GMTOFF
static void
update_tzname_etc(struct state const *sp, struct ttinfo const *ttisp)
{
# if HAVE_TZNAME
tzname[ttisp->tt_isdst] = UNCONST(&sp->chars[ttisp->tt_desigidx]);
# endif
# if USG_COMPAT
if (!ttisp->tt_isdst)
timezone = - ttisp->tt_utoff;
# endif
# if ALTZONE
if (ttisp->tt_isdst)
altzone = - ttisp->tt_utoff;
# endif
}
/* If STDDST_MASK indicates that SP's TYPE provides useful info,
update tzname, timezone, and/or altzone and return STDDST_MASK,
diminished by the provided info if it is a specified local time.
Otherwise, return STDDST_MASK. See settzname for STDDST_MASK. */
static int
may_update_tzname_etc(int stddst_mask, struct state *sp, int type)
{
struct ttinfo *ttisp = &sp->ttis[type];
int this_bit = 1 << ttisp->tt_isdst;
if (stddst_mask & this_bit) {
update_tzname_etc(sp, ttisp);
if (!ttunspecified(sp, type))
return stddst_mask & ~this_bit;
}
return stddst_mask;
}
static void
settzname(void)
{
register struct state * const sp = lclptr;
register int i;
/* If STDDST_MASK & 1 we need info about a standard time.
If STDDST_MASK & 2 we need info about a daylight saving time.
When STDDST_MASK becomes zero we can stop looking. */
int stddst_mask = 0;
# if HAVE_TZNAME
tzname[0] = tzname[1] = UNCONST(sp ? wildabbr : utc);
stddst_mask = 3;
# endif
# if USG_COMPAT
timezone = 0;
stddst_mask = 3;
# endif
# if ALTZONE
altzone = 0;
stddst_mask |= 2;
# endif
/*
** And to get the latest time zone abbreviations into tzname. . .
*/
if (sp) {
for (i = sp->timecnt - 1; stddst_mask && 0 <= i; i--)
stddst_mask = may_update_tzname_etc(stddst_mask, sp, sp->types[i]);
for (i = sp->typecnt - 1; stddst_mask && 0 <= i; i--)
stddst_mask = may_update_tzname_etc(stddst_mask, sp, i);
}
# if USG_COMPAT
daylight = stddst_mask >> 1 ^ 1;
# endif
}
/* Replace bogus characters in time zone abbreviations.
Return 0 on success, an errno value if a time zone abbreviation is
too long. */
static int
scrub_abbrs(struct state *sp)
{
int i;
/* Reject overlong abbreviations. */
for (i = 0; i < sp->charcnt - (TZNAME_MAXIMUM + 1); ) {
int len = strnlen(&sp->chars[i], TZNAME_MAXIMUM + 1);
if (TZNAME_MAXIMUM < len)
return EOVERFLOW;
i += len + 1;
}
/* Replace bogus characters. */
for (i = 0; i < sp->charcnt; ++i)
switch (sp->chars[i]) {
case '\0':
case '+': case '-': case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case ':':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
break;
default:
sp->chars[i] = '_';
break;
}
return 0;
}
#endif
/* Return true if the TZif file with descriptor FD changed,
or may have changed, since the last time we were called.
Return false if it did not change.
If *ST is valid it is the file's current status;
otherwise, update *ST to the status if possible. */
static bool
tzfile_changed(int fd, struct stat *st)
{
/* If old_ctim.tv_sec, these variables hold the corresponding part
of the file's metadata the last time this function was called. */
static struct timespec old_ctim;
static dev_t old_dev;
static ino_t old_ino;
if (!st->st_ctime && fstat(fd, st) < 0) {
/* We do not know the file's state, so reset. */
old_ctim.tv_sec = 0;
return true;
} else {
/* Use the change time, as it changes more reliably; mod time can
be set back with futimens etc. Use subsecond timestamp
resolution if available, as this can help distinguish files on
non-POSIX platforms where st_dev and st_ino are unreliable. */
struct timespec ctim;
#if HAVE_STRUCT_STAT_ST_CTIM
ctim = st->st_ctim;
#else
ctim.tv_sec = st->st_ctime;
ctim.tv_nsec = 0;
#endif
if ((ctim.tv_sec ^ old_ctim.tv_sec) | (ctim.tv_nsec ^ old_ctim.tv_nsec)
| (st->st_dev ^ old_dev) | (st->st_ino ^ old_ino)) {
old_ctim = ctim;
old_dev = st->st_dev;
old_ino = st->st_ino;
return true;
}
return false;
}
}
/* Input buffer for data read from a compiled tz file. */
union input_buffer {
/* The first part of the buffer, interpreted as a header. */
struct tzhead tzhead;
/* The entire buffer. Ideally this would have no size limits;
the following should suffice for practical use. */
char buf[2 * sizeof(struct tzhead) + 2 * sizeof(struct state)
+ 4 * TZ_MAX_TIMES];
};
/* TZDIR with a trailing '/'. It is null-terminated if OPENAT_TZDIR. */
#if !OPENAT_TZDIR
ATTRIBUTE_NONSTRING
#endif
static char const tzdirslash[sizeof TZDIR + OPENAT_TZDIR] = TZDIR "/";
enum { tzdirslashlen = sizeof TZDIR };
#ifdef PATH_MAX
static_assert(tzdirslashlen <= PATH_MAX); /* Sanity check; assumed below. */
#endif
/* Local storage needed for 'tzloadbody'. */
union local_storage {
/* The results of analyzing the file's contents after it is opened. */
struct file_analysis {
/* The input buffer. */
union input_buffer u;
/* A temporary state used for parsing a TZ string in the file. */
struct state st;
} u;
#if defined PATH_MAX && !OPENAT_TZDIR && !SUPPRESS_TZDIR
/* The name of the file to be opened. */
char fullname[PATH_MAX];
#endif
};
/* These tzload flags can be ORed together, and fit into 'char'. */
enum { TZLOAD_FROMENV = 1 }; /* The TZ string came from the environment. */
enum { TZLOAD_TZSTRING = 2 }; /* Read any newline-surrounded TZ string. */
enum { TZLOAD_TZDIR_SUB = 4 }; /* TZ should be a file under TZDIR. */
/* Load tz data from the file named NAME into *SP. Respect TZLOADFLAGS.
Use **LSPP for temporary storage. Return 0 on
success, an errno value on failure. */
static int
tzloadbody(char const *name, struct state *sp, char tzloadflags,
union local_storage **lspp)
{
register int i;
register int fid;
register int stored;
register ssize_t nread;
char const *relname;
union local_storage *lsp = *lspp;
union input_buffer *up;
register int tzheadsize = sizeof(struct tzhead);
int dd = AT_FDCWD;
int oflags = (O_RDONLY | O_BINARY | O_CLOEXEC | O_CLOFORK
| O_IGNORE_CTTY | O_NOCTTY | O_REGULAR);
int err;
struct stat st;
st.st_ctime = 0;
sp->goback = sp->goahead = false;
if (! name) {
name = TZDEFAULT;
if (! name)
return EINVAL;
}
if (name[0] == ':')
++name;
relname = name;
/* If the program is privileged, NAME is TZDEFAULT or
subsidiary to TZDIR. Also, NAME is not a device. */
if (name[0] == '/' && strcmp(name, TZDEFAULT) != 0) {
if (!SUPPRESS_TZDIR
&& strncmp(relname, tzdirslash, tzdirslashlen) == 0)
for (relname += tzdirslashlen; *relname == '/'; relname++)
continue;
else if (issetugid())
return ENOTCAPABLE;
else if (!O_REGULAR) {
/* Check for devices, as their mere opening could have
unwanted side effects. Though racy, there is no
portable way to fix the races. This check is needed
only for files not otherwise known to be non-devices. */
if (stat(name, &st) < 0)
return errno;
if (!S_ISREG(st.st_mode))
return EINVAL;
}
}
if (relname[0] != '/') {
if (!OPENAT_TZDIR || !O_RESOLVE_BENEATH) {
/* Fail if a relative name contains a non-terminal ".." component,
as such a name could read a non-directory outside TZDIR
when AT_FDCWD and O_RESOLVE_BENEATH are not available. */
char const *component;
for (component = relname; component[0]; component++)
if (component[0] == '.' && component[1] == '.'
&& component[2] == '/'
&& (component == relname || component[-1] == '/'))
return ENOTCAPABLE;
}
if (OPENAT_TZDIR && !SUPPRESS_TZDIR) {
/* Prefer O_SEARCH or O_PATH if available;
O_RDONLY should be OK too, as TZDIR is invariably readable.
O_DIRECTORY should be redundant but might help
on old platforms that mishandle trailing '/'. */
dd = open(tzdirslash,
((O_SEARCH ? O_SEARCH : O_PATH ? O_PATH : O_RDONLY)
| O_BINARY | O_CLOEXEC | O_CLOFORK | O_DIRECTORY));
if (dd < 0)
return errno;
oflags |= O_RESOLVE_BENEATH;
}
}
if (!OPENAT_TZDIR && !SUPPRESS_TZDIR && name[0] != '/') {
char *cp;
size_t fullnamesize;
#ifdef PATH_MAX
size_t namesizemax = PATH_MAX - tzdirslashlen;
size_t namelen = strnlen (name, namesizemax);
if (namesizemax <= namelen)
return ENAMETOOLONG;
#else
size_t namelen = strlen (name);
#endif
fullnamesize = tzdirslashlen + namelen + 1;
/* Create a string "TZDIR/NAME". Using sprintf here
would pull in stdio (and would fail if the
resulting string length exceeded INT_MAX!). */