Coverage Report

Created: 2022-01-17 10:46

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