blob: bee59b8d2ae0cc63503dd56b6a2b952c7db85d13 [file] [log] [blame]
Paul Ganssle62972d92020-05-16 04:20:06 -04001#include "Python.h"
2#include "structmember.h"
3
4#include <ctype.h>
5#include <stddef.h>
6#include <stdint.h>
7
8#include "datetime.h"
9
10// Imports
11static PyObject *io_open = NULL;
12static PyObject *_tzpath_find_tzfile = NULL;
13static PyObject *_common_mod = NULL;
14
15typedef struct TransitionRuleType TransitionRuleType;
16typedef struct StrongCacheNode StrongCacheNode;
17
18typedef struct {
19 PyObject *utcoff;
20 PyObject *dstoff;
21 PyObject *tzname;
22 long utcoff_seconds;
23} _ttinfo;
24
25typedef struct {
26 _ttinfo std;
27 _ttinfo dst;
28 int dst_diff;
29 TransitionRuleType *start;
30 TransitionRuleType *end;
31 unsigned char std_only;
32} _tzrule;
33
34typedef struct {
35 PyDateTime_TZInfo base;
36 PyObject *key;
37 PyObject *file_repr;
38 PyObject *weakreflist;
Pablo Galindoe4799b92020-05-27 21:48:12 +010039 size_t num_transitions;
40 size_t num_ttinfos;
Paul Ganssle62972d92020-05-16 04:20:06 -040041 int64_t *trans_list_utc;
42 int64_t *trans_list_wall[2];
43 _ttinfo **trans_ttinfos; // References to the ttinfo for each transition
44 _ttinfo *ttinfo_before;
45 _tzrule tzrule_after;
46 _ttinfo *_ttinfos; // Unique array of ttinfos for ease of deallocation
47 unsigned char fixed_offset;
48 unsigned char source;
49} PyZoneInfo_ZoneInfo;
50
51struct TransitionRuleType {
52 int64_t (*year_to_timestamp)(TransitionRuleType *, int);
53};
54
55typedef struct {
56 TransitionRuleType base;
57 uint8_t month;
58 uint8_t week;
59 uint8_t day;
60 int8_t hour;
61 int8_t minute;
62 int8_t second;
63} CalendarRule;
64
65typedef struct {
66 TransitionRuleType base;
67 uint8_t julian;
68 unsigned int day;
69 int8_t hour;
70 int8_t minute;
71 int8_t second;
72} DayRule;
73
74struct StrongCacheNode {
75 StrongCacheNode *next;
76 StrongCacheNode *prev;
77 PyObject *key;
78 PyObject *zone;
79};
80
81static PyTypeObject PyZoneInfo_ZoneInfoType;
82
83// Globals
84static PyObject *TIMEDELTA_CACHE = NULL;
85static PyObject *ZONEINFO_WEAK_CACHE = NULL;
86static StrongCacheNode *ZONEINFO_STRONG_CACHE = NULL;
87static size_t ZONEINFO_STRONG_CACHE_MAX_SIZE = 8;
88
89static _ttinfo NO_TTINFO = {NULL, NULL, NULL, 0};
90
91// Constants
92static const int EPOCHORDINAL = 719163;
93static int DAYS_IN_MONTH[] = {
94 -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
95};
96
97static int DAYS_BEFORE_MONTH[] = {
98 -1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
99};
100
101static const int SOURCE_NOCACHE = 0;
102static const int SOURCE_CACHE = 1;
103static const int SOURCE_FILE = 2;
104
105// Forward declarations
106static int
107load_data(PyZoneInfo_ZoneInfo *self, PyObject *file_obj);
108static void
109utcoff_to_dstoff(size_t *trans_idx, long *utcoffs, long *dstoffs,
110 unsigned char *isdsts, size_t num_transitions,
111 size_t num_ttinfos);
112static int
113ts_to_local(size_t *trans_idx, int64_t *trans_utc, long *utcoff,
114 int64_t *trans_local[2], size_t num_ttinfos,
115 size_t num_transitions);
116
117static int
118parse_tz_str(PyObject *tz_str_obj, _tzrule *out);
119
Pablo Galindoe4799b92020-05-27 21:48:12 +0100120static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -0400121parse_abbr(const char *const p, PyObject **abbr);
Pablo Galindoe4799b92020-05-27 21:48:12 +0100122static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -0400123parse_tz_delta(const char *const p, long *total_seconds);
Pablo Galindoe4799b92020-05-27 21:48:12 +0100124static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -0400125parse_transition_time(const char *const p, int8_t *hour, int8_t *minute,
126 int8_t *second);
Pablo Galindoe4799b92020-05-27 21:48:12 +0100127static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -0400128parse_transition_rule(const char *const p, TransitionRuleType **out);
129
130static _ttinfo *
131find_tzrule_ttinfo(_tzrule *rule, int64_t ts, unsigned char fold, int year);
132static _ttinfo *
133find_tzrule_ttinfo_fromutc(_tzrule *rule, int64_t ts, int year,
134 unsigned char *fold);
135
136static int
137build_ttinfo(long utcoffset, long dstoffset, PyObject *tzname, _ttinfo *out);
138static void
139xdecref_ttinfo(_ttinfo *ttinfo);
140static int
141ttinfo_eq(const _ttinfo *const tti0, const _ttinfo *const tti1);
142
143static int
144build_tzrule(PyObject *std_abbr, PyObject *dst_abbr, long std_offset,
145 long dst_offset, TransitionRuleType *start,
146 TransitionRuleType *end, _tzrule *out);
147static void
148free_tzrule(_tzrule *tzrule);
149
150static PyObject *
151load_timedelta(long seconds);
152
153static int
154get_local_timestamp(PyObject *dt, int64_t *local_ts);
155static _ttinfo *
156find_ttinfo(PyZoneInfo_ZoneInfo *self, PyObject *dt);
157
158static int
159ymd_to_ord(int y, int m, int d);
160static int
161is_leap_year(int year);
162
163static size_t
164_bisect(const int64_t value, const int64_t *arr, size_t size);
165
166static void
167eject_from_strong_cache(const PyTypeObject *const type, PyObject *key);
168static void
169clear_strong_cache(const PyTypeObject *const type);
170static void
171update_strong_cache(const PyTypeObject *const type, PyObject *key,
172 PyObject *zone);
173static PyObject *
174zone_from_strong_cache(const PyTypeObject *const type, PyObject *key);
175
176static PyObject *
177zoneinfo_new_instance(PyTypeObject *type, PyObject *key)
178{
179 PyObject *file_obj = NULL;
180 PyObject *file_path = NULL;
181
182 file_path = PyObject_CallFunctionObjArgs(_tzpath_find_tzfile, key, NULL);
183 if (file_path == NULL) {
184 return NULL;
185 }
186 else if (file_path == Py_None) {
187 file_obj = PyObject_CallMethod(_common_mod, "load_tzdata", "O", key);
188 if (file_obj == NULL) {
189 Py_DECREF(file_path);
190 return NULL;
191 }
192 }
193
194 PyObject *self = (PyObject *)(type->tp_alloc(type, 0));
195 if (self == NULL) {
196 goto error;
197 }
198
199 if (file_obj == NULL) {
200 file_obj = PyObject_CallFunction(io_open, "Os", file_path, "rb");
201 if (file_obj == NULL) {
202 goto error;
203 }
204 }
205
206 if (load_data((PyZoneInfo_ZoneInfo *)self, file_obj)) {
207 goto error;
208 }
209
210 PyObject *rv = PyObject_CallMethod(file_obj, "close", NULL);
211 Py_DECREF(file_obj);
212 file_obj = NULL;
213 if (rv == NULL) {
214 goto error;
215 }
216 Py_DECREF(rv);
217
218 ((PyZoneInfo_ZoneInfo *)self)->key = key;
219 Py_INCREF(key);
220
221 goto cleanup;
222error:
223 Py_XDECREF(self);
224 self = NULL;
225cleanup:
226 if (file_obj != NULL) {
Zackery Spytzeca25492020-07-20 06:51:26 -0600227 PyObject *exc, *val, *tb;
228 PyErr_Fetch(&exc, &val, &tb);
Paul Ganssle62972d92020-05-16 04:20:06 -0400229 PyObject *tmp = PyObject_CallMethod(file_obj, "close", NULL);
Zackery Spytzeca25492020-07-20 06:51:26 -0600230 _PyErr_ChainExceptions(exc, val, tb);
231 if (tmp == NULL) {
232 Py_CLEAR(self);
233 }
234 Py_XDECREF(tmp);
Paul Ganssle62972d92020-05-16 04:20:06 -0400235 Py_DECREF(file_obj);
236 }
237 Py_DECREF(file_path);
238 return self;
239}
240
241static PyObject *
242get_weak_cache(PyTypeObject *type)
243{
244 if (type == &PyZoneInfo_ZoneInfoType) {
245 return ZONEINFO_WEAK_CACHE;
246 }
247 else {
248 PyObject *cache =
249 PyObject_GetAttrString((PyObject *)type, "_weak_cache");
250 // We are assuming that the type lives at least as long as the function
251 // that calls get_weak_cache, and that it holds a reference to the
252 // cache, so we'll return a "borrowed reference".
253 Py_XDECREF(cache);
254 return cache;
255 }
256}
257
258static PyObject *
259zoneinfo_new(PyTypeObject *type, PyObject *args, PyObject *kw)
260{
261 PyObject *key = NULL;
262 static char *kwlist[] = {"key", NULL};
263 if (PyArg_ParseTupleAndKeywords(args, kw, "O", kwlist, &key) == 0) {
264 return NULL;
265 }
266
267 PyObject *instance = zone_from_strong_cache(type, key);
268 if (instance != NULL) {
269 return instance;
270 }
271
272 PyObject *weak_cache = get_weak_cache(type);
273 instance = PyObject_CallMethod(weak_cache, "get", "O", key, Py_None);
274 if (instance == NULL) {
275 return NULL;
276 }
277
278 if (instance == Py_None) {
279 Py_DECREF(instance);
280 PyObject *tmp = zoneinfo_new_instance(type, key);
281 if (tmp == NULL) {
282 return NULL;
283 }
284
285 instance =
286 PyObject_CallMethod(weak_cache, "setdefault", "OO", key, tmp);
Paul Ganssle62972d92020-05-16 04:20:06 -0400287 Py_DECREF(tmp);
Paul Ganssle62972d92020-05-16 04:20:06 -0400288 if (instance == NULL) {
289 return NULL;
290 }
Gregory P. Smithd780fa72020-06-22 00:39:28 -0700291 ((PyZoneInfo_ZoneInfo *)instance)->source = SOURCE_CACHE;
Paul Ganssle62972d92020-05-16 04:20:06 -0400292 }
293
294 update_strong_cache(type, key, instance);
295 return instance;
296}
297
298static void
299zoneinfo_dealloc(PyObject *obj_self)
300{
301 PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
302
303 if (self->weakreflist != NULL) {
304 PyObject_ClearWeakRefs(obj_self);
305 }
306
307 if (self->trans_list_utc != NULL) {
308 PyMem_Free(self->trans_list_utc);
309 }
310
311 for (size_t i = 0; i < 2; i++) {
312 if (self->trans_list_wall[i] != NULL) {
313 PyMem_Free(self->trans_list_wall[i]);
314 }
315 }
316
317 if (self->_ttinfos != NULL) {
318 for (size_t i = 0; i < self->num_ttinfos; ++i) {
319 xdecref_ttinfo(&(self->_ttinfos[i]));
320 }
321 PyMem_Free(self->_ttinfos);
322 }
323
324 if (self->trans_ttinfos != NULL) {
325 PyMem_Free(self->trans_ttinfos);
326 }
327
328 free_tzrule(&(self->tzrule_after));
329
330 Py_XDECREF(self->key);
331 Py_XDECREF(self->file_repr);
332
333 Py_TYPE(self)->tp_free((PyObject *)self);
334}
335
336static PyObject *
337zoneinfo_from_file(PyTypeObject *type, PyObject *args, PyObject *kwargs)
338{
339 PyObject *file_obj = NULL;
340 PyObject *file_repr = NULL;
341 PyObject *key = Py_None;
342 PyZoneInfo_ZoneInfo *self = NULL;
343
344 static char *kwlist[] = {"", "key", NULL};
345 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &file_obj,
346 &key)) {
347 return NULL;
348 }
349
350 PyObject *obj_self = (PyObject *)(type->tp_alloc(type, 0));
351 self = (PyZoneInfo_ZoneInfo *)obj_self;
352 if (self == NULL) {
353 return NULL;
354 }
355
356 file_repr = PyUnicode_FromFormat("%R", file_obj);
357 if (file_repr == NULL) {
358 goto error;
359 }
360
361 if (load_data(self, file_obj)) {
362 goto error;
363 }
364
365 self->source = SOURCE_FILE;
366 self->file_repr = file_repr;
367 self->key = key;
368 Py_INCREF(key);
369
370 return obj_self;
371error:
372 Py_XDECREF(file_repr);
373 Py_XDECREF(self);
374 return NULL;
375}
376
377static PyObject *
378zoneinfo_no_cache(PyTypeObject *cls, PyObject *args, PyObject *kwargs)
379{
380 static char *kwlist[] = {"key", NULL};
381 PyObject *key = NULL;
382 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", kwlist, &key)) {
383 return NULL;
384 }
385
386 PyObject *out = zoneinfo_new_instance(cls, key);
387 if (out != NULL) {
388 ((PyZoneInfo_ZoneInfo *)out)->source = SOURCE_NOCACHE;
389 }
390
391 return out;
392}
393
394static PyObject *
395zoneinfo_clear_cache(PyObject *cls, PyObject *args, PyObject *kwargs)
396{
397 PyObject *only_keys = NULL;
398 static char *kwlist[] = {"only_keys", NULL};
399
400 if (!(PyArg_ParseTupleAndKeywords(args, kwargs, "|$O", kwlist,
401 &only_keys))) {
402 return NULL;
403 }
404
405 PyTypeObject *type = (PyTypeObject *)cls;
406 PyObject *weak_cache = get_weak_cache(type);
407
408 if (only_keys == NULL || only_keys == Py_None) {
409 PyObject *rv = PyObject_CallMethod(weak_cache, "clear", NULL);
410 if (rv != NULL) {
411 Py_DECREF(rv);
412 }
413
414 clear_strong_cache(type);
Paul Ganssle62972d92020-05-16 04:20:06 -0400415 }
416 else {
417 PyObject *item = NULL;
418 PyObject *pop = PyUnicode_FromString("pop");
419 if (pop == NULL) {
420 return NULL;
421 }
422
423 PyObject *iter = PyObject_GetIter(only_keys);
424 if (iter == NULL) {
425 Py_DECREF(pop);
426 return NULL;
427 }
428
429 while ((item = PyIter_Next(iter))) {
430 // Remove from strong cache
431 eject_from_strong_cache(type, item);
432
433 // Remove from weak cache
434 PyObject *tmp = PyObject_CallMethodObjArgs(weak_cache, pop, item,
435 Py_None, NULL);
436
437 Py_DECREF(item);
438 if (tmp == NULL) {
439 break;
440 }
441 Py_DECREF(tmp);
442 }
443 Py_DECREF(iter);
444 Py_DECREF(pop);
445 }
446
447 if (PyErr_Occurred()) {
448 return NULL;
449 }
450
451 Py_RETURN_NONE;
452}
453
454static PyObject *
455zoneinfo_utcoffset(PyObject *self, PyObject *dt)
456{
457 _ttinfo *tti = find_ttinfo((PyZoneInfo_ZoneInfo *)self, dt);
458 if (tti == NULL) {
459 return NULL;
460 }
461 Py_INCREF(tti->utcoff);
462 return tti->utcoff;
463}
464
465static PyObject *
466zoneinfo_dst(PyObject *self, PyObject *dt)
467{
468 _ttinfo *tti = find_ttinfo((PyZoneInfo_ZoneInfo *)self, dt);
469 if (tti == NULL) {
470 return NULL;
471 }
472 Py_INCREF(tti->dstoff);
473 return tti->dstoff;
474}
475
476static PyObject *
477zoneinfo_tzname(PyObject *self, PyObject *dt)
478{
479 _ttinfo *tti = find_ttinfo((PyZoneInfo_ZoneInfo *)self, dt);
480 if (tti == NULL) {
481 return NULL;
482 }
483 Py_INCREF(tti->tzname);
484 return tti->tzname;
485}
486
Zackery Spytz2e4dd332020-09-23 12:43:45 -0600487#define GET_DT_TZINFO PyDateTime_DATE_GET_TZINFO
Paul Ganssle62972d92020-05-16 04:20:06 -0400488
489static PyObject *
490zoneinfo_fromutc(PyObject *obj_self, PyObject *dt)
491{
492 if (!PyDateTime_Check(dt)) {
493 PyErr_SetString(PyExc_TypeError,
494 "fromutc: argument must be a datetime");
495 return NULL;
496 }
497 if (GET_DT_TZINFO(dt) != obj_self) {
498 PyErr_SetString(PyExc_ValueError,
499 "fromutc: dt.tzinfo "
500 "is not self");
501 return NULL;
502 }
503
504 PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
505
506 int64_t timestamp;
507 if (get_local_timestamp(dt, &timestamp)) {
508 return NULL;
509 }
510 size_t num_trans = self->num_transitions;
511
512 _ttinfo *tti = NULL;
513 unsigned char fold = 0;
514
515 if (num_trans >= 1 && timestamp < self->trans_list_utc[0]) {
516 tti = self->ttinfo_before;
517 }
518 else if (num_trans == 0 ||
519 timestamp > self->trans_list_utc[num_trans - 1]) {
520 tti = find_tzrule_ttinfo_fromutc(&(self->tzrule_after), timestamp,
521 PyDateTime_GET_YEAR(dt), &fold);
522
523 // Immediately after the last manual transition, the fold/gap is
524 // between self->trans_ttinfos[num_transitions - 1] and whatever
525 // ttinfo applies immediately after the last transition, not between
526 // the STD and DST rules in the tzrule_after, so we may need to
527 // adjust the fold value.
528 if (num_trans) {
529 _ttinfo *tti_prev = NULL;
530 if (num_trans == 1) {
531 tti_prev = self->ttinfo_before;
532 }
533 else {
534 tti_prev = self->trans_ttinfos[num_trans - 2];
535 }
536 int64_t diff = tti_prev->utcoff_seconds - tti->utcoff_seconds;
537 if (diff > 0 &&
538 timestamp < (self->trans_list_utc[num_trans - 1] + diff)) {
539 fold = 1;
540 }
541 }
542 }
543 else {
544 size_t idx = _bisect(timestamp, self->trans_list_utc, num_trans);
545 _ttinfo *tti_prev = NULL;
546
547 if (idx >= 2) {
548 tti_prev = self->trans_ttinfos[idx - 2];
549 tti = self->trans_ttinfos[idx - 1];
550 }
551 else {
552 tti_prev = self->ttinfo_before;
553 tti = self->trans_ttinfos[0];
554 }
555
556 // Detect fold
557 int64_t shift =
558 (int64_t)(tti_prev->utcoff_seconds - tti->utcoff_seconds);
559 if (shift > (timestamp - self->trans_list_utc[idx - 1])) {
560 fold = 1;
561 }
562 }
563
564 PyObject *tmp = PyNumber_Add(dt, tti->utcoff);
565 if (tmp == NULL) {
566 return NULL;
567 }
568
569 if (fold) {
570 if (PyDateTime_CheckExact(tmp)) {
571 ((PyDateTime_DateTime *)tmp)->fold = 1;
572 dt = tmp;
573 }
574 else {
575 PyObject *replace = PyObject_GetAttrString(tmp, "replace");
576 PyObject *args = PyTuple_New(0);
577 PyObject *kwargs = PyDict_New();
578
579 Py_DECREF(tmp);
580 if (args == NULL || kwargs == NULL || replace == NULL) {
581 Py_XDECREF(args);
582 Py_XDECREF(kwargs);
583 Py_XDECREF(replace);
584 return NULL;
585 }
586
587 dt = NULL;
588 if (!PyDict_SetItemString(kwargs, "fold", _PyLong_One)) {
589 dt = PyObject_Call(replace, args, kwargs);
590 }
591
592 Py_DECREF(args);
593 Py_DECREF(kwargs);
594 Py_DECREF(replace);
595
596 if (dt == NULL) {
597 return NULL;
598 }
599 }
600 }
601 else {
602 dt = tmp;
603 }
604 return dt;
605}
606
607static PyObject *
608zoneinfo_repr(PyZoneInfo_ZoneInfo *self)
609{
610 PyObject *rv = NULL;
611 const char *type_name = Py_TYPE((PyObject *)self)->tp_name;
612 if (!(self->key == Py_None)) {
613 rv = PyUnicode_FromFormat("%s(key=%R)", type_name, self->key);
614 }
615 else {
616 assert(PyUnicode_Check(self->file_repr));
617 rv = PyUnicode_FromFormat("%s.from_file(%U)", type_name,
618 self->file_repr);
619 }
620
621 return rv;
622}
623
624static PyObject *
625zoneinfo_str(PyZoneInfo_ZoneInfo *self)
626{
627 if (!(self->key == Py_None)) {
628 Py_INCREF(self->key);
629 return self->key;
630 }
631 else {
632 return zoneinfo_repr(self);
633 }
634}
635
636/* Pickles the ZoneInfo object by key and source.
637 *
638 * ZoneInfo objects are pickled by reference to the TZif file that they came
639 * from, which means that the exact transitions may be different or the file
640 * may not un-pickle if the data has changed on disk in the interim.
641 *
642 * It is necessary to include a bit indicating whether or not the object
643 * was constructed from the cache, because from-cache objects will hit the
644 * unpickling process's cache, whereas no-cache objects will bypass it.
645 *
646 * Objects constructed from ZoneInfo.from_file cannot be pickled.
647 */
648static PyObject *
649zoneinfo_reduce(PyObject *obj_self, PyObject *unused)
650{
651 PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
652 if (self->source == SOURCE_FILE) {
653 // Objects constructed from files cannot be pickled.
654 PyObject *pickle = PyImport_ImportModule("pickle");
655 if (pickle == NULL) {
656 return NULL;
657 }
658
659 PyObject *pickle_error =
660 PyObject_GetAttrString(pickle, "PicklingError");
661 Py_DECREF(pickle);
662 if (pickle_error == NULL) {
663 return NULL;
664 }
665
666 PyErr_Format(pickle_error,
667 "Cannot pickle a ZoneInfo file from a file stream.");
668 Py_DECREF(pickle_error);
669 return NULL;
670 }
671
672 unsigned char from_cache = self->source == SOURCE_CACHE ? 1 : 0;
673 PyObject *constructor = PyObject_GetAttrString(obj_self, "_unpickle");
674
675 if (constructor == NULL) {
676 return NULL;
677 }
678
679 PyObject *rv = Py_BuildValue("O(OB)", constructor, self->key, from_cache);
680 Py_DECREF(constructor);
681 return rv;
682}
683
684static PyObject *
685zoneinfo__unpickle(PyTypeObject *cls, PyObject *args)
686{
687 PyObject *key;
688 unsigned char from_cache;
689 if (!PyArg_ParseTuple(args, "OB", &key, &from_cache)) {
690 return NULL;
691 }
692
693 if (from_cache) {
694 PyObject *val_args = Py_BuildValue("(O)", key);
695 if (val_args == NULL) {
696 return NULL;
697 }
698
699 PyObject *rv = zoneinfo_new(cls, val_args, NULL);
700
701 Py_DECREF(val_args);
702 return rv;
703 }
704 else {
705 return zoneinfo_new_instance(cls, key);
706 }
707}
708
709/* It is relatively expensive to construct new timedelta objects, and in most
710 * cases we're looking at a relatively small number of timedeltas, such as
711 * integer number of hours, etc. We will keep a cache so that we construct
712 * a minimal number of these.
713 *
714 * Possibly this should be replaced with an LRU cache so that it's not possible
715 * for the memory usage to explode from this, but in order for this to be a
716 * serious problem, one would need to deliberately craft a malicious time zone
717 * file with many distinct offsets. As of tzdb 2019c, loading every single zone
718 * fills the cache with ~450 timedeltas for a total size of ~12kB.
719 *
720 * This returns a new reference to the timedelta.
721 */
722static PyObject *
723load_timedelta(long seconds)
724{
725 PyObject *rv = NULL;
726 PyObject *pyoffset = PyLong_FromLong(seconds);
727 if (pyoffset == NULL) {
728 return NULL;
729 }
730 int contains = PyDict_Contains(TIMEDELTA_CACHE, pyoffset);
731 if (contains == -1) {
732 goto error;
733 }
734
735 if (!contains) {
736 PyObject *tmp = PyDateTimeAPI->Delta_FromDelta(
737 0, seconds, 0, 1, PyDateTimeAPI->DeltaType);
738
739 if (tmp == NULL) {
740 goto error;
741 }
742
743 rv = PyDict_SetDefault(TIMEDELTA_CACHE, pyoffset, tmp);
744 Py_DECREF(tmp);
745 }
746 else {
747 rv = PyDict_GetItem(TIMEDELTA_CACHE, pyoffset);
748 }
749
750 Py_DECREF(pyoffset);
751 Py_INCREF(rv);
752 return rv;
753error:
754 Py_DECREF(pyoffset);
755 return NULL;
756}
757
758/* Constructor for _ttinfo object - this starts by initializing the _ttinfo
759 * to { NULL, NULL, NULL }, so that Py_XDECREF will work on partially
760 * initialized _ttinfo objects.
761 */
762static int
763build_ttinfo(long utcoffset, long dstoffset, PyObject *tzname, _ttinfo *out)
764{
765 out->utcoff = NULL;
766 out->dstoff = NULL;
767 out->tzname = NULL;
768
769 out->utcoff_seconds = utcoffset;
770 out->utcoff = load_timedelta(utcoffset);
771 if (out->utcoff == NULL) {
772 return -1;
773 }
774
775 out->dstoff = load_timedelta(dstoffset);
776 if (out->dstoff == NULL) {
777 return -1;
778 }
779
780 out->tzname = tzname;
781 Py_INCREF(tzname);
782
783 return 0;
784}
785
786/* Decrease reference count on any non-NULL members of a _ttinfo */
787static void
788xdecref_ttinfo(_ttinfo *ttinfo)
789{
790 if (ttinfo != NULL) {
791 Py_XDECREF(ttinfo->utcoff);
792 Py_XDECREF(ttinfo->dstoff);
793 Py_XDECREF(ttinfo->tzname);
794 }
795}
796
797/* Equality function for _ttinfo. */
798static int
799ttinfo_eq(const _ttinfo *const tti0, const _ttinfo *const tti1)
800{
801 int rv;
802 if ((rv = PyObject_RichCompareBool(tti0->utcoff, tti1->utcoff, Py_EQ)) <
803 1) {
804 goto end;
805 }
806
807 if ((rv = PyObject_RichCompareBool(tti0->dstoff, tti1->dstoff, Py_EQ)) <
808 1) {
809 goto end;
810 }
811
812 if ((rv = PyObject_RichCompareBool(tti0->tzname, tti1->tzname, Py_EQ)) <
813 1) {
814 goto end;
815 }
816end:
817 return rv;
818}
819
820/* Given a file-like object, this populates a ZoneInfo object
821 *
822 * The current version calls into a Python function to read the data from
823 * file into Python objects, and this translates those Python objects into
824 * C values and calculates derived values (e.g. dstoff) in C.
825 *
826 * This returns 0 on success and -1 on failure.
827 *
828 * The function will never return while `self` is partially initialized —
829 * the object only needs to be freed / deallocated if this succeeds.
830 */
831static int
832load_data(PyZoneInfo_ZoneInfo *self, PyObject *file_obj)
833{
834 PyObject *data_tuple = NULL;
835
836 long *utcoff = NULL;
837 long *dstoff = NULL;
838 size_t *trans_idx = NULL;
839 unsigned char *isdst = NULL;
840
841 self->trans_list_utc = NULL;
842 self->trans_list_wall[0] = NULL;
843 self->trans_list_wall[1] = NULL;
844 self->trans_ttinfos = NULL;
845 self->_ttinfos = NULL;
846 self->file_repr = NULL;
847
848 size_t ttinfos_allocated = 0;
849
850 data_tuple = PyObject_CallMethod(_common_mod, "load_data", "O", file_obj);
851
852 if (data_tuple == NULL) {
853 goto error;
854 }
855
856 if (!PyTuple_CheckExact(data_tuple)) {
857 PyErr_Format(PyExc_TypeError, "Invalid data result type: %r",
858 data_tuple);
859 goto error;
860 }
861
862 // Unpack the data tuple
863 PyObject *trans_idx_list = PyTuple_GetItem(data_tuple, 0);
864 if (trans_idx_list == NULL) {
865 goto error;
866 }
867
868 PyObject *trans_utc = PyTuple_GetItem(data_tuple, 1);
869 if (trans_utc == NULL) {
870 goto error;
871 }
872
873 PyObject *utcoff_list = PyTuple_GetItem(data_tuple, 2);
874 if (utcoff_list == NULL) {
875 goto error;
876 }
877
878 PyObject *isdst_list = PyTuple_GetItem(data_tuple, 3);
879 if (isdst_list == NULL) {
880 goto error;
881 }
882
883 PyObject *abbr = PyTuple_GetItem(data_tuple, 4);
884 if (abbr == NULL) {
885 goto error;
886 }
887
888 PyObject *tz_str = PyTuple_GetItem(data_tuple, 5);
889 if (tz_str == NULL) {
890 goto error;
891 }
892
893 // Load the relevant sizes
894 Py_ssize_t num_transitions = PyTuple_Size(trans_utc);
Pablo Galindoe4799b92020-05-27 21:48:12 +0100895 if (num_transitions < 0) {
Paul Ganssle62972d92020-05-16 04:20:06 -0400896 goto error;
897 }
898
899 Py_ssize_t num_ttinfos = PyTuple_Size(utcoff_list);
Pablo Galindoe4799b92020-05-27 21:48:12 +0100900 if (num_ttinfos < 0) {
Paul Ganssle62972d92020-05-16 04:20:06 -0400901 goto error;
902 }
903
904 self->num_transitions = (size_t)num_transitions;
905 self->num_ttinfos = (size_t)num_ttinfos;
906
907 // Load the transition indices and list
908 self->trans_list_utc =
909 PyMem_Malloc(self->num_transitions * sizeof(int64_t));
910 trans_idx = PyMem_Malloc(self->num_transitions * sizeof(Py_ssize_t));
911
Pablo Galindoe4799b92020-05-27 21:48:12 +0100912 for (size_t i = 0; i < self->num_transitions; ++i) {
Paul Ganssle62972d92020-05-16 04:20:06 -0400913 PyObject *num = PyTuple_GetItem(trans_utc, i);
914 if (num == NULL) {
915 goto error;
916 }
917 self->trans_list_utc[i] = PyLong_AsLongLong(num);
918 if (self->trans_list_utc[i] == -1 && PyErr_Occurred()) {
919 goto error;
920 }
921
922 num = PyTuple_GetItem(trans_idx_list, i);
923 if (num == NULL) {
924 goto error;
925 }
926
927 Py_ssize_t cur_trans_idx = PyLong_AsSsize_t(num);
928 if (cur_trans_idx == -1) {
929 goto error;
930 }
931
932 trans_idx[i] = (size_t)cur_trans_idx;
933 if (trans_idx[i] > self->num_ttinfos) {
934 PyErr_Format(
935 PyExc_ValueError,
936 "Invalid transition index found while reading TZif: %zd",
937 cur_trans_idx);
938
939 goto error;
940 }
941 }
942
943 // Load UTC offsets and isdst (size num_ttinfos)
944 utcoff = PyMem_Malloc(self->num_ttinfos * sizeof(long));
945 isdst = PyMem_Malloc(self->num_ttinfos * sizeof(unsigned char));
946
947 if (utcoff == NULL || isdst == NULL) {
948 goto error;
949 }
Pablo Galindoe4799b92020-05-27 21:48:12 +0100950 for (size_t i = 0; i < self->num_ttinfos; ++i) {
Paul Ganssle62972d92020-05-16 04:20:06 -0400951 PyObject *num = PyTuple_GetItem(utcoff_list, i);
952 if (num == NULL) {
953 goto error;
954 }
955
956 utcoff[i] = PyLong_AsLong(num);
957 if (utcoff[i] == -1 && PyErr_Occurred()) {
958 goto error;
959 }
960
961 num = PyTuple_GetItem(isdst_list, i);
962 if (num == NULL) {
963 goto error;
964 }
965
966 int isdst_with_error = PyObject_IsTrue(num);
967 if (isdst_with_error == -1) {
968 goto error;
969 }
970 else {
971 isdst[i] = (unsigned char)isdst_with_error;
972 }
973 }
974
975 dstoff = PyMem_Calloc(self->num_ttinfos, sizeof(long));
976 if (dstoff == NULL) {
977 goto error;
978 }
979
980 // Derive dstoff and trans_list_wall from the information we've loaded
981 utcoff_to_dstoff(trans_idx, utcoff, dstoff, isdst, self->num_transitions,
982 self->num_ttinfos);
983
984 if (ts_to_local(trans_idx, self->trans_list_utc, utcoff,
985 self->trans_list_wall, self->num_ttinfos,
986 self->num_transitions)) {
987 goto error;
988 }
989
990 // Build _ttinfo objects from utcoff, dstoff and abbr
991 self->_ttinfos = PyMem_Malloc(self->num_ttinfos * sizeof(_ttinfo));
992 for (size_t i = 0; i < self->num_ttinfos; ++i) {
993 PyObject *tzname = PyTuple_GetItem(abbr, i);
994 if (tzname == NULL) {
995 goto error;
996 }
997
998 ttinfos_allocated++;
999 if (build_ttinfo(utcoff[i], dstoff[i], tzname, &(self->_ttinfos[i]))) {
1000 goto error;
1001 }
1002 }
1003
1004 // Build our mapping from transition to the ttinfo that applies
1005 self->trans_ttinfos =
1006 PyMem_Calloc(self->num_transitions, sizeof(_ttinfo *));
1007 for (size_t i = 0; i < self->num_transitions; ++i) {
1008 size_t ttinfo_idx = trans_idx[i];
1009 assert(ttinfo_idx < self->num_ttinfos);
1010 self->trans_ttinfos[i] = &(self->_ttinfos[ttinfo_idx]);
1011 }
1012
1013 // Set ttinfo_before to the first non-DST transition
1014 for (size_t i = 0; i < self->num_ttinfos; ++i) {
1015 if (!isdst[i]) {
1016 self->ttinfo_before = &(self->_ttinfos[i]);
1017 break;
1018 }
1019 }
1020
1021 // If there are only DST ttinfos, pick the first one, if there are no
1022 // ttinfos at all, set ttinfo_before to NULL
1023 if (self->ttinfo_before == NULL && self->num_ttinfos > 0) {
1024 self->ttinfo_before = &(self->_ttinfos[0]);
1025 }
1026
1027 if (tz_str != Py_None && PyObject_IsTrue(tz_str)) {
1028 if (parse_tz_str(tz_str, &(self->tzrule_after))) {
1029 goto error;
1030 }
1031 }
1032 else {
1033 if (!self->num_ttinfos) {
1034 PyErr_Format(PyExc_ValueError, "No time zone information found.");
1035 goto error;
1036 }
1037
1038 size_t idx;
1039 if (!self->num_transitions) {
1040 idx = self->num_ttinfos - 1;
1041 }
1042 else {
1043 idx = trans_idx[self->num_transitions - 1];
1044 }
1045
1046 _ttinfo *tti = &(self->_ttinfos[idx]);
1047 build_tzrule(tti->tzname, NULL, tti->utcoff_seconds, 0, NULL, NULL,
1048 &(self->tzrule_after));
1049
1050 // We've abused the build_tzrule constructor to construct an STD-only
1051 // rule mimicking whatever ttinfo we've picked up, but it's possible
1052 // that the one we've picked up is a DST zone, so we need to make sure
1053 // that the dstoff is set correctly in that case.
1054 if (PyObject_IsTrue(tti->dstoff)) {
1055 _ttinfo *tti_after = &(self->tzrule_after.std);
1056 Py_DECREF(tti_after->dstoff);
1057 tti_after->dstoff = tti->dstoff;
1058 Py_INCREF(tti_after->dstoff);
1059 }
1060 }
1061
1062 // Determine if this is a "fixed offset" zone, meaning that the output of
1063 // the utcoffset, dst and tzname functions does not depend on the specific
1064 // datetime passed.
1065 //
1066 // We make three simplifying assumptions here:
1067 //
1068 // 1. If tzrule_after is not std_only, it has transitions that might occur
1069 // (it is possible to construct TZ strings that specify STD and DST but
1070 // no transitions ever occur, such as AAA0BBB,0/0,J365/25).
1071 // 2. If self->_ttinfos contains more than one _ttinfo object, the objects
1072 // represent different offsets.
1073 // 3. self->ttinfos contains no unused _ttinfos (in which case an otherwise
1074 // fixed-offset zone with extra _ttinfos defined may appear to *not* be
1075 // a fixed offset zone).
1076 //
1077 // Violations to these assumptions would be fairly exotic, and exotic
1078 // zones should almost certainly not be used with datetime.time (the
1079 // only thing that would be affected by this).
1080 if (self->num_ttinfos > 1 || !self->tzrule_after.std_only) {
1081 self->fixed_offset = 0;
1082 }
1083 else if (self->num_ttinfos == 0) {
1084 self->fixed_offset = 1;
1085 }
1086 else {
1087 int constant_offset =
1088 ttinfo_eq(&(self->_ttinfos[0]), &self->tzrule_after.std);
1089 if (constant_offset < 0) {
1090 goto error;
1091 }
1092 else {
1093 self->fixed_offset = constant_offset;
1094 }
1095 }
1096
1097 int rv = 0;
1098 goto cleanup;
1099error:
1100 // These resources only need to be freed if we have failed, if we succeed
1101 // in initializing a PyZoneInfo_ZoneInfo object, we can rely on its dealloc
1102 // method to free the relevant resources.
1103 if (self->trans_list_utc != NULL) {
1104 PyMem_Free(self->trans_list_utc);
1105 self->trans_list_utc = NULL;
1106 }
1107
1108 for (size_t i = 0; i < 2; ++i) {
1109 if (self->trans_list_wall[i] != NULL) {
1110 PyMem_Free(self->trans_list_wall[i]);
1111 self->trans_list_wall[i] = NULL;
1112 }
1113 }
1114
1115 if (self->_ttinfos != NULL) {
1116 for (size_t i = 0; i < ttinfos_allocated; ++i) {
1117 xdecref_ttinfo(&(self->_ttinfos[i]));
1118 }
1119 PyMem_Free(self->_ttinfos);
1120 self->_ttinfos = NULL;
1121 }
1122
1123 if (self->trans_ttinfos != NULL) {
1124 PyMem_Free(self->trans_ttinfos);
1125 self->trans_ttinfos = NULL;
1126 }
1127
1128 rv = -1;
1129cleanup:
1130 Py_XDECREF(data_tuple);
1131
1132 if (utcoff != NULL) {
1133 PyMem_Free(utcoff);
1134 }
1135
1136 if (dstoff != NULL) {
1137 PyMem_Free(dstoff);
1138 }
1139
1140 if (isdst != NULL) {
1141 PyMem_Free(isdst);
1142 }
1143
1144 if (trans_idx != NULL) {
1145 PyMem_Free(trans_idx);
1146 }
1147
1148 return rv;
1149}
1150
1151/* Function to calculate the local timestamp of a transition from the year. */
1152int64_t
1153calendarrule_year_to_timestamp(TransitionRuleType *base_self, int year)
1154{
1155 CalendarRule *self = (CalendarRule *)base_self;
1156
1157 // We want (year, month, day of month); we have year and month, but we
1158 // need to turn (week, day-of-week) into day-of-month
1159 //
1160 // Week 1 is the first week in which day `day` (where 0 = Sunday) appears.
1161 // Week 5 represents the last occurrence of day `day`, so we need to know
1162 // the first weekday of the month and the number of days in the month.
1163 int8_t first_day = (ymd_to_ord(year, self->month, 1) + 6) % 7;
1164 uint8_t days_in_month = DAYS_IN_MONTH[self->month];
1165 if (self->month == 2 && is_leap_year(year)) {
1166 days_in_month += 1;
1167 }
1168
1169 // This equation seems magical, so I'll break it down:
1170 // 1. calendar says 0 = Monday, POSIX says 0 = Sunday so we need first_day
1171 // + 1 to get 1 = Monday -> 7 = Sunday, which is still equivalent
1172 // because this math is mod 7
1173 // 2. Get first day - desired day mod 7 (adjusting by 7 for negative
1174 // numbers so that -1 % 7 = 6).
1175 // 3. Add 1 because month days are a 1-based index.
1176 int8_t month_day = ((int8_t)(self->day) - (first_day + 1)) % 7;
1177 if (month_day < 0) {
1178 month_day += 7;
1179 }
1180 month_day += 1;
1181
1182 // Now use a 0-based index version of `week` to calculate the w-th
1183 // occurrence of `day`
1184 month_day += ((int8_t)(self->week) - 1) * 7;
1185
1186 // month_day will only be > days_in_month if w was 5, and `w` means "last
1187 // occurrence of `d`", so now we just check if we over-shot the end of the
1188 // month and if so knock off 1 week.
1189 if (month_day > days_in_month) {
1190 month_day -= 7;
1191 }
1192
1193 int64_t ordinal = ymd_to_ord(year, self->month, month_day) - EPOCHORDINAL;
1194 return ((ordinal * 86400) + (int64_t)(self->hour * 3600) +
1195 (int64_t)(self->minute * 60) + (int64_t)(self->second));
1196}
1197
1198/* Constructor for CalendarRule. */
1199int
1200calendarrule_new(uint8_t month, uint8_t week, uint8_t day, int8_t hour,
1201 int8_t minute, int8_t second, CalendarRule *out)
1202{
1203 // These bounds come from the POSIX standard, which describes an Mm.n.d
1204 // rule as:
1205 //
1206 // The d'th day (0 <= d <= 6) of week n of month m of the year (1 <= n <=
1207 // 5, 1 <= m <= 12, where week 5 means "the last d day in month m" which
1208 // may occur in either the fourth or the fifth week). Week 1 is the first
1209 // week in which the d'th day occurs. Day zero is Sunday.
1210 if (month <= 0 || month > 12) {
1211 PyErr_Format(PyExc_ValueError, "Month must be in (0, 12]");
1212 return -1;
1213 }
1214
1215 if (week <= 0 || week > 5) {
1216 PyErr_Format(PyExc_ValueError, "Week must be in (0, 5]");
1217 return -1;
1218 }
1219
1220 // day is an unsigned integer, so day < 0 should always return false, but
1221 // if day's type changes to a signed integer *without* changing this value,
1222 // it may create a bug. Considering that the compiler should be able to
1223 // optimize out the first comparison if day is an unsigned integer anyway,
1224 // we will leave this comparison in place and disable the compiler warning.
1225#pragma GCC diagnostic push
1226#pragma GCC diagnostic ignored "-Wtype-limits"
1227 if (day < 0 || day > 6) {
1228#pragma GCC diagnostic pop
1229 PyErr_Format(PyExc_ValueError, "Day must be in [0, 6]");
1230 return -1;
1231 }
1232
1233 TransitionRuleType base = {&calendarrule_year_to_timestamp};
1234
1235 CalendarRule new_offset = {
1236 .base = base,
1237 .month = month,
1238 .week = week,
1239 .day = day,
1240 .hour = hour,
1241 .minute = minute,
1242 .second = second,
1243 };
1244
1245 *out = new_offset;
1246 return 0;
1247}
1248
1249/* Function to calculate the local timestamp of a transition from the year.
1250 *
1251 * This translates the day of the year into a local timestamp — either a
1252 * 1-based Julian day, not including leap days, or the 0-based year-day,
1253 * including leap days.
1254 * */
1255int64_t
1256dayrule_year_to_timestamp(TransitionRuleType *base_self, int year)
1257{
1258 // The function signature requires a TransitionRuleType pointer, but this
1259 // function is only applicable to DayRule* objects.
1260 DayRule *self = (DayRule *)base_self;
1261
1262 // ymd_to_ord calculates the number of days since 0001-01-01, but we want
1263 // to know the number of days since 1970-01-01, so we must subtract off
1264 // the equivalent of ymd_to_ord(1970, 1, 1).
1265 //
1266 // We subtract off an additional 1 day to account for January 1st (we want
1267 // the number of full days *before* the date of the transition - partial
1268 // days are accounted for in the hour, minute and second portions.
1269 int64_t days_before_year = ymd_to_ord(year, 1, 1) - EPOCHORDINAL - 1;
1270
1271 // The Julian day specification skips over February 29th in leap years,
1272 // from the POSIX standard:
1273 //
1274 // Leap days shall not be counted. That is, in all years-including leap
1275 // years-February 28 is day 59 and March 1 is day 60. It is impossible to
1276 // refer explicitly to the occasional February 29.
1277 //
1278 // This is actually more useful than you'd think — if you want a rule that
1279 // always transitions on a given calendar day (other than February 29th),
1280 // you would use a Julian day, e.g. J91 always refers to April 1st and J365
1281 // always refers to December 31st.
1282 unsigned int day = self->day;
1283 if (self->julian && day >= 59 && is_leap_year(year)) {
1284 day += 1;
1285 }
1286
1287 return ((days_before_year + day) * 86400) + (self->hour * 3600) +
1288 (self->minute * 60) + self->second;
1289}
1290
1291/* Constructor for DayRule. */
1292static int
1293dayrule_new(uint8_t julian, unsigned int day, int8_t hour, int8_t minute,
1294 int8_t second, DayRule *out)
1295{
1296 // The POSIX standard specifies that Julian days must be in the range (1 <=
1297 // n <= 365) and that non-Julian (they call it "0-based Julian") days must
1298 // be in the range (0 <= n <= 365).
1299 if (day < julian || day > 365) {
1300 PyErr_Format(PyExc_ValueError, "day must be in [%u, 365], not: %u",
1301 julian, day);
1302 return -1;
1303 }
1304
1305 TransitionRuleType base = {
1306 &dayrule_year_to_timestamp,
1307 };
1308
1309 DayRule tmp = {
1310 .base = base,
1311 .julian = julian,
1312 .day = day,
1313 .hour = hour,
1314 .minute = minute,
1315 .second = second,
1316 };
1317
1318 *out = tmp;
1319
1320 return 0;
1321}
1322
1323/* Calculate the start and end rules for a _tzrule in the given year. */
1324static void
1325tzrule_transitions(_tzrule *rule, int year, int64_t *start, int64_t *end)
1326{
1327 assert(rule->start != NULL);
1328 assert(rule->end != NULL);
1329 *start = rule->start->year_to_timestamp(rule->start, year);
1330 *end = rule->end->year_to_timestamp(rule->end, year);
1331}
1332
1333/* Calculate the _ttinfo that applies at a given local time from a _tzrule.
1334 *
1335 * This takes a local timestamp and fold for disambiguation purposes; the year
1336 * could technically be calculated from the timestamp, but given that the
1337 * callers of this function already have the year information accessible from
1338 * the datetime struct, it is taken as an additional parameter to reduce
1339 * unncessary calculation.
1340 * */
1341static _ttinfo *
1342find_tzrule_ttinfo(_tzrule *rule, int64_t ts, unsigned char fold, int year)
1343{
1344 if (rule->std_only) {
1345 return &(rule->std);
1346 }
1347
1348 int64_t start, end;
1349 uint8_t isdst;
1350
1351 tzrule_transitions(rule, year, &start, &end);
1352
1353 // With fold = 0, the period (denominated in local time) with the smaller
1354 // offset starts at the end of the gap and ends at the end of the fold;
1355 // with fold = 1, it runs from the start of the gap to the beginning of the
1356 // fold.
1357 //
1358 // So in order to determine the DST boundaries we need to know both the
1359 // fold and whether DST is positive or negative (rare), and it turns out
1360 // that this boils down to fold XOR is_positive.
1361 if (fold == (rule->dst_diff >= 0)) {
1362 end -= rule->dst_diff;
1363 }
1364 else {
1365 start += rule->dst_diff;
1366 }
1367
1368 if (start < end) {
1369 isdst = (ts >= start) && (ts < end);
1370 }
1371 else {
1372 isdst = (ts < end) || (ts >= start);
1373 }
1374
1375 if (isdst) {
1376 return &(rule->dst);
1377 }
1378 else {
1379 return &(rule->std);
1380 }
1381}
1382
1383/* Calculate the ttinfo and fold that applies for a _tzrule at an epoch time.
1384 *
1385 * This function can determine the _ttinfo that applies at a given epoch time,
1386 * (analogous to trans_list_utc), and whether or not the datetime is in a fold.
1387 * This is to be used in the .fromutc() function.
1388 *
1389 * The year is technically a redundant parameter, because it can be calculated
1390 * from the timestamp, but all callers of this function should have the year
1391 * in the datetime struct anyway, so taking it as a parameter saves unnecessary
1392 * calculation.
1393 **/
1394static _ttinfo *
1395find_tzrule_ttinfo_fromutc(_tzrule *rule, int64_t ts, int year,
1396 unsigned char *fold)
1397{
1398 if (rule->std_only) {
1399 *fold = 0;
1400 return &(rule->std);
1401 }
1402
1403 int64_t start, end;
1404 uint8_t isdst;
1405 tzrule_transitions(rule, year, &start, &end);
1406 start -= rule->std.utcoff_seconds;
1407 end -= rule->dst.utcoff_seconds;
1408
1409 if (start < end) {
1410 isdst = (ts >= start) && (ts < end);
1411 }
1412 else {
1413 isdst = (ts < end) || (ts >= start);
1414 }
1415
1416 // For positive DST, the ambiguous period is one dst_diff after the end of
1417 // DST; for negative DST, the ambiguous period is one dst_diff before the
1418 // start of DST.
1419 int64_t ambig_start, ambig_end;
1420 if (rule->dst_diff > 0) {
1421 ambig_start = end;
1422 ambig_end = end + rule->dst_diff;
1423 }
1424 else {
1425 ambig_start = start;
1426 ambig_end = start - rule->dst_diff;
1427 }
1428
1429 *fold = (ts >= ambig_start) && (ts < ambig_end);
1430
1431 if (isdst) {
1432 return &(rule->dst);
1433 }
1434 else {
1435 return &(rule->std);
1436 }
1437}
1438
1439/* Parse a TZ string in the format specified by the POSIX standard:
1440 *
1441 * std offset[dst[offset],start[/time],end[/time]]
1442 *
1443 * std and dst must be 3 or more characters long and must not contain a
1444 * leading colon, embedded digits, commas, nor a plus or minus signs; The
1445 * spaces between "std" and "offset" are only for display and are not actually
1446 * present in the string.
1447 *
1448 * The format of the offset is ``[+|-]hh[:mm[:ss]]``
1449 *
1450 * See the POSIX.1 spec: IEE Std 1003.1-2018 §8.3:
1451 *
1452 * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
1453 */
1454static int
1455parse_tz_str(PyObject *tz_str_obj, _tzrule *out)
1456{
1457 PyObject *std_abbr = NULL;
1458 PyObject *dst_abbr = NULL;
1459 TransitionRuleType *start = NULL;
1460 TransitionRuleType *end = NULL;
Dong-hee Naa487a392020-05-22 01:56:03 +09001461 // Initialize offsets to invalid value (> 24 hours)
1462 long std_offset = 1 << 20;
1463 long dst_offset = 1 << 20;
Paul Ganssle62972d92020-05-16 04:20:06 -04001464
1465 char *tz_str = PyBytes_AsString(tz_str_obj);
1466 if (tz_str == NULL) {
1467 return -1;
1468 }
1469 char *p = tz_str;
1470
1471 // Read the `std` abbreviation, which must be at least 3 characters long.
Pablo Galindoe4799b92020-05-27 21:48:12 +01001472 Py_ssize_t num_chars = parse_abbr(p, &std_abbr);
Paul Ganssle62972d92020-05-16 04:20:06 -04001473 if (num_chars < 1) {
1474 PyErr_Format(PyExc_ValueError, "Invalid STD format in %R", tz_str_obj);
1475 goto error;
1476 }
1477
1478 p += num_chars;
1479
1480 // Now read the STD offset, which is required
1481 num_chars = parse_tz_delta(p, &std_offset);
1482 if (num_chars < 0) {
1483 PyErr_Format(PyExc_ValueError, "Invalid STD offset in %R", tz_str_obj);
1484 goto error;
1485 }
1486 p += num_chars;
1487
1488 // If the string ends here, there is no DST, otherwise we must parse the
1489 // DST abbreviation and start and end dates and times.
1490 if (*p == '\0') {
1491 goto complete;
1492 }
1493
1494 num_chars = parse_abbr(p, &dst_abbr);
1495 if (num_chars < 1) {
1496 PyErr_Format(PyExc_ValueError, "Invalid DST format in %R", tz_str_obj);
1497 goto error;
1498 }
1499 p += num_chars;
1500
1501 if (*p == ',') {
1502 // From the POSIX standard:
1503 //
1504 // If no offset follows dst, the alternative time is assumed to be one
1505 // hour ahead of standard time.
1506 dst_offset = std_offset + 3600;
1507 }
1508 else {
1509 num_chars = parse_tz_delta(p, &dst_offset);
1510 if (num_chars < 0) {
1511 PyErr_Format(PyExc_ValueError, "Invalid DST offset in %R",
1512 tz_str_obj);
1513 goto error;
1514 }
1515
1516 p += num_chars;
1517 }
1518
1519 TransitionRuleType **transitions[2] = {&start, &end};
1520 for (size_t i = 0; i < 2; ++i) {
1521 if (*p != ',') {
1522 PyErr_Format(PyExc_ValueError,
1523 "Missing transition rules in TZ string: %R",
1524 tz_str_obj);
1525 goto error;
1526 }
1527 p++;
1528
1529 num_chars = parse_transition_rule(p, transitions[i]);
1530 if (num_chars < 0) {
1531 PyErr_Format(PyExc_ValueError,
1532 "Malformed transition rule in TZ string: %R",
1533 tz_str_obj);
1534 goto error;
1535 }
1536 p += num_chars;
1537 }
1538
1539 if (*p != '\0') {
1540 PyErr_Format(PyExc_ValueError,
1541 "Extraneous characters at end of TZ string: %R",
1542 tz_str_obj);
1543 goto error;
1544 }
1545
1546complete:
1547 build_tzrule(std_abbr, dst_abbr, std_offset, dst_offset, start, end, out);
1548 Py_DECREF(std_abbr);
1549 Py_XDECREF(dst_abbr);
1550
1551 return 0;
1552error:
1553 Py_XDECREF(std_abbr);
1554 if (dst_abbr != NULL && dst_abbr != Py_None) {
1555 Py_DECREF(dst_abbr);
1556 }
1557
1558 if (start != NULL) {
1559 PyMem_Free(start);
1560 }
1561
1562 if (end != NULL) {
1563 PyMem_Free(end);
1564 }
1565
1566 return -1;
1567}
1568
Pablo Galindoe4799b92020-05-27 21:48:12 +01001569static int
1570parse_uint(const char *const p, uint8_t *value)
Paul Ganssle62972d92020-05-16 04:20:06 -04001571{
1572 if (!isdigit(*p)) {
1573 return -1;
1574 }
1575
Pablo Galindoe4799b92020-05-27 21:48:12 +01001576 *value = (*p) - '0';
1577 return 0;
Paul Ganssle62972d92020-05-16 04:20:06 -04001578}
1579
1580/* Parse the STD and DST abbreviations from a TZ string. */
Pablo Galindoe4799b92020-05-27 21:48:12 +01001581static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -04001582parse_abbr(const char *const p, PyObject **abbr)
1583{
1584 const char *ptr = p;
1585 char buff = *ptr;
1586 const char *str_start;
1587 const char *str_end;
1588
1589 if (*ptr == '<') {
1590 ptr++;
1591 str_start = ptr;
1592 while ((buff = *ptr) != '>') {
1593 // From the POSIX standard:
1594 //
1595 // In the quoted form, the first character shall be the less-than
1596 // ( '<' ) character and the last character shall be the
1597 // greater-than ( '>' ) character. All characters between these
1598 // quoting characters shall be alphanumeric characters from the
1599 // portable character set in the current locale, the plus-sign (
1600 // '+' ) character, or the minus-sign ( '-' ) character. The std
1601 // and dst fields in this case shall not include the quoting
1602 // characters.
1603 if (!isalpha(buff) && !isdigit(buff) && buff != '+' &&
1604 buff != '-') {
1605 return -1;
1606 }
1607 ptr++;
1608 }
1609 str_end = ptr;
1610 ptr++;
1611 }
1612 else {
1613 str_start = p;
1614 // From the POSIX standard:
1615 //
1616 // In the unquoted form, all characters in these fields shall be
1617 // alphabetic characters from the portable character set in the
1618 // current locale.
1619 while (isalpha(*ptr)) {
1620 ptr++;
1621 }
1622 str_end = ptr;
1623 }
1624
1625 *abbr = PyUnicode_FromStringAndSize(str_start, str_end - str_start);
Gregory P. Smithd780fa72020-06-22 00:39:28 -07001626 if (*abbr == NULL) {
Paul Ganssle62972d92020-05-16 04:20:06 -04001627 return -1;
1628 }
1629
1630 return ptr - p;
1631}
1632
1633/* Parse a UTC offset from a TZ str. */
Pablo Galindoe4799b92020-05-27 21:48:12 +01001634static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -04001635parse_tz_delta(const char *const p, long *total_seconds)
1636{
1637 // From the POSIX spec:
1638 //
1639 // Indicates the value added to the local time to arrive at Coordinated
1640 // Universal Time. The offset has the form:
1641 //
1642 // hh[:mm[:ss]]
1643 //
1644 // One or more digits may be used; the value is always interpreted as a
1645 // decimal number.
1646 //
1647 // The POSIX spec says that the values for `hour` must be between 0 and 24
1648 // hours, but RFC 8536 §3.3.1 specifies that the hours part of the
1649 // transition times may be signed and range from -167 to 167.
1650 long sign = -1;
1651 long hours = 0;
1652 long minutes = 0;
1653 long seconds = 0;
1654
1655 const char *ptr = p;
1656 char buff = *ptr;
1657 if (buff == '-' || buff == '+') {
1658 // Negative numbers correspond to *positive* offsets, from the spec:
1659 //
1660 // If preceded by a '-', the timezone shall be east of the Prime
1661 // Meridian; otherwise, it shall be west (which may be indicated by
1662 // an optional preceding '+' ).
1663 if (buff == '-') {
1664 sign = 1;
1665 }
1666
1667 ptr++;
1668 }
1669
1670 // The hour can be 1 or 2 numeric characters
1671 for (size_t i = 0; i < 2; ++i) {
1672 buff = *ptr;
1673 if (!isdigit(buff)) {
1674 if (i == 0) {
1675 return -1;
1676 }
1677 else {
1678 break;
1679 }
1680 }
1681
1682 hours *= 10;
1683 hours += buff - '0';
1684 ptr++;
1685 }
1686
1687 if (hours > 24 || hours < 0) {
1688 return -1;
1689 }
1690
1691 // Minutes and seconds always of the format ":dd"
1692 long *outputs[2] = {&minutes, &seconds};
1693 for (size_t i = 0; i < 2; ++i) {
1694 if (*ptr != ':') {
1695 goto complete;
1696 }
1697 ptr++;
1698
1699 for (size_t j = 0; j < 2; ++j) {
1700 buff = *ptr;
1701 if (!isdigit(buff)) {
1702 return -1;
1703 }
1704 *(outputs[i]) *= 10;
1705 *(outputs[i]) += buff - '0';
1706 ptr++;
1707 }
1708 }
1709
1710complete:
1711 *total_seconds = sign * ((hours * 3600) + (minutes * 60) + seconds);
1712
1713 return ptr - p;
1714}
1715
1716/* Parse the date portion of a transition rule. */
Pablo Galindoe4799b92020-05-27 21:48:12 +01001717static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -04001718parse_transition_rule(const char *const p, TransitionRuleType **out)
1719{
1720 // The full transition rule indicates when to change back and forth between
1721 // STD and DST, and has the form:
1722 //
1723 // date[/time],date[/time]
1724 //
1725 // This function parses an individual date[/time] section, and returns
1726 // the number of characters that contributed to the transition rule. This
1727 // does not include the ',' at the end of the first rule.
1728 //
1729 // The POSIX spec states that if *time* is not given, the default is 02:00.
1730 const char *ptr = p;
1731 int8_t hour = 2;
1732 int8_t minute = 0;
1733 int8_t second = 0;
1734
1735 // Rules come in one of three flavors:
1736 //
1737 // 1. Jn: Julian day n, with no leap days.
1738 // 2. n: Day of year (0-based, with leap days)
1739 // 3. Mm.n.d: Specifying by month, week and day-of-week.
1740
1741 if (*ptr == 'M') {
1742 uint8_t month, week, day;
1743 ptr++;
Pablo Galindoe4799b92020-05-27 21:48:12 +01001744 if (parse_uint(ptr, &month)) {
Paul Ganssle62972d92020-05-16 04:20:06 -04001745 return -1;
1746 }
Paul Ganssle62972d92020-05-16 04:20:06 -04001747 ptr++;
1748 if (*ptr != '.') {
Pablo Galindoe4799b92020-05-27 21:48:12 +01001749 uint8_t tmp;
1750 if (parse_uint(ptr, &tmp)) {
Paul Ganssle62972d92020-05-16 04:20:06 -04001751 return -1;
1752 }
1753
1754 month *= 10;
Pablo Galindoe4799b92020-05-27 21:48:12 +01001755 month += tmp;
Paul Ganssle62972d92020-05-16 04:20:06 -04001756 ptr++;
1757 }
1758
1759 uint8_t *values[2] = {&week, &day};
1760 for (size_t i = 0; i < 2; ++i) {
1761 if (*ptr != '.') {
1762 return -1;
1763 }
1764 ptr++;
1765
Pablo Galindoe4799b92020-05-27 21:48:12 +01001766 if (parse_uint(ptr, values[i])) {
Paul Ganssle62972d92020-05-16 04:20:06 -04001767 return -1;
1768 }
1769 ptr++;
Paul Ganssle62972d92020-05-16 04:20:06 -04001770 }
1771
1772 if (*ptr == '/') {
1773 ptr++;
Pablo Galindoe4799b92020-05-27 21:48:12 +01001774 Py_ssize_t num_chars =
Paul Ganssle62972d92020-05-16 04:20:06 -04001775 parse_transition_time(ptr, &hour, &minute, &second);
1776 if (num_chars < 0) {
1777 return -1;
1778 }
1779 ptr += num_chars;
1780 }
1781
1782 CalendarRule *rv = PyMem_Calloc(1, sizeof(CalendarRule));
1783 if (rv == NULL) {
1784 return -1;
1785 }
1786
1787 if (calendarrule_new(month, week, day, hour, minute, second, rv)) {
1788 PyMem_Free(rv);
1789 return -1;
1790 }
1791
1792 *out = (TransitionRuleType *)rv;
1793 }
1794 else {
1795 uint8_t julian = 0;
1796 unsigned int day = 0;
1797 if (*ptr == 'J') {
1798 julian = 1;
1799 ptr++;
1800 }
1801
1802 for (size_t i = 0; i < 3; ++i) {
1803 if (!isdigit(*ptr)) {
1804 if (i == 0) {
1805 return -1;
1806 }
1807 break;
1808 }
1809 day *= 10;
1810 day += (*ptr) - '0';
1811 ptr++;
1812 }
1813
1814 if (*ptr == '/') {
1815 ptr++;
Pablo Galindoe4799b92020-05-27 21:48:12 +01001816 Py_ssize_t num_chars =
Paul Ganssle62972d92020-05-16 04:20:06 -04001817 parse_transition_time(ptr, &hour, &minute, &second);
1818 if (num_chars < 0) {
1819 return -1;
1820 }
1821 ptr += num_chars;
1822 }
1823
1824 DayRule *rv = PyMem_Calloc(1, sizeof(DayRule));
1825 if (rv == NULL) {
1826 return -1;
1827 }
1828
1829 if (dayrule_new(julian, day, hour, minute, second, rv)) {
1830 PyMem_Free(rv);
1831 return -1;
1832 }
1833 *out = (TransitionRuleType *)rv;
1834 }
1835
1836 return ptr - p;
1837}
1838
1839/* Parse the time portion of a transition rule (e.g. following an /) */
Pablo Galindoe4799b92020-05-27 21:48:12 +01001840static Py_ssize_t
Paul Ganssle62972d92020-05-16 04:20:06 -04001841parse_transition_time(const char *const p, int8_t *hour, int8_t *minute,
1842 int8_t *second)
1843{
1844 // From the spec:
1845 //
1846 // The time has the same format as offset except that no leading sign
1847 // ( '-' or '+' ) is allowed.
1848 //
1849 // The format for the offset is:
1850 //
1851 // h[h][:mm[:ss]]
1852 //
1853 // RFC 8536 also allows transition times to be signed and to range from
1854 // -167 to +167, but the current version only supports [0, 99].
1855 //
1856 // TODO: Support the full range of transition hours.
1857 int8_t *components[3] = {hour, minute, second};
1858 const char *ptr = p;
1859 int8_t sign = 1;
1860
1861 if (*ptr == '-' || *ptr == '+') {
1862 if (*ptr == '-') {
1863 sign = -1;
1864 }
1865 ptr++;
1866 }
1867
1868 for (size_t i = 0; i < 3; ++i) {
1869 if (i > 0) {
1870 if (*ptr != ':') {
1871 break;
1872 }
1873 ptr++;
1874 }
1875
1876 uint8_t buff = 0;
1877 for (size_t j = 0; j < 2; j++) {
1878 if (!isdigit(*ptr)) {
1879 if (i == 0 && j > 0) {
1880 break;
1881 }
1882 return -1;
1883 }
1884
1885 buff *= 10;
1886 buff += (*ptr) - '0';
1887 ptr++;
1888 }
1889
1890 *(components[i]) = sign * buff;
1891 }
1892
1893 return ptr - p;
1894}
1895
1896/* Constructor for a _tzrule.
1897 *
1898 * If `dst_abbr` is NULL, this will construct an "STD-only" _tzrule, in which
1899 * case `dst_offset` will be ignored and `start` and `end` are expected to be
1900 * NULL as well.
1901 *
1902 * Returns 0 on success.
1903 */
1904static int
1905build_tzrule(PyObject *std_abbr, PyObject *dst_abbr, long std_offset,
1906 long dst_offset, TransitionRuleType *start,
1907 TransitionRuleType *end, _tzrule *out)
1908{
Dong-hee Naa487a392020-05-22 01:56:03 +09001909 _tzrule rv = {{0}};
Paul Ganssle62972d92020-05-16 04:20:06 -04001910
1911 rv.start = start;
1912 rv.end = end;
1913
1914 if (build_ttinfo(std_offset, 0, std_abbr, &rv.std)) {
1915 goto error;
1916 }
1917
1918 if (dst_abbr != NULL) {
1919 rv.dst_diff = dst_offset - std_offset;
1920 if (build_ttinfo(dst_offset, rv.dst_diff, dst_abbr, &rv.dst)) {
1921 goto error;
1922 }
1923 }
1924 else {
1925 rv.std_only = 1;
1926 }
1927
1928 *out = rv;
1929
1930 return 0;
1931error:
1932 xdecref_ttinfo(&rv.std);
1933 xdecref_ttinfo(&rv.dst);
1934 return -1;
1935}
1936
1937/* Destructor for _tzrule. */
1938static void
1939free_tzrule(_tzrule *tzrule)
1940{
1941 xdecref_ttinfo(&(tzrule->std));
1942 if (!tzrule->std_only) {
1943 xdecref_ttinfo(&(tzrule->dst));
1944 }
1945
1946 if (tzrule->start != NULL) {
1947 PyMem_Free(tzrule->start);
1948 }
1949
1950 if (tzrule->end != NULL) {
1951 PyMem_Free(tzrule->end);
1952 }
1953}
1954
1955/* Calculate DST offsets from transitions and UTC offsets
1956 *
1957 * This is necessary because each C `ttinfo` only contains the UTC offset,
1958 * time zone abbreviation and an isdst boolean - it does not include the
1959 * amount of the DST offset, but we need the amount for the dst() function.
1960 *
1961 * Thus function uses heuristics to infer what the offset should be, so it
1962 * is not guaranteed that this will work for all zones. If we cannot assign
1963 * a value for a given DST offset, we'll assume it's 1H rather than 0H, so
1964 * bool(dt.dst()) will always match ttinfo.isdst.
1965 */
1966static void
1967utcoff_to_dstoff(size_t *trans_idx, long *utcoffs, long *dstoffs,
1968 unsigned char *isdsts, size_t num_transitions,
1969 size_t num_ttinfos)
1970{
1971 size_t dst_count = 0;
1972 size_t dst_found = 0;
1973 for (size_t i = 0; i < num_ttinfos; ++i) {
1974 dst_count++;
1975 }
1976
1977 for (size_t i = 1; i < num_transitions; ++i) {
1978 if (dst_count == dst_found) {
1979 break;
1980 }
1981
1982 size_t idx = trans_idx[i];
1983 size_t comp_idx = trans_idx[i - 1];
1984
1985 // Only look at DST offsets that have nto been assigned already
1986 if (!isdsts[idx] || dstoffs[idx] != 0) {
1987 continue;
1988 }
1989
1990 long dstoff = 0;
1991 long utcoff = utcoffs[idx];
1992
1993 if (!isdsts[comp_idx]) {
1994 dstoff = utcoff - utcoffs[comp_idx];
1995 }
1996
1997 if (!dstoff && idx < (num_ttinfos - 1)) {
1998 comp_idx = trans_idx[i + 1];
1999
2000 // If the following transition is also DST and we couldn't find
2001 // the DST offset by this point, we're going to have to skip it
2002 // and hope this transition gets assigned later
2003 if (isdsts[comp_idx]) {
2004 continue;
2005 }
2006
2007 dstoff = utcoff - utcoffs[comp_idx];
2008 }
2009
2010 if (dstoff) {
2011 dst_found++;
2012 dstoffs[idx] = dstoff;
2013 }
2014 }
2015
2016 if (dst_found < dst_count) {
2017 // If there are time zones we didn't find a value for, we'll end up
2018 // with dstoff = 0 for something where isdst=1. This is obviously
2019 // wrong — one hour will be a much better guess than 0.
2020 for (size_t idx = 0; idx < num_ttinfos; ++idx) {
2021 if (isdsts[idx] && !dstoffs[idx]) {
2022 dstoffs[idx] = 3600;
2023 }
2024 }
2025 }
2026}
2027
2028#define _swap(x, y, buffer) \
2029 buffer = x; \
2030 x = y; \
2031 y = buffer;
2032
2033/* Calculate transitions in local time from UTC time and offsets.
2034 *
2035 * We want to know when each transition occurs, denominated in the number of
2036 * nominal wall-time seconds between 1970-01-01T00:00:00 and the transition in
2037 * *local time* (note: this is *not* equivalent to the output of
2038 * datetime.timestamp, which is the total number of seconds actual elapsed
2039 * since 1970-01-01T00:00:00Z in UTC).
2040 *
2041 * This is an ambiguous question because "local time" can be ambiguous — but it
2042 * is disambiguated by the `fold` parameter, so we allocate two arrays:
2043 *
2044 * trans_local[0]: The wall-time transitions for fold=0
2045 * trans_local[1]: The wall-time transitions for fold=1
2046 *
2047 * This returns 0 on success and a negative number of failure. The trans_local
2048 * arrays must be freed if they are not NULL.
2049 */
2050static int
2051ts_to_local(size_t *trans_idx, int64_t *trans_utc, long *utcoff,
2052 int64_t *trans_local[2], size_t num_ttinfos,
2053 size_t num_transitions)
2054{
2055 if (num_transitions == 0) {
2056 return 0;
2057 }
2058
2059 // Copy the UTC transitions into each array to be modified in place later
2060 for (size_t i = 0; i < 2; ++i) {
2061 trans_local[i] = PyMem_Malloc(num_transitions * sizeof(int64_t));
2062 if (trans_local[i] == NULL) {
2063 return -1;
2064 }
2065
2066 memcpy(trans_local[i], trans_utc, num_transitions * sizeof(int64_t));
2067 }
2068
2069 int64_t offset_0, offset_1, buff;
2070 if (num_ttinfos > 1) {
2071 offset_0 = utcoff[0];
2072 offset_1 = utcoff[trans_idx[0]];
2073
2074 if (offset_1 > offset_0) {
2075 _swap(offset_0, offset_1, buff);
2076 }
2077 }
2078 else {
2079 offset_0 = utcoff[0];
2080 offset_1 = utcoff[0];
2081 }
2082
2083 trans_local[0][0] += offset_0;
2084 trans_local[1][0] += offset_1;
2085
2086 for (size_t i = 1; i < num_transitions; ++i) {
2087 offset_0 = utcoff[trans_idx[i - 1]];
2088 offset_1 = utcoff[trans_idx[i]];
2089
2090 if (offset_1 > offset_0) {
2091 _swap(offset_1, offset_0, buff);
2092 }
2093
2094 trans_local[0][i] += offset_0;
2095 trans_local[1][i] += offset_1;
2096 }
2097
2098 return 0;
2099}
2100
2101/* Simple bisect_right binary search implementation */
2102static size_t
2103_bisect(const int64_t value, const int64_t *arr, size_t size)
2104{
2105 size_t lo = 0;
2106 size_t hi = size;
2107 size_t m;
2108
2109 while (lo < hi) {
2110 m = (lo + hi) / 2;
2111 if (arr[m] > value) {
2112 hi = m;
2113 }
2114 else {
2115 lo = m + 1;
2116 }
2117 }
2118
2119 return hi;
2120}
2121
2122/* Find the ttinfo rules that apply at a given local datetime. */
2123static _ttinfo *
2124find_ttinfo(PyZoneInfo_ZoneInfo *self, PyObject *dt)
2125{
2126 // datetime.time has a .tzinfo attribute that passes None as the dt
2127 // argument; it only really has meaning for fixed-offset zones.
2128 if (dt == Py_None) {
2129 if (self->fixed_offset) {
2130 return &(self->tzrule_after.std);
2131 }
2132 else {
2133 return &NO_TTINFO;
2134 }
2135 }
2136
2137 int64_t ts;
2138 if (get_local_timestamp(dt, &ts)) {
2139 return NULL;
2140 }
2141
2142 unsigned char fold = PyDateTime_DATE_GET_FOLD(dt);
2143 assert(fold < 2);
2144 int64_t *local_transitions = self->trans_list_wall[fold];
2145 size_t num_trans = self->num_transitions;
2146
2147 if (num_trans && ts < local_transitions[0]) {
2148 return self->ttinfo_before;
2149 }
2150 else if (!num_trans || ts > local_transitions[self->num_transitions - 1]) {
2151 return find_tzrule_ttinfo(&(self->tzrule_after), ts, fold,
2152 PyDateTime_GET_YEAR(dt));
2153 }
2154 else {
2155 size_t idx = _bisect(ts, local_transitions, self->num_transitions) - 1;
2156 assert(idx < self->num_transitions);
2157 return self->trans_ttinfos[idx];
2158 }
2159}
2160
2161static int
2162is_leap_year(int year)
2163{
2164 const unsigned int ayear = (unsigned int)year;
2165 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
2166}
2167
2168/* Calculates ordinal datetime from year, month and day. */
2169static int
2170ymd_to_ord(int y, int m, int d)
2171{
2172 y -= 1;
2173 int days_before_year = (y * 365) + (y / 4) - (y / 100) + (y / 400);
2174 int yearday = DAYS_BEFORE_MONTH[m];
2175 if (m > 2 && is_leap_year(y + 1)) {
2176 yearday += 1;
2177 }
2178
2179 return days_before_year + yearday + d;
2180}
2181
2182/* Calculate the number of seconds since 1970-01-01 in local time.
2183 *
2184 * This gets a datetime in the same "units" as self->trans_list_wall so that we
2185 * can easily determine which transitions a datetime falls between. See the
2186 * comment above ts_to_local for more information.
2187 * */
2188static int
2189get_local_timestamp(PyObject *dt, int64_t *local_ts)
2190{
2191 assert(local_ts != NULL);
2192
2193 int hour, minute, second;
2194 int ord;
2195 if (PyDateTime_CheckExact(dt)) {
2196 int y = PyDateTime_GET_YEAR(dt);
2197 int m = PyDateTime_GET_MONTH(dt);
2198 int d = PyDateTime_GET_DAY(dt);
2199 hour = PyDateTime_DATE_GET_HOUR(dt);
2200 minute = PyDateTime_DATE_GET_MINUTE(dt);
2201 second = PyDateTime_DATE_GET_SECOND(dt);
2202
2203 ord = ymd_to_ord(y, m, d);
2204 }
2205 else {
2206 PyObject *num = PyObject_CallMethod(dt, "toordinal", NULL);
2207 if (num == NULL) {
2208 return -1;
2209 }
2210
2211 ord = PyLong_AsLong(num);
2212 Py_DECREF(num);
2213 if (ord == -1 && PyErr_Occurred()) {
2214 return -1;
2215 }
2216
2217 num = PyObject_GetAttrString(dt, "hour");
2218 if (num == NULL) {
2219 return -1;
2220 }
2221 hour = PyLong_AsLong(num);
2222 Py_DECREF(num);
2223 if (hour == -1) {
2224 return -1;
2225 }
2226
2227 num = PyObject_GetAttrString(dt, "minute");
2228 if (num == NULL) {
2229 return -1;
2230 }
2231 minute = PyLong_AsLong(num);
2232 Py_DECREF(num);
2233 if (minute == -1) {
2234 return -1;
2235 }
2236
2237 num = PyObject_GetAttrString(dt, "second");
2238 if (num == NULL) {
2239 return -1;
2240 }
2241 second = PyLong_AsLong(num);
2242 Py_DECREF(num);
2243 if (second == -1) {
2244 return -1;
2245 }
2246 }
2247
2248 *local_ts = (int64_t)(ord - EPOCHORDINAL) * 86400 +
2249 (int64_t)(hour * 3600 + minute * 60 + second);
2250
2251 return 0;
2252}
2253
2254/////
2255// Functions for cache handling
2256
2257/* Constructor for StrongCacheNode */
2258static StrongCacheNode *
2259strong_cache_node_new(PyObject *key, PyObject *zone)
2260{
2261 StrongCacheNode *node = PyMem_Malloc(sizeof(StrongCacheNode));
2262 if (node == NULL) {
2263 return NULL;
2264 }
2265
2266 Py_INCREF(key);
2267 Py_INCREF(zone);
2268
2269 node->next = NULL;
2270 node->prev = NULL;
2271 node->key = key;
2272 node->zone = zone;
2273
2274 return node;
2275}
2276
2277/* Destructor for StrongCacheNode */
2278void
2279strong_cache_node_free(StrongCacheNode *node)
2280{
2281 Py_XDECREF(node->key);
2282 Py_XDECREF(node->zone);
2283
2284 PyMem_Free(node);
2285}
2286
2287/* Frees all nodes at or after a specified root in the strong cache.
2288 *
2289 * This can be used on the root node to free the entire cache or it can be used
2290 * to clear all nodes that have been expired (which, if everything is going
2291 * right, will actually only be 1 node at a time).
2292 */
2293void
2294strong_cache_free(StrongCacheNode *root)
2295{
2296 StrongCacheNode *node = root;
2297 StrongCacheNode *next_node;
2298 while (node != NULL) {
2299 next_node = node->next;
2300 strong_cache_node_free(node);
2301
2302 node = next_node;
2303 }
2304}
2305
2306/* Removes a node from the cache and update its neighbors.
2307 *
2308 * This is used both when ejecting a node from the cache and when moving it to
2309 * the front of the cache.
2310 */
2311static void
2312remove_from_strong_cache(StrongCacheNode *node)
2313{
2314 if (ZONEINFO_STRONG_CACHE == node) {
2315 ZONEINFO_STRONG_CACHE = node->next;
2316 }
2317
2318 if (node->prev != NULL) {
2319 node->prev->next = node->next;
2320 }
2321
2322 if (node->next != NULL) {
2323 node->next->prev = node->prev;
2324 }
2325
2326 node->next = NULL;
2327 node->prev = NULL;
2328}
2329
2330/* Retrieves the node associated with a key, if it exists.
2331 *
2332 * This traverses the strong cache until it finds a matching key and returns a
2333 * pointer to the relevant node if found. Returns NULL if no node is found.
2334 *
2335 * root may be NULL, indicating an empty cache.
2336 */
2337static StrongCacheNode *
2338find_in_strong_cache(const StrongCacheNode *const root, PyObject *const key)
2339{
2340 const StrongCacheNode *node = root;
2341 while (node != NULL) {
2342 if (PyObject_RichCompareBool(key, node->key, Py_EQ)) {
2343 return (StrongCacheNode *)node;
2344 }
2345
2346 node = node->next;
2347 }
2348
2349 return NULL;
2350}
2351
2352/* Ejects a given key from the class's strong cache, if applicable.
2353 *
2354 * This function is used to enable the per-key functionality in clear_cache.
2355 */
2356static void
2357eject_from_strong_cache(const PyTypeObject *const type, PyObject *key)
2358{
2359 if (type != &PyZoneInfo_ZoneInfoType) {
2360 return;
2361 }
2362
2363 StrongCacheNode *node = find_in_strong_cache(ZONEINFO_STRONG_CACHE, key);
2364 if (node != NULL) {
2365 remove_from_strong_cache(node);
2366
2367 strong_cache_node_free(node);
2368 }
2369}
2370
2371/* Moves a node to the front of the LRU cache.
2372 *
2373 * The strong cache is an LRU cache, so whenever a given node is accessed, if
2374 * it is not at the front of the cache, it needs to be moved there.
2375 */
2376static void
2377move_strong_cache_node_to_front(StrongCacheNode **root, StrongCacheNode *node)
2378{
2379 StrongCacheNode *root_p = *root;
2380 if (root_p == node) {
2381 return;
2382 }
2383
2384 remove_from_strong_cache(node);
2385
2386 node->prev = NULL;
2387 node->next = root_p;
2388
2389 if (root_p != NULL) {
2390 root_p->prev = node;
2391 }
2392
2393 *root = node;
2394}
2395
2396/* Retrieves a ZoneInfo from the strong cache if it's present.
2397 *
2398 * This function finds the ZoneInfo by key and if found will move the node to
2399 * the front of the LRU cache and return a new reference to it. It returns NULL
2400 * if the key is not in the cache.
2401 *
2402 * The strong cache is currently only implemented for the base class, so this
2403 * always returns a cache miss for subclasses.
2404 */
2405static PyObject *
2406zone_from_strong_cache(const PyTypeObject *const type, PyObject *const key)
2407{
2408 if (type != &PyZoneInfo_ZoneInfoType) {
2409 return NULL; // Strong cache currently only implemented for base class
2410 }
2411
2412 StrongCacheNode *node = find_in_strong_cache(ZONEINFO_STRONG_CACHE, key);
2413
2414 if (node != NULL) {
2415 move_strong_cache_node_to_front(&ZONEINFO_STRONG_CACHE, node);
2416 Py_INCREF(node->zone);
2417 return node->zone;
2418 }
2419
2420 return NULL; // Cache miss
2421}
2422
2423/* Inserts a new key into the strong LRU cache.
2424 *
2425 * This function is only to be used after a cache miss — it creates a new node
2426 * at the front of the cache and ejects any stale entries (keeping the size of
2427 * the cache to at most ZONEINFO_STRONG_CACHE_MAX_SIZE).
2428 */
2429static void
2430update_strong_cache(const PyTypeObject *const type, PyObject *key,
2431 PyObject *zone)
2432{
2433 if (type != &PyZoneInfo_ZoneInfoType) {
2434 return;
2435 }
2436
2437 StrongCacheNode *new_node = strong_cache_node_new(key, zone);
2438
2439 move_strong_cache_node_to_front(&ZONEINFO_STRONG_CACHE, new_node);
2440
2441 StrongCacheNode *node = new_node->next;
2442 for (size_t i = 1; i < ZONEINFO_STRONG_CACHE_MAX_SIZE; ++i) {
2443 if (node == NULL) {
2444 return;
2445 }
2446 node = node->next;
2447 }
2448
2449 // Everything beyond this point needs to be freed
2450 if (node != NULL) {
2451 if (node->prev != NULL) {
2452 node->prev->next = NULL;
2453 }
2454 strong_cache_free(node);
2455 }
2456}
2457
2458/* Clears all entries into a type's strong cache.
2459 *
2460 * Because the strong cache is not implemented for subclasses, this is a no-op
2461 * for everything except the base class.
2462 */
2463void
2464clear_strong_cache(const PyTypeObject *const type)
2465{
2466 if (type != &PyZoneInfo_ZoneInfoType) {
2467 return;
2468 }
2469
2470 strong_cache_free(ZONEINFO_STRONG_CACHE);
Paul Gansslec3dd7e42020-08-17 18:40:07 -04002471 ZONEINFO_STRONG_CACHE = NULL;
Paul Ganssle62972d92020-05-16 04:20:06 -04002472}
2473
2474static PyObject *
Benjamin Peterson0108b2a2020-07-15 10:02:14 -07002475new_weak_cache(void)
Paul Ganssle62972d92020-05-16 04:20:06 -04002476{
2477 PyObject *weakref_module = PyImport_ImportModule("weakref");
2478 if (weakref_module == NULL) {
2479 return NULL;
2480 }
2481
2482 PyObject *weak_cache =
2483 PyObject_CallMethod(weakref_module, "WeakValueDictionary", "");
2484 Py_DECREF(weakref_module);
2485 return weak_cache;
2486}
2487
2488static int
Benjamin Peterson0108b2a2020-07-15 10:02:14 -07002489initialize_caches(void)
Paul Ganssle62972d92020-05-16 04:20:06 -04002490{
Ammar Askar06a1b892020-05-22 16:10:55 +00002491 // TODO: Move to a PyModule_GetState / PEP 573 based caching system.
Paul Ganssle62972d92020-05-16 04:20:06 -04002492 if (TIMEDELTA_CACHE == NULL) {
2493 TIMEDELTA_CACHE = PyDict_New();
2494 }
2495 else {
2496 Py_INCREF(TIMEDELTA_CACHE);
2497 }
2498
2499 if (TIMEDELTA_CACHE == NULL) {
2500 return -1;
2501 }
2502
2503 if (ZONEINFO_WEAK_CACHE == NULL) {
2504 ZONEINFO_WEAK_CACHE = new_weak_cache();
2505 }
2506 else {
2507 Py_INCREF(ZONEINFO_WEAK_CACHE);
2508 }
2509
2510 if (ZONEINFO_WEAK_CACHE == NULL) {
2511 return -1;
2512 }
2513
2514 return 0;
2515}
2516
2517static PyObject *
2518zoneinfo_init_subclass(PyTypeObject *cls, PyObject *args, PyObject **kwargs)
2519{
2520 PyObject *weak_cache = new_weak_cache();
2521 if (weak_cache == NULL) {
2522 return NULL;
2523 }
2524
2525 PyObject_SetAttrString((PyObject *)cls, "_weak_cache", weak_cache);
Paul Gansslec3dd7e42020-08-17 18:40:07 -04002526 Py_DECREF(weak_cache);
Paul Ganssle62972d92020-05-16 04:20:06 -04002527 Py_RETURN_NONE;
2528}
2529
2530/////
2531// Specify the ZoneInfo type
2532static PyMethodDef zoneinfo_methods[] = {
2533 {"clear_cache", (PyCFunction)(void (*)(void))zoneinfo_clear_cache,
2534 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2535 PyDoc_STR("Clear the ZoneInfo cache.")},
2536 {"no_cache", (PyCFunction)(void (*)(void))zoneinfo_no_cache,
2537 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2538 PyDoc_STR("Get a new instance of ZoneInfo, bypassing the cache.")},
2539 {"from_file", (PyCFunction)(void (*)(void))zoneinfo_from_file,
2540 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
2541 PyDoc_STR("Create a ZoneInfo file from a file object.")},
2542 {"utcoffset", (PyCFunction)zoneinfo_utcoffset, METH_O,
2543 PyDoc_STR("Retrieve a timedelta representing the UTC offset in a zone at "
2544 "the given datetime.")},
2545 {"dst", (PyCFunction)zoneinfo_dst, METH_O,
2546 PyDoc_STR("Retrieve a timedelta representing the amount of DST applied "
2547 "in a zone at the given datetime.")},
2548 {"tzname", (PyCFunction)zoneinfo_tzname, METH_O,
2549 PyDoc_STR("Retrieve a string containing the abbreviation for the time "
2550 "zone that applies in a zone at a given datetime.")},
2551 {"fromutc", (PyCFunction)zoneinfo_fromutc, METH_O,
2552 PyDoc_STR("Given a datetime with local time in UTC, retrieve an adjusted "
2553 "datetime in local time.")},
2554 {"__reduce__", (PyCFunction)zoneinfo_reduce, METH_NOARGS,
2555 PyDoc_STR("Function for serialization with the pickle protocol.")},
2556 {"_unpickle", (PyCFunction)zoneinfo__unpickle, METH_VARARGS | METH_CLASS,
2557 PyDoc_STR("Private method used in unpickling.")},
2558 {"__init_subclass__", (PyCFunction)(void (*)(void))zoneinfo_init_subclass,
Paul Ganssle87d82872020-08-13 22:38:30 -04002559 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Paul Ganssle62972d92020-05-16 04:20:06 -04002560 PyDoc_STR("Function to initialize subclasses.")},
2561 {NULL} /* Sentinel */
2562};
2563
2564static PyMemberDef zoneinfo_members[] = {
2565 {.name = "key",
2566 .offset = offsetof(PyZoneInfo_ZoneInfo, key),
2567 .type = T_OBJECT_EX,
2568 .flags = READONLY,
2569 .doc = NULL},
2570 {NULL}, /* Sentinel */
2571};
2572
2573static PyTypeObject PyZoneInfo_ZoneInfoType = {
2574 PyVarObject_HEAD_INIT(NULL, 0) //
2575 .tp_name = "zoneinfo.ZoneInfo",
2576 .tp_basicsize = sizeof(PyZoneInfo_ZoneInfo),
2577 .tp_weaklistoffset = offsetof(PyZoneInfo_ZoneInfo, weakreflist),
2578 .tp_repr = (reprfunc)zoneinfo_repr,
2579 .tp_str = (reprfunc)zoneinfo_str,
2580 .tp_getattro = PyObject_GenericGetAttr,
2581 .tp_flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE),
2582 /* .tp_doc = zoneinfo_doc, */
2583 .tp_methods = zoneinfo_methods,
2584 .tp_members = zoneinfo_members,
2585 .tp_new = zoneinfo_new,
2586 .tp_dealloc = zoneinfo_dealloc,
2587};
2588
2589/////
2590// Specify the _zoneinfo module
2591static PyMethodDef module_methods[] = {{NULL, NULL}};
2592static void
2593module_free()
2594{
2595 Py_XDECREF(_tzpath_find_tzfile);
2596 _tzpath_find_tzfile = NULL;
2597
2598 Py_XDECREF(_common_mod);
2599 _common_mod = NULL;
2600
2601 Py_XDECREF(io_open);
2602 io_open = NULL;
2603
2604 xdecref_ttinfo(&NO_TTINFO);
2605
Ammar Askar06a1b892020-05-22 16:10:55 +00002606 if (TIMEDELTA_CACHE != NULL && Py_REFCNT(TIMEDELTA_CACHE) > 1) {
2607 Py_DECREF(TIMEDELTA_CACHE);
2608 } else {
2609 Py_CLEAR(TIMEDELTA_CACHE);
Paul Ganssle62972d92020-05-16 04:20:06 -04002610 }
2611
Ammar Askar06a1b892020-05-22 16:10:55 +00002612 if (ZONEINFO_WEAK_CACHE != NULL && Py_REFCNT(ZONEINFO_WEAK_CACHE) > 1) {
2613 Py_DECREF(ZONEINFO_WEAK_CACHE);
2614 } else {
2615 Py_CLEAR(ZONEINFO_WEAK_CACHE);
Paul Ganssle62972d92020-05-16 04:20:06 -04002616 }
2617
Paul Gansslec3dd7e42020-08-17 18:40:07 -04002618 clear_strong_cache(&PyZoneInfo_ZoneInfoType);
Paul Ganssle62972d92020-05-16 04:20:06 -04002619}
2620
2621static int
2622zoneinfomodule_exec(PyObject *m)
2623{
2624 PyDateTime_IMPORT;
2625 PyZoneInfo_ZoneInfoType.tp_base = PyDateTimeAPI->TZInfoType;
2626 if (PyType_Ready(&PyZoneInfo_ZoneInfoType) < 0) {
2627 goto error;
2628 }
2629
2630 Py_INCREF(&PyZoneInfo_ZoneInfoType);
2631 PyModule_AddObject(m, "ZoneInfo", (PyObject *)&PyZoneInfo_ZoneInfoType);
2632
2633 /* Populate imports */
2634 PyObject *_tzpath_module = PyImport_ImportModule("zoneinfo._tzpath");
2635 if (_tzpath_module == NULL) {
2636 goto error;
2637 }
2638
2639 _tzpath_find_tzfile =
2640 PyObject_GetAttrString(_tzpath_module, "find_tzfile");
2641 Py_DECREF(_tzpath_module);
2642 if (_tzpath_find_tzfile == NULL) {
2643 goto error;
2644 }
2645
2646 PyObject *io_module = PyImport_ImportModule("io");
2647 if (io_module == NULL) {
2648 goto error;
2649 }
2650
2651 io_open = PyObject_GetAttrString(io_module, "open");
2652 Py_DECREF(io_module);
2653 if (io_open == NULL) {
2654 goto error;
2655 }
2656
2657 _common_mod = PyImport_ImportModule("zoneinfo._common");
2658 if (_common_mod == NULL) {
2659 goto error;
2660 }
2661
2662 if (NO_TTINFO.utcoff == NULL) {
2663 NO_TTINFO.utcoff = Py_None;
2664 NO_TTINFO.dstoff = Py_None;
2665 NO_TTINFO.tzname = Py_None;
2666
2667 for (size_t i = 0; i < 3; ++i) {
2668 Py_INCREF(Py_None);
2669 }
2670 }
2671
2672 if (initialize_caches()) {
2673 goto error;
2674 }
2675
2676 return 0;
2677
2678error:
2679 return -1;
2680}
2681
2682static PyModuleDef_Slot zoneinfomodule_slots[] = {
2683 {Py_mod_exec, zoneinfomodule_exec}, {0, NULL}};
2684
2685static struct PyModuleDef zoneinfomodule = {
2686 PyModuleDef_HEAD_INIT,
2687 .m_name = "_zoneinfo",
2688 .m_doc = "C implementation of the zoneinfo module",
2689 .m_size = 0,
2690 .m_methods = module_methods,
2691 .m_slots = zoneinfomodule_slots,
2692 .m_free = (freefunc)module_free};
2693
2694PyMODINIT_FUNC
2695PyInit__zoneinfo(void)
2696{
2697 return PyModuleDef_Init(&zoneinfomodule);
2698}