• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 19603132989

22 Nov 2025 10:41PM UTC coverage: 72.453% (-0.07%) from 72.518%
19603132989

push

github

YHNdnzj
docs: Document cast formatting rules

308192 of 425371 relevant lines covered (72.45%)

1182701.2 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.64
/src/basic/time-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <sys/timerfd.h>
5
#include <threads.h>
6
#include <unistd.h>
7

8
#include "alloc-util.h"
9
#include "env-util.h"
10
#include "errno-util.h"
11
#include "extract-word.h"
12
#include "hexdecoct.h"          /* IWYU pragma: keep */
13
#include "fd-util.h"
14
#include "fileio.h"
15
#include "fs-util.h"
16
#include "io-util.h"
17
#include "log.h"
18
#include "parse-util.h"
19
#include "path-util.h"
20
#include "stat-util.h"
21
#include "stdio-util.h"
22
#include "string-table.h"
23
#include "string-util.h"
24
#include "strv.h"
25
#include "time-util.h"
26

27
static clockid_t map_clock_id(clockid_t c) {
29,470,619✔
28

29
        /* Some more exotic archs (s390, ppc, …) lack the "ALARM" flavour of the clocks. Thus,
30
         * clock_gettime() will fail for them. Since they are essentially the same as their non-ALARM
31
         * pendants (their only difference is when timers are set on them), let's just map them
32
         * accordingly. This way, we can get the correct time even on those archs. */
33

34
        switch (c) {
29,470,619✔
35

36
        case CLOCK_BOOTTIME_ALARM:
37
                return CLOCK_BOOTTIME;
38

39
        case CLOCK_REALTIME_ALARM:
8✔
40
                return CLOCK_REALTIME;
8✔
41

42
        default:
29,470,610✔
43
                return c;
29,470,610✔
44
        }
45
}
46

47
usec_t now(clockid_t clock_id) {
29,467,981✔
48
        struct timespec ts;
29,467,981✔
49

50
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
29,467,981✔
51

52
        return timespec_load(&ts);
29,467,981✔
53
}
54

55
nsec_t now_nsec(clockid_t clock_id) {
620✔
56
        struct timespec ts;
620✔
57

58
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
620✔
59

60
        return timespec_load_nsec(&ts);
620✔
61
}
62

63
dual_timestamp* dual_timestamp_now(dual_timestamp *ts) {
1,951,647✔
64
        assert(ts);
1,951,647✔
65

66
        ts->realtime = now(CLOCK_REALTIME);
1,951,647✔
67
        ts->monotonic = now(CLOCK_MONOTONIC);
1,951,647✔
68

69
        return ts;
1,951,647✔
70
}
71

72
triple_timestamp* triple_timestamp_now(triple_timestamp *ts) {
3,379,817✔
73
        assert(ts);
3,379,817✔
74

75
        ts->realtime = now(CLOCK_REALTIME);
3,379,817✔
76
        ts->monotonic = now(CLOCK_MONOTONIC);
3,379,817✔
77
        ts->boottime = now(CLOCK_BOOTTIME);
3,379,817✔
78

79
        return ts;
3,379,817✔
80
}
81

82
usec_t map_clock_usec_raw(usec_t from, usec_t from_base, usec_t to_base) {
8,688✔
83

84
        /* Maps the time 'from' between two clocks, based on a common reference point where the first clock
85
         * is at 'from_base' and the second clock at 'to_base'. Basically calculates:
86
         *
87
         *         from - from_base + to_base
88
         *
89
         * But takes care of overflows/underflows and avoids signed operations. */
90

91
        if (from >= from_base) { /* In the future */
8,688✔
92
                usec_t delta = from - from_base;
33✔
93

94
                if (to_base >= USEC_INFINITY - delta) /* overflow? */
33✔
95
                        return USEC_INFINITY;
96

97
                return to_base + delta;
33✔
98

99
        } else { /* In the past */
100
                usec_t delta = from_base - from;
8,655✔
101

102
                if (to_base <= delta) /* underflow? */
8,655✔
103
                        return 0;
104

105
                return to_base - delta;
8,647✔
106
        }
107
}
108

109
usec_t map_clock_usec(usec_t from, clockid_t from_clock, clockid_t to_clock) {
478✔
110

111
        /* Try to avoid any inaccuracy needlessly added in case we convert from effectively the same clock
112
         * onto itself */
113
        if (map_clock_id(from_clock) == map_clock_id(to_clock))
478✔
114
                return from;
115

116
        /* Keep infinity as is */
117
        if (from == USEC_INFINITY)
478✔
118
                return from;
119

120
        return map_clock_usec_raw(from, now(from_clock), now(to_clock));
436✔
121
}
122

123
dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
12✔
124
        assert(ts);
12✔
125

126
        if (!timestamp_is_set(u)) {
12✔
127
                ts->realtime = ts->monotonic = u;
×
128
                return ts;
×
129
        }
130

131
        ts->realtime = u;
12✔
132
        ts->monotonic = map_clock_usec(u, CLOCK_REALTIME, CLOCK_MONOTONIC);
12✔
133
        return ts;
12✔
134
}
135

136
triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
341✔
137
        usec_t nowr;
341✔
138

139
        assert(ts);
341✔
140

141
        if (!timestamp_is_set(u)) {
341✔
142
                ts->realtime = ts->monotonic = ts->boottime = u;
×
143
                return ts;
×
144
        }
145

146
        nowr = now(CLOCK_REALTIME);
341✔
147

148
        ts->realtime = u;
341✔
149
        ts->monotonic = map_clock_usec_raw(u, nowr, now(CLOCK_MONOTONIC));
341✔
150
        ts->boottime = map_clock_usec_raw(u, nowr, now(CLOCK_BOOTTIME));
341✔
151

152
        return ts;
341✔
153
}
154

155
triple_timestamp* triple_timestamp_from_boottime(triple_timestamp *ts, usec_t u) {
×
156
        usec_t nowb;
×
157

158
        assert(ts);
×
159

160
        if (u == USEC_INFINITY) {
×
161
                ts->realtime = ts->monotonic = ts->boottime = u;
×
162
                return ts;
×
163
        }
164

165
        nowb = now(CLOCK_BOOTTIME);
×
166

167
        ts->boottime = u;
×
168
        ts->monotonic = map_clock_usec_raw(u, nowb, now(CLOCK_MONOTONIC));
×
169
        ts->realtime = map_clock_usec_raw(u, nowb, now(CLOCK_REALTIME));
×
170

171
        return ts;
×
172
}
173

174
dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
241✔
175
        assert(ts);
241✔
176

177
        if (u == USEC_INFINITY) {
241✔
178
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
179
                return ts;
×
180
        }
181

182
        ts->monotonic = u;
241✔
183
        ts->realtime = map_clock_usec(u, CLOCK_MONOTONIC, CLOCK_REALTIME);
241✔
184
        return ts;
241✔
185
}
186

187
dual_timestamp* dual_timestamp_from_boottime(dual_timestamp *ts, usec_t u) {
584✔
188
        usec_t nowm;
584✔
189

190
        assert(ts);
584✔
191

192
        if (u == USEC_INFINITY) {
584✔
193
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
194
                return ts;
×
195
        }
196

197
        nowm = now(CLOCK_BOOTTIME);
584✔
198
        ts->monotonic = map_clock_usec_raw(u, nowm, now(CLOCK_MONOTONIC));
584✔
199
        ts->realtime = map_clock_usec_raw(u, nowm, now(CLOCK_REALTIME));
584✔
200
        return ts;
584✔
201
}
202

203
usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
3,433,449✔
204
        assert(ts);
3,433,449✔
205

206
        switch (clock) {
3,433,449✔
207

208
        case CLOCK_REALTIME:
1,882,275✔
209
        case CLOCK_REALTIME_ALARM:
210
                return ts->realtime;
1,882,275✔
211

212
        case CLOCK_MONOTONIC:
1,512,349✔
213
                return ts->monotonic;
1,512,349✔
214

215
        case CLOCK_BOOTTIME:
38,825✔
216
        case CLOCK_BOOTTIME_ALARM:
217
                return ts->boottime;
38,825✔
218

219
        default:
220
                return USEC_INFINITY;
221
        }
222
}
223

224
usec_t timespec_load(const struct timespec *ts) {
29,847,292✔
225
        assert(ts);
29,847,292✔
226

227
        if (ts->tv_sec < 0 || ts->tv_nsec < 0)
29,847,292✔
228
                return USEC_INFINITY;
229

230
        if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
29,847,292✔
231
                return USEC_INFINITY;
232

233
        return
29,847,292✔
234
                (usec_t) ts->tv_sec * USEC_PER_SEC +
29,847,292✔
235
                (usec_t) ts->tv_nsec / NSEC_PER_USEC;
236
}
237

238
nsec_t timespec_load_nsec(const struct timespec *ts) {
1,444✔
239
        assert(ts);
1,444✔
240

241
        if (ts->tv_sec < 0 || ts->tv_nsec < 0)
1,444✔
242
                return NSEC_INFINITY;
243

244
        if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
1,444✔
245
                return NSEC_INFINITY;
246

247
        return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
1,444✔
248
}
249

250
struct timespec *timespec_store(struct timespec *ts, usec_t u) {
2,294,582✔
251
        assert(ts);
2,294,582✔
252

253
        if (u == USEC_INFINITY ||
2,294,582✔
254
            u / USEC_PER_SEC >= TIME_T_MAX) {
255
                ts->tv_sec = (time_t) -1;
×
256
                ts->tv_nsec = -1L;
×
257
                return ts;
×
258
        }
259

260
        ts->tv_sec = (time_t) (u / USEC_PER_SEC);
2,294,582✔
261
        ts->tv_nsec = (long) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
2,294,582✔
262

263
        return ts;
2,294,582✔
264
}
265

266
struct timespec *timespec_store_nsec(struct timespec *ts, nsec_t n) {
56✔
267
        assert(ts);
56✔
268

269
        if (n == NSEC_INFINITY ||
56✔
270
            n / NSEC_PER_SEC >= TIME_T_MAX) {
271
                ts->tv_sec = (time_t) -1;
×
272
                ts->tv_nsec = -1L;
×
273
                return ts;
×
274
        }
275

276
        ts->tv_sec = (time_t) (n / NSEC_PER_SEC);
56✔
277
        ts->tv_nsec = (long) (n % NSEC_PER_SEC);
56✔
278

279
        return ts;
56✔
280
}
281

282
usec_t timeval_load(const struct timeval *tv) {
772,374✔
283
        assert(tv);
772,374✔
284

285
        if (tv->tv_sec < 0 || tv->tv_usec < 0)
772,374✔
286
                return USEC_INFINITY;
287

288
        if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
772,374✔
289
                return USEC_INFINITY;
290

291
        return
772,374✔
292
                (usec_t) tv->tv_sec * USEC_PER_SEC +
772,374✔
293
                (usec_t) tv->tv_usec;
294
}
295

296
struct timeval *timeval_store(struct timeval *tv, usec_t u) {
134,620✔
297
        assert(tv);
134,620✔
298

299
        if (u == USEC_INFINITY ||
134,620✔
300
            u / USEC_PER_SEC > TIME_T_MAX) {
301
                tv->tv_sec = (time_t) -1;
×
302
                tv->tv_usec = (suseconds_t) -1;
×
303
        } else {
304
                tv->tv_sec = (time_t) (u / USEC_PER_SEC);
134,620✔
305
                tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
134,620✔
306
        }
307

308
        return tv;
134,620✔
309
}
310

311
char* format_timestamp_style(
7,384✔
312
                char *buf,
313
                size_t l,
314
                usec_t t,
315
                TimestampStyle style) {
316

317
        /* The weekdays in non-localized (English) form. We use this instead of the localized form, so that
318
         * our generated timestamps may be parsed with parse_timestamp(), and always read the same. */
319
        static const char * const weekdays[] = {
7,384✔
320
                [0] = "Sun",
321
                [1] = "Mon",
322
                [2] = "Tue",
323
                [3] = "Wed",
324
                [4] = "Thu",
325
                [5] = "Fri",
326
                [6] = "Sat",
327
        };
328

329
        struct tm tm;
7,384✔
330
        bool utc, us;
7,384✔
331
        size_t n;
7,384✔
332

333
        assert(buf);
7,384✔
334
        assert(style >= 0);
7,384✔
335
        assert(style < _TIMESTAMP_STYLE_MAX);
7,384✔
336

337
        if (!timestamp_is_set(t))
7,384✔
338
                return NULL; /* Timestamp is unset */
7,384✔
339

340
        if (style == TIMESTAMP_UNIX) {
4,951✔
341
                if (l < (size_t) (1 + 1 + 1))
102✔
342
                        return NULL; /* not enough space for even the shortest of forms */
343

344
                return snprintf_ok(buf, l, "@" USEC_FMT, t / USEC_PER_SEC);  /* round down μs → s */
102✔
345
        }
346

347
        utc = IN_SET(style, TIMESTAMP_UTC, TIMESTAMP_US_UTC, TIMESTAMP_DATE);
4,849✔
348
        us = IN_SET(style, TIMESTAMP_US, TIMESTAMP_US_UTC);
4,849✔
349

350
        if (l < (size_t) (3 +                   /* week day */
4,349✔
351
                          1 + 10 +              /* space and date */
352
                          style == TIMESTAMP_DATE ? 0 :
353
                          (1 + 8 +              /* space and time */
354
                           (us ? 1 + 6 : 0) +   /* "." and microsecond part */
4,849✔
355
                           1 + (utc ? 3 : 1)) + /* space and shortest possible zone */
9,361✔
356
                          1))
357
                return NULL; /* Not enough space even for the shortest form. */
358

359
        /* Let's not format times with years > 9999 */
360
        if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
4,849✔
361
                static const char* const xxx[_TIMESTAMP_STYLE_MAX] = {
4✔
362
                        [TIMESTAMP_PRETTY] = "--- XXXX-XX-XX XX:XX:XX",
363
                        [TIMESTAMP_US]     = "--- XXXX-XX-XX XX:XX:XX.XXXXXX",
364
                        [TIMESTAMP_UTC]    = "--- XXXX-XX-XX XX:XX:XX UTC",
365
                        [TIMESTAMP_US_UTC] = "--- XXXX-XX-XX XX:XX:XX.XXXXXX UTC",
366
                        [TIMESTAMP_DATE]   = "--- XXXX-XX-XX",
367
                };
368

369
                assert(l >= strlen(xxx[style]) + 1);
4✔
370
                return strcpy(buf, xxx[style]);
4✔
371
        }
372

373
        if (localtime_or_gmtime_usec(t, utc, &tm) < 0)
4,845✔
374
                return NULL;
375

376
        /* Start with the week day */
377
        assert((size_t) tm.tm_wday < ELEMENTSOF(weekdays));
4,845✔
378
        memcpy(buf, weekdays[tm.tm_wday], 4);
4,845✔
379

380
        if (style == TIMESTAMP_DATE) {
4,845✔
381
                /* Special format string if only date should be shown. */
382
                if (strftime(buf + 3, l - 3, " %Y-%m-%d", &tm) <= 0)
104✔
383
                        return NULL; /* Doesn't fit */
384

385
                return buf;
104✔
386
        }
387

388
        /* Add the main components */
389
        if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
4,741✔
390
                return NULL; /* Doesn't fit */
391

392
        /* Append the microseconds part, if that's requested */
393
        if (us) {
4,741✔
394
                n = strlen(buf);
499✔
395
                if (n + 8 > l)
499✔
396
                        return NULL; /* Microseconds part doesn't fit. */
397

398
                sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
499✔
399
        }
400

401
        /* Append the timezone */
402
        n = strlen(buf);
4,741✔
403
        if (utc) {
4,741✔
404
                /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r()
405
                 * normally uses the obsolete "GMT" instead. */
406
                if (n + 5 > l)
230✔
407
                        return NULL; /* "UTC" doesn't fit. */
408

409
                strcpy(buf + n, " UTC");
230✔
410

411
        } else if (!isempty(tm.tm_zone)) {
4,511✔
412
                size_t tn;
4,511✔
413

414
                /* An explicit timezone is specified, let's use it, if it fits */
415
                tn = strlen(tm.tm_zone);
4,511✔
416
                if (n + 1 + tn + 1 > l) {
4,511✔
417
                        /* The full time zone does not fit in. Yuck. */
418

419
                        if (n + 1 + _POSIX_TZNAME_MAX + 1 > l)
×
420
                                return NULL; /* Not even enough space for the POSIX minimum (of 6)? In that
×
421
                                              * case, complain that it doesn't fit. */
422

423
                        /* So the time zone doesn't fit in fully, but the caller passed enough space for the
424
                         * POSIX minimum time zone length. In this case suppress the timezone entirely, in
425
                         * order not to dump an overly long, hard to read string on the user. This should be
426
                         * safe, because the user will assume the local timezone anyway if none is shown. And
427
                         * so does parse_timestamp(). */
428
                } else {
429
                        buf[n++] = ' ';
4,511✔
430
                        strcpy(buf + n, tm.tm_zone);
4,511✔
431
                }
432
        }
433

434
        return buf;
435
}
436

437
char* format_timestamp_relative_full(char *buf, size_t l, usec_t t, clockid_t clock, bool implicit_left) {
1,418✔
438
        const char *s;
1,418✔
439
        usec_t n, d;
1,418✔
440

441
        assert(buf);
1,418✔
442

443
        if (!timestamp_is_set(t))
1,418✔
444
                return NULL;
445

446
        n = now(clock);
1,412✔
447
        if (n > t) {
1,412✔
448
                d = n - t;
1,217✔
449
                s = " ago";
1,217✔
450
        } else {
451
                d = t - n;
195✔
452
                s = implicit_left ? "" : " left";
195✔
453
        }
454

455
        if (d >= USEC_PER_YEAR) {
1,412✔
456
                usec_t years = d / USEC_PER_YEAR;
742✔
457
                usec_t months = (d % USEC_PER_YEAR) / USEC_PER_MONTH;
742✔
458

459
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
2,202✔
460
                                years,
461
                                years == 1 ? "year" : "years",
462
                                months,
463
                                months == 1 ? "month" : "months",
464
                                s);
465
        } else if (d >= USEC_PER_MONTH) {
670✔
466
                usec_t months = d / USEC_PER_MONTH;
13✔
467
                usec_t days = (d % USEC_PER_MONTH) / USEC_PER_DAY;
13✔
468

469
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
31✔
470
                                months,
471
                                months == 1 ? "month" : "months",
472
                                days,
473
                                days == 1 ? "day" : "days",
474
                                s);
475
        } else if (d >= USEC_PER_WEEK) {
657✔
476
                usec_t weeks = d / USEC_PER_WEEK;
8✔
477
                usec_t days = (d % USEC_PER_WEEK) / USEC_PER_DAY;
8✔
478

479
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
16✔
480
                                weeks,
481
                                weeks == 1 ? "week" : "weeks",
482
                                days,
483
                                days == 1 ? "day" : "days",
484
                                s);
485
        } else if (d >= 2*USEC_PER_DAY)
649✔
486
                (void) snprintf(buf, l, USEC_FMT " days%s", d / USEC_PER_DAY,s);
×
487
        else if (d >= 25*USEC_PER_HOUR)
649✔
488
                (void) snprintf(buf, l, "1 day " USEC_FMT "h%s",
8✔
489
                                (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
8✔
490
        else if (d >= 6*USEC_PER_HOUR)
641✔
491
                (void) snprintf(buf, l, USEC_FMT "h%s",
27✔
492
                                d / USEC_PER_HOUR, s);
493
        else if (d >= USEC_PER_HOUR)
614✔
494
                (void) snprintf(buf, l, USEC_FMT "h " USEC_FMT "min%s",
3✔
495
                                d / USEC_PER_HOUR,
496
                                (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
3✔
497
        else if (d >= 5*USEC_PER_MINUTE)
611✔
498
                (void) snprintf(buf, l, USEC_FMT "min%s",
8✔
499
                                d / USEC_PER_MINUTE, s);
500
        else if (d >= USEC_PER_MINUTE)
603✔
501
                (void) snprintf(buf, l, USEC_FMT "min " USEC_FMT "s%s",
1✔
502
                                d / USEC_PER_MINUTE,
503
                                (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
1✔
504
        else if (d >= USEC_PER_SEC)
602✔
505
                (void) snprintf(buf, l, USEC_FMT "s%s",
507✔
506
                                d / USEC_PER_SEC, s);
507
        else if (d >= USEC_PER_MSEC)
95✔
508
                (void) snprintf(buf, l, USEC_FMT "ms%s",
92✔
509
                                d / USEC_PER_MSEC, s);
510
        else if (d > 0)
3✔
511
                (void) snprintf(buf, l, USEC_FMT"us%s",
3✔
512
                                d, s);
513
        else
514
                (void) snprintf(buf, l, "now");
×
515

516
        buf[l-1] = 0;
1,412✔
517
        return buf;
1,412✔
518
}
519

520
char* format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
17,339✔
521
        static const struct {
17,339✔
522
                const char *suffix;
523
                usec_t usec;
524
        } table[] = {
525
                { "y",     USEC_PER_YEAR   },
526
                { "month", USEC_PER_MONTH  },
527
                { "w",     USEC_PER_WEEK   },
528
                { "d",     USEC_PER_DAY    },
529
                { "h",     USEC_PER_HOUR   },
530
                { "min",   USEC_PER_MINUTE },
531
                { "s",     USEC_PER_SEC    },
532
                { "ms",    USEC_PER_MSEC   },
533
                { "us",    1               },
534
        };
535

536
        char *p = ASSERT_PTR(buf);
17,339✔
537
        bool something = false;
17,339✔
538

539
        assert(l > 0);
17,339✔
540

541
        if (t == USEC_INFINITY) {
17,339✔
542
                strncpy(p, "infinity", l-1);
1,744✔
543
                p[l-1] = 0;
1,744✔
544
                return p;
1,744✔
545
        }
546

547
        if (t <= 0) {
15,595✔
548
                strncpy(p, "0", l-1);
766✔
549
                p[l-1] = 0;
766✔
550
                return p;
766✔
551
        }
552

553
        /* The result of this function can be parsed with parse_sec */
554

555
        FOREACH_ELEMENT(i, table) {
123,703✔
556
                int k = 0;
123,605✔
557
                size_t n;
123,605✔
558
                bool done = false;
123,605✔
559
                usec_t a, b;
123,605✔
560

561
                if (t <= 0)
123,605✔
562
                        break;
563

564
                if (t < accuracy && something)
108,926✔
565
                        break;
566

567
                if (t < i->usec)
108,874✔
568
                        continue;
88,457✔
569

570
                if (l <= 1)
20,417✔
571
                        break;
572

573
                a = t / i->usec;
20,417✔
574
                b = t % i->usec;
20,417✔
575

576
                /* Let's see if we should shows this in dot notation */
577
                if (t < USEC_PER_MINUTE && b > 0) {
20,417✔
578
                        signed char j = 0;
579

580
                        for (usec_t cc = i->usec; cc > 1; cc /= 10)
65,533✔
581
                                j++;
53,949✔
582

583
                        for (usec_t cc = accuracy; cc > 1; cc /= 10) {
53,811✔
584
                                b /= 10;
42,227✔
585
                                j--;
42,227✔
586
                        }
587

588
                        if (j > 0) {
11,584✔
589
                                k = snprintf(p, l,
6,576✔
590
                                             "%s"USEC_FMT".%0*"PRI_USEC"%s",
591
                                             p > buf ? " " : "",
592
                                             a,
593
                                             j,
594
                                             b,
595
                                             i->suffix);
3,288✔
596

597
                                t = 0;
3,288✔
598
                                done = true;
3,288✔
599
                        }
600
                }
601

602
                /* No? Then let's show it normally */
603
                if (!done) {
3,288✔
604
                        k = snprintf(p, l,
34,258✔
605
                                     "%s"USEC_FMT"%s",
606
                                     p > buf ? " " : "",
607
                                     a,
608
                                     i->suffix);
17,129✔
609

610
                        t = b;
17,129✔
611
                }
612

613
                n = MIN((size_t) k, l-1);
20,417✔
614

615
                l -= n;
20,417✔
616
                p += n;
20,417✔
617

618
                something = true;
20,417✔
619
        }
620

621
        *p = 0;
14,829✔
622

623
        return buf;
14,829✔
624
}
625

626
const char* get_tzname(bool dst) {
2,987✔
627
        /* musl leaves the DST timezone name unset if there is no DST, map this back to no DST */
628
        if (dst && isempty(tzname[1]))
2,988✔
629
                dst = false;
630

631
        return empty_to_null(tzname[dst]);
2,987✔
632
}
633

634
int parse_gmtoff(const char *t, long *ret) {
1,233✔
635
        assert(t);
1,233✔
636

637
        struct tm tm;
1,233✔
638
        const char *k = strptime(t, "%z", &tm);
1,233✔
639
        if (k && *k == '\0') {
1,233✔
640
                /* Success! */
641
                if (ret)
172✔
642
                        *ret = tm.tm_gmtoff;
172✔
643
                return 0;
172✔
644
        }
645

646
#ifdef __GLIBC__
647
        return -EINVAL;
648
#else
649
        int r;
650

651
        /* musl v1.2.5 does not support %z specifier in strptime(). Since
652
         * https://github.com/kraj/musl/commit/fced99e93daeefb0192fd16304f978d4401d1d77
653
         * %z is supported, but it only supports strict RFC-822/ISO 8601 format, that is, 4 digits with sign
654
         * (e.g. +0900 or -1400), but does not support extended format: 2 digits or colon separated 4 digits
655
         * (e.g. +09 or -14:00). Let's add fallback logic to make it support the extended timezone spec. */
656

657
        bool positive;
658
        switch (*t) {
659
        case '+':
660
                positive = true;
661
                break;
662
        case '-':
663
                positive = false;
664
                break;
665
        default:
666
                return -EINVAL;
667
        }
668

669
        t++;
670
        r = undecchar(*t);
671
        if (r < 0)
672
                return r;
673

674
        usec_t u = r * 10 * USEC_PER_HOUR;
675

676
        t++;
677
        r = undecchar(*t);
678
        if (r < 0)
679
                return r;
680
        u += r * USEC_PER_HOUR;
681

682
        t++;
683
        if (*t == '\0') /* 2 digits case */
684
                goto finalize;
685

686
        if (*t == ':') /* skip colon */
687
                t++;
688

689
        r = undecchar(*t);
690
        if (r < 0)
691
                return r;
692
        if (r >= 6) /* refuse minutes equal to or larger than 60 */
693
                return -EINVAL;
694

695
        u += r * 10 * USEC_PER_MINUTE;
696

697
        t++;
698
        r = undecchar(*t);
699
        if (r < 0)
700
                return r;
701

702
        u += r * USEC_PER_MINUTE;
703

704
        t++;
705
        if (*t != '\0')
706
                return -EINVAL;
707

708
finalize:
709
        if (u > USEC_PER_DAY) /* refuse larger than one day */
710
                return -EINVAL;
711

712
        if (ret) {
713
                long gmtoff = u / USEC_PER_SEC;
714
                *ret = positive ? gmtoff : -gmtoff;
715
        }
716

717
        return 0;
718
#endif
719
}
720

721
static int parse_timestamp_impl(
2,129✔
722
                const char *t,
723
                size_t max_len,
724
                bool utc,
725
                int isdst,
726
                long gmtoff,
727
                usec_t *ret) {
728

729
        static const struct {
2,129✔
730
                const char *name;
731
                const int nr;
732
        } day_nr[] = {
733
                { "Sunday",    0 },
734
                { "Sun",       0 },
735
                { "Monday",    1 },
736
                { "Mon",       1 },
737
                { "Tuesday",   2 },
738
                { "Tue",       2 },
739
                { "Wednesday", 3 },
740
                { "Wed",       3 },
741
                { "Thursday",  4 },
742
                { "Thu",       4 },
743
                { "Friday",    5 },
744
                { "Fri",       5 },
745
                { "Saturday",  6 },
746
                { "Sat",       6 },
747
        };
748

749
        _cleanup_free_ char *t_alloc = NULL;
2,129✔
750
        usec_t usec, plus = 0, minus = 0;
2,129✔
751
        bool with_tz = false;
2,129✔
752
        int r, weekday = -1;
2,129✔
753
        unsigned fractional = 0;
2,129✔
754
        const char *k;
2,129✔
755
        struct tm tm, copy;
2,129✔
756

757
        /* Allowed syntaxes:
758
         *
759
         *   2012-09-22 16:34:22.1[2[3[4[5[6]]]]]
760
         *   2012-09-22 16:34:22  (µsec will be set to 0)
761
         *   2012-09-22 16:34     (seconds will be set to 0)
762
         *   2012-09-22T16:34:22.1[2[3[4[5[6]]]]]
763
         *   2012-09-22T16:34:22  (µsec will be set to 0)
764
         *   2012-09-22T16:34     (seconds will be set to 0)
765
         *   2012-09-22           (time will be set to 00:00:00)
766
         *   16:34:22             (date will be set to today)
767
         *   16:34                (date will be set to today, seconds to 0)
768
         *   now
769
         *   yesterday            (time is set to 00:00:00)
770
         *   today                (time is set to 00:00:00)
771
         *   tomorrow             (time is set to 00:00:00)
772
         *   +5min
773
         *   -5days
774
         *   @2147483647          (seconds since epoch)
775
         *
776
         * Note, on DST change, 00:00:00 may not exist and in that case the time part may be shifted.
777
         * E.g. "Sun 2023-03-13 America/Havana" is parsed as "Sun 2023-03-13 01:00:00 CDT".
778
         *
779
         * A simplified strptime-spelled RFC3339 ABNF looks like
780
         *   "%Y-%m-%d" "T" "%H" ":" "%M" ":" "%S" [".%N"] ("Z" / (("+" / "-") "%H:%M"))
781
         * We additionally allow no seconds and inherited timezone
782
         * for symmetry with our other syntaxes and improved interactive usability:
783
         *   "%Y-%m-%d" "T" "%H" ":" "%M" ":" ["%S" [".%N"]] ["Z" / (("+" / "-") "%H:%M")]
784
         * RFC3339 defines time-secfrac to as "." 1*DIGIT, but we limit to 6 digits,
785
         * since we're limited to 1µs resolution.
786
         * We also accept "Sat 2012-09-22T16:34:22", RFC3339 warns against it.
787
         */
788

789
        assert(t);
2,129✔
790

791
        if (max_len != SIZE_MAX) {
2,129✔
792
                /* If the input string contains timezone, then cut it here. */
793

794
                if (max_len == 0) /* Can't be the only field */
1,690✔
795
                        return -EINVAL;
796

797
                t_alloc = strndup(t, max_len);
1,690✔
798
                if (!t_alloc)
1,690✔
799
                        return -ENOMEM;
800

801
                t = t_alloc;
802
                with_tz = true;
803
        }
804

805
        if (utc) {
2,129✔
806
                /* glibc accepts gmtoff more than 24 hours, but we refuse it. */
807
                if ((usec_t) labs(gmtoff) * USEC_PER_SEC > USEC_PER_DAY)
991✔
808
                        return -EINVAL;
809
        } else {
810
                if (gmtoff != 0)
1,138✔
811
                        return -EINVAL;
812
        }
813

814
        if (t[0] == '@' && !with_tz)
2,129✔
815
                return parse_sec(t + 1, ret);
107✔
816

817
        usec = now(CLOCK_REALTIME);
2,022✔
818

819
        if (!with_tz) {
2,022✔
820
                if (streq(t, "now"))
332✔
821
                        goto finish;
5✔
822

823
                if (t[0] == '+') {
327✔
824
                        r = parse_sec(t+1, &plus);
6✔
825
                        if (r < 0)
6✔
826
                                return r;
827

828
                        goto finish;
6✔
829
                }
830

831
                if (t[0] == '-') {
321✔
832
                        r = parse_sec(t+1, &minus);
6✔
833
                        if (r < 0)
6✔
834
                                return r;
835

836
                        goto finish;
6✔
837
                }
838

839
                if ((k = endswith(t, " ago"))) {
315✔
840
                        _cleanup_free_ char *buf = NULL;
4✔
841

842
                        buf = strndup(t, k - t);
4✔
843
                        if (!buf)
4✔
844
                                return -ENOMEM;
845

846
                        r = parse_sec(buf, &minus);
4✔
847
                        if (r < 0)
4✔
848
                                return r;
849

850
                        goto finish;
4✔
851
                }
852

853
                if ((k = endswith(t, " left"))) {
311✔
854
                        _cleanup_free_ char *buf = NULL;
101✔
855

856
                        buf = strndup(t, k - t);
101✔
857
                        if (!buf)
101✔
858
                                return -ENOMEM;
859

860
                        r = parse_sec(buf, &plus);
101✔
861
                        if (r < 0)
101✔
862
                                return r;
863

864
                        goto finish;
101✔
865
                }
866
        }
867

868
        r = localtime_or_gmtime_usec(usec, utc, &tm);
1,900✔
869
        if (r < 0)
1,900✔
870
                return r;
871

872
        tm.tm_isdst = isdst;
1,900✔
873

874
        if (streq(t, "today")) {
1,900✔
875
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
13✔
876
                goto from_tm;
13✔
877

878
        } else if (streq(t, "yesterday")) {
1,887✔
879
                tm.tm_mday--;
10✔
880
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
10✔
881
                goto from_tm;
10✔
882

883
        } else if (streq(t, "tomorrow")) {
1,877✔
884
                tm.tm_mday++;
8✔
885
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
8✔
886
                goto from_tm;
8✔
887
        }
888

889
        FOREACH_ELEMENT(day, day_nr) {
19,555✔
890
                k = startswith_no_case(t, day->name);
19,238✔
891
                if (!k || *k != ' ')
19,238✔
892
                        continue;
17,686✔
893

894
#ifdef __GLIBC__
895
                /* musl does not set tm_wday field and set 0 unless it is explicitly requested by %w or so.
896
                 * In the below, let's only check tm_wday field only when built with glibc. */
897
                weekday = day->nr;
1,552✔
898
#endif
899
                t = k + 1;
1,552✔
900
                break;
1,552✔
901
        }
902

903
        copy = tm;
1,869✔
904
        k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
1,869✔
905
        if (k) {
1,869✔
906
                if (*k == '.')
100✔
907
                        goto parse_usec;
64✔
908
                else if (*k == 0)
36✔
909
                        goto from_tm;
32✔
910
        }
911

912
        /* Our "canonical" RFC3339 syntax variant */
913
        tm = copy;
1,773✔
914
        k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
1,773✔
915
        if (k) {
1,773✔
916
                if (*k == '.')
1,473✔
917
                        goto parse_usec;
344✔
918
                else if (*k == 0)
1,129✔
919
                        goto from_tm;
1,120✔
920
        }
921

922
        /* RFC3339 syntax */
923
        tm = copy;
309✔
924
        k = strptime(t, "%Y-%m-%dT%H:%M:%S", &tm);
309✔
925
        if (k) {
309✔
926
                if (*k == '.')
42✔
927
                        goto parse_usec;
20✔
928
                else if (*k == 0)
22✔
929
                        goto from_tm;
22✔
930
        }
931

932
        /* Support OUTPUT_SHORT and OUTPUT_SHORT_PRECISE formats */
933
        tm = copy;
267✔
934
        k = strptime(t, "%b %d %H:%M:%S", &tm);
267✔
935
        if (k) {
267✔
936
                if (*k == '.')
4✔
937
                        goto parse_usec;
2✔
938
                else if (*k == 0)
2✔
939
                        goto from_tm;
2✔
940
        }
941

942
        tm = copy;
263✔
943
        k = strptime(t, "%y-%m-%d %H:%M", &tm);
263✔
944
        if (k && *k == 0) {
263✔
945
                tm.tm_sec = 0;
30✔
946
                goto from_tm;
30✔
947
        }
948

949
        /* Our "canonical" RFC3339 syntax variant without seconds */
950
        tm = copy;
233✔
951
        k = strptime(t, "%Y-%m-%d %H:%M", &tm);
233✔
952
        if (k && *k == 0) {
233✔
953
                tm.tm_sec = 0;
31✔
954
                goto from_tm;
31✔
955
        }
956

957
        /* RFC3339 syntax without seconds */
958
        tm = copy;
202✔
959
        k = strptime(t, "%Y-%m-%dT%H:%M", &tm);
202✔
960
        if (k && *k == 0) {
202✔
961
                tm.tm_sec = 0;
8✔
962
                goto from_tm;
8✔
963
        }
964

965
        tm = copy;
194✔
966
        k = strptime(t, "%y-%m-%d", &tm);
194✔
967
        if (k && *k == 0) {
194✔
968
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
×
969
                goto from_tm;
×
970
        }
971

972
        tm = copy;
194✔
973
        k = strptime(t, "%Y-%m-%d", &tm);
194✔
974
        if (k && *k == 0) {
194✔
975
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
106✔
976
                goto from_tm;
106✔
977
        }
978

979
        tm = copy;
88✔
980
        k = strptime(t, "%H:%M:%S", &tm);
88✔
981
        if (k) {
88✔
982
                if (*k == '.')
30✔
983
                        goto parse_usec;
8✔
984
                else if (*k == 0)
22✔
985
                        goto from_tm;
22✔
986
        }
987

988
        tm = copy;
58✔
989
        k = strptime(t, "%H:%M", &tm);
58✔
990
        if (k && *k == 0) {
58✔
991
                tm.tm_sec = 0;
6✔
992
                goto from_tm;
6✔
993
        }
994

995
        return -EINVAL;
996

997
parse_usec:
438✔
998
        k++;
438✔
999
        r = parse_fractional_part_u(&k, 6, &fractional);
438✔
1000
        if (r < 0)
438✔
1001
                return -EINVAL;
1002
        if (*k != '\0')
438✔
1003
                return -EINVAL;
1004

1005
from_tm:
422✔
1006
        assert(plus == 0);
1,832✔
1007
        assert(minus == 0);
1,832✔
1008

1009
        if (weekday >= 0 && tm.tm_wday != weekday)
1,832✔
1010
                return -EINVAL;
1011

1012
        if (gmtoff < 0) {
1,832✔
1013
                plus = -gmtoff * USEC_PER_SEC;
110✔
1014

1015
                /* If gmtoff is negative, the string may be too old to be parsed as UTC.
1016
                 * E.g. 1969-12-31 23:00:00 -06 == 1970-01-01 05:00:00 UTC
1017
                 * We assumed that gmtoff is in the range of -24:00…+24:00, hence the only date we need to
1018
                 * handle here is 1969-12-31. So, let's shift the date with one day, then subtract the shift
1019
                 * later. */
1020
                if (tm.tm_year == 69 && tm.tm_mon == 11 && tm.tm_mday == 31) {
110✔
1021
                        /* Thu 1970-01-01-00:00:00 */
1022
                        tm.tm_year = 70;
96✔
1023
                        tm.tm_mon = 0;
96✔
1024
                        tm.tm_mday = 1;
96✔
1025
                        tm.tm_wday = 4;
96✔
1026
                        tm.tm_yday = 0;
96✔
1027
                        minus = USEC_PER_DAY;
96✔
1028
                }
1029
        } else
1030
                minus = gmtoff * USEC_PER_SEC;
1,722✔
1031

1032
        r = mktime_or_timegm_usec(&tm, utc, &usec);
1,832✔
1033
        if (r < 0)
1,832✔
1034
                return r;
1035

1036
        usec = usec_add(usec, fractional);
3,658✔
1037

1038
finish:
1,951✔
1039
        usec = usec_add(usec, plus);
1,951✔
1040

1041
        if (usec < minus)
1,951✔
1042
                return -EINVAL;
1043

1044
        usec = usec_sub_unsigned(usec, minus);
1,950✔
1045

1046
        if (usec > USEC_TIMESTAMP_FORMATTABLE_MAX)
1,950✔
1047
                return -EINVAL;
1048

1049
        if (ret)
1,949✔
1050
                *ret = usec;
1,947✔
1051
        return 0;
1052
}
1053

1054
int parse_timestamp(const char *t, usec_t *ret) {
2,096✔
1055
        long gmtoff;
2,096✔
1056
        int r;
2,096✔
1057

1058
        assert(t);
2,096✔
1059

1060
        size_t t_len = strlen(t);
2,096✔
1061
        if (t_len > 2 && t[t_len - 1] == 'Z') {
2,096✔
1062
                /* Try to parse as RFC3339-style welded UTC: "1985-04-12T23:20:50.52Z" */
1063
                r = parse_timestamp_impl(t, t_len - 1, /* utc = */ true, /* isdst = */ -1, /* gmtoff = */ 0, ret);
67✔
1064
                if (r >= 0)
67✔
1065
                        return r;
2,096✔
1066
        }
1067

1068
        /* RFC3339-style welded offset: "1990-12-31T15:59:60-08:00" */
1069
        if (t_len > 7 && IN_SET(t[t_len - 6], '+', '-') && t[t_len - 7] != ' ' && parse_gmtoff(&t[t_len - 6], &gmtoff) >= 0)
2,048✔
1070
                return parse_timestamp_impl(t, t_len - 6, /* utc = */ true, /* isdst = */ -1, gmtoff, ret);
40✔
1071

1072
        const char *tz = strrchr(t, ' ');
2,022✔
1073
        if (!tz)
2,022✔
1074
                return parse_timestamp_impl(t, /* max_len = */ SIZE_MAX, /* utc = */ false, /* isdst = */ -1, /* gmtoff = */ 0, ret);
191✔
1075

1076
        size_t max_len = tz - t;
1,831✔
1077
        tz++;
1,831✔
1078

1079
        /* Shortcut, parse the string as UTC. */
1080
        if (streq(tz, "UTC"))
1,831✔
1081
                return parse_timestamp_impl(t, max_len, /* utc = */ true, /* isdst = */ -1, /* gmtoff = */ 0, ret);
758✔
1082

1083
        /* If the timezone is compatible with RFC-822/ISO 8601 (e.g. +06, or -03:00) then parse the string as
1084
         * UTC and shift the result. Note, this must be earlier than the timezone check with tzname[], as
1085
         * tzname[] may be in the same format. */
1086
        if (parse_gmtoff(tz, &gmtoff) >= 0)
1,073✔
1087
                return parse_timestamp_impl(t, max_len, /* utc = */ true, /* isdst = */ -1, gmtoff, ret);
126✔
1088

1089
        /* Check if the last word matches tzname[] of the local timezone. Note, this must be done earlier
1090
         * than the check by timezone_is_valid() below, as some short timezone specifications have their own
1091
         * timezone files (e.g. WET has its own timezone file, but JST does not), but using such files does
1092
         * not follow the timezone change in the current area. */
1093
        tzset();
947✔
1094
        for (int j = 0; j <= 1; j++) {
2,841✔
1095
                if (!streq_ptr(tz, get_tzname(j)))
1,894✔
1096
                        continue;
1,894✔
1097

1098
                /* The specified timezone matches tzname[] of the local timezone. */
1099
                return parse_timestamp_impl(t, max_len, /* utc = */ false, /* isdst = */ j, /* gmtoff = */ 0, ret);
×
1100
        }
1101

1102
        /* If the last word is a valid timezone file (e.g. Asia/Tokyo), then save the current timezone, apply
1103
         * the specified timezone, and parse the remaining string as a local time. */
1104
        if (timezone_is_valid(tz, LOG_DEBUG)) {
947✔
1105
                SAVE_TIMEZONE;
1,398✔
1106

1107
                if (setenv("TZ", tz, /* overwrite = */ true) < 0)
699✔
1108
                        return negative_errno();
×
1109

1110
                return parse_timestamp_impl(t, max_len, /* utc = */ false, /* isdst = */ -1, /* gmtoff = */ 0, ret);
699✔
1111
        }
1112

1113
        /* Otherwise, assume that the last word is a part of the time and try to parse the whole string as a
1114
         * local time. */
1115
        return parse_timestamp_impl(t, SIZE_MAX, /* utc = */ false, /* isdst = */ -1, /* gmtoff = */ 0, ret);
248✔
1116
}
1117

1118
static const char* extract_multiplier(const char *p, usec_t *ret) {
10,619✔
1119
        static const struct {
10,619✔
1120
                const char *suffix;
1121
                usec_t usec;
1122
        } table[] = {
1123
                { "seconds", USEC_PER_SEC    },
1124
                { "second",  USEC_PER_SEC    },
1125
                { "sec",     USEC_PER_SEC    },
1126
                { "s",       USEC_PER_SEC    },
1127
                { "minutes", USEC_PER_MINUTE },
1128
                { "minute",  USEC_PER_MINUTE },
1129
                { "min",     USEC_PER_MINUTE },
1130
                { "months",  USEC_PER_MONTH  },
1131
                { "month",   USEC_PER_MONTH  },
1132
                { "M",       USEC_PER_MONTH  },
1133
                { "msec",    USEC_PER_MSEC   },
1134
                { "ms",      USEC_PER_MSEC   },
1135
                { "m",       USEC_PER_MINUTE },
1136
                { "hours",   USEC_PER_HOUR   },
1137
                { "hour",    USEC_PER_HOUR   },
1138
                { "hr",      USEC_PER_HOUR   },
1139
                { "h",       USEC_PER_HOUR   },
1140
                { "days",    USEC_PER_DAY    },
1141
                { "day",     USEC_PER_DAY    },
1142
                { "d",       USEC_PER_DAY    },
1143
                { "weeks",   USEC_PER_WEEK   },
1144
                { "week",    USEC_PER_WEEK   },
1145
                { "w",       USEC_PER_WEEK   },
1146
                { "years",   USEC_PER_YEAR   },
1147
                { "year",    USEC_PER_YEAR   },
1148
                { "y",       USEC_PER_YEAR   },
1149
                { "usec",    1ULL            },
1150
                { "us",      1ULL            },
1151
                { "μs",      1ULL            }, /* U+03bc (aka GREEK SMALL LETTER MU) */
1152
                { "µs",      1ULL            }, /* U+b5 (aka MICRO SIGN) */
1153
        };
1154

1155
        assert(p);
10,619✔
1156
        assert(ret);
10,619✔
1157

1158
        FOREACH_ELEMENT(i, table) {
180,872✔
1159
                char *e;
177,200✔
1160

1161
                e = startswith(p, i->suffix);
177,200✔
1162
                if (e) {
177,200✔
1163
                        *ret = i->usec;
6,947✔
1164
                        return e;
6,947✔
1165
                }
1166
        }
1167

1168
        return p;
1169
}
1170

1171
int parse_time(const char *t, usec_t *ret, usec_t default_unit) {
10,721✔
1172
        const char *p, *s;
10,721✔
1173

1174
        assert(t);
10,721✔
1175
        assert(default_unit > 0);
10,721✔
1176

1177
        p = skip_leading_chars(t, /* bad = */ NULL);
10,721✔
1178
        s = startswith(p, "infinity");
10,721✔
1179
        if (s) {
10,721✔
1180
                if (!in_charset(s, WHITESPACE))
320✔
1181
                        return -EINVAL;
1182

1183
                if (ret)
319✔
1184
                        *ret = USEC_INFINITY;
319✔
1185
                return 0;
319✔
1186
        }
1187

1188
        usec_t usec = 0;
1189

1190
        for (bool something = false;;) {
10,603✔
1191
                usec_t multiplier = default_unit, k;
21,004✔
1192
                long long l;
21,004✔
1193
                char *e;
21,004✔
1194

1195
                p = skip_leading_chars(p, /* bad = */ NULL);
21,004✔
1196
                if (*p == 0) {
21,004✔
1197
                        if (!something)
10,363✔
1198
                                return -EINVAL;
43✔
1199

1200
                        break;
10,358✔
1201
                }
1202

1203
                if (*p == '-') /* Don't allow "-0" */
10,641✔
1204
                        return -ERANGE;
1205

1206
                errno = 0;
10,633✔
1207
                l = strtoll(p, &e, 10);
10,633✔
1208
                if (errno > 0)
10,633✔
1209
                        return -errno;
×
1210
                if (l < 0)
10,633✔
1211
                        return -ERANGE;
1212

1213
                if (*e == '.') {
10,633✔
1214
                        p = e + 1;
55✔
1215
                        p += strspn(p, DIGITS);
55✔
1216
                } else if (e == p)
10,578✔
1217
                        return -EINVAL;
1218
                else
1219
                        p = e;
1220

1221
                s = extract_multiplier(p + strspn(p, WHITESPACE), &multiplier);
10,619✔
1222
                if (s == p && *s != '\0')
10,619✔
1223
                        /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56' */
1224
                        return -EINVAL;
1225

1226
                p = s;
10,610✔
1227

1228
                if ((usec_t) l >= USEC_INFINITY / multiplier)
10,610✔
1229
                        return -ERANGE;
1230

1231
                k = (usec_t) l * multiplier;
10,608✔
1232
                if (k >= USEC_INFINITY - usec)
10,608✔
1233
                        return -ERANGE;
1234

1235
                usec += k;
10,608✔
1236

1237
                something = true;
10,608✔
1238

1239
                if (*e == '.') {
10,608✔
1240
                        usec_t m = multiplier / 10;
48✔
1241
                        const char *b;
48✔
1242

1243
                        for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
188✔
1244
                                k = (usec_t) (*b - '0') * m;
140✔
1245
                                if (k >= USEC_INFINITY - usec)
140✔
1246
                                        return -ERANGE;
1247

1248
                                usec += k;
140✔
1249
                        }
1250

1251
                        /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge" */
1252
                        if (b == e + 1)
48✔
1253
                                return -EINVAL;
1254
                }
1255
        }
1256

1257
        if (ret)
10,358✔
1258
                *ret = usec;
10,356✔
1259
        return 0;
1260
}
1261

1262
int parse_sec(const char *t, usec_t *ret) {
10,642✔
1263
        return parse_time(t, ret, USEC_PER_SEC);
10,642✔
1264
}
1265

1266
int parse_sec_fix_0(const char *t, usec_t *ret) {
1,894✔
1267
        usec_t k;
1,894✔
1268
        int r;
1,894✔
1269

1270
        assert(t);
1,894✔
1271
        assert(ret);
1,894✔
1272

1273
        r = parse_sec(t, &k);
1,894✔
1274
        if (r < 0)
1,894✔
1275
                return r;
1,894✔
1276

1277
        *ret = k == 0 ? USEC_INFINITY : k;
1,894✔
1278
        return r;
1,894✔
1279
}
1280

1281
int parse_sec_def_infinity(const char *t, usec_t *ret) {
7✔
1282
        assert(t);
7✔
1283
        assert(ret);
7✔
1284

1285
        t += strspn(t, WHITESPACE);
7✔
1286
        if (isempty(t)) {
7✔
1287
                *ret = USEC_INFINITY;
2✔
1288
                return 0;
2✔
1289
        }
1290
        return parse_sec(t, ret);
5✔
1291
}
1292

1293
static const char* extract_nsec_multiplier(const char *p, nsec_t *ret) {
44✔
1294
        static const struct {
44✔
1295
                const char *suffix;
1296
                nsec_t nsec;
1297
        } table[] = {
1298
                { "seconds", NSEC_PER_SEC    },
1299
                { "second",  NSEC_PER_SEC    },
1300
                { "sec",     NSEC_PER_SEC    },
1301
                { "s",       NSEC_PER_SEC    },
1302
                { "minutes", NSEC_PER_MINUTE },
1303
                { "minute",  NSEC_PER_MINUTE },
1304
                { "min",     NSEC_PER_MINUTE },
1305
                { "months",  NSEC_PER_MONTH  },
1306
                { "month",   NSEC_PER_MONTH  },
1307
                { "M",       NSEC_PER_MONTH  },
1308
                { "msec",    NSEC_PER_MSEC   },
1309
                { "ms",      NSEC_PER_MSEC   },
1310
                { "m",       NSEC_PER_MINUTE },
1311
                { "hours",   NSEC_PER_HOUR   },
1312
                { "hour",    NSEC_PER_HOUR   },
1313
                { "hr",      NSEC_PER_HOUR   },
1314
                { "h",       NSEC_PER_HOUR   },
1315
                { "days",    NSEC_PER_DAY    },
1316
                { "day",     NSEC_PER_DAY    },
1317
                { "d",       NSEC_PER_DAY    },
1318
                { "weeks",   NSEC_PER_WEEK   },
1319
                { "week",    NSEC_PER_WEEK   },
1320
                { "w",       NSEC_PER_WEEK   },
1321
                { "years",   NSEC_PER_YEAR   },
1322
                { "year",    NSEC_PER_YEAR   },
1323
                { "y",       NSEC_PER_YEAR   },
1324
                { "usec",    NSEC_PER_USEC   },
1325
                { "us",      NSEC_PER_USEC   },
1326
                { "μs",      NSEC_PER_USEC   }, /* U+03bc (aka GREEK LETTER MU) */
1327
                { "µs",      NSEC_PER_USEC   }, /* U+b5 (aka MICRO SIGN) */
1328
                { "nsec",    1ULL            },
1329
                { "ns",      1ULL            },
1330
                { "",        1ULL            }, /* default is nsec */
1331
        };
1332

1333
        assert(p);
44✔
1334
        assert(ret);
44✔
1335

1336
        FOREACH_ELEMENT(i, table) {
803✔
1337
                char *e;
803✔
1338

1339
                e = startswith(p, i->suffix);
803✔
1340
                if (e) {
803✔
1341
                        *ret = i->nsec;
44✔
1342
                        return e;
44✔
1343
                }
1344
        }
1345

1346
        return p;
1347
}
1348

1349
int parse_nsec(const char *t, nsec_t *ret) {
48✔
1350
        const char *p, *s;
48✔
1351
        nsec_t nsec = 0;
48✔
1352
        bool something = false;
48✔
1353

1354
        assert(t);
48✔
1355
        assert(ret);
48✔
1356

1357
        p = t;
48✔
1358

1359
        p += strspn(p, WHITESPACE);
48✔
1360
        s = startswith(p, "infinity");
48✔
1361
        if (s) {
48✔
1362
                s += strspn(s, WHITESPACE);
4✔
1363
                if (*s != 0)
4✔
1364
                        return -EINVAL;
1365

1366
                *ret = NSEC_INFINITY;
2✔
1367
                return 0;
2✔
1368
        }
1369

1370
        for (;;) {
30✔
1371
                nsec_t multiplier = 1, k;
74✔
1372
                long long l;
74✔
1373
                char *e;
74✔
1374

1375
                p += strspn(p, WHITESPACE);
74✔
1376

1377
                if (*p == 0) {
74✔
1378
                        if (!something)
21✔
1379
                                return -EINVAL;
24✔
1380

1381
                        break;
20✔
1382
                }
1383

1384
                if (*p == '-') /* Don't allow "-0" */
53✔
1385
                        return -ERANGE;
1386

1387
                errno = 0;
48✔
1388
                l = strtoll(p, &e, 10);
48✔
1389
                if (errno > 0)
48✔
1390
                        return -errno;
×
1391
                if (l < 0)
48✔
1392
                        return -ERANGE;
1393

1394
                if (*e == '.') {
48✔
1395
                        p = e + 1;
31✔
1396
                        p += strspn(p, DIGITS);
31✔
1397
                } else if (e == p)
17✔
1398
                        return -EINVAL;
1399
                else
1400
                        p = e;
1401

1402
                s = extract_nsec_multiplier(p + strspn(p, WHITESPACE), &multiplier);
44✔
1403
                if (s == p && *s != '\0')
44✔
1404
                        /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56' */
1405
                        return -EINVAL;
1406

1407
                p = s;
36✔
1408

1409
                if ((nsec_t) l >= NSEC_INFINITY / multiplier)
36✔
1410
                        return -ERANGE;
1411

1412
                k = (nsec_t) l * multiplier;
35✔
1413
                if (k >= NSEC_INFINITY - nsec)
35✔
1414
                        return -ERANGE;
1415

1416
                nsec += k;
35✔
1417

1418
                something = true;
35✔
1419

1420
                if (*e == '.') {
35✔
1421
                        nsec_t m = multiplier / 10;
24✔
1422
                        const char *b;
24✔
1423

1424
                        for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
56✔
1425
                                k = (nsec_t) (*b - '0') * m;
32✔
1426
                                if (k >= NSEC_INFINITY - nsec)
32✔
1427
                                        return -ERANGE;
1428

1429
                                nsec += k;
32✔
1430
                        }
1431

1432
                        /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge" */
1433
                        if (b == e + 1)
24✔
1434
                                return -EINVAL;
1435
                }
1436
        }
1437

1438
        *ret = nsec;
20✔
1439

1440
        return 0;
20✔
1441
}
1442

1443
static int get_timezones_from_zone1970_tab(char ***ret) {
×
1444
        _cleanup_fclose_ FILE *f = NULL;
×
1445
        _cleanup_strv_free_ char **zones = NULL;
×
1446
        int r;
×
1447

1448
        assert(ret);
×
1449

1450
        f = fopen("/usr/share/zoneinfo/zone1970.tab", "re");
×
1451
        if (!f)
×
1452
                return -errno;
×
1453

1454
        for (;;) {
×
1455
                _cleanup_free_ char *line = NULL, *cc = NULL, *co = NULL, *tz = NULL;
×
1456

1457
                r = read_line(f, LONG_LINE_MAX, &line);
×
1458
                if (r < 0)
×
1459
                        return r;
1460
                if (r == 0)
×
1461
                        break;
1462

1463
                const char *p = line;
×
1464

1465
                /* Line format is:
1466
                 * 'country codes' 'coordinates' 'timezone' 'comments' */
1467
                r = extract_many_words(&p, NULL, 0, &cc, &co, &tz);
×
1468
                if (r < 0)
×
1469
                        continue;
×
1470

1471
                /* Lines that start with # are comments. */
1472
                if (*cc == '#')
×
1473
                        continue;
×
1474

1475
                if (!timezone_is_valid(tz, LOG_DEBUG))
×
1476
                        /* Don't list unusable timezones. */
1477
                        continue;
×
1478

1479
                r = strv_extend(&zones, tz);
×
1480
                if (r < 0)
×
1481
                        return r;
1482
        }
1483

1484
        *ret = TAKE_PTR(zones);
×
1485
        return 0;
×
1486
}
1487

1488
static int get_timezones_from_tzdata_zi(char ***ret) {
4✔
1489
        _cleanup_fclose_ FILE *f = NULL;
4✔
1490
        _cleanup_strv_free_ char **zones = NULL;
4✔
1491
        int r;
4✔
1492

1493
        assert(ret);
4✔
1494

1495
        f = fopen("/usr/share/zoneinfo/tzdata.zi", "re");
4✔
1496
        if (!f)
4✔
1497
                return -errno;
×
1498

1499
        for (;;) {
17,204✔
1500
                _cleanup_free_ char *line = NULL, *type = NULL, *f1 = NULL, *f2 = NULL;
17,200✔
1501

1502
                r = read_line(f, LONG_LINE_MAX, &line);
17,204✔
1503
                if (r < 0)
17,204✔
1504
                        return r;
1505
                if (r == 0)
17,204✔
1506
                        break;
1507

1508
                const char *p = line;
17,200✔
1509

1510
                /* The only lines we care about are Zone and Link lines.
1511
                 * Zone line format is:
1512
                 * 'Zone' 'timezone' ...
1513
                 * Link line format is:
1514
                 * 'Link' 'target' 'alias'
1515
                 * See 'man zic' for more detail. */
1516
                r = extract_many_words(&p, NULL, 0, &type, &f1, &f2);
17,200✔
1517
                if (r < 0)
17,200✔
1518
                        continue;
×
1519

1520
                char *tz;
17,200✔
1521
                if (IN_SET(*type, 'Z', 'z'))
17,200✔
1522
                        /* Zone lines have timezone in field 1. */
1523
                        tz = f1;
1,364✔
1524
                else if (IN_SET(*type, 'L', 'l'))
15,836✔
1525
                        /* Link lines have timezone in field 2. */
1526
                        tz = f2;
1,028✔
1527
                else
1528
                        /* Not a line we care about. */
1529
                        continue;
14,808✔
1530

1531
                if (!timezone_is_valid(tz, LOG_DEBUG))
2,392✔
1532
                        /* Don't list unusable timezones. */
1533
                        continue;
×
1534

1535
                r = strv_extend(&zones, tz);
2,392✔
1536
                if (r < 0)
2,392✔
1537
                        return r;
1538
        }
1539

1540
        *ret = TAKE_PTR(zones);
4✔
1541
        return 0;
4✔
1542
}
1543

1544
int get_timezones(char ***ret) {
4✔
1545
        _cleanup_strv_free_ char **zones = NULL;
4✔
1546
        int r;
4✔
1547

1548
        assert(ret);
4✔
1549

1550
        r = get_timezones_from_tzdata_zi(&zones);
4✔
1551
        if (r == -ENOENT) {
4✔
1552
                log_debug_errno(r, "Could not get timezone data from tzdata.zi, using zone1970.tab: %m");
×
1553
                r = get_timezones_from_zone1970_tab(&zones);
×
1554
                if (r == -ENOENT)
×
1555
                        log_debug_errno(r, "Could not get timezone data from zone1970.tab, using UTC: %m");
×
1556
        }
1557
        if (r < 0 && r != -ENOENT)
4✔
1558
                return r;
1559

1560
        /* Always include UTC */
1561
        r = strv_extend(&zones, "UTC");
4✔
1562
        if (r < 0)
4✔
1563
                return r;
1564

1565
        strv_sort_uniq(zones);
4✔
1566

1567
        *ret = TAKE_PTR(zones);
4✔
1568
        return 0;
4✔
1569
}
1570

1571
int verify_timezone(const char *name, int log_level) {
4,222✔
1572
        bool slash = false;
4,222✔
1573
        const char *p, *t;
4,222✔
1574
        _cleanup_close_ int fd = -EBADF;
4,222✔
1575
        char buf[4];
4,222✔
1576
        int r;
4,222✔
1577

1578
        if (isempty(name))
8,444✔
1579
                return -EINVAL;
1580

1581
        /* Always accept "UTC" as valid timezone, since it's the fallback, even if user has no timezones installed. */
1582
        if (streq(name, "UTC"))
4,220✔
1583
                return 0;
1584

1585
        if (name[0] == '/')
4,213✔
1586
                return -EINVAL;
1587

1588
        for (p = name; *p; p++) {
59,333✔
1589
                if (!ascii_isdigit(*p) &&
55,269✔
1590
                    !ascii_isalpha(*p) &&
53,971✔
1591
                    !IN_SET(*p, '-', '_', '+', '/'))
4,796✔
1592
                        return -EINVAL;
1593

1594
                if (*p == '/') {
55,121✔
1595

1596
                        if (slash)
3,716✔
1597
                                return -EINVAL;
1598

1599
                        slash = true;
1600
                } else
1601
                        slash = false;
1602
        }
1603

1604
        if (slash)
4,064✔
1605
                return -EINVAL;
1606

1607
        if (p - name >= PATH_MAX)
4,063✔
1608
                return -ENAMETOOLONG;
1609

1610
        t = strjoina("/usr/share/zoneinfo/", name);
20,315✔
1611

1612
        fd = open(t, O_RDONLY|O_CLOEXEC);
4,063✔
1613
        if (fd < 0)
4,063✔
1614
                return log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
210✔
1615

1616
        r = fd_verify_regular(fd);
3,853✔
1617
        if (r < 0)
3,853✔
1618
                return log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
×
1619

1620
        r = loop_read_exact(fd, buf, 4, false);
3,853✔
1621
        if (r < 0)
3,853✔
1622
                return log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
×
1623

1624
        /* Magic from tzfile(5) */
1625
        if (memcmp(buf, "TZif", 4) != 0)
3,853✔
1626
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EBADMSG),
×
1627
                                      "Timezone file '%s' has wrong magic bytes", t);
1628

1629
        return 0;
1630
}
1631

1632
void reset_timezonep(char **p) {
757✔
1633
        assert(p);
757✔
1634

1635
        (void) set_unset_env("TZ", *p, /* overwrite = */ true);
757✔
1636
        tzset();
757✔
1637
        *p = mfree(*p);
757✔
1638
}
757✔
1639

1640
char* save_timezone(void) {
757✔
1641
        const char *e = getenv("TZ");
757✔
1642
        if (!e)
757✔
1643
                return NULL;
1644

1645
        char *s = strdup(e);
57✔
1646
        if (!s)
57✔
1647
                log_debug("Failed to save $TZ=%s, unsetting the environment variable.", e);
×
1648

1649
        return s;
1650
}
1651

1652
bool clock_supported(clockid_t clock) {
310,358✔
1653
        struct timespec ts;
310,358✔
1654

1655
        switch (clock) {
310,358✔
1656

1657
        case CLOCK_MONOTONIC:
1658
        case CLOCK_REALTIME:
1659
        case CLOCK_BOOTTIME:
1660
                /* These three are always available in our baseline, and work in timerfd, as of kernel 3.15 */
1661
                return true;
1662

1663
        default:
1✔
1664
                /* For everything else, check properly */
1665
                return clock_gettime(clock, &ts) >= 0;
1✔
1666
        }
1667
}
1668

1669
int get_timezone(char **ret) {
61✔
1670
        _cleanup_free_ char *t = NULL;
61✔
1671
        int r;
61✔
1672

1673
        assert(ret);
61✔
1674

1675
        r = readlink_malloc(etc_localtime(), &t);
61✔
1676
        if (r == -ENOENT)
61✔
1677
                /* If the symlink does not exist, assume "UTC", like glibc does */
1678
                return strdup_to(ret, "UTC");
1✔
1679
        if (r < 0)
60✔
1680
                return r; /* Return EINVAL if not a symlink */
1681

1682
        const char *e = PATH_STARTSWITH_SET(t, "/usr/share/zoneinfo/", "../usr/share/zoneinfo/");
60✔
1683
        if (!e)
60✔
1684
                return -EINVAL;
1685
        if (!timezone_is_valid(e, LOG_DEBUG))
60✔
1686
                return -EINVAL;
1687

1688
        return strdup_to(ret, e);
60✔
1689
}
1690

1691
const char* etc_localtime(void) {
991✔
1692
        static const char *cached = NULL;
991✔
1693

1694
        if (!cached)
991✔
1695
                cached = secure_getenv("SYSTEMD_ETC_LOCALTIME") ?: "/etc/localtime";
882✔
1696

1697
        return cached;
991✔
1698
}
1699

1700
int mktime_or_timegm_usec(
7,414✔
1701
                struct tm *tm, /* input + normalized output */
1702
                bool utc,
1703
                usec_t *ret) {
1704

1705
        time_t t;
7,414✔
1706

1707
        assert(tm);
7,414✔
1708

1709
        if (tm->tm_year < 69) /* early check for negative (i.e. before 1970) time_t (Note that in some timezones the epoch is in the year 1969!) */
7,414✔
1710
                return -ERANGE;
1711
        if ((usec_t) tm->tm_year > CONST_MIN(USEC_INFINITY / USEC_PER_YEAR, (usec_t) TIME_T_MAX / (365U * 24U * 60U * 60U)) - 1900) /* early check for possible overrun of usec_t or time_t */
7,411✔
1712
                return -ERANGE;
1713

1714
        /* timegm()/mktime() is a bit weird to use, since it returns -1 in two cases: on error as well as a
1715
         * valid time indicating one second before the UNIX epoch. Let's treat both cases the same here, and
1716
         * return -ERANGE for anything negative, since usec_t is unsigned, and we can thus not express
1717
         * negative times anyway. */
1718

1719
        t = utc ? timegm(tm) : mktime(tm);
7,411✔
1720
        if (t < 0) /* Refuse negative times and errors */
7,411✔
1721
                return -ERANGE;
1722
        if ((usec_t) t >= USEC_INFINITY / USEC_PER_SEC) /* Never return USEC_INFINITY by accident (or overflow) */
7,409✔
1723
                return -ERANGE;
1724

1725
        if (ret)
7,409✔
1726
                *ret = (usec_t) t * USEC_PER_SEC;
2,160✔
1727
        return 0;
1728
}
1729

1730
int localtime_or_gmtime_usec(
131,603✔
1731
                usec_t t,
1732
                bool utc,
1733
                struct tm *ret) {
1734

1735
        t /= USEC_PER_SEC; /* Round down */
131,603✔
1736
        if (t > (usec_t) TIME_T_MAX)
131,603✔
1737
                return -ERANGE;
1738
        time_t sec = (time_t) t;
131,603✔
1739

1740
        struct tm buf = {};
131,603✔
1741
        if (!(utc ? gmtime_r(&sec, &buf) : localtime_r(&sec, &buf)))
131,603✔
1742
                return -EINVAL;
1743

1744
        if (ret)
131,603✔
1745
                *ret = buf;
131,603✔
1746

1747
        return 0;
1748
}
1749

1750
static uint32_t sysconf_clock_ticks_cached(void) {
731✔
1751
        static thread_local uint32_t hz = 0;
731✔
1752
        long r;
731✔
1753

1754
        if (hz == 0) {
731✔
1755
                r = sysconf(_SC_CLK_TCK);
70✔
1756

1757
                assert(r > 0);
70✔
1758
                hz = r;
70✔
1759
        }
1760

1761
        return hz;
731✔
1762
}
1763

1764
uint32_t usec_to_jiffies(usec_t u) {
9✔
1765
        uint32_t hz = sysconf_clock_ticks_cached();
9✔
1766
        return DIV_ROUND_UP(u, USEC_PER_SEC / hz);
9✔
1767
}
1768

1769
usec_t jiffies_to_usec(uint32_t j) {
722✔
1770
        uint32_t hz = sysconf_clock_ticks_cached();
722✔
1771
        return DIV_ROUND_UP(j * USEC_PER_SEC, hz);
722✔
1772
}
1773

1774
usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
686✔
1775
        usec_t a, b;
686✔
1776

1777
        if (x == USEC_INFINITY)
686✔
1778
                return USEC_INFINITY;
1779
        if (map_clock_id(from) == map_clock_id(to))
531✔
1780
                return x;
1781

1782
        a = now(from);
8✔
1783
        b = now(to);
8✔
1784

1785
        if (x > a)
8✔
1786
                /* x lies in the future */
1787
                return usec_add(b, usec_sub_unsigned(x, a));
12✔
1788
        else
1789
                /* x lies in the past */
1790
                return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
6✔
1791
}
1792

1793
bool in_utc_timezone(void) {
676✔
1794
        tzset();
676✔
1795

1796
        return timezone == 0 && daylight == 0;
676✔
1797
}
1798

1799
int time_change_fd(void) {
449✔
1800

1801
        /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1802
        static const struct itimerspec its = {
449✔
1803
                .it_value.tv_sec = TIME_T_MAX,
1804
        };
1805

1806
        _cleanup_close_ int fd = -EBADF;
898✔
1807

1808
        assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
449✔
1809

1810
        /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1811
         * CLOCK_MONOTONIC. */
1812

1813
        fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
449✔
1814
        if (fd < 0)
449✔
1815
                return -errno;
×
1816

1817
        if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) >= 0)
449✔
1818
                return TAKE_FD(fd);
449✔
1819

1820
        /* So apparently there are systems where time_t is 64-bit, but the kernel actually doesn't support
1821
         * 64-bit time_t. In that case configuring a timer to TIME_T_MAX will fail with EOPNOTSUPP or a
1822
         * similar error. If that's the case let's try with INT32_MAX instead, maybe that works. It's a bit
1823
         * of a black magic thing though, but what can we do?
1824
         *
1825
         * We don't want this code on x86-64, hence let's conditionalize this for systems with 64-bit time_t
1826
         * but where "long" is shorter than 64-bit, i.e. 32-bit archs.
1827
         *
1828
         * See: https://github.com/systemd/systemd/issues/14362 */
1829

1830
#if SIZEOF_TIME_T == 8 && ULONG_MAX < UINT64_MAX
1831
        if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EOVERFLOW) {
1832
                static const struct itimerspec its32 = {
1833
                        .it_value.tv_sec = INT32_MAX,
1834
                };
1835

1836
                if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its32, NULL) >= 0)
1837
                        return TAKE_FD(fd);
1838
        }
1839
#endif
1840

1841
        return -errno;
×
1842
}
1843

1844
static const char* const timestamp_style_table[_TIMESTAMP_STYLE_MAX] = {
1845
        [TIMESTAMP_PRETTY] = "pretty",
1846
        [TIMESTAMP_US]     = "us",
1847
        [TIMESTAMP_UTC]    = "utc",
1848
        [TIMESTAMP_US_UTC] = "us+utc",
1849
        [TIMESTAMP_UNIX]   = "unix",
1850
};
1851

1852
/* Use the macro for enum → string to allow for aliases */
1853
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(timestamp_style, TimestampStyle);
×
1854

1855
/* For the string → enum mapping we use the generic implementation, but also support two aliases */
1856
TimestampStyle timestamp_style_from_string(const char *s) {
8✔
1857
        TimestampStyle t;
8✔
1858

1859
        t = (TimestampStyle) string_table_lookup_from_string(timestamp_style_table, ELEMENTSOF(timestamp_style_table), s);
8✔
1860
        if (t >= 0)
8✔
1861
                return t;
1862
        if (STRPTR_IN_SET(s, "µs", "μs")) /* accept both µ symbols in unicode, i.e. micro symbol + Greek small letter mu. */
2✔
1863
                return TIMESTAMP_US;
1✔
1864
        if (STRPTR_IN_SET(s, "µs+utc", "μs+utc"))
1✔
1865
                return TIMESTAMP_US_UTC;
1✔
1866
        return t;
1867
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc