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

systemd / systemd / 19349812769

13 Nov 2025 10:50PM UTC coverage: 72.393% (+0.1%) from 72.251%
19349812769

push

github

yuwata
sd-dhcp-server: Add Hostname= option to static leases

This adds a new `Hostname=` option to the [DHCPServerStaticLease]
section in .network files, allowing an administrator to assign a
specific hostname to a client receiving a static lease.

We automatically select the correct DHCP option to use based on the
format of the provided string:

- Single DNS labels are sent as Option 12.
- Names with multiple DNS labels are sent as Option 81 in wire format.

Fixes: #39634

90 of 109 new or added lines in 8 files covered. (82.57%)

1896 existing lines in 46 files now uncovered.

307159 of 424291 relevant lines covered (72.39%)

1105072.08 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/mman.h>
5
#include <sys/timerfd.h>
6
#include <threads.h>
7
#include <unistd.h>
8

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

29
static clockid_t map_clock_id(clockid_t c) {
29,643,110✔
30

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

36
        switch (c) {
29,643,110✔
37

38
        case CLOCK_BOOTTIME_ALARM:
39
                return CLOCK_BOOTTIME;
40

41
        case CLOCK_REALTIME_ALARM:
8✔
42
                return CLOCK_REALTIME;
8✔
43

44
        default:
29,643,101✔
45
                return c;
29,643,101✔
46
        }
47
}
48

49
usec_t now(clockid_t clock_id) {
29,640,552✔
50
        struct timespec ts;
29,640,552✔
51

52
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
29,640,552✔
53

54
        return timespec_load(&ts);
29,640,552✔
55
}
56

57
nsec_t now_nsec(clockid_t clock_id) {
620✔
58
        struct timespec ts;
620✔
59

60
        assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
620✔
61

62
        return timespec_load_nsec(&ts);
620✔
63
}
64

65
dual_timestamp* dual_timestamp_now(dual_timestamp *ts) {
2,024,027✔
66
        assert(ts);
2,024,027✔
67

68
        ts->realtime = now(CLOCK_REALTIME);
2,024,027✔
69
        ts->monotonic = now(CLOCK_MONOTONIC);
2,024,027✔
70

71
        return ts;
2,024,027✔
72
}
73

74
triple_timestamp* triple_timestamp_now(triple_timestamp *ts) {
3,271,174✔
75
        assert(ts);
3,271,174✔
76

77
        ts->realtime = now(CLOCK_REALTIME);
3,271,174✔
78
        ts->monotonic = now(CLOCK_MONOTONIC);
3,271,174✔
79
        ts->boottime = now(CLOCK_BOOTTIME);
3,271,174✔
80

81
        return ts;
3,271,174✔
82
}
83

84
usec_t map_clock_usec_raw(usec_t from, usec_t from_base, usec_t to_base) {
8,367✔
85

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

93
        if (from >= from_base) { /* In the future */
8,367✔
94
                usec_t delta = from - from_base;
31✔
95

96
                if (to_base >= USEC_INFINITY - delta) /* overflow? */
31✔
97
                        return USEC_INFINITY;
98

99
                return to_base + delta;
31✔
100

101
        } else { /* In the past */
102
                usec_t delta = from_base - from;
8,336✔
103

104
                if (to_base <= delta) /* underflow? */
8,336✔
105
                        return 0;
106

107
                return to_base - delta;
8,330✔
108
        }
109
}
110

111
usec_t map_clock_usec(usec_t from, clockid_t from_clock, clockid_t to_clock) {
451✔
112

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

118
        /* Keep infinity as is */
119
        if (from == USEC_INFINITY)
451✔
120
                return from;
121

122
        return map_clock_usec_raw(from, now(from_clock), now(to_clock));
417✔
123
}
124

125
dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
12✔
126
        assert(ts);
12✔
127

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

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

138
triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u) {
348✔
139
        usec_t nowr;
348✔
140

141
        assert(ts);
348✔
142

143
        if (!timestamp_is_set(u)) {
348✔
144
                ts->realtime = ts->monotonic = ts->boottime = u;
×
145
                return ts;
×
146
        }
147

148
        nowr = now(CLOCK_REALTIME);
348✔
149

150
        ts->realtime = u;
348✔
151
        ts->monotonic = map_clock_usec_raw(u, nowr, now(CLOCK_MONOTONIC));
348✔
152
        ts->boottime = map_clock_usec_raw(u, nowr, now(CLOCK_BOOTTIME));
348✔
153

154
        return ts;
348✔
155
}
156

157
triple_timestamp* triple_timestamp_from_boottime(triple_timestamp *ts, usec_t u) {
×
158
        usec_t nowb;
×
159

160
        assert(ts);
×
161

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

167
        nowb = now(CLOCK_BOOTTIME);
×
168

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

173
        return ts;
×
174
}
175

176
dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u) {
239✔
177
        assert(ts);
239✔
178

179
        if (u == USEC_INFINITY) {
239✔
180
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
181
                return ts;
×
182
        }
183

184
        ts->monotonic = u;
239✔
185
        ts->realtime = map_clock_usec(u, CLOCK_MONOTONIC, CLOCK_REALTIME);
239✔
186
        return ts;
239✔
187
}
188

189
dual_timestamp* dual_timestamp_from_boottime(dual_timestamp *ts, usec_t u) {
506✔
190
        usec_t nowm;
506✔
191

192
        assert(ts);
506✔
193

194
        if (u == USEC_INFINITY) {
506✔
195
                ts->realtime = ts->monotonic = USEC_INFINITY;
×
196
                return ts;
×
197
        }
198

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

205
usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock) {
3,425,633✔
206
        assert(ts);
3,425,633✔
207

208
        switch (clock) {
3,425,633✔
209

210
        case CLOCK_REALTIME:
1,875,572✔
211
        case CLOCK_REALTIME_ALARM:
212
                return ts->realtime;
1,875,572✔
213

214
        case CLOCK_MONOTONIC:
1,510,320✔
215
                return ts->monotonic;
1,510,320✔
216

217
        case CLOCK_BOOTTIME:
39,741✔
218
        case CLOCK_BOOTTIME_ALARM:
219
                return ts->boottime;
39,741✔
220

221
        default:
222
                return USEC_INFINITY;
223
        }
224
}
225

226
usec_t timespec_load(const struct timespec *ts) {
29,997,532✔
227
        assert(ts);
29,997,532✔
228

229
        if (ts->tv_sec < 0 || ts->tv_nsec < 0)
29,997,532✔
230
                return USEC_INFINITY;
231

232
        if ((usec_t) ts->tv_sec > (UINT64_MAX - (ts->tv_nsec / NSEC_PER_USEC)) / USEC_PER_SEC)
29,997,532✔
233
                return USEC_INFINITY;
234

235
        return
29,997,532✔
236
                (usec_t) ts->tv_sec * USEC_PER_SEC +
29,997,532✔
237
                (usec_t) ts->tv_nsec / NSEC_PER_USEC;
238
}
239

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

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

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

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

252
struct timespec *timespec_store(struct timespec *ts, usec_t u) {
2,222,780✔
253
        assert(ts);
2,222,780✔
254

255
        if (u == USEC_INFINITY ||
2,222,780✔
256
            u / USEC_PER_SEC >= TIME_T_MAX) {
257
                ts->tv_sec = (time_t) -1;
×
258
                ts->tv_nsec = -1L;
×
259
                return ts;
×
260
        }
261

262
        ts->tv_sec = (time_t) (u / USEC_PER_SEC);
2,222,780✔
263
        ts->tv_nsec = (long) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
2,222,780✔
264

265
        return ts;
2,222,780✔
266
}
267

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

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

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

281
        return ts;
56✔
282
}
283

284
usec_t timeval_load(const struct timeval *tv) {
767,949✔
285
        assert(tv);
767,949✔
286

287
        if (tv->tv_sec < 0 || tv->tv_usec < 0)
767,949✔
288
                return USEC_INFINITY;
289

290
        if ((usec_t) tv->tv_sec > (UINT64_MAX - tv->tv_usec) / USEC_PER_SEC)
767,949✔
291
                return USEC_INFINITY;
292

293
        return
767,949✔
294
                (usec_t) tv->tv_sec * USEC_PER_SEC +
767,949✔
295
                (usec_t) tv->tv_usec;
296
}
297

298
struct timeval *timeval_store(struct timeval *tv, usec_t u) {
142,639✔
299
        assert(tv);
142,639✔
300

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

310
        return tv;
142,639✔
311
}
312

313
char* format_timestamp_style(
5,891✔
314
                char *buf,
315
                size_t l,
316
                usec_t t,
317
                TimestampStyle style) {
318

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

331
        struct tm tm;
5,891✔
332
        bool utc, us;
5,891✔
333
        size_t n;
5,891✔
334

335
        assert(buf);
5,891✔
336
        assert(style >= 0);
5,891✔
337
        assert(style < _TIMESTAMP_STYLE_MAX);
5,891✔
338

339
        if (!timestamp_is_set(t))
5,891✔
340
                return NULL; /* Timestamp is unset */
5,891✔
341

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

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

349
        utc = IN_SET(style, TIMESTAMP_UTC, TIMESTAMP_US_UTC, TIMESTAMP_DATE);
4,189✔
350
        us = IN_SET(style, TIMESTAMP_US, TIMESTAMP_US_UTC);
4,189✔
351

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

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

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

375
        if (localtime_or_gmtime_usec(t, utc, &tm) < 0)
4,185✔
376
                return NULL;
377

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

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

387
                return buf;
104✔
388
        }
389

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

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

400
                sprintf(buf + n, ".%06"PRI_USEC, t % USEC_PER_SEC);
467✔
401
        }
402

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

411
                strcpy(buf + n, " UTC");
230✔
412

413
        } else if (!isempty(tm.tm_zone)) {
3,851✔
414
                size_t tn;
3,851✔
415

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

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

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

436
        return buf;
437
}
438

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

443
        assert(buf);
1,412✔
444

445
        if (!timestamp_is_set(t))
1,412✔
446
                return NULL;
447

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

457
        if (d >= USEC_PER_YEAR) {
1,406✔
458
                usec_t years = d / USEC_PER_YEAR;
742✔
459
                usec_t months = (d % USEC_PER_YEAR) / USEC_PER_MONTH;
742✔
460

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

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

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

518
        buf[l-1] = 0;
1,406✔
519
        return buf;
1,406✔
520
}
521

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

538
        char *p = ASSERT_PTR(buf);
14,404✔
539
        bool something = false;
14,404✔
540

541
        assert(l > 0);
14,404✔
542

543
        if (t == USEC_INFINITY) {
14,404✔
544
                strncpy(p, "infinity", l-1);
932✔
545
                p[l-1] = 0;
932✔
546
                return p;
932✔
547
        }
548

549
        if (t <= 0) {
13,472✔
550
                strncpy(p, "0", l-1);
568✔
551
                p[l-1] = 0;
568✔
552
                return p;
568✔
553
        }
554

555
        /* The result of this function can be parsed with parse_sec */
556

557
        FOREACH_ELEMENT(i, table) {
107,300✔
558
                int k = 0;
107,212✔
559
                size_t n;
107,212✔
560
                bool done = false;
107,212✔
561
                usec_t a, b;
107,212✔
562

563
                if (t <= 0)
107,212✔
564
                        break;
565

566
                if (t < accuracy && something)
94,451✔
567
                        break;
568

569
                if (t < i->usec)
94,396✔
570
                        continue;
76,638✔
571

572
                if (l <= 1)
17,758✔
573
                        break;
574

575
                a = t / i->usec;
17,758✔
576
                b = t % i->usec;
17,758✔
577

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

582
                        for (usec_t cc = i->usec; cc > 1; cc /= 10)
58,350✔
583
                                j++;
48,105✔
584

585
                        for (usec_t cc = accuracy; cc > 1; cc /= 10) {
46,720✔
586
                                b /= 10;
36,475✔
587
                                j--;
36,475✔
588
                        }
589

590
                        if (j > 0) {
10,245✔
591
                                k = snprintf(p, l,
6,368✔
592
                                             "%s"USEC_FMT".%0*"PRI_USEC"%s",
593
                                             p > buf ? " " : "",
594
                                             a,
595
                                             j,
596
                                             b,
597
                                             i->suffix);
3,184✔
598

599
                                t = 0;
3,184✔
600
                                done = true;
3,184✔
601
                        }
602
                }
603

604
                /* No? Then let's show it normally */
605
                if (!done) {
3,184✔
606
                        k = snprintf(p, l,
29,148✔
607
                                     "%s"USEC_FMT"%s",
608
                                     p > buf ? " " : "",
609
                                     a,
610
                                     i->suffix);
14,574✔
611

612
                        t = b;
14,574✔
613
                }
614

615
                n = MIN((size_t) k, l-1);
17,758✔
616

617
                l -= n;
17,758✔
618
                p += n;
17,758✔
619

620
                something = true;
17,758✔
621
        }
622

623
        *p = 0;
12,904✔
624

625
        return buf;
12,904✔
626
}
627

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

633
        return empty_to_null(tzname[dst]);
2,953✔
634
}
635

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

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

648
#ifdef __GLIBC__
649
        return -EINVAL;
650
#else
651
        int r;
652

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

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

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

676
        usec_t u = r * 10 * USEC_PER_HOUR;
677

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

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

688
        if (*t == ':') /* skip colon */
689
                t++;
690

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

697
        u += r * 10 * USEC_PER_MINUTE;
698

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

704
        u += r * USEC_PER_MINUTE;
705

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

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

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

719
        return 0;
720
#endif
721
}
722

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

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

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

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

791
        assert(t);
2,129✔
792

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

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

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

803
                t = t_alloc;
804
                with_tz = true;
805
        }
806

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

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

819
        usec = now(CLOCK_REALTIME);
2,022✔
820

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

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

830
                        goto finish;
6✔
831
                }
832

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

838
                        goto finish;
6✔
839
                }
840

841
                if ((k = endswith(t, " ago"))) {
315✔
842
                        _cleanup_free_ char *buf = NULL;
3✔
843

844
                        buf = strndup(t, k - t);
3✔
845
                        if (!buf)
3✔
846
                                return -ENOMEM;
847

848
                        r = parse_sec(buf, &minus);
3✔
849
                        if (r < 0)
3✔
850
                                return r;
851

852
                        goto finish;
3✔
853
                }
854

855
                if ((k = endswith(t, " left"))) {
312✔
856
                        _cleanup_free_ char *buf = NULL;
102✔
857

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

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

866
                        goto finish;
102✔
867
                }
868
        }
869

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

874
        tm.tm_isdst = isdst;
1,900✔
875

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

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

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

891
        FOREACH_ELEMENT(day, day_nr) {
19,807✔
892
                k = startswith_no_case(t, day->name);
19,490✔
893
                if (!k || *k != ' ')
19,490✔
894
                        continue;
17,938✔
895

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

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

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

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

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

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

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

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

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

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

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

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

997
        return -EINVAL;
998

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

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

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

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

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

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

1038
        usec = usec_add(usec, fractional);
3,658✔
1039

1040
finish:
1,951✔
1041
        usec = usec_add(usec, plus);
1,951✔
1042

1043
        if (usec < minus)
1,951✔
1044
                return -EINVAL;
1045

1046
        usec = usec_sub_unsigned(usec, minus);
1,950✔
1047

1048
        if (usec > USEC_TIMESTAMP_FORMATTABLE_MAX)
1,950✔
1049
                return -EINVAL;
1050

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

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

1060
        assert(t);
2,096✔
1061

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

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

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

1078
        size_t max_len = tz - t;
1,831✔
1079
        tz++;
1,831✔
1080

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

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

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

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

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

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

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

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

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

1157
        assert(p);
10,260✔
1158
        assert(ret);
10,260✔
1159

1160
        FOREACH_ELEMENT(i, table) {
175,905✔
1161
                char *e;
172,337✔
1162

1163
                e = startswith(p, i->suffix);
172,337✔
1164
                if (e) {
172,337✔
1165
                        *ret = i->usec;
6,692✔
1166
                        return e;
6,692✔
1167
                }
1168
        }
1169

1170
        return p;
1171
}
1172

1173
int parse_time(const char *t, usec_t *ret, usec_t default_unit) {
10,349✔
1174
        const char *p, *s;
10,349✔
1175

1176
        assert(t);
10,349✔
1177
        assert(default_unit > 0);
10,349✔
1178

1179
        p = skip_leading_chars(t, /* bad = */ NULL);
10,349✔
1180
        s = startswith(p, "infinity");
10,349✔
1181
        if (s) {
10,349✔
1182
                if (!in_charset(s, WHITESPACE))
305✔
1183
                        return -EINVAL;
1184

1185
                if (ret)
304✔
1186
                        *ret = USEC_INFINITY;
304✔
1187
                return 0;
304✔
1188
        }
1189

1190
        usec_t usec = 0;
1191

1192
        for (bool something = false;;) {
10,244✔
1193
                usec_t multiplier = default_unit, k;
20,288✔
1194
                long long l;
20,288✔
1195
                char *e;
20,288✔
1196

1197
                p = skip_leading_chars(p, /* bad = */ NULL);
20,288✔
1198
                if (*p == 0) {
20,288✔
1199
                        if (!something)
10,006✔
1200
                                return -EINVAL;
43✔
1201

1202
                        break;
10,001✔
1203
                }
1204

1205
                if (*p == '-') /* Don't allow "-0" */
10,282✔
1206
                        return -ERANGE;
1207

1208
                errno = 0;
10,274✔
1209
                l = strtoll(p, &e, 10);
10,274✔
1210
                if (errno > 0)
10,274✔
UNCOV
1211
                        return -errno;
×
1212
                if (l < 0)
10,274✔
1213
                        return -ERANGE;
1214

1215
                if (*e == '.') {
10,274✔
1216
                        p = e + 1;
55✔
1217
                        p += strspn(p, DIGITS);
55✔
1218
                } else if (e == p)
10,219✔
1219
                        return -EINVAL;
1220
                else
1221
                        p = e;
1222

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

1228
                p = s;
10,251✔
1229

1230
                if ((usec_t) l >= USEC_INFINITY / multiplier)
10,251✔
1231
                        return -ERANGE;
1232

1233
                k = (usec_t) l * multiplier;
10,249✔
1234
                if (k >= USEC_INFINITY - usec)
10,249✔
1235
                        return -ERANGE;
1236

1237
                usec += k;
10,249✔
1238

1239
                something = true;
10,249✔
1240

1241
                if (*e == '.') {
10,249✔
1242
                        usec_t m = multiplier / 10;
48✔
1243
                        const char *b;
48✔
1244

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

1250
                                usec += k;
140✔
1251
                        }
1252

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

1259
        if (ret)
10,001✔
1260
                *ret = usec;
9,999✔
1261
        return 0;
1262
}
1263

1264
int parse_sec(const char *t, usec_t *ret) {
10,266✔
1265
        return parse_time(t, ret, USEC_PER_SEC);
10,266✔
1266
}
1267

1268
int parse_sec_fix_0(const char *t, usec_t *ret) {
1,777✔
1269
        usec_t k;
1,777✔
1270
        int r;
1,777✔
1271

1272
        assert(t);
1,777✔
1273
        assert(ret);
1,777✔
1274

1275
        r = parse_sec(t, &k);
1,777✔
1276
        if (r < 0)
1,777✔
1277
                return r;
1,777✔
1278

1279
        *ret = k == 0 ? USEC_INFINITY : k;
1,777✔
1280
        return r;
1,777✔
1281
}
1282

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

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

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

1335
        assert(p);
44✔
1336
        assert(ret);
44✔
1337

1338
        FOREACH_ELEMENT(i, table) {
803✔
1339
                char *e;
803✔
1340

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

1348
        return p;
1349
}
1350

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

1356
        assert(t);
48✔
1357
        assert(ret);
48✔
1358

1359
        p = t;
48✔
1360

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

1368
                *ret = NSEC_INFINITY;
2✔
1369
                return 0;
2✔
1370
        }
1371

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

1377
                p += strspn(p, WHITESPACE);
74✔
1378

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

1383
                        break;
20✔
1384
                }
1385

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

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

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

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

1409
                p = s;
36✔
1410

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

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

1418
                nsec += k;
35✔
1419

1420
                something = true;
35✔
1421

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

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

1431
                                nsec += k;
32✔
1432
                        }
1433

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

1440
        *ret = nsec;
20✔
1441

1442
        return 0;
20✔
1443
}
1444

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

1450
        assert(ret);
×
1451

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

1456
        for (;;) {
×
UNCOV
1457
                _cleanup_free_ char *line = NULL, *cc = NULL, *co = NULL, *tz = NULL;
×
1458

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

1465
                const char *p = line;
×
1466

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

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

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

UNCOV
1481
                r = strv_extend(&zones, tz);
×
1482
                if (r < 0)
×
1483
                        return r;
1484
        }
1485

UNCOV
1486
        *ret = TAKE_PTR(zones);
×
UNCOV
1487
        return 0;
×
1488
}
1489

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

1495
        assert(ret);
4✔
1496

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

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

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

1510
                const char *p = line;
17,200✔
1511

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

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

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

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

1542
        *ret = TAKE_PTR(zones);
4✔
1543
        return 0;
4✔
1544
}
1545

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

1550
        assert(ret);
4✔
1551

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

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

1567
        strv_sort_uniq(zones);
4✔
1568

1569
        *ret = TAKE_PTR(zones);
4✔
1570
        return 0;
4✔
1571
}
1572

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

1580
        if (isempty(name))
8,434✔
1581
                return -EINVAL;
1582

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

1587
        if (name[0] == '/')
4,208✔
1588
                return -EINVAL;
1589

1590
        for (p = name; *p; p++) {
59,308✔
1591
                if (!ascii_isdigit(*p) &&
55,247✔
1592
                    !ascii_isalpha(*p) &&
53,949✔
1593
                    !IN_SET(*p, '-', '_', '+', '/'))
4,791✔
1594
                        return -EINVAL;
1595

1596
                if (*p == '/') {
55,101✔
1597

1598
                        if (slash)
3,713✔
1599
                                return -EINVAL;
1600

1601
                        slash = true;
1602
                } else
1603
                        slash = false;
1604
        }
1605

1606
        if (slash)
4,061✔
1607
                return -EINVAL;
1608

1609
        if (p - name >= PATH_MAX)
4,060✔
1610
                return -ENAMETOOLONG;
1611

1612
        t = strjoina("/usr/share/zoneinfo/", name);
20,300✔
1613

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

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

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

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

1631
        return 0;
1632
}
1633

1634
void reset_timezonep(char **p) {
757✔
1635
        assert(p);
757✔
1636

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

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

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

1651
        return s;
1652
}
1653

1654
bool clock_supported(clockid_t clock) {
303,802✔
1655
        struct timespec ts;
303,802✔
1656

1657
        switch (clock) {
303,802✔
1658

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

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

1671
int get_timezone(char **ret) {
60✔
1672
        _cleanup_free_ char *t = NULL;
60✔
1673
        int r;
60✔
1674

1675
        assert(ret);
60✔
1676

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

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

1690
        return strdup_to(ret, e);
59✔
1691
}
1692

1693
const char* etc_localtime(void) {
981✔
1694
        static const char *cached = NULL;
981✔
1695

1696
        if (!cached)
981✔
1697
                cached = secure_getenv("SYSTEMD_ETC_LOCALTIME") ?: "/etc/localtime";
876✔
1698

1699
        return cached;
981✔
1700
}
1701

1702
int mktime_or_timegm_usec(
7,415✔
1703
                struct tm *tm, /* input + normalized output */
1704
                bool utc,
1705
                usec_t *ret) {
1706

1707
        time_t t;
7,415✔
1708

1709
        assert(tm);
7,415✔
1710

1711
        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,415✔
1712
                return -ERANGE;
1713
        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,412✔
1714
                return -ERANGE;
1715

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

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

1727
        if (ret)
7,410✔
1728
                *ret = (usec_t) t * USEC_PER_SEC;
2,145✔
1729
        return 0;
1730
}
1731

1732
int localtime_or_gmtime_usec(
127,238✔
1733
                usec_t t,
1734
                bool utc,
1735
                struct tm *ret) {
1736

1737
        t /= USEC_PER_SEC; /* Round down */
127,238✔
1738
        if (t > (usec_t) TIME_T_MAX)
127,238✔
1739
                return -ERANGE;
1740
        time_t sec = (time_t) t;
127,238✔
1741

1742
        struct tm buf = {};
127,238✔
1743
        if (!(utc ? gmtime_r(&sec, &buf) : localtime_r(&sec, &buf)))
127,238✔
1744
                return -EINVAL;
1745

1746
        if (ret)
127,238✔
1747
                *ret = buf;
127,238✔
1748

1749
        return 0;
1750
}
1751

1752
static uint32_t sysconf_clock_ticks_cached(void) {
653✔
1753
        static thread_local uint32_t hz = 0;
653✔
1754
        long r;
653✔
1755

1756
        if (hz == 0) {
653✔
1757
                r = sysconf(_SC_CLK_TCK);
69✔
1758

1759
                assert(r > 0);
69✔
1760
                hz = r;
69✔
1761
        }
1762

1763
        return hz;
653✔
1764
}
1765

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

1771
usec_t jiffies_to_usec(uint32_t j) {
644✔
1772
        uint32_t hz = sysconf_clock_ticks_cached();
644✔
1773
        return DIV_ROUND_UP(j * USEC_PER_SEC, hz);
644✔
1774
}
1775

1776
usec_t usec_shift_clock(usec_t x, clockid_t from, clockid_t to) {
651✔
1777
        usec_t a, b;
651✔
1778

1779
        if (x == USEC_INFINITY)
651✔
1780
                return USEC_INFINITY;
1781
        if (map_clock_id(from) == map_clock_id(to))
518✔
1782
                return x;
1783

1784
        a = now(from);
8✔
1785
        b = now(to);
8✔
1786

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

1795
bool in_utc_timezone(void) {
676✔
1796
        tzset();
676✔
1797

1798
        return timezone == 0 && daylight == 0;
676✔
1799
}
1800

1801
int time_change_fd(void) {
450✔
1802

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

1808
        _cleanup_close_ int fd = -EBADF;
900✔
1809

1810
        assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
450✔
1811

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

1815
        fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
450✔
1816
        if (fd < 0)
450✔
UNCOV
1817
                return -errno;
×
1818

1819
        if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) >= 0)
450✔
1820
                return TAKE_FD(fd);
450✔
1821

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

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

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

UNCOV
1843
        return -errno;
×
1844
}
1845

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

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

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

1861
        t = (TimestampStyle) string_table_lookup_from_string(timestamp_style_table, ELEMENTSOF(timestamp_style_table), s);
8✔
1862
        if (t >= 0)
8✔
1863
                return t;
1864
        if (STRPTR_IN_SET(s, "µs", "μs")) /* accept both µ symbols in unicode, i.e. micro symbol + Greek small letter mu. */
2✔
1865
                return TIMESTAMP_US;
1✔
1866
        if (STRPTR_IN_SET(s, "µs+utc", "μs+utc"))
1✔
1867
                return TIMESTAMP_US_UTC;
1✔
1868
        return t;
1869
}
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