|
20 | 20 | * port/posix/posix_timeout.c |
21 | 21 | * |
22 | 22 | * POSIX implementation of the wolfHSM timeout abstraction. |
23 | | - * Uses posixGetTime() from posix_time.h for time measurement. |
| 23 | + * Uses CLOCK_MONOTONIC for time measurement. |
24 | 24 | */ |
25 | 25 |
|
26 | 26 | #include "wolfhsm/wh_settings.h" |
27 | 27 |
|
28 | 28 | #ifdef WOLFHSM_CFG_ENABLE_TIMEOUT |
29 | 29 |
|
30 | 30 | #include <stddef.h> |
| 31 | +#include <time.h> |
31 | 32 |
|
32 | 33 | #include "wolfhsm/wh_error.h" |
33 | 34 | #include "wolfhsm/wh_timeout.h" |
34 | 35 |
|
35 | | -#include "port/posix/posix_time.h" |
36 | 36 | #include "port/posix/posix_timeout.h" |
37 | 37 |
|
| 38 | +/* Use CLOCK_MONOTONIC for timeout measurement to avoid issues with wall-clock |
| 39 | + * adjustments (NTP, manual changes, etc.) that could cause spurious expirations |
| 40 | + * or overly long timeouts. */ |
| 41 | +static uint64_t _getMonotonicTimeUs(void) |
| 42 | +{ |
| 43 | + struct timespec ts; |
| 44 | + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) { |
| 45 | + return 0; |
| 46 | + } |
| 47 | + return (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)(ts.tv_nsec / 1000); |
| 48 | +} |
| 49 | + |
38 | 50 | int posixTimeout_Init(void* context, const void* config) |
39 | 51 | { |
40 | 52 | posixTimeoutContext* ctx = (posixTimeoutContext*)context; |
@@ -107,7 +119,7 @@ int posixTimeout_Start(void* context) |
107 | 119 | return WH_ERROR_NOTREADY; |
108 | 120 | } |
109 | 121 |
|
110 | | - ctx->startUs = posixGetTime(); |
| 122 | + ctx->startUs = _getMonotonicTimeUs(); |
111 | 123 | ctx->started = 1; |
112 | 124 |
|
113 | 125 | return WH_ERROR_OK; |
@@ -150,7 +162,7 @@ int posixTimeout_Expired(void* context, int* expired) |
150 | 162 | return WH_ERROR_OK; |
151 | 163 | } |
152 | 164 |
|
153 | | - nowUs = posixGetTime(); |
| 165 | + nowUs = _getMonotonicTimeUs(); |
154 | 166 | *expired = ((nowUs - ctx->startUs) >= ctx->timeoutUs) ? 1 : 0; |
155 | 167 |
|
156 | 168 | return WH_ERROR_OK; |
|
0 commit comments