Coverage Report

Created: 2024-06-03 09:43

/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
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#include <errno.h>
9
#include "fido.h"
10
11
static int
12
timespec_to_ms(const struct timespec *ts)
13
621k
{
14
621k
        int64_t x, y;
15
16
621k
        if (ts->tv_sec < 0 || ts->tv_nsec < 0 ||
17
621k
            ts->tv_nsec >= 1000000000LL)
18
859
                return -1;
19
20
620k
        if ((uint64_t)ts->tv_sec >= INT64_MAX / 1000LL)
21
0
                return -1;
22
23
620k
        x = ts->tv_sec * 1000LL;
24
620k
        y = ts->tv_nsec / 1000000LL;
25
26
620k
        if (INT64_MAX - x < y || x + y > INT_MAX)
27
0
                return -1;
28
29
620k
        return (int)(x + y);
30
620k
}
31
32
int
33
fido_time_now(struct timespec *ts_now)
34
704k
{
35
704k
        if (clock_gettime(CLOCK_MONOTONIC, ts_now) != 0) {
36
1.41k
                fido_log_error(errno, "%s: clock_gettime", __func__);
37
1.41k
                return -1;
38
1.41k
        }
39
40
702k
        return 0;
41
704k
}
42
43
int
44
fido_time_delta(const struct timespec *ts_start, int *ms_remain)
45
632k
{
46
632k
        struct timespec ts_end, ts_delta;
47
632k
        int ms;
48
49
632k
        if (*ms_remain < 0)
50
9.96k
                return 0;
51
52
622k
        if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) {
53
812
                fido_log_error(errno, "%s: clock_gettime", __func__);
54
812
                return -1;
55
812
        }
56
57
621k
        if (timespeccmp(&ts_end, ts_start, <)) {
58
521
                fido_log_debug("%s: timespeccmp", __func__);
59
521
                return -1;
60
521
        }
61
62
621k
        timespecsub(&ts_end, ts_start, &ts_delta);
63
64
621k
        if ((ms = timespec_to_ms(&ts_delta)) < 0) {
65
859
                fido_log_debug("%s: timespec_to_ms", __func__);
66
859
                return -1;
67
859
        }
68
69
620k
        if (ms > *ms_remain)
70
41.1k
                ms = *ms_remain;
71
72
620k
        *ms_remain -= ms;
73
74
620k
        return 0;
75
621k
}