Coverage Report

Created: 2022-07-22 12:05

/libfido2/src/time.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2021 Yubico AB. All rights reserved.
3
 * Use of this source code is governed by a BSD-style
4
 * license that can be found in the LICENSE file.
5
 */
6
7
#include <errno.h>
8
#include "fido.h"
9
10
static int
11
timespec_to_ms(const struct timespec *ts)
12
246k
{
13
246k
        int64_t x, y;
14
15
246k
        if (ts->tv_sec < 0 || ts->tv_nsec < 0 ||
16
246k
            ts->tv_nsec >= 1000000000LL)
17
496
                return -1;
18
19
245k
        if ((uint64_t)ts->tv_sec >= INT64_MAX / 1000LL)
20
0
                return -1;
21
22
245k
        x = ts->tv_sec * 1000LL;
23
245k
        y = ts->tv_nsec / 1000000LL;
24
25
245k
        if (INT64_MAX - x < y || x + y > INT_MAX)
26
0
                return -1;
27
28
245k
        return (int)(x + y);
29
245k
}
30
31
int
32
fido_time_now(struct timespec *ts_now)
33
276k
{
34
276k
        if (clock_gettime(CLOCK_MONOTONIC, ts_now) != 0) {
35
676
                fido_log_error(errno, "%s: clock_gettime", __func__);
36
676
                return -1;
37
676
        }
38
39
275k
        return 0;
40
276k
}
41
42
int
43
fido_time_delta(const struct timespec *ts_start, int *ms_remain)
44
252k
{
45
252k
        struct timespec ts_end, ts_delta;
46
252k
        int ms;
47
48
252k
        if (*ms_remain < 0)
49
5.96k
                return 0;
50
51
246k
        if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) {
52
461
                fido_log_error(errno, "%s: clock_gettime", __func__);
53
461
                return -1;
54
461
        }
55
56
246k
        if (timespeccmp(&ts_end, ts_start, <)) {
57
282
                fido_log_debug("%s: timespeccmp", __func__);
58
282
                return -1;
59
282
        }
60
61
246k
        timespecsub(&ts_end, ts_start, &ts_delta);
62
63
246k
        if ((ms = timespec_to_ms(&ts_delta)) < 0) {
64
496
                fido_log_debug("%s: timespec_to_ms", __func__);
65
496
                return -1;
66
496
        }
67
68
245k
        if (ms > *ms_remain)
69
24.6k
                ms = *ms_remain;
70
71
245k
        *ms_remain -= ms;
72
73
245k
        return 0;
74
246k
}