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

systemd / systemd / 28689257516

03 Jul 2026 11:32PM UTC coverage: 72.9% (+0.3%) from 72.618%
28689257516

push

github

bluca
hwdb: map mic-mute key on Logitech K950 (Bluetooth)

The mic-mute key on the Logitech K950 keyboard (046D:B388, Bluetooth)
emits BTN_0 (scancode 0x100e1) instead of a usable key, so it does
nothing under GNOME/KDE. Map it to KEY_MICMUTE, its intended function.

Scancode determined with evtest on the device.

343301 of 470919 relevant lines covered (72.9%)

1344559.44 hits per line

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

90.12
/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) {
297,483,629✔
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) {
297,483,629✔
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:
297,483,620✔
43
                return c;
297,483,620✔
44
        }
45
}
46

47
usec_t now(clockid_t clock_id) {
297,480,042✔
48
        struct timespec ts;
297,480,042✔
49

50
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
297,480,042✔
51

52
        usec_t n = timespec_load(&ts);
297,480,042✔
53

54
        /* We use both 0 and USEC_INFINITY as niche values. If the current time collides with either, things are
55
         * really weird and really broken. Let's not allow this to go through, it would break too many of our
56
         * assumptions in code. */
57
        assert(n > 0);
297,480,042✔
58
        assert(n < USEC_INFINITY);
297,480,042✔
59

60
        return n;
297,480,042✔
61
}
62

63
nsec_t now_nsec(clockid_t clock_id) {
677✔
64
        struct timespec ts;
677✔
65

66
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
677✔
67

68
        nsec_t n = timespec_load_nsec(&ts);
677✔
69

70
        assert(n > 0);
677✔
71
        assert(n < NSEC_INFINITY);
677✔
72

73
        return n;
677✔
74
}
75

76
dual_timestamp* dual_timestamp_now(dual_timestamp *ts) {
2,005,765✔
77
        assert(ts);
2,005,765✔
78

79
        ts->realtime = now(CLOCK_REALTIME);
2,005,765✔
80
        ts->monotonic = now(CLOCK_MONOTONIC);
2,005,765✔
81

82
        return ts;
2,005,765✔
83
}
84

85
triple_timestamp* triple_timestamp_now(triple_timestamp *ts) {
4,121,188✔
86
        assert(ts);
4,121,188✔
87

88
        ts->realtime = now(CLOCK_REALTIME);
4,121,188✔
89
        ts->monotonic = now(CLOCK_MONOTONIC);
4,121,188✔
90
        ts->boottime = now(CLOCK_BOOTTIME);
4,121,188✔
91

92
        return ts;
4,121,188✔
93
}
94

95
usec_t map_clock_usec_raw(usec_t from, usec_t from_base, usec_t to_base) {
14,573✔
96

97
        /* Maps the time 'from' between two clocks, based on a common reference point where the first clock
98
         * is at 'from_base' and the second clock at 'to_base'. Basically calculates:
99
         *
100
         *         from - from_base + to_base
101
         *
102
         * But takes care of overflows/underflows and avoids signed operations. */
103

104
        if (from >= from_base) { /* In the future */
14,573✔
105
                usec_t delta = from - from_base;
64✔
106

107
                if (to_base >= USEC_INFINITY - delta) /* overflow? */
64✔
108
                        return USEC_INFINITY;
109

110
                return to_base + delta;
64✔
111

112
        } else { /* In the past */
113
                usec_t delta = from_base - from;
14,509✔
114

115
                if (to_base <= delta) /* underflow? */
14,509✔
116
                        return 0;
117

118
                return to_base - delta;
14,500✔
119
        }
120
}
121

122
usec_t map_clock_usec(usec_t from, clockid_t from_clock, clockid_t to_clock) {
572✔
123

124
        /* Try to avoid any inaccuracy needlessly added in case we convert from effectively the same clock
125
         * onto itself */
126
        if (map_clock_id(from_clock) == map_clock_id(to_clock))
572✔
127
                return from;
128

129
        /* Keep infinity as is */
130
        if (from == USEC_INFINITY)
572✔
131
                return from;
132

133
        return map_clock_usec_raw(from, now(from_clock), now(to_clock));
526✔
134
}
135

136
dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
12✔
137
        assert(ts);
12✔
138

139
        if (!timestamp_is_set(u)) {
12✔
140
                ts->realtime = ts->monotonic = u;
×
141
                return ts;
×
142
        }
143

144
        ts->realtime = u;
12✔
145
        ts->monotonic = map_clock_usec(u, CLOCK_REALTIME, CLOCK_MONOTONIC);
12✔
146
        return ts;
12✔
147
}
148

149
triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
353✔
150
        usec_t nowr;
353✔
151

152
        assert(ts);
353✔
153

154
        if (!timestamp_is_set(u)) {
353✔
155
                ts->realtime = ts->monotonic = ts->boottime = u;
×
156
                return ts;
×
157
        }
158

159
        nowr = now(CLOCK_REALTIME);
353✔
160

161
        ts->realtime = u;
353✔
162
        ts->monotonic = map_clock_usec_raw(u, nowr, now(CLOCK_MONOTONIC));
353✔
163
        ts->boottime = map_clock_usec_raw(u, nowr, now(CLOCK_BOOTTIME));
353✔
164

165
        return ts;
353✔
166
}
167

168
triple_timestamp* triple_timestamp_from_boottime(triple_timestamp *ts, usec_t u) {
×
169
        usec_t nowb;
×
170

171
        assert(ts);
×
172

173
        if (u == USEC_INFINITY) {
×
174
                ts->realtime = ts->monotonic = ts->boottime = u;
×
175
                return ts;
×
176
        }
177

178
        nowb = now(CLOCK_BOOTTIME);
×
179

180
        ts->boottime = u;
×
181
        ts->monotonic = map_clock_usec_raw(u, nowb, now(CLOCK_MONOTONIC));
×
182
        ts->realtime = map_clock_usec_raw(u, nowb, now(CLOCK_REALTIME));
×
183

184
        return ts;
×
185
}
186

187
dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
295✔
188
        assert(ts);
295✔
189

190
        if (u == USEC_INFINITY) {
295✔
191
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
192
                return ts;
×
193
        }
194

195
        ts->monotonic = u;
295✔
196
        ts->realtime = map_clock_usec(u, CLOCK_MONOTONIC, CLOCK_REALTIME);
295✔
197
        return ts;
295✔
198
}
199

200
dual_timestamp* dual_timestamp_from_boottime(dual_timestamp *ts, usec_t u) {
2,954✔
201
        usec_t nowm;
2,954✔
202

203
        assert(ts);
2,954✔
204

205
        if (u == USEC_INFINITY) {
2,954✔
206
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
207
                return ts;
×
208
        }
209

210
        nowm = now(CLOCK_BOOTTIME);
2,954✔
211
        ts->monotonic = map_clock_usec_raw(u, nowm, now(CLOCK_MONOTONIC));
2,954✔
212
        ts->realtime = map_clock_usec_raw(u, nowm, now(CLOCK_REALTIME));
2,954✔
213
        return ts;
2,954✔
214
}
215

216
usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
5,235,561✔
217
        assert(ts);
5,235,561✔
218

219
        switch (clock) {
5,235,561✔
220

221
        case CLOCK_REALTIME:
2,887,145✔
222
        case CLOCK_REALTIME_ALARM:
223
                return ts->realtime;
2,887,145✔
224

225
        case CLOCK_MONOTONIC:
2,305,271✔
226
                return ts->monotonic;
2,305,271✔
227

228
        case CLOCK_BOOTTIME:
43,145✔
229
        case CLOCK_BOOTTIME_ALARM:
230
                return ts->boottime;
43,145✔
231

232
        default:
233
                return USEC_INFINITY;
234
        }
235
}
236

237
usec_t timespec_load(const struct timespec *ts) {
299,200,841✔
238
        assert(ts);
299,200,841✔
239

240
        if (ts->tv_sec < 0 || ts->tv_nsec < 0)
299,200,841✔
241
                return USEC_INFINITY;
242

243
        if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
299,200,841✔
244
                return USEC_INFINITY;
245

246
        return
299,200,841✔
247
                (usec_t) ts->tv_sec * USEC_PER_SEC +
299,200,841✔
248
                (usec_t) ts->tv_nsec / NSEC_PER_USEC;
249
}
250

251
nsec_t timespec_load_nsec(const struct timespec *ts) {
1,504✔
252
        assert(ts);
1,504✔
253

254
        if (ts->tv_sec < 0 || ts->tv_nsec < 0)
1,504✔
255
                return NSEC_INFINITY;
256

257
        if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
1,504✔
258
                return NSEC_INFINITY;
259

260
        return (nsec_t) ts->tv_sec * NSEC_PER_SEC + (nsec_t) ts->tv_nsec;
1,504✔
261
}
262

263
struct timespec *timespec_store(struct timespec *ts, usec_t u) {
684,825✔
264
        assert(ts);
684,825✔
265

266
        if (u == USEC_INFINITY ||
684,825✔
267
            u / USEC_PER_SEC >= TIME_T_MAX) {
268
                ts->tv_sec = (time_t) -1;
×
269
                ts->tv_nsec = -1L;
×
270
                return ts;
×
271
        }
272

273
        ts->tv_sec = (time_t) (u / USEC_PER_SEC);
684,825✔
274
        ts->tv_nsec = (long) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
684,825✔
275

276
        return ts;
684,825✔
277
}
278

279
struct timespec *timespec_store_nsec(struct timespec *ts, nsec_t n) {
56✔
280
        assert(ts);
56✔
281

282
        if (n == NSEC_INFINITY ||
56✔
283
            n / NSEC_PER_SEC >= TIME_T_MAX) {
284
                ts->tv_sec = (time_t) -1;
×
285
                ts->tv_nsec = -1L;
×
286
                return ts;
×
287
        }
288

289
        ts->tv_sec = (time_t) (n / NSEC_PER_SEC);
56✔
290
        ts->tv_nsec = (long) (n % NSEC_PER_SEC);
56✔
291

292
        return ts;
56✔
293
}
294

295
usec_t timeval_load(const struct timeval *tv) {
1,679,827✔
296
        assert(tv);
1,679,827✔
297

298
        if (tv->tv_sec < 0 || tv->tv_usec < 0)
1,679,827✔
299
                return USEC_INFINITY;
300

301
        if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
1,679,827✔
302
                return USEC_INFINITY;
303

304
        return
1,679,827✔
305
                (usec_t) tv->tv_sec * USEC_PER_SEC +
1,679,827✔
306
                (usec_t) tv->tv_usec;
307
}
308

309
struct timeval *timeval_store(struct timeval *tv, usec_t u) {
225,207✔
310
        assert(tv);
225,207✔
311

312
        if (u == USEC_INFINITY ||
225,207✔
313
            u / USEC_PER_SEC > TIME_T_MAX) {
314
                tv->tv_sec = (time_t) -1;
×
315
                tv->tv_usec = (suseconds_t) -1;
×
316
        } else {
317
                tv->tv_sec = (time_t) (u / USEC_PER_SEC);
225,207✔
318
                tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
225,207✔
319
        }
320

321
        return tv;
225,207✔
322
}
323

324
/* Returns the abbreviated English weekday name for wd in Mon=0 … Sun=6 order.
325
 * We use non-localized (English) form so that timestamps can be parsed with
326
 * parse_timestamp() and always read the same regardless of locale. */
327
static const char *const weekday_table[_WEEKDAY_MAX] = {
328
        [WEEKDAY_MON] = "Mon",
329
        [WEEKDAY_TUE] = "Tue",
330
        [WEEKDAY_WED] = "Wed",
331
        [WEEKDAY_THU] = "Thu",
332
        [WEEKDAY_FRI] = "Fri",
333
        [WEEKDAY_SAT] = "Sat",
334
        [WEEKDAY_SUN] = "Sun",
335
};
336

337
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(weekday, int);
5,801✔
338

339
char* format_timestamp_style(
8,425✔
340
                char *buf,
341
                size_t l,
342
                usec_t t,
343
                TimestampStyle style) {
344
        struct tm tm;
8,425✔
345
        bool utc, us;
8,425✔
346
        size_t n;
8,425✔
347

348
        assert(buf);
8,425✔
349
        assert(style >= 0);
8,425✔
350
        assert(style < _TIMESTAMP_STYLE_MAX);
8,425✔
351

352
        if (!timestamp_is_set(t))
8,425✔
353
                return NULL; /* Timestamp is unset */
8,425✔
354

355
        if (style == TIMESTAMP_UNIX) {
5,841✔
356
                if (l < (size_t) (1 + 1 + 1))
102✔
357
                        return NULL; /* not enough space for even the shortest of forms */
358

359
                return snprintf_ok(buf, l, "@" USEC_FMT, t / USEC_PER_SEC);  /* round down μs → s */
102✔
360
        }
361

362
        utc = IN_SET(style, TIMESTAMP_UTC, TIMESTAMP_US_UTC, TIMESTAMP_DATE);
5,739✔
363
        us = IN_SET(style, TIMESTAMP_US, TIMESTAMP_US_UTC);
5,739✔
364

365
        if (l < (size_t) (3 +                   /* week day */
5,238✔
366
                          1 + 10 +              /* space and date */
367
                          style == TIMESTAMP_DATE ? 0 :
368
                          (1 + 8 +              /* space and time */
369
                           (us ? 1 + 6 : 0) +   /* "." and microsecond part */
5,739✔
370
                           1 + (utc ? 3 : 1)) + /* space and shortest possible zone */
11,135✔
371
                          1))
372
                return NULL; /* Not enough space even for the shortest form. */
373

374
        /* Let's not format times with years > 9999 */
375
        if (t > USEC_TIMESTAMP_FORMATTABLE_MAX) {
5,739✔
376
                static const char* const xxx[_TIMESTAMP_STYLE_MAX] = {
4✔
377
                        [TIMESTAMP_PRETTY] = "--- XXXX-XX-XX XX:XX:XX",
378
                        [TIMESTAMP_US]     = "--- XXXX-XX-XX XX:XX:XX.XXXXXX",
379
                        [TIMESTAMP_UTC]    = "--- XXXX-XX-XX XX:XX:XX UTC",
380
                        [TIMESTAMP_US_UTC] = "--- XXXX-XX-XX XX:XX:XX.XXXXXX UTC",
381
                        [TIMESTAMP_DATE]   = "--- XXXX-XX-XX",
382
                };
383

384
                assert(l >= strlen(xxx[style]) + 1);
4✔
385
                return strcpy(buf, xxx[style]);
4✔
386
        }
387

388
        if (localtime_or_gmtime_usec(t, utc, &tm) < 0)
5,735✔
389
                return NULL;
390

391
        /* Start with the week day */
392
        const char *weekday = weekday_to_string(tm.tm_wday == 0 ? 6 : tm.tm_wday - 1);
5,735✔
393
        assert(weekday);
5,735✔
394
        memcpy(buf, weekday, 4);
5,735✔
395

396
        if (style == TIMESTAMP_DATE) {
5,735✔
397
                /* Special format string if only date should be shown. */
398
                if (strftime(buf + 3, l - 3, " %Y-%m-%d", &tm) <= 0)
105✔
399
                        return NULL; /* Doesn't fit */
400

401
                return buf;
105✔
402
        }
403

404
        /* Add the main components */
405
        if (strftime(buf + 3, l - 3, " %Y-%m-%d %H:%M:%S", &tm) <= 0)
5,630✔
406
                return NULL; /* Doesn't fit */
407

408
        /* Append the microseconds part, if that's requested */
409
        if (us) {
5,630✔
410
                n = strlen(buf);
500✔
411
                if (n + 8 > l)
500✔
412
                        return NULL; /* Microseconds part doesn't fit. */
413

414
                sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
500✔
415
        }
416

417
        /* Append the timezone */
418
        n = strlen(buf);
5,630✔
419
        if (utc) {
5,630✔
420
                /* If this is UTC then let's explicitly use the "UTC" string here, because gmtime_r()
421
                 * normally uses the obsolete "GMT" instead. */
422
                if (n + 5 > l)
235✔
423
                        return NULL; /* "UTC" doesn't fit. */
424

425
                strcpy(buf + n, " UTC");
235✔
426

427
        } else if (!isempty(tm.tm_zone)) {
5,395✔
428
                size_t tn;
5,395✔
429

430
                /* An explicit timezone is specified, let's use it, if it fits */
431
                tn = strlen(tm.tm_zone);
5,395✔
432
                if (n + 1 + tn + 1 > l) {
5,395✔
433
                        /* The full time zone does not fit in. Yuck. */
434

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

439
                        /* So the time zone doesn't fit in fully, but the caller passed enough space for the
440
                         * POSIX minimum time zone length. In this case suppress the timezone entirely, in
441
                         * order not to dump an overly long, hard to read string on the user. This should be
442
                         * safe, because the user will assume the local timezone anyway if none is shown. And
443
                         * so does parse_timestamp(). */
444
                } else {
445
                        buf[n++] = ' ';
5,395✔
446
                        strcpy(buf + n, tm.tm_zone);
5,395✔
447
                }
448
        }
449

450
        return buf;
451
}
452

453
char* format_timestamp_relative_full(char *buf, size_t l, usec_t t, clockid_t clock, bool implicit_left) {
1,469✔
454
        const char *s;
1,469✔
455
        usec_t n, d;
1,469✔
456

457
        assert(buf);
1,469✔
458

459
        if (!timestamp_is_set(t))
1,469✔
460
                return NULL;
461

462
        n = now(clock);
1,463✔
463
        if (n > t) {
1,463✔
464
                d = n - t;
1,267✔
465
                s = " ago";
1,267✔
466
        } else {
467
                d = t - n;
196✔
468
                s = implicit_left ? "" : " left";
196✔
469
        }
470

471
        if (d >= USEC_PER_YEAR) {
1,463✔
472
                usec_t years = d / USEC_PER_YEAR;
742✔
473
                usec_t months = (d % USEC_PER_YEAR) / USEC_PER_MONTH;
742✔
474

475
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
2,205✔
476
                                years,
477
                                years == 1 ? "year" : "years",
478
                                months,
479
                                months == 1 ? "month" : "months",
480
                                s);
481
        } else if (d >= USEC_PER_MONTH) {
721✔
482
                usec_t months = d / USEC_PER_MONTH;
13✔
483
                usec_t days = (d % USEC_PER_MONTH) / USEC_PER_DAY;
13✔
484

485
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
31✔
486
                                months,
487
                                months == 1 ? "month" : "months",
488
                                days,
489
                                days == 1 ? "day" : "days",
490
                                s);
491
        } else if (d >= USEC_PER_WEEK) {
708✔
492
                usec_t weeks = d / USEC_PER_WEEK;
8✔
493
                usec_t days = (d % USEC_PER_WEEK) / USEC_PER_DAY;
8✔
494

495
                (void) snprintf(buf, l, USEC_FMT " %s " USEC_FMT " %s%s",
16✔
496
                                weeks,
497
                                weeks == 1 ? "week" : "weeks",
498
                                days,
499
                                days == 1 ? "day" : "days",
500
                                s);
501
        } else if (d >= 2*USEC_PER_DAY)
700✔
502
                (void) snprintf(buf, l, USEC_FMT " days%s", d / USEC_PER_DAY,s);
×
503
        else if (d >= 25*USEC_PER_HOUR)
700✔
504
                (void) snprintf(buf, l, "1 day " USEC_FMT "h%s",
11✔
505
                                (d - USEC_PER_DAY) / USEC_PER_HOUR, s);
11✔
506
        else if (d >= 6*USEC_PER_HOUR)
689✔
507
                (void) snprintf(buf, l, USEC_FMT "h%s",
22✔
508
                                d / USEC_PER_HOUR, s);
509
        else if (d >= USEC_PER_HOUR)
667✔
510
                (void) snprintf(buf, l, USEC_FMT "h " USEC_FMT "min%s",
5✔
511
                                d / USEC_PER_HOUR,
512
                                (d % USEC_PER_HOUR) / USEC_PER_MINUTE, s);
5✔
513
        else if (d >= 5*USEC_PER_MINUTE)
662✔
514
                (void) snprintf(buf, l, USEC_FMT "min%s",
8✔
515
                                d / USEC_PER_MINUTE, s);
516
        else if (d >= USEC_PER_MINUTE)
654✔
517
                (void) snprintf(buf, l, USEC_FMT "min " USEC_FMT "s%s",
1✔
518
                                d / USEC_PER_MINUTE,
519
                                (d % USEC_PER_MINUTE) / USEC_PER_SEC, s);
1✔
520
        else if (d >= USEC_PER_SEC)
653✔
521
                (void) snprintf(buf, l, USEC_FMT "s%s",
549✔
522
                                d / USEC_PER_SEC, s);
523
        else if (d >= USEC_PER_MSEC)
104✔
524
                (void) snprintf(buf, l, USEC_FMT "ms%s",
101✔
525
                                d / USEC_PER_MSEC, s);
526
        else if (d > 0)
3✔
527
                (void) snprintf(buf, l, USEC_FMT"us%s",
3✔
528
                                d, s);
529
        else
530
                (void) snprintf(buf, l, "now");
×
531

532
        buf[l-1] = 0;
1,463✔
533
        return buf;
1,463✔
534
}
535

536
char* format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
22,533✔
537
        static const struct {
22,533✔
538
                const char *suffix;
539
                usec_t usec;
540
        } table[] = {
541
                { "y",     USEC_PER_YEAR   },
542
                { "month", USEC_PER_MONTH  },
543
                { "w",     USEC_PER_WEEK   },
544
                { "d",     USEC_PER_DAY    },
545
                { "h",     USEC_PER_HOUR   },
546
                { "min",   USEC_PER_MINUTE },
547
                { "s",     USEC_PER_SEC    },
548
                { "ms",    USEC_PER_MSEC   },
549
                { "us",    1               },
550
        };
551

552
        char *p = ASSERT_PTR(buf);
22,533✔
553
        bool something = false;
22,533✔
554

555
        assert(l > 0);
22,533✔
556

557
        if (t == USEC_INFINITY) {
22,533✔
558
                strncpy(p, "infinity", l-1);
1,916✔
559
                p[l-1] = 0;
1,916✔
560
                return p;
1,916✔
561
        }
562

563
        if (t <= 0) {
20,617✔
564
                strncpy(p, "0", l-1);
1,006✔
565
                p[l-1] = 0;
1,006✔
566
                return p;
1,006✔
567
        }
568

569
        /* The result of this function can be parsed with parse_sec */
570

571
        FOREACH_ELEMENT(i, table) {
165,788✔
572
                int k = 0;
165,685✔
573
                size_t n;
165,685✔
574
                bool done = false;
165,685✔
575
                usec_t a, b;
165,685✔
576

577
                if (t <= 0)
165,685✔
578
                        break;
579

580
                if (t < accuracy && something)
146,254✔
581
                        break;
582

583
                if (t < i->usec)
146,177✔
584
                        continue;
120,598✔
585

586
                if (l <= 1)
25,579✔
587
                        break;
588

589
                a = t / i->usec;
25,579✔
590
                b = t % i->usec;
25,579✔
591

592
                /* Let's see if we should shows this in dot notation */
593
                if (t < USEC_PER_MINUTE && b > 0) {
25,579✔
594
                        signed char j = 0;
595

596
                        for (usec_t cc = i->usec; cc > 1; cc /= 10)
88,335✔
597
                                j++;
72,498✔
598

599
                        for (usec_t cc = accuracy; cc > 1; cc /= 10) {
69,384✔
600
                                b /= 10;
53,547✔
601
                                j--;
53,547✔
602
                        }
603

604
                        if (j > 0) {
15,837✔
605
                                k = snprintf(p, l,
10,446✔
606
                                             "%s"USEC_FMT".%0*"PRI_USEC"%s",
607
                                             p > buf ? " " : "",
608
                                             a,
609
                                             j,
610
                                             b,
611
                                             i->suffix);
5,223✔
612

613
                                t = 0;
5,223✔
614
                                done = true;
5,223✔
615
                        }
616
                }
617

618
                /* No? Then let's show it normally */
619
                if (!done) {
5,223✔
620
                        k = snprintf(p, l,
40,712✔
621
                                     "%s"USEC_FMT"%s",
622
                                     p > buf ? " " : "",
623
                                     a,
624
                                     i->suffix);
20,356✔
625

626
                        t = b;
20,356✔
627
                }
628

629
                n = MIN((size_t) k, l-1);
25,579✔
630

631
                l -= n;
25,579✔
632
                p += n;
25,579✔
633

634
                something = true;
25,579✔
635
        }
636

637
        *p = 0;
19,611✔
638

639
        return buf;
19,611✔
640
}
641

642
const char* get_tzname(bool dst) {
3,538✔
643
        /* musl leaves the DST timezone name unset if there is no DST, map this back to no DST */
644
        if (dst && isempty(tzname[1]))
3,539✔
645
                dst = false;
646

647
        return empty_to_null(tzname[dst]);
3,538✔
648
}
649

650
int parse_gmtoff(const char *t, long *ret) {
1,247✔
651
        assert(t);
1,247✔
652

653
        struct tm tm;
1,247✔
654
        const char *k = strptime(t, "%z", &tm);
1,247✔
655
        if (k && *k == '\0') {
1,247✔
656
                /* Success! */
657
                if (ret)
172✔
658
                        *ret = tm.tm_gmtoff;
172✔
659
                return 0;
1,247✔
660
        }
661

662
#ifdef __GLIBC__
663
        return -EINVAL;
664
#else
665
        int r;
666

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

673
        bool positive;
674
        switch (*t) {
675
        case '+':
676
                positive = true;
677
                break;
678
        case '-':
679
                positive = false;
680
                break;
681
        default:
682
                return -EINVAL;
683
        }
684

685
        t++;
686
        r = undecchar(*t);
687
        if (r < 0)
688
                return r;
689

690
        usec_t u = r * 10 * USEC_PER_HOUR;
691

692
        t++;
693
        r = undecchar(*t);
694
        if (r < 0)
695
                return r;
696
        u += r * USEC_PER_HOUR;
697

698
        t++;
699
        if (*t == '\0') /* 2 digits case */
700
                goto finalize;
701

702
        if (*t == ':') /* skip colon */
703
                t++;
704

705
        r = undecchar(*t);
706
        if (r < 0)
707
                return r;
708
        if (r >= 6) /* refuse minutes equal to or larger than 60 */
709
                return -EINVAL;
710

711
        u += r * 10 * USEC_PER_MINUTE;
712

713
        t++;
714
        r = undecchar(*t);
715
        if (r < 0)
716
                return r;
717

718
        u += r * USEC_PER_MINUTE;
719

720
        t++;
721
        if (*t != '\0')
722
                return -EINVAL;
723

724
finalize:
725
        if (u > USEC_PER_DAY) /* refuse larger than one day */
726
                return -EINVAL;
727

728
        if (ret) {
729
                long gmtoff = u / USEC_PER_SEC;
730
                *ret = positive ? gmtoff : -gmtoff;
731
        }
732

733
        return 0;
734
#endif
735
}
736

737
static int parse_timestamp_impl(
2,155✔
738
                const char *t,
739
                size_t max_len,
740
                bool utc,
741
                int isdst,
742
                long gmtoff,
743
                usec_t *ret) {
744

745
        static const struct {
2,155✔
746
                const char *name;
747
                const int nr;
748
        } day_nr[] = {
749
                { "Sunday",    0 },
750
                { "Sun",       0 },
751
                { "Monday",    1 },
752
                { "Mon",       1 },
753
                { "Tuesday",   2 },
754
                { "Tue",       2 },
755
                { "Wednesday", 3 },
756
                { "Wed",       3 },
757
                { "Thursday",  4 },
758
                { "Thu",       4 },
759
                { "Friday",    5 },
760
                { "Fri",       5 },
761
                { "Saturday",  6 },
762
                { "Sat",       6 },
763
        };
764

765
        _cleanup_free_ char *t_alloc = NULL;
2,155✔
766
        usec_t usec, plus = 0, minus = 0;
2,155✔
767
        bool with_tz = false;
2,155✔
768
        int r, weekday = -1;
2,155✔
769
        unsigned fractional = 0;
2,155✔
770
        const char *k;
2,155✔
771
        struct tm tm, copy;
2,155✔
772

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

805
        assert(t);
2,155✔
806

807
        if (max_len != SIZE_MAX) {
2,155✔
808
                /* If the input string contains timezone, then cut it here. */
809

810
                if (max_len == 0) /* Can't be the only field */
1,696✔
811
                        return -EINVAL;
812

813
                t_alloc = strndup(t, max_len);
1,696✔
814
                if (!t_alloc)
1,696✔
815
                        return -ENOMEM;
816

817
                t = t_alloc;
818
                with_tz = true;
819
        }
820

821
        if (utc) {
2,155✔
822
                /* glibc accepts gmtoff more than 24 hours, but we refuse it. */
823
                if ((usec_t) labs(gmtoff) * USEC_PER_SEC > USEC_PER_DAY)
997✔
824
                        return -EINVAL;
825
        } else {
826
                if (gmtoff != 0)
1,158✔
827
                        return -EINVAL;
828
        }
829

830
        if (t[0] == '@' && !with_tz)
2,155✔
831
                return parse_sec(t + 1, ret);
107✔
832

833
        usec = now(CLOCK_REALTIME);
2,048✔
834

835
        if (!with_tz) {
2,048✔
836
                if (streq(t, "now"))
352✔
837
                        goto finish;
5✔
838

839
                if (t[0] == '+') {
347✔
840
                        r = parse_sec(t+1, &plus);
6✔
841
                        if (r < 0)
6✔
842
                                return r;
843

844
                        goto finish;
6✔
845
                }
846

847
                if (t[0] == '-') {
341✔
848
                        r = parse_sec(t+1, &minus);
9✔
849
                        if (r < 0)
9✔
850
                                return r;
851

852
                        goto finish;
9✔
853
                }
854

855
                if ((k = endswith(t, " ago"))) {
332✔
856
                        _cleanup_free_ char *buf = NULL;
3✔
857

858
                        buf = strndup(t, k - t);
3✔
859
                        if (!buf)
3✔
860
                                return -ENOMEM;
861

862
                        r = parse_sec(buf, &minus);
3✔
863
                        if (r < 0)
3✔
864
                                return r;
865

866
                        goto finish;
3✔
867
                }
868

869
                if ((k = endswith(t, " left"))) {
329✔
870
                        _cleanup_free_ char *buf = NULL;
102✔
871

872
                        buf = strndup(t, k - t);
102✔
873
                        if (!buf)
102✔
874
                                return -ENOMEM;
875

876
                        r = parse_sec(buf, &plus);
102✔
877
                        if (r < 0)
102✔
878
                                return r;
879

880
                        goto finish;
102✔
881
                }
882
        }
883

884
        r = localtime_or_gmtime_usec(usec, utc, &tm);
1,923✔
885
        if (r < 0)
1,923✔
886
                return r;
887

888
        tm.tm_isdst = isdst;
1,923✔
889

890
        if (streq(t, "today")) {
1,923✔
891
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
13✔
892
                goto from_tm;
13✔
893

894
        } else if (streq(t, "yesterday")) {
1,910✔
895
                tm.tm_mday--;
10✔
896
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
10✔
897
                goto from_tm;
10✔
898

899
        } else if (streq(t, "tomorrow")) {
1,900✔
900
                tm.tm_mday++;
8✔
901
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
8✔
902
                goto from_tm;
8✔
903
        }
904

905
        FOREACH_ELEMENT(day, day_nr) {
19,768✔
906
                k = startswith_no_case(t, day->name);
19,434✔
907
                if (!k || *k != ' ')
19,434✔
908
                        continue;
17,876✔
909

910
#ifdef __GLIBC__
911
                /* musl does not set tm_wday field and set 0 unless it is explicitly requested by %w or so.
912
                 * In the below, let's only check tm_wday field only when built with glibc. */
913
                weekday = day->nr;
1,558✔
914
#endif
915
                t = k + 1;
1,558✔
916
                break;
1,558✔
917
        }
918

919
        copy = tm;
1,892✔
920
        k = strptime(t, "%y-%m-%d %H:%M:%S", &tm);
1,892✔
921
        if (k) {
1,892✔
922
                if (*k == '.')
100✔
923
                        goto parse_usec;
64✔
924
                else if (*k == 0)
36✔
925
                        goto from_tm;
32✔
926
        }
927

928
        /* Our "canonical" RFC3339 syntax variant */
929
        tm = copy;
1,796✔
930
        k = strptime(t, "%Y-%m-%d %H:%M:%S", &tm);
1,796✔
931
        if (k) {
1,796✔
932
                if (*k == '.')
1,493✔
933
                        goto parse_usec;
346✔
934
                else if (*k == 0)
1,147✔
935
                        goto from_tm;
1,138✔
936
        }
937

938
        /* RFC3339 syntax */
939
        tm = copy;
312✔
940
        k = strptime(t, "%Y-%m-%dT%H:%M:%S", &tm);
312✔
941
        if (k) {
312✔
942
                if (*k == '.')
42✔
943
                        goto parse_usec;
20✔
944
                else if (*k == 0)
22✔
945
                        goto from_tm;
22✔
946
        }
947

948
        /* Support OUTPUT_SHORT and OUTPUT_SHORT_PRECISE formats */
949
        tm = copy;
270✔
950
        k = strptime(t, "%b %d %H:%M:%S", &tm);
270✔
951
        if (k) {
270✔
952
                if (*k == '.')
4✔
953
                        goto parse_usec;
2✔
954
                else if (*k == 0)
2✔
955
                        goto from_tm;
2✔
956
        }
957

958
        tm = copy;
266✔
959
        k = strptime(t, "%y-%m-%d %H:%M", &tm);
266✔
960
        if (k && *k == 0) {
266✔
961
                tm.tm_sec = 0;
30✔
962
                goto from_tm;
30✔
963
        }
964

965
        /* Our "canonical" RFC3339 syntax variant without seconds */
966
        tm = copy;
236✔
967
        k = strptime(t, "%Y-%m-%d %H:%M", &tm);
236✔
968
        if (k && *k == 0) {
236✔
969
                tm.tm_sec = 0;
31✔
970
                goto from_tm;
31✔
971
        }
972

973
        /* RFC3339 syntax without seconds */
974
        tm = copy;
205✔
975
        k = strptime(t, "%Y-%m-%dT%H:%M", &tm);
205✔
976
        if (k && *k == 0) {
205✔
977
                tm.tm_sec = 0;
8✔
978
                goto from_tm;
8✔
979
        }
980

981
        tm = copy;
197✔
982
        k = strptime(t, "%y-%m-%d", &tm);
197✔
983
        if (k && *k == 0) {
197✔
984
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
×
985
                goto from_tm;
×
986
        }
987

988
        tm = copy;
197✔
989
        k = strptime(t, "%Y-%m-%d", &tm);
197✔
990
        if (k && *k == 0) {
197✔
991
                tm.tm_sec = tm.tm_min = tm.tm_hour = 0;
106✔
992
                goto from_tm;
106✔
993
        }
994

995
        tm = copy;
91✔
996
        k = strptime(t, "%H:%M:%S", &tm);
91✔
997
        if (k) {
91✔
998
                if (*k == '.')
33✔
999
                        goto parse_usec;
8✔
1000
                else if (*k == 0)
25✔
1001
                        goto from_tm;
25✔
1002
        }
1003

1004
        tm = copy;
58✔
1005
        k = strptime(t, "%H:%M", &tm);
58✔
1006
        if (k && *k == 0) {
58✔
1007
                tm.tm_sec = 0;
6✔
1008
                goto from_tm;
6✔
1009
        }
1010

1011
        return -EINVAL;
1012

1013
parse_usec:
440✔
1014
        k++;
440✔
1015
        r = parse_fractional_part_u(&k, 6, &fractional);
440✔
1016
        if (r < 0)
440✔
1017
                return -EINVAL;
1018
        if (*k != '\0')
440✔
1019
                return -EINVAL;
1020

1021
from_tm:
424✔
1022
        assert(plus == 0);
1,855✔
1023
        assert(minus == 0);
1,855✔
1024

1025
        if (weekday >= 0 && tm.tm_wday != weekday)
1,855✔
1026
                return -EINVAL;
1027

1028
        if (gmtoff < 0) {
1,855✔
1029
                plus = -gmtoff * USEC_PER_SEC;
110✔
1030

1031
                /* If gmtoff is negative, the string may be too old to be parsed as UTC.
1032
                 * E.g. 1969-12-31 23:00:00 -06 == 1970-01-01 05:00:00 UTC
1033
                 * We assumed that gmtoff is in the range of -24:00…+24:00, hence the only date we need to
1034
                 * handle here is 1969-12-31. So, let's shift the date with one day, then subtract the shift
1035
                 * later. */
1036
                if (tm.tm_year == 69 && tm.tm_mon == 11 && tm.tm_mday == 31) {
110✔
1037
                        /* Thu 1970-01-01-00:00:00 */
1038
                        tm.tm_year = 70;
96✔
1039
                        tm.tm_mon = 0;
96✔
1040
                        tm.tm_mday = 1;
96✔
1041
                        tm.tm_wday = 4;
96✔
1042
                        tm.tm_yday = 0;
96✔
1043
                        minus = USEC_PER_DAY;
96✔
1044
                }
1045
        } else
1046
                minus = gmtoff * USEC_PER_SEC;
1,745✔
1047

1048
        r = mktime_or_timegm_usec(&tm, utc, &usec);
1,855✔
1049
        if (r < 0)
1,855✔
1050
                return r;
1051

1052
        usec = usec_add(usec, fractional);
3,704✔
1053

1054
finish:
1,977✔
1055
        usec = usec_add(usec, plus);
1,977✔
1056

1057
        if (usec < minus)
1,977✔
1058
                return -EINVAL;
1059

1060
        usec = usec_sub_unsigned(usec, minus);
1,976✔
1061

1062
        if (usec > USEC_TIMESTAMP_FORMATTABLE_MAX)
1,976✔
1063
                return -EINVAL;
1064

1065
        if (ret)
1,975✔
1066
                *ret = usec;
1,973✔
1067
        return 0;
1068
}
1069

1070
int parse_timestamp(const char *t, usec_t *ret) {
2,122✔
1071
        long gmtoff;
2,122✔
1072
        int r;
2,122✔
1073

1074
        assert(t);
2,122✔
1075

1076
        size_t t_len = strlen(t);
2,122✔
1077
        if (t_len > 2 && t[t_len - 1] == 'Z') {
2,122✔
1078
                /* Try to parse as RFC3339-style welded UTC: "1985-04-12T23:20:50.52Z" */
1079
                r = parse_timestamp_impl(t, t_len - 1, /* utc= */ true, /* isdst= */ -1, /* gmtoff= */ 0, ret);
67✔
1080
                if (r >= 0)
67✔
1081
                        return r;
2,122✔
1082
        }
1083

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

1088
        const char *tz = strrchr(t, ' ');
2,048✔
1089
        if (!tz)
2,048✔
1090
                return parse_timestamp_impl(t, /* max_len= */ SIZE_MAX, /* utc= */ false, /* isdst= */ -1, /* gmtoff= */ 0, ret);
197✔
1091

1092
        size_t max_len = tz - t;
1,851✔
1093
        tz++;
1,851✔
1094

1095
        /* Shortcut, parse the string as UTC. */
1096
        if (streq(tz, "UTC"))
1,851✔
1097
                return parse_timestamp_impl(t, max_len, /* utc= */ true, /* isdst= */ -1, /* gmtoff= */ 0, ret);
764✔
1098

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

1105
        /* Check if the last word matches tzname[] of the local timezone. Note, this must be done earlier
1106
         * than the check by timezone_is_valid() below, as some short timezone specifications have their own
1107
         * timezone files (e.g. WET has its own timezone file, but JST does not), but using such files does
1108
         * not follow the timezone change in the current area. */
1109
        tzset();
961✔
1110
        for (int j = 0; j <= 1; j++) {
3,844✔
1111
                if (!streq_ptr(tz, get_tzname(j)))
1,922✔
1112
                        continue;
1,922✔
1113

1114
                /* The specified timezone matches tzname[] of the local timezone. */
1115
                return parse_timestamp_impl(t, max_len, /* utc= */ false, /* isdst= */ j, /* gmtoff= */ 0, ret);
×
1116
        }
1117

1118
        /* If the last word is a valid timezone file (e.g. Asia/Tokyo), then save the current timezone, apply
1119
         * the specified timezone, and parse the remaining string as a local time. */
1120
        if (timezone_is_valid(tz, LOG_DEBUG)) {
961✔
1121
                SAVE_TIMEZONE;
1,398✔
1122

1123
                if (setenv("TZ", tz, /* overwrite= */ true) < 0)
699✔
1124
                        return negative_errno();
×
1125

1126
                return parse_timestamp_impl(t, max_len, /* utc= */ false, /* isdst= */ -1, /* gmtoff= */ 0, ret);
699✔
1127
        }
1128

1129
        /* Otherwise, assume that the last word is a part of the time and try to parse the whole string as a
1130
         * local time. */
1131
        return parse_timestamp_impl(t, SIZE_MAX, /* utc= */ false, /* isdst= */ -1, /* gmtoff= */ 0, ret);
262✔
1132
}
1133

1134
static const char* extract_multiplier(const char *p, usec_t *ret) {
17,432✔
1135
        static const struct {
17,432✔
1136
                const char *suffix;
1137
                usec_t usec;
1138
        } table[] = {
1139
                { "seconds", USEC_PER_SEC    },
1140
                { "second",  USEC_PER_SEC    },
1141
                { "sec",     USEC_PER_SEC    },
1142
                { "s",       USEC_PER_SEC    },
1143
                { "minutes", USEC_PER_MINUTE },
1144
                { "minute",  USEC_PER_MINUTE },
1145
                { "min",     USEC_PER_MINUTE },
1146
                { "months",  USEC_PER_MONTH  },
1147
                { "month",   USEC_PER_MONTH  },
1148
                { "M",       USEC_PER_MONTH  },
1149
                { "msec",    USEC_PER_MSEC   },
1150
                { "ms",      USEC_PER_MSEC   },
1151
                { "m",       USEC_PER_MINUTE },
1152
                { "hours",   USEC_PER_HOUR   },
1153
                { "hour",    USEC_PER_HOUR   },
1154
                { "hr",      USEC_PER_HOUR   },
1155
                { "h",       USEC_PER_HOUR   },
1156
                { "days",    USEC_PER_DAY    },
1157
                { "day",     USEC_PER_DAY    },
1158
                { "d",       USEC_PER_DAY    },
1159
                { "weeks",   USEC_PER_WEEK   },
1160
                { "week",    USEC_PER_WEEK   },
1161
                { "w",       USEC_PER_WEEK   },
1162
                { "years",   USEC_PER_YEAR   },
1163
                { "year",    USEC_PER_YEAR   },
1164
                { "y",       USEC_PER_YEAR   },
1165
                { "usec",    1ULL            },
1166
                { "us",      1ULL            },
1167
                { "μs",      1ULL            }, /* U+03bc (aka GREEK SMALL LETTER MU) */
1168
                { "µs",      1ULL            }, /* U+b5 (aka MICRO SIGN) */
1169
        };
1170

1171
        assert(p);
17,432✔
1172
        assert(ret);
17,432✔
1173

1174
        FOREACH_ELEMENT(i, table) {
282,039✔
1175
                const char *e = startswith(p, i->suffix);
276,153✔
1176
                if (e) {
276,153✔
1177
                        *ret = i->usec;
11,546✔
1178
                        return e;
11,546✔
1179
                }
1180
        }
1181

1182
        return p;
1183
}
1184

1185
int parse_time(const char *t, usec_t *ret, usec_t default_unit) {
18,677✔
1186
        const char *p, *s;
18,677✔
1187

1188
        assert(t);
18,677✔
1189
        assert(default_unit > 0);
18,677✔
1190

1191
        p = skip_leading_chars(t, /* bad= */ NULL);
18,677✔
1192
        s = startswith(p, "infinity");
18,677✔
1193
        if (s) {
18,677✔
1194
                if (!in_charset(s, WHITESPACE))
1,362✔
1195
                        return -EINVAL;
1196

1197
                if (ret)
1,361✔
1198
                        *ret = USEC_INFINITY;
1,361✔
1199
                return 0;
1200
        }
1201

1202
        usec_t usec = 0;
1203

1204
        for (bool something = false;;) {
17,416✔
1205
                usec_t multiplier = default_unit, k;
34,731✔
1206
                long long l;
34,731✔
1207
                char *e;
34,731✔
1208

1209
                p = skip_leading_chars(p, /* bad= */ NULL);
34,731✔
1210
                if (*p == 0) {
34,731✔
1211
                        if (!something)
17,277✔
1212
                                return -EINVAL;
43✔
1213

1214
                        break;
17,272✔
1215
                }
1216

1217
                if (*p == '-') /* Don't allow "-0" */
17,454✔
1218
                        return -ERANGE;
1219

1220
                errno = 0;
17,446✔
1221
                l = strtoll(p, &e, 10);
17,446✔
1222
                if (errno > 0)
17,446✔
1223
                        return -errno;
×
1224
                if (l < 0)
17,446✔
1225
                        return -ERANGE;
1226

1227
                if (*e == '.') {
17,446✔
1228
                        p = e + 1;
55✔
1229
                        p += strspn(p, DIGITS);
55✔
1230
                } else if (e == p)
17,391✔
1231
                        return -EINVAL;
1232
                else
1233
                        p = e;
1234

1235
                s = extract_multiplier(p + strspn(p, WHITESPACE), &multiplier);
17,432✔
1236
                if (s == p && *s != '\0')
17,432✔
1237
                        /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56' */
1238
                        return -EINVAL;
1239

1240
                p = s;
17,423✔
1241

1242
                if ((usec_t) l >= USEC_INFINITY / multiplier)
17,423✔
1243
                        return -ERANGE;
1244

1245
                k = (usec_t) l * multiplier;
17,421✔
1246
                if (k >= USEC_INFINITY - usec)
17,421✔
1247
                        return -ERANGE;
1248

1249
                usec += k;
17,421✔
1250

1251
                something = true;
17,421✔
1252

1253
                if (*e == '.') {
17,421✔
1254
                        usec_t m = multiplier / 10;
48✔
1255
                        const char *b;
48✔
1256

1257
                        for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
188✔
1258
                                k = (usec_t) (*b - '0') * m;
140✔
1259
                                if (k >= USEC_INFINITY - usec)
140✔
1260
                                        return -ERANGE;
1261

1262
                                usec += k;
140✔
1263
                        }
1264

1265
                        /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge" */
1266
                        if (b == e + 1)
48✔
1267
                                return -EINVAL;
1268
                }
1269
        }
1270

1271
        if (ret)
17,272✔
1272
                *ret = usec;
17,270✔
1273
        return 0;
1274
}
1275

1276
int parse_sec(const char *t, usec_t *ret) {
18,596✔
1277
        return parse_time(t, ret, USEC_PER_SEC);
18,596✔
1278
}
1279

1280
int parse_sec_fix_0(const char *t, usec_t *ret) {
4,980✔
1281
        usec_t k;
4,980✔
1282
        int r;
4,980✔
1283

1284
        assert(t);
4,980✔
1285
        assert(ret);
4,980✔
1286

1287
        r = parse_sec(t, &k);
4,980✔
1288
        if (r < 0)
4,980✔
1289
                return r;
4,980✔
1290

1291
        *ret = k == 0 ? USEC_INFINITY : k;
4,980✔
1292
        return r;
4,980✔
1293
}
1294

1295
int parse_sec_def_infinity(const char *t, usec_t *ret) {
7✔
1296
        assert(t);
7✔
1297
        assert(ret);
7✔
1298

1299
        t += strspn(t, WHITESPACE);
7✔
1300
        if (isempty(t)) {
7✔
1301
                *ret = USEC_INFINITY;
2✔
1302
                return 0;
2✔
1303
        }
1304
        return parse_sec(t, ret);
5✔
1305
}
1306

1307
static const char* extract_nsec_multiplier(const char *p, nsec_t *ret) {
44✔
1308
        static const struct {
44✔
1309
                const char *suffix;
1310
                nsec_t nsec;
1311
        } table[] = {
1312
                { "seconds", NSEC_PER_SEC    },
1313
                { "second",  NSEC_PER_SEC    },
1314
                { "sec",     NSEC_PER_SEC    },
1315
                { "s",       NSEC_PER_SEC    },
1316
                { "minutes", NSEC_PER_MINUTE },
1317
                { "minute",  NSEC_PER_MINUTE },
1318
                { "min",     NSEC_PER_MINUTE },
1319
                { "months",  NSEC_PER_MONTH  },
1320
                { "month",   NSEC_PER_MONTH  },
1321
                { "M",       NSEC_PER_MONTH  },
1322
                { "msec",    NSEC_PER_MSEC   },
1323
                { "ms",      NSEC_PER_MSEC   },
1324
                { "m",       NSEC_PER_MINUTE },
1325
                { "hours",   NSEC_PER_HOUR   },
1326
                { "hour",    NSEC_PER_HOUR   },
1327
                { "hr",      NSEC_PER_HOUR   },
1328
                { "h",       NSEC_PER_HOUR   },
1329
                { "days",    NSEC_PER_DAY    },
1330
                { "day",     NSEC_PER_DAY    },
1331
                { "d",       NSEC_PER_DAY    },
1332
                { "weeks",   NSEC_PER_WEEK   },
1333
                { "week",    NSEC_PER_WEEK   },
1334
                { "w",       NSEC_PER_WEEK   },
1335
                { "years",   NSEC_PER_YEAR   },
1336
                { "year",    NSEC_PER_YEAR   },
1337
                { "y",       NSEC_PER_YEAR   },
1338
                { "usec",    NSEC_PER_USEC   },
1339
                { "us",      NSEC_PER_USEC   },
1340
                { "μs",      NSEC_PER_USEC   }, /* U+03bc (aka GREEK LETTER MU) */
1341
                { "µs",      NSEC_PER_USEC   }, /* U+b5 (aka MICRO SIGN) */
1342
                { "nsec",    1ULL            },
1343
                { "ns",      1ULL            },
1344
                { "",        1ULL            }, /* default is nsec */
1345
        };
1346

1347
        assert(p);
44✔
1348
        assert(ret);
44✔
1349

1350
        FOREACH_ELEMENT(i, table) {
803✔
1351
                const char *e = startswith(p, i->suffix);
803✔
1352
                if (e) {
803✔
1353
                        *ret = i->nsec;
44✔
1354
                        return e;
44✔
1355
                }
1356
        }
1357

1358
        return p;
1359
}
1360

1361
int parse_nsec(const char *t, nsec_t *ret) {
48✔
1362
        const char *p, *s;
48✔
1363
        nsec_t nsec = 0;
48✔
1364
        bool something = false;
48✔
1365

1366
        assert(t);
48✔
1367
        assert(ret);
48✔
1368

1369
        p = t;
48✔
1370

1371
        p += strspn(p, WHITESPACE);
48✔
1372
        s = startswith(p, "infinity");
48✔
1373
        if (s) {
48✔
1374
                s += strspn(s, WHITESPACE);
4✔
1375
                if (*s != 0)
4✔
1376
                        return -EINVAL;
1377

1378
                *ret = NSEC_INFINITY;
2✔
1379
                return 0;
2✔
1380
        }
1381

1382
        for (;;) {
30✔
1383
                nsec_t multiplier = 1, k;
74✔
1384
                long long l;
74✔
1385
                char *e;
74✔
1386

1387
                p += strspn(p, WHITESPACE);
74✔
1388

1389
                if (*p == 0) {
74✔
1390
                        if (!something)
21✔
1391
                                return -EINVAL;
24✔
1392

1393
                        break;
20✔
1394
                }
1395

1396
                if (*p == '-') /* Don't allow "-0" */
53✔
1397
                        return -ERANGE;
1398

1399
                errno = 0;
48✔
1400
                l = strtoll(p, &e, 10);
48✔
1401
                if (errno > 0)
48✔
1402
                        return -errno;
×
1403
                if (l < 0)
48✔
1404
                        return -ERANGE;
1405

1406
                if (*e == '.') {
48✔
1407
                        p = e + 1;
31✔
1408
                        p += strspn(p, DIGITS);
31✔
1409
                } else if (e == p)
17✔
1410
                        return -EINVAL;
1411
                else
1412
                        p = e;
1413

1414
                s = extract_nsec_multiplier(p + strspn(p, WHITESPACE), &multiplier);
44✔
1415
                if (s == p && *s != '\0')
44✔
1416
                        /* Don't allow '12.34.56', but accept '12.34 .56' or '12.34s.56' */
1417
                        return -EINVAL;
1418

1419
                p = s;
36✔
1420

1421
                if ((nsec_t) l >= NSEC_INFINITY / multiplier)
36✔
1422
                        return -ERANGE;
1423

1424
                k = (nsec_t) l * multiplier;
35✔
1425
                if (k >= NSEC_INFINITY - nsec)
35✔
1426
                        return -ERANGE;
1427

1428
                nsec += k;
35✔
1429

1430
                something = true;
35✔
1431

1432
                if (*e == '.') {
35✔
1433
                        nsec_t m = multiplier / 10;
24✔
1434
                        const char *b;
24✔
1435

1436
                        for (b = e + 1; *b >= '0' && *b <= '9'; b++, m /= 10) {
56✔
1437
                                k = (nsec_t) (*b - '0') * m;
32✔
1438
                                if (k >= NSEC_INFINITY - nsec)
32✔
1439
                                        return -ERANGE;
1440

1441
                                nsec += k;
32✔
1442
                        }
1443

1444
                        /* Don't allow "0.-0", "3.+1", "3. 1", "3.sec" or "3.hoge" */
1445
                        if (b == e + 1)
24✔
1446
                                return -EINVAL;
1447
                }
1448
        }
1449

1450
        *ret = nsec;
20✔
1451

1452
        return 0;
20✔
1453
}
1454

1455
static int get_timezones_from_zone1970_tab(char ***ret) {
×
1456
        _cleanup_fclose_ FILE *f = NULL;
×
1457
        _cleanup_strv_free_ char **zones = NULL;
×
1458
        int r;
×
1459

1460
        assert(ret);
×
1461

1462
        f = fopen("/usr/share/zoneinfo/zone1970.tab", "re");
×
1463
        if (!f)
×
1464
                return -errno;
×
1465

1466
        for (;;) {
×
1467
                _cleanup_free_ char *line = NULL, *cc = NULL, *co = NULL, *tz = NULL;
×
1468

1469
                r = read_line(f, LONG_LINE_MAX, &line);
×
1470
                if (r < 0)
×
1471
                        return r;
1472
                if (r == 0)
×
1473
                        break;
1474

1475
                const char *p = line;
×
1476

1477
                /* Line format is:
1478
                 * 'country codes' 'coordinates' 'timezone' 'comments' */
1479
                r = extract_many_words(&p, NULL, 0, &cc, &co, &tz);
×
1480
                if (r < 0)
×
1481
                        continue;
×
1482

1483
                /* Lines that start with # are comments. */
1484
                if (*cc == '#')
×
1485
                        continue;
×
1486

1487
                if (!timezone_is_valid(tz, LOG_DEBUG))
×
1488
                        /* Don't list unusable timezones. */
1489
                        continue;
×
1490

1491
                r = strv_extend(&zones, tz);
×
1492
                if (r < 0)
×
1493
                        return r;
1494
        }
1495

1496
        *ret = TAKE_PTR(zones);
×
1497
        return 0;
×
1498
}
1499

1500
static int get_timezones_from_tzdata_zi(char ***ret) {
4✔
1501
        _cleanup_fclose_ FILE *f = NULL;
4✔
1502
        _cleanup_strv_free_ char **zones = NULL;
4✔
1503
        int r;
4✔
1504

1505
        assert(ret);
4✔
1506

1507
        f = fopen("/usr/share/zoneinfo/tzdata.zi", "re");
4✔
1508
        if (!f)
4✔
1509
                return -errno;
×
1510

1511
        for (;;) {
17,212✔
1512
                _cleanup_free_ char *line = NULL, *type = NULL, *f1 = NULL, *f2 = NULL;
17,208✔
1513

1514
                r = read_line(f, LONG_LINE_MAX, &line);
17,212✔
1515
                if (r < 0)
17,212✔
1516
                        return r;
1517
                if (r == 0)
17,212✔
1518
                        break;
1519

1520
                const char *p = line;
17,208✔
1521

1522
                /* The only lines we care about are Zone and Link lines.
1523
                 * Zone line format is:
1524
                 * 'Zone' 'timezone' ...
1525
                 * Link line format is:
1526
                 * 'Link' 'target' 'alias'
1527
                 * See 'man zic' for more detail. */
1528
                r = extract_many_words(&p, NULL, 0, &type, &f1, &f2);
17,208✔
1529
                if (r < 0)
17,208✔
1530
                        continue;
×
1531

1532
                char *tz;
17,208✔
1533
                if (IN_SET(*type, 'Z', 'z'))
17,208✔
1534
                        /* Zone lines have timezone in field 1. */
1535
                        tz = f1;
1,364✔
1536
                else if (IN_SET(*type, 'L', 'l'))
15,844✔
1537
                        /* Link lines have timezone in field 2. */
1538
                        tz = f2;
1,028✔
1539
                else
1540
                        /* Not a line we care about. */
1541
                        continue;
14,816✔
1542

1543
                if (!timezone_is_valid(tz, LOG_DEBUG))
2,392✔
1544
                        /* Don't list unusable timezones. */
1545
                        continue;
×
1546

1547
                r = strv_extend(&zones, tz);
2,392✔
1548
                if (r < 0)
2,392✔
1549
                        return r;
1550
        }
1551

1552
        *ret = TAKE_PTR(zones);
4✔
1553
        return 0;
4✔
1554
}
1555

1556
int get_timezones(char ***ret) {
4✔
1557
        _cleanup_strv_free_ char **zones = NULL;
4✔
1558
        int r;
4✔
1559

1560
        assert(ret);
4✔
1561

1562
        r = get_timezones_from_tzdata_zi(&zones);
4✔
1563
        if (r == -ENOENT) {
4✔
1564
                log_debug_errno(r, "Could not get timezone data from tzdata.zi, using zone1970.tab: %m");
×
1565
                r = get_timezones_from_zone1970_tab(&zones);
×
1566
                if (r == -ENOENT)
×
1567
                        log_debug_errno(r, "Could not get timezone data from zone1970.tab, using UTC: %m");
×
1568
        }
1569
        if (r < 0 && r != -ENOENT)
4✔
1570
                return r;
1571

1572
        /* Always include UTC */
1573
        r = strv_extend(&zones, "UTC");
4✔
1574
        if (r < 0)
4✔
1575
                return r;
1576

1577
        strv_sort_uniq(zones);
4✔
1578

1579
        *ret = TAKE_PTR(zones);
4✔
1580
        return 0;
4✔
1581
}
1582

1583
int verify_timezone(const char *name, int log_level) {
4,392✔
1584
        bool slash = false;
4,392✔
1585
        const char *p, *t;
4,392✔
1586
        _cleanup_close_ int fd = -EBADF;
4,392✔
1587
        char buf[4];
4,392✔
1588
        int r;
4,392✔
1589

1590
        if (isempty(name))
8,784✔
1591
                return -EINVAL;
1592

1593
        /* Always accept "UTC" as valid timezone, since it's the fallback, even if user has no timezones installed. */
1594
        if (streq(name, "UTC"))
4,390✔
1595
                return 0;
1596

1597
        if (name[0] == '/')
4,383✔
1598
                return -EINVAL;
1599

1600
        for (p = name; *p; p++) {
60,641✔
1601
                if (!ascii_isdigit(*p) &&
56,422✔
1602
                    !ascii_isalpha(*p) &&
55,080✔
1603
                    !IN_SET(*p, '-', '_', '+', '/'))
4,968✔
1604
                        return -EINVAL;
1605

1606
                if (*p == '/') {
56,259✔
1607

1608
                        if (slash)
3,869✔
1609
                                return -EINVAL;
1610

1611
                        slash = true;
1612
                } else
1613
                        slash = false;
1614
        }
1615

1616
        if (slash)
4,219✔
1617
                return -EINVAL;
1618

1619
        if (p - name >= PATH_MAX)
4,218✔
1620
                return -ENAMETOOLONG;
1621

1622
        t = strjoina("/usr/share/zoneinfo/", name);
21,090✔
1623

1624
        fd = open(t, O_RDONLY|O_CLOEXEC);
4,218✔
1625
        if (fd < 0)
4,218✔
1626
                return log_full_errno(log_level, errno, "Failed to open timezone file '%s': %m", t);
212✔
1627

1628
        r = fd_verify_regular(fd);
4,006✔
1629
        if (r < 0)
4,006✔
1630
                return log_full_errno(log_level, r, "Timezone file '%s' is not a regular file: %m", t);
×
1631

1632
        r = loop_read_exact(fd, buf, 4, false);
4,006✔
1633
        if (r < 0)
4,006✔
1634
                return log_full_errno(log_level, r, "Failed to read from timezone file '%s': %m", t);
×
1635

1636
        /* Magic from tzfile(5) */
1637
        if (memcmp(buf, "TZif", 4) != 0)
4,006✔
1638
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EBADMSG),
×
1639
                                      "Timezone file '%s' has wrong magic bytes", t);
1640

1641
        return 0;
1642
}
1643

1644
void reset_timezonep(char **p) {
758✔
1645
        assert(p);
758✔
1646

1647
        (void) set_unset_env("TZ", *p, /* overwrite= */ true);
758✔
1648
        tzset();
758✔
1649
        *p = mfree(*p);
758✔
1650
}
758✔
1651

1652
char* save_timezone(void) {
758✔
1653
        const char *e = getenv("TZ");
758✔
1654
        if (!e)
758✔
1655
                return NULL;
1656

1657
        char *s = strdup(e);
57✔
1658
        if (!s)
57✔
1659
                log_debug("Failed to save $TZ=%s, unsetting the environment variable.", e);
×
1660

1661
        return s;
1662
}
1663

1664
bool clock_supported(clockid_t clock) {
294,812✔
1665
        struct timespec ts;
294,812✔
1666

1667
        switch (clock) {
294,812✔
1668

1669
        case CLOCK_MONOTONIC:
1670
        case CLOCK_REALTIME:
1671
        case CLOCK_BOOTTIME:
1672
                /* These three are always available in our baseline, and work in timerfd, as of kernel 3.15 */
1673
                return true;
1674

1675
        default:
1✔
1676
                /* For everything else, check properly */
1677
                return clock_gettime(clock, &ts) >= 0;
1✔
1678
        }
1679
}
1680

1681
int get_timezone(char **ret) {
61✔
1682
        _cleanup_free_ char *t = NULL;
61✔
1683
        int r;
61✔
1684

1685
        assert(ret);
61✔
1686

1687
        r = readlink_malloc(etc_localtime(), &t);
61✔
1688
        if (r == -ENOENT)
61✔
1689
                /* If the symlink does not exist, assume "UTC", like glibc does */
1690
                return strdup_to(ret, "UTC");
1✔
1691
        if (r < 0)
60✔
1692
                return r; /* Return EINVAL if not a symlink */
1693

1694
        const char *e = PATH_STARTSWITH_SET(t, "/usr/share/zoneinfo/", "../usr/share/zoneinfo/");
60✔
1695
        if (!e)
60✔
1696
                return -EINVAL;
1697
        if (!timezone_is_valid(e, LOG_DEBUG))
60✔
1698
                return -EINVAL;
1699

1700
        return strdup_to(ret, e);
60✔
1701
}
1702

1703
int get_timezone_prefer_env(char **ret) {
×
1704
        assert(ret);
×
1705

1706
        const char *e = getenv("TZ");
×
1707
        if (e && e[0] == ':' && timezone_is_valid(e + 1, LOG_DEBUG))
×
1708
                return strdup_to(ret, e + 1);
×
1709

1710
        return get_timezone(ret);
×
1711
}
1712

1713
const char* etc_localtime(void) {
1,169✔
1714
        static const char *cached = NULL;
1,169✔
1715

1716
        if (!cached)
1,169✔
1717
                cached = secure_getenv("SYSTEMD_ETC_LOCALTIME") ?: "/etc/localtime";
1,022✔
1718

1719
        return cached;
1,169✔
1720
}
1721

1722
int mktime_or_timegm_usec(
10,796✔
1723
                struct tm *tm, /* input + normalized output */
1724
                bool utc,
1725
                usec_t *ret) {
1726

1727
        time_t t;
10,796✔
1728

1729
        assert(tm);
10,796✔
1730

1731
        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!) */
10,796✔
1732
                return -ERANGE;
1733
        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 */
10,793✔
1734
                return -ERANGE;
1735

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

1741
        t = utc ? timegm(tm) : mktime(tm);
10,793✔
1742
        if (t < 0) /* Refuse negative times and errors */
10,793✔
1743
                return -ERANGE;
1744
        if ((usec_t) t >= USEC_INFINITY / USEC_PER_SEC) /* Never return USEC_INFINITY by accident (or overflow) */
10,791✔
1745
                return -ERANGE;
1746

1747
        if (ret)
10,791✔
1748
                *ret = (usec_t) t * USEC_PER_SEC;
2,678✔
1749
        return 0;
1750
}
1751

1752
int localtime_or_gmtime_usec(
283,121✔
1753
                usec_t t,
1754
                bool utc,
1755
                struct tm *ret) {
1756

1757
        t /= USEC_PER_SEC; /* Round down */
283,121✔
1758
        if (t > (usec_t) TIME_T_MAX)
283,121✔
1759
                return -ERANGE;
1760
        time_t sec = (time_t) t;
283,121✔
1761

1762
        struct tm buf = {};
283,121✔
1763
        if (!(utc ? gmtime_r(&sec, &buf) : localtime_r(&sec, &buf)))
283,121✔
1764
                return -EINVAL;
1765

1766
        if (ret)
283,121✔
1767
                *ret = buf;
283,121✔
1768

1769
        return 0;
1770
}
1771

1772
uint64_t sysconf_clock_ticks_cached(void) {
3,099✔
1773
        static thread_local uint64_t hz = 0;
3,099✔
1774

1775
        if (hz != 0)
3,099✔
1776
                return hz;
1777

1778
        long t = sysconf(_SC_CLK_TCK);
92✔
1779
        assert(t > 0);
92✔
1780
        hz = (uint64_t) t;
92✔
1781

1782
        return hz;
92✔
1783
}
1784

1785
uint32_t usec_to_jiffies(usec_t u) {
9✔
1786
        uint64_t hz = sysconf_clock_ticks_cached();
9✔
1787
        return DIV_ROUND_UP(u, USEC_PER_SEC / hz);
9✔
1788
}
1789

1790
usec_t jiffies_to_usec(uint32_t j) {
3,089✔
1791
        uint64_t hz = sysconf_clock_ticks_cached();
3,089✔
1792
        return DIV_ROUND_UP(j * USEC_PER_SEC, hz);
3,089✔
1793
}
1794

1795
usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
1,098✔
1796
        usec_t a, b;
1,098✔
1797

1798
        if (x == USEC_INFINITY)
1,098✔
1799
                return USEC_INFINITY;
1800
        if (map_clock_id(from) == map_clock_id(to))
883✔
1801
                return x;
1802

1803
        a = now(from);
8✔
1804
        b = now(to);
8✔
1805

1806
        if (x > a)
8✔
1807
                /* x lies in the future */
1808
                return usec_add(b, usec_sub_unsigned(x, a));
6✔
1809
        else
1810
                /* x lies in the past */
1811
                return usec_sub_unsigned(b, usec_sub_unsigned(a, x));
4✔
1812
}
1813

1814
bool in_utc_timezone(void) {
676✔
1815
        tzset();
676✔
1816

1817
        return timezone == 0 && daylight == 0;
676✔
1818
}
1819

1820
int usleep_safe(usec_t usec) {
544✔
1821
        int r;
544✔
1822

1823
        /* usleep() takes useconds_t that is (typically?) uint32_t. Also, usleep() may only support the
1824
         * range [0, 1000000]. See usleep(3). Let's override usleep() with clock_nanosleep().
1825
         *
1826
         * ⚠️ Note we are not using plain nanosleep() here, since that operates on CLOCK_REALTIME, not
1827
         *    CLOCK_MONOTONIC! */
1828

1829
        if (usec == 0)
544✔
1830
                return 0;
544✔
1831

1832
        if (usec == USEC_INFINITY)
544✔
1833
                return RET_NERRNO(pause());
×
1834

1835
        struct timespec t;
544✔
1836
        timespec_store(&t, usec);
544✔
1837

1838
        for (;;) {
544✔
1839
                struct timespec remaining;
544✔
1840

1841
                /* `clock_nanosleep()` does not use `errno`, but returns positive error codes. */
1842
                r = -clock_nanosleep(CLOCK_MONOTONIC, /* flags= */ 0, &t, &remaining);
544✔
1843
                if (r == -EINTR) {
544✔
1844
                        /* Interrupted. Continue sleeping for the remaining time. */
1845
                        t = remaining;
×
1846
                        continue;
×
1847
                }
1848

1849
                return r;
544✔
1850
        }
1851
}
1852

1853
int time_change_fd(void) {
528✔
1854

1855
        /* We only care for the cancellation event, hence we set the timeout to the latest possible value. */
1856
        static const struct itimerspec its = {
528✔
1857
                .it_value.tv_sec = TIME_T_MAX,
1858
        };
1859

1860
        _cleanup_close_ int fd = -EBADF;
1,056✔
1861

1862
        /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever CLOCK_REALTIME makes a jump relative to
1863
         * CLOCK_MONOTONIC. */
1864

1865
        fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
528✔
1866
        if (fd < 0)
528✔
1867
                return -errno;
×
1868

1869
        if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) >= 0)
528✔
1870
                return TAKE_FD(fd);
528✔
1871

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

1882
#if SIZEOF_TIME_T == 8 && ULONG_MAX < UINT64_MAX
1883
        if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EOVERFLOW) {
1884
                static const struct itimerspec its32 = {
1885
                        .it_value.tv_sec = INT32_MAX,
1886
                };
1887

1888
                if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its32, NULL) >= 0)
1889
                        return TAKE_FD(fd);
1890
        }
1891
#endif
1892

1893
        return -errno;
×
1894
}
1895

1896
static const char* const timestamp_style_table[_TIMESTAMP_STYLE_MAX] = {
1897
        [TIMESTAMP_PRETTY] = "pretty",
1898
        [TIMESTAMP_US]     = "us",
1899
        [TIMESTAMP_UTC]    = "utc",
1900
        [TIMESTAMP_US_UTC] = "us+utc",
1901
        [TIMESTAMP_UNIX]   = "unix",
1902
};
1903

1904
/* Use the macro for enum → string to allow for aliases */
1905
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(timestamp_style, TimestampStyle);
×
1906

1907
/* For the string → enum mapping we use the generic implementation, but also support two aliases */
1908
TimestampStyle timestamp_style_from_string(const char *s) {
8✔
1909
        TimestampStyle t;
8✔
1910

1911
        t = (TimestampStyle) string_table_lookup_from_string(timestamp_style_table, ELEMENTSOF(timestamp_style_table), s);
8✔
1912
        if (t >= 0)
8✔
1913
                return t;
1914
        if (STRPTR_IN_SET(s, "µs", "μs")) /* accept both µ symbols in unicode, i.e. micro symbol + Greek small letter mu. */
2✔
1915
                return TIMESTAMP_US;
1✔
1916
        if (STRPTR_IN_SET(s, "µs+utc", "μs+utc"))
1✔
1917
                return TIMESTAMP_US_UTC;
1✔
1918
        return t;
1919
}
1920

1921
int parse_calendar_date_full(const char *s, bool allow_pre_epoch, usec_t *ret_usec, struct tm *ret_tm) {
104✔
1922
        struct tm parsed_tm = {}, copy_tm;
104✔
1923
        const char *k;
104✔
1924
        int r;
104✔
1925

1926
        assert(s);
104✔
1927

1928
        k = strptime(s, "%Y-%m-%d", &parsed_tm);
104✔
1929
        if (!k || *k)
104✔
1930
                return -EINVAL;
104✔
1931

1932
        copy_tm = parsed_tm;
94✔
1933

1934
        usec_t usec = USEC_INFINITY;
94✔
1935

1936
        if (allow_pre_epoch) {
94✔
1937
                /* For birth dates we use timegm() directly since we need to accept pre-epoch dates.
1938
                 * timegm() returns (time_t) -1 both on error and for one second before the epoch.
1939
                 * Initialize wday to -1 beforehand: if it remains -1 after the call, it's a genuine
1940
                 * error; if timegm() changed it, the date was successfully normalized. */
1941
                copy_tm.tm_wday = -1;
8✔
1942
                if (timegm(&copy_tm) == (time_t) -1 && copy_tm.tm_wday == -1)
8✔
1943
                        return -EINVAL;
1944
        } else {
1945
                r = mktime_or_timegm_usec(&copy_tm, /* utc= */ true, &usec);
86✔
1946
                if (r < 0)
86✔
1947
                        return r;
1948
        }
1949

1950
        /* Refuse non-normalized dates, e.g. Feb 30 */
1951
        if (copy_tm.tm_mday != parsed_tm.tm_mday ||
94✔
1952
            copy_tm.tm_mon  != parsed_tm.tm_mon  ||
90✔
1953
            copy_tm.tm_year != parsed_tm.tm_year)
90✔
1954
                return -EINVAL;
1955

1956
        if (ret_usec)
90✔
1957
                *ret_usec = usec;
83✔
1958
        if (ret_tm) {
90✔
1959
                /* Reset to unset, then fill in only the date fields we parsed and validated */
1960
                *ret_tm = BIRTH_DATE_UNSET;
5✔
1961
                ret_tm->tm_mday = parsed_tm.tm_mday;
5✔
1962
                ret_tm->tm_mon = parsed_tm.tm_mon;
5✔
1963
                ret_tm->tm_year = parsed_tm.tm_year;
5✔
1964
        }
1965

1966
        return 0;
1967
}
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