-
Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathiso8601.c
More file actions
2437 lines (2061 loc) · 67.1 KB
/
Copy pathiso8601.c
File metadata and controls
2437 lines (2061 loc) · 67.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
/*
* Copyright 2005-2026 the Pacemaker project contributors
*
* The version control history for this file may have further details.
*
* This source code is licensed under the GNU Lesser General Public License
* version 2.1 or later (LGPLv2.1+) WITHOUT ANY WARRANTY.
*/
/*
* References:
* https://en.wikipedia.org/wiki/ISO_8601
* http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm
*/
#include <crm_internal.h>
#include <crm/crm.h>
#include <time.h>
#include <ctype.h>
#include <inttypes.h>
#include <limits.h> // INT_MIN, INT_MAX
#include <string.h>
#include <stdbool.h>
#include <glib.h> // g_strchomp()
#include <crm/common/iso8601.h>
#include "crmcommon_private.h"
/*
* Andrew's code was originally written for OSes whose "struct tm" contains:
* long tm_gmtoff; :: Seconds east of UTC
* const char *tm_zone; :: Timezone abbreviation
* Some OSes lack these, instead having:
* time_t (or long) timezone;
:: "difference between UTC and local standard time"
* char *tzname[2] = { "...", "..." };
* I (David Lee) confess to not understanding the details. So my attempted
* generalisations for where their use is necessary may be flawed.
*
* 1. Does "difference between ..." subtract the same or opposite way?
* 2. Should it use "altzone" instead of "timezone"?
* 3. Should it use tzname[0] or tzname[1]? Interaction with timezone/altzone?
*/
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
# define GMTOFF(tm) ((tm)->tm_gmtoff)
#else
/* Note: extern variable; macro argument not actually used. */
# define GMTOFF(tm) (-timezone+daylight)
#endif
#define SECONDS_IN_MINUTE 60
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_HOUR (SECONDS_IN_MINUTE * MINUTES_IN_HOUR)
#define HOURS_IN_DAY 24
#define SECONDS_IN_DAY (SECONDS_IN_HOUR * HOURS_IN_DAY)
#define BEGIN_VALID_RANGE_S "0001-01-01T00:00:00"
#define END_VALID_RANGE_S "9999-12-31T23:59:59"
/*!
* \internal
* \brief Validate a seconds/microseconds tuple
*
* The microseconds value must be in the correct range, and if both are nonzero
* they must have the same sign.
*
* \param[in] sec Seconds
* \param[in] usec Microseconds
*
* \return true if the seconds/microseconds tuple is valid, or false otherwise
*/
#define valid_sec_usec(sec, usec) \
((QB_ABS(usec) < QB_TIME_US_IN_SEC) \
&& (((sec) == 0) || ((usec) == 0) || (((sec) < 0) == ((usec) < 0))))
/*!
* \brief Allocate memory for an uninitialized time object
*
* \return Newly allocated time object (guaranteed not to be \c NULL)
*
* \note The caller is responsible for freeing the return value using
* \c crm_time_free().
*/
crm_time_t *
crm_time_new_undefined(void)
{
return pcmk__assert_alloc(1, sizeof(crm_time_t));
}
/*!
* \internal
* \brief Check whether a year is positive and representable by four digits
*
* \param[in] year Year
*
* \return \c true if \p year is between 1 and 9999 (inclusive), or \c false
* otherwise
*/
bool
pcmk__time_valid_year(int year)
{
return (year >= 1) && (year <= 9999);
}
static bool
is_leap_year(int year)
{
/* @COMPAT Remove this fallback when we can ensure that the year argument is
* always in the range 1 to 9999.
*/
if (!pcmk__time_valid_year(year)) {
return ((year % 4) == 0)
&& (((year % 100) != 0) || (year % 400 == 0));
}
return g_date_is_leap_year(year);
}
/*!
* \internal
* \brief Return number of days in given month of given year
*
* \param[in] month Ordinal month (1-12)
* \param[in] year Gregorian year
*
* \return Number of days in given month (0 if given month or year is invalid)
*/
static int
days_in_month_year(int month, int year)
{
if (!g_date_valid_month(month)) {
return 0;
}
if (year < 1) {
return 0;
}
/* @COMPAT Remove this fallback when we can ensure that the year argument is
* always in the range 1 to 9999. g_date_get_days_in_month() takes a
* GDateYear, which is defined as guint16.
*/
if (year > UINT16_MAX) {
static const int month_days[12] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
if ((month == 2) && is_leap_year(year)) {
return month_days[1] + 1;
}
return month_days[month - 1];
}
return g_date_get_days_in_month(month, year);
}
/*!
* \internal
* \brief Get ordinal day number of year corresponding to given date
*
* \param[in] year Year
* \param[in] month Month (1-12)
* \param[in] day Day of month (1-31)
*
* \return Day number of year \p year corresponding to month \p month and day
* \p day, or 0 for invalid arguments
*/
static int
get_ordinal_days(uint32_t year, uint32_t month, uint32_t day)
{
int prev_month_days = 0;
CRM_CHECK((year >= 1) && (year <= INT_MAX)
&& (month >= 1) && (month <= 12)
&& (day >= 1) && (day <= 31), return 0);
for (int i = 1; i < month; i++) {
prev_month_days += days_in_month_year(i, year);
}
return prev_month_days + day;
}
static int
year_days(int year)
{
return is_leap_year(year)? 366 : 365;
}
/* From http://myweb.ecu.edu/mccartyr/ISOwdALG.txt :
*
* 5. Find the Jan1Weekday for Y (Monday=1, Sunday=7)
* YY = (Y-1) % 100
* C = (Y-1) - YY
* G = YY + YY/4
* Jan1Weekday = 1 + (((((C / 100) % 4) x 5) + G) % 7)
*/
static int
jan1_day_of_week(int year)
{
int YY = (year - 1) % 100;
int C = (year - 1) - YY;
int G = YY + YY / 4;
int jan1 = 1 + (((((C / 100) % 4) * 5) + G) % 7);
pcmk__trace("YY=%d, C=%d, G=%d", YY, C, G);
pcmk__trace("January 1 %.4d: %d", year, jan1);
return jan1;
}
static int
weeks_in_year(int year)
{
int weeks = 52;
int jan1 = jan1_day_of_week(year);
/* if jan1 == thursday */
if (jan1 == 4) {
weeks++;
} else {
jan1 = jan1_day_of_week(year + 1);
/* if dec31 == thursday aka. jan1 of next year is a friday */
if (jan1 == 5) {
weeks++;
}
}
return weeks;
}
/*!
* \internal
* \brief Determine number of seconds from an hour:minute:second string
*
* \param[in] time_str Time specification string
* \param[out] result Number of seconds equivalent to time_str
*
* \return \c true if specification was valid, or \c false otherwise
* \note This may return the number of seconds in a day (which is out of bounds
* for a time object) if given 24:00:00.
*/
static bool
parse_hms(const char *time_str, int *result)
{
int rc;
uint32_t hour = 0;
uint32_t minute = 0;
uint32_t second = 0;
*result = 0;
// Must have at least hour, but minutes and seconds are optional
rc = sscanf(time_str, "%" SCNu32 ":%" SCNu32 ":%" SCNu32,
&hour, &minute, &second);
if (rc == 1) {
rc = sscanf(time_str, "%2" SCNu32 "%2" SCNu32 "%2" SCNu32,
&hour, &minute, &second);
}
if (rc < 1) {
pcmk__err("'%s' is not a valid ISO 8601 time specification", time_str);
return false;
}
pcmk__trace("Got valid time: %.2" PRIu32 ":%.2" PRIu32 ":%.2" PRIu32,
hour, minute, second);
if ((hour == HOURS_IN_DAY) && (minute == 0) && (second == 0)) {
// Equivalent to 00:00:00 of next day, return number of seconds in day
} else if (hour >= HOURS_IN_DAY) {
pcmk__err("%s is not a valid ISO 8601 time specification "
"because %" PRIu32 " is not a valid hour", time_str, hour);
return false;
}
if (minute >= MINUTES_IN_HOUR) {
pcmk__err("%s is not a valid ISO 8601 time specification "
"because %" PRIu32 " is not a valid minute", time_str,
minute);
return false;
}
if (second >= SECONDS_IN_MINUTE) {
pcmk__err("%s is not a valid ISO 8601 time specification "
"because %" PRIu32 " is not a valid second", time_str,
second);
return false;
}
*result = (hour * SECONDS_IN_HOUR) + (minute * SECONDS_IN_MINUTE) + second;
return true;
}
static bool
parse_offset(const char *offset_str, int *offset)
{
tzset();
if (offset_str == NULL) {
// Use local offset
#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
time_t now = time(NULL);
struct tm *now_tm = localtime(&now);
#endif
int h_offset = GMTOFF(now_tm) / SECONDS_IN_HOUR;
int m_offset = (GMTOFF(now_tm) - (SECONDS_IN_HOUR * h_offset))
/ SECONDS_IN_MINUTE;
if (h_offset < 0 && m_offset < 0) {
m_offset = 0 - m_offset;
}
*offset = (SECONDS_IN_HOUR * h_offset) + (SECONDS_IN_MINUTE * m_offset);
return true;
}
if (offset_str[0] == 'Z') { // @TODO invalid if anything after?
*offset = 0;
return true;
}
*offset = 0;
if ((offset_str[0] == '+') || (offset_str[0] == '-')
|| isdigit((int)offset_str[0])) {
bool negate = false;
if (offset_str[0] == '+') {
offset_str++;
} else if (offset_str[0] == '-') {
negate = true;
offset_str++;
}
if (!parse_hms(offset_str, offset)) {
return false;
}
if (negate) {
*offset = 0 - *offset;
}
} // @TODO else invalid?
return true;
}
/*!
* \internal
* \brief Convert seconds to hours, minutes, and seconds
*
* The resulting minutes and seconds are in the range [0, 59]. Accordingly, the
* number of hours is \p seconds_i divided by \c SECONDS_IN_HOUR.
*
* \param[in] seconds_i Seconds to convert
* \param[out] hours Where to store hours
* \param[out] minutes Where to store minutes
* \param[out] seconds If not \c NULL, where to store seconds
*/
static void
seconds_to_hms(int seconds_i, uint32_t *hours, uint32_t *minutes,
uint32_t *seconds)
{
int hours_i = 0;
int minutes_i = 0;
hours_i = seconds_i / SECONDS_IN_HOUR;
seconds_i %= SECONDS_IN_HOUR;
minutes_i = seconds_i / SECONDS_IN_MINUTE;
seconds_i %= SECONDS_IN_MINUTE;
*hours = (uint32_t) QB_ABS(hours_i);
*minutes = (uint32_t) QB_ABS(minutes_i);
if (seconds != NULL) {
*seconds = (uint32_t) QB_ABS(seconds_i);
}
}
/*!
* \internal
* \brief Parse the time portion of an ISO 8601 date/time string
*
* \param[in] time_str Time portion of specification (after any 'T')
* \param[in,out] a_time Time object to parse into
*
* \return \c true if valid time was parsed, \c false otherwise
* \note This may add a day to a_time (if the time is 24:00:00).
*/
static bool
parse_time(const char *time_str, crm_time_t *a_time)
{
uint32_t h = 0;
uint32_t m = 0;
const char *offset_s = NULL;
tzset();
if (!parse_hms(time_str, &(a_time->seconds))) {
return false;
}
offset_s = strchr(time_str, 'Z');
/* @COMPAT: Spaces between the time and the offset are not supported by the
* standard according to section 3.4.1 and 4.2.5.2.
*/
if (offset_s == NULL) {
offset_s = strpbrk(time_str, " +-");
}
if (offset_s != NULL) {
while (isspace(*offset_s)) {
offset_s++;
}
}
if (!parse_offset(offset_s, &(a_time->offset))) {
return false;
}
seconds_to_hms(a_time->offset, &h, &m, NULL);
pcmk__trace("Got tz: %c%2." PRIu32 ":%.2" PRIu32,
(a_time->offset < 0)? '-' : '+', h, m);
if (a_time->seconds == SECONDS_IN_DAY) {
// 24:00:00 == 00:00:00 of next day
a_time->seconds = 0;
crm_time_add_days(a_time, 1);
}
return true;
}
/*!
* \internal
* \brief Check whether a time object represents a sensible date/time
*
* \param[in] dt Date/time object to check
*
* \return \c true if days and seconds are valid given the year, or \c false
* otherwise
*/
bool
valid_time(const crm_time_t *dt)
{
return (dt != NULL)
&& (dt->days > 0) && (dt->days <= year_days(dt->years))
&& (dt->seconds >= 0) && (dt->seconds < SECONDS_IN_DAY);
}
/*
* \internal
* \brief Parse a time object from an ISO 8601 date/time specification
*
* \param[in] date_str ISO 8601 date/time specification (or
* \c PCMK__VALUE_EPOCH)
*
* \return New time object on success, NULL (and set errno) otherwise
*/
static crm_time_t *
parse_date(const char *date_str)
{
const uint32_t flags = crm_time_log_date|crm_time_log_timeofday;
const char *time_s = NULL;
crm_time_t *dt = NULL;
uint32_t year = 0U;
uint32_t month = 0U;
uint32_t day = 0U;
uint32_t week = 0U;
int rc = 0;
if (pcmk__str_empty(date_str)) {
pcmk__err("No ISO 8601 date/time specification given");
goto invalid;
}
if ((date_str[0] == 'T')
|| ((strlen(date_str) > 2) && (date_str[2] == ':'))) {
/* Just a time supplied - Infer current date */
dt = pcmk__copy_timet(time(NULL));
if (date_str[0] == 'T') {
time_s = date_str + 1;
} else {
time_s = date_str;
}
goto parse_time_segment;
}
dt = crm_time_new_undefined();
if ((strncasecmp(PCMK__VALUE_EPOCH, date_str, 5) == 0)
&& ((date_str[5] == '\0')
|| (date_str[5] == '/')
|| isspace(date_str[5]))) {
dt->days = 1;
dt->years = 1970;
pcmk__time_log(LOG_TRACE, "Unpacked", dt, flags);
return dt;
}
/* YYYY-MM-DD */
rc = sscanf(date_str, "%" SCNu32 "-%" SCNu32 "-%" SCNu32 "",
&year, &month, &day);
if (rc == 1) {
/* YYYYMMDD */
rc = sscanf(date_str, "%4" SCNu32 "%2" SCNu32 "%2" SCNu32 "",
&year, &month, &day);
}
if (rc == 3) {
if ((month < 1U) || (month > 12U)) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid month",
date_str, month);
goto invalid;
} else if ((year < 1U) || (year > INT_MAX)) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid year",
date_str, year);
goto invalid;
} else if ((day < 1) || (day > INT_MAX)
|| (day > days_in_month_year(month, year))) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid day of the month",
date_str, day);
goto invalid;
} else {
dt->years = year;
dt->days = get_ordinal_days(year, month, day);
pcmk__trace("Parsed Gregorian date '%.4" PRIu32 "-%.3d' "
"from date string '%s'", year, dt->days, date_str);
}
goto parse_time_segment;
}
/* YYYY-DDD */
rc = sscanf(date_str, "%" SCNu32 "-%" SCNu32, &year, &day);
if (rc == 2) {
if ((year < 1U) || (year > INT_MAX)) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid year",
date_str, year);
goto invalid;
} else if ((day < 1U) || (day > INT_MAX) || (day > year_days(year))) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid day of year %"
PRIu32 " (1-%d)",
date_str, day, year, year_days(year));
goto invalid;
}
pcmk__trace("Parsed ordinal year %d and days %d from date string '%s'",
year, day, date_str);
dt->days = day;
dt->years = year;
goto parse_time_segment;
}
/* YYYY-Www-D */
rc = sscanf(date_str, "%" SCNu32 "-W%" SCNu32 "-%" SCNu32,
&year, &week, &day);
if (rc == 3) {
if ((week < 1U) || (week > weeks_in_year(year))) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid week of year %"
PRIu32 " (1-%d)",
date_str, week, year, weeks_in_year(year));
goto invalid;
} else if ((day < 1U) || (day > 7U)) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification "
"because '%" PRIu32 "' is not a valid day of the week",
date_str, day);
goto invalid;
} else {
/*
* See https://en.wikipedia.org/wiki/ISO_week_date
*
* Monday 29 December 2008 is written "2009-W01-1"
* Sunday 3 January 2010 is written "2009-W53-7"
* Saturday 27 September 2008 is written "2008-W37-6"
*
* If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it
* is in week 1. If 1 January is on a Friday, Saturday or Sunday,
* it is in week 52 or 53 of the previous year.
*/
int jan1 = jan1_day_of_week(year);
pcmk__trace("Parsed year %" PRIu32 " (Jan 1 = %d), week %" PRIu32
", and day %" PRIu32 " from date string '%s'",
year, jan1, week, day, date_str);
dt->years = year;
crm_time_add_days(dt, (week - 1) * 7);
if (jan1 <= 4) {
crm_time_add_days(dt, 1 - jan1);
} else {
crm_time_add_days(dt, 8 - jan1);
}
crm_time_add_days(dt, day);
}
goto parse_time_segment;
}
pcmk__err("'%s' is not a valid ISO 8601 date/time specification", date_str);
goto invalid;
parse_time_segment:
if (time_s == NULL) {
time_s = date_str + strspn(date_str, "0123456789-W");
if ((time_s[0] == ' ') || (time_s[0] == 'T')) {
++time_s;
} else {
time_s = NULL;
}
}
if ((time_s != NULL) && !parse_time(time_s, dt)) {
goto invalid;
}
pcmk__time_log(LOG_TRACE, "Unpacked", dt, flags);
if (!valid_time(dt)) {
pcmk__err("'%s' is not a valid ISO 8601 date/time specification",
date_str);
goto invalid;
}
return dt;
invalid:
crm_time_free(dt);
errno = EINVAL;
return NULL;
}
// Return value is guaranteed not to be NULL
static crm_time_t *
copy_time_to_utc(const crm_time_t *dt)
{
const uint32_t flags = crm_time_log_date
|crm_time_log_timeofday
|crm_time_log_with_timezone;
crm_time_t *utc = NULL;
pcmk__assert(dt != NULL);
utc = crm_time_new_undefined();
utc->years = dt->years;
utc->days = dt->days;
utc->seconds = dt->seconds;
utc->offset = 0;
if (dt->offset != 0) {
crm_time_add_seconds(utc, -dt->offset);
} else {
// Durations (the only things that can include months) never have a TZ
utc->months = dt->months;
}
pcmk__time_log(LOG_TRACE, "utc-source", dt, flags);
pcmk__time_log(LOG_TRACE, "utc-target", utc, flags);
return utc;
}
crm_time_t *
crm_time_new(const char *date_time)
{
tzset();
if (date_time == NULL) {
return pcmk__copy_timet(time(NULL));
}
return parse_date(date_time);
}
/*!
* \brief Check whether a time object has been initialized yet
*
* \param[in] t Time object to check
*
* \return \c true if time object has been initialized, \c false otherwise
*/
bool
crm_time_is_defined(const crm_time_t *t)
{
// Any nonzero member indicates something has been done to t
return (t != NULL) && (t->years || t->months || t->days || t->seconds
|| t->offset || t->duration);
}
void
crm_time_free(crm_time_t * dt)
{
if (dt == NULL) {
return;
}
free(dt);
}
void
pcmk__time_log_as(const char *file, const char *function, int line,
uint8_t level, const char *prefix, const crm_time_t *dt,
uint32_t flags)
{
char *date_s = crm_time_as_string(dt, flags);
if (prefix != NULL) {
char *old = date_s;
date_s = pcmk__assert_asprintf("%s: %s", prefix, date_s);
free(old);
}
if (level == PCMK__LOG_STDOUT) {
printf("%s\n", date_s);
} else {
do_crm_log_alias(level, file, function, line, "%s", date_s);
}
free(date_s);
}
int
crm_time_get_timeofday(const crm_time_t *dt, uint32_t *h, uint32_t *m,
uint32_t *s)
{
pcmk__assert((dt != NULL) && (h != NULL) && (m != NULL) && (s != NULL));
seconds_to_hms(dt->seconds, h, m, s);
return TRUE;
}
long long
crm_time_get_seconds(const crm_time_t *dt)
{
crm_time_t *utc = NULL;
long long days = 0;
long long seconds = 0;
if (dt == NULL) {
return 0;
}
if (dt->offset != 0) {
utc = copy_time_to_utc(dt);
dt = utc;
}
if (dt->duration) {
/* Assume 365-day years and 30-day months. The correct number of days in
* years and months varies depending on the start date to which the
* duration will be applied, which is unknown.
*/
days = (365 * (long long) dt->years)
+ (30 * (long long) dt->months)
+ dt->days;
} else {
// The months field can be set only for durations, so ignore it here
for (int i = 1; i < dt->years; i++) {
days += year_days(i);
}
// This is probably always true
if (dt->days > 0) {
days += dt->days - 1;
}
}
seconds = dt->seconds + (SECONDS_IN_DAY * days);
crm_time_free(utc);
return seconds;
}
#define EPOCH_SECONDS 62135596800ULL /* Calculated using crm_time_get_seconds() */
long long
crm_time_get_seconds_since_epoch(const crm_time_t *dt)
{
return (dt == NULL)? 0 : (crm_time_get_seconds(dt) - EPOCH_SECONDS);
}
int
crm_time_get_gregorian(const crm_time_t *dt, uint32_t *y, uint32_t *m,
uint32_t *d)
{
int months = 0;
int days = dt->days;
pcmk__assert((dt != NULL) && (y != NULL) && (m != NULL) && (d != NULL));
if(dt->years != 0) {
for (months = 1; months <= 12 && days > 0; months++) {
int mdays = days_in_month_year(months, dt->years);
if (mdays >= days) {
break;
} else {
days -= mdays;
}
}
} else if (dt->months) {
/* This is a duration including months, don't convert the days field */
months = dt->months;
} else {
/* This is a duration not including months, still don't convert the days field */
}
*y = dt->years;
*m = months;
*d = days;
pcmk__trace("%.4d-%.3d -> %.4d-%.2d-%.2d", dt->years, dt->days, dt->years,
months, days);
return TRUE;
}
int
crm_time_get_ordinal(const crm_time_t *dt, uint32_t *y, uint32_t *d)
{
pcmk__assert((dt != NULL) && (y != NULL) && (d != NULL));
*y = dt->years;
*d = dt->days;
return TRUE;
}
void
pcmk__time_get_ywd(const crm_time_t *dt, uint32_t *y, uint32_t *w, uint32_t *d)
{
// Based on ISO week date: https://en.wikipedia.org/wiki/ISO_week_date
int year_num = 0;
int jan1 = 0;
int h = -1;
pcmk__assert((dt != NULL) && (y != NULL) && (w != NULL) && (d != NULL));
if (dt->days <= 0) {
return;
}
jan1 = jan1_day_of_week(dt->years);
/* 6. Find the Weekday for Y M D */
h = dt->days + jan1 - 1;
*d = 1 + ((h - 1) % 7);
/* 7. Find if Y M D falls in YearNumber Y-1, WeekNumber 52 or 53 */
if (dt->days <= (8 - jan1) && jan1 > 4) {
pcmk__trace("year--, jan1=%d", jan1);
year_num = dt->years - 1;
*w = weeks_in_year(year_num);
} else {
year_num = dt->years;
}
/* 8. Find if Y M D falls in YearNumber Y+1, WeekNumber 1 */
if (year_num == dt->years) {
int dmax = year_days(year_num);
int correction = 4 - *d;
if ((dmax - dt->days) < correction) {
pcmk__trace("year++, jan1=%d, i=%d vs. %d", jan1, dmax - dt->days,
correction);
year_num = dt->years + 1;
*w = 1;
}
}
/* 9. Find if Y M D falls in YearNumber Y, WeekNumber 1 through 53 */
if (year_num == dt->years) {
int j = dt->days + (7 - *d) + (jan1 - 1);
*w = j / 7;
if (jan1 > 4) {
*w -= 1;
}
}
*y = year_num;
pcmk__trace("Converted %.4d-%.3d to %.4" PRIu32 "-W%.2" PRIu32 "-%" PRIu32,
dt->years, dt->days, *y, *w, *d);
}
/*!
* \internal
* \brief Print "<seconds>.<microseconds>" to a buffer
*
* \param[in] sec Seconds
* \param[in] usec Microseconds (must be of same sign as \p sec and of
* absolute value less than \c QB_TIME_US_IN_SEC)
* \param[in,out] buf Result buffer
*/
static inline void
sec_usec_as_string(long long sec, int usec, GString *buf)
{
/* A negative value smaller than -1 second should have the negative sign
* before the 0, not before the usec part
*/
if ((sec == 0) && (usec < 0)) {
g_string_append_c(buf, '-');
}
g_string_append_printf(buf, "%lld.%06d", sec, QB_ABS(usec));
}
/*!
* \internal
* \brief Get a string representation of a duration
*
* \param[in] dt Time object to interpret as a duration
* \param[in] usec Microseconds to add to \p dt
* \param[in] show_usec Whether to include microseconds in \p buf
* \param[in,out] buf Result buffer
*/
static void
duration_as_string(const crm_time_t *dt, int usec, bool show_usec, GString *buf)
{
pcmk__assert(valid_sec_usec(dt->seconds, usec));
if (dt->years) {
g_string_append_printf(buf, "%4d year%s ",
dt->years, pcmk__plural_s(dt->years));
}
if (dt->months) {
g_string_append_printf(buf, "%2d month%s ",
dt->months, pcmk__plural_s(dt->months));
}
if (dt->days) {
g_string_append_printf(buf, "%2d day%s ",
dt->days, pcmk__plural_s(dt->days));
}
// At least print seconds (and optionally usecs)
if ((buf->len == 0) || (dt->seconds != 0) || (show_usec && (usec != 0))) {
if (show_usec) {
sec_usec_as_string(dt->seconds, usec, buf);
} else {
g_string_append_printf(buf, "%d", dt->seconds);
}
g_string_append_printf(buf, " second%s", pcmk__plural_s(dt->seconds));
}
// More than one minute, so provide a more readable breakdown into units
if (QB_ABS(dt->seconds) >= SECONDS_IN_MINUTE) {
uint32_t h = 0;
uint32_t m = 0;
uint32_t s = 0;
uint32_t u = QB_ABS(usec);
bool print_sec_component = false;
seconds_to_hms(dt->seconds, &h, &m, &s);
print_sec_component = ((s != 0) || (show_usec && (u != 0)));
g_string_append(buf, " (");
if (h) {
g_string_append_printf(buf, "%" PRIu32 " hour%s",
h, pcmk__plural_s(h));
if ((m != 0) || print_sec_component) {
g_string_append_c(buf, ' ');
}
}
if (m) {
g_string_append_printf(buf, "%" PRIu32 " minute%s",
m, pcmk__plural_s(m));
if (print_sec_component) {
g_string_append_c(buf, ' ');
}
}
if (print_sec_component) {
if (show_usec) {
sec_usec_as_string(s, u, buf);
} else {
g_string_append_printf(buf, "%" PRIu32, s);
}
g_string_append_printf(buf, " second%s",
pcmk__plural_s(dt->seconds));
}
g_string_append_c(buf, ')');
}
}
/*!
* \internal
* \brief Get a string representation of a time object
*
* \param[in] dt Time to convert to string
* \param[in] usec Microseconds to add to \p dt
* \param[in] flags Group of \c crm_time_* string format options
*
* \return Newly allocated string representation of \p dt plus \p usec
*
* \note The caller is responsible for freeing the return value using \c free().
*/
static char *
time_as_string_common(const crm_time_t *dt, int usec, uint32_t flags)
{
crm_time_t *utc = NULL;