Coverage Report

Created: 2021-10-21 13:35

/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
363k
{
13
363k
        int64_t x, y;
14
15
363k
        if (ts->tv_sec < 0 || ts->tv_nsec < 0 ||
16
363k
            ts->tv_nsec >= 1000000000LL)
17
611
                return -1;
18
19
362k
        if ((uint64_t)ts->tv_sec >= INT64_MAX / 1000LL)
20
0
                return -1;
21
22
362k
        x = ts->tv_sec * 1000LL;
23
362k
        y = ts->tv_nsec / 1000000LL;
24
25
362k
        if (INT64_MAX - x < y || x + y > INT_MAX)
26
362k
                return -1;
27
28
362k
        return (int)(x + y);
29
362k
}
30
31
int
32
fido_time_now(struct timespec *ts_now)
33
410k
{
34
410k
        if (clock_gettime(CLOCK_MONOTONIC, ts_now) != 0) {
35
1.10k
                fido_log_error(errno, "%s: clock_gettime", __func__);
36
1.10k
                return -1;
37
1.10k
        }
38
39
409k
        return 0;
40
409k
}
41
42
int
43
fido_time_delta(const struct timespec *ts_start, int *ms_remain)
44
368k
{
45
368k
        struct timespec ts_end, ts_delta;
46
368k
        int ms;
47
48
368k
        if (*ms_remain < 0)
49
4.15k
                return 0;
50
51
364k
        if (clock_gettime(CLOCK_MONOTONIC, &ts_end) != 0) {
52
607
                fido_log_error(errno, "%s: clock_gettime", __func__);
53
607
                return -1;
54
607
        }
55
56
363k
        if (timespeccmp(&ts_end, ts_start, <)) {
57
371
                fido_log_debug("%s: timespeccmp", __func__);
58
371
                return -1;
59
371
        }
60
61
363k
        timespecsub(&ts_end, ts_start, &ts_delta);
62
63
363k
        if ((ms = timespec_to_ms(&ts_delta)) < 0) {
64
611
                fido_log_debug("%s: timespec_to_ms", __func__);
65
611
                return -1;
66
611
        }
67
68
362k
        if (ms > *ms_remain)
69
23.8k
                ms = *ms_remain;
70
71
362k
        *ms_remain -= ms;
72
73
362k
        return 0;
74
362k
}