xref: /openssl/crypto/time.c (revision 0022bc81)
1 /*
2  * Copyright 2022-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <errno.h>
11 #include <openssl/err.h>
12 #include "internal/time.h"
13 #include "internal/e_os.h"
14 
ossl_time_now(void)15 OSSL_TIME ossl_time_now(void)
16 {
17     OSSL_TIME r;
18 
19 #if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI)
20     SYSTEMTIME st;
21     union {
22         unsigned __int64 ul;
23         FILETIME ft;
24     } now;
25 
26     GetSystemTime(&st);
27     SystemTimeToFileTime(&st, &now.ft);
28     /* re-bias to 1/1/1970 */
29 # ifdef  __MINGW32__
30     now.ul -= 116444736000000000ULL;
31 # else
32     now.ul -= 116444736000000000UI64;
33 # endif
34     r.t = ((uint64_t)now.ul) * (OSSL_TIME_SECOND / 10000000);
35 #else   /* defined(_WIN32) */
36     struct timeval t;
37 
38     if (gettimeofday(&t, NULL) < 0) {
39         ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
40                        "calling gettimeofday()");
41         return ossl_time_zero();
42     }
43     if (t.tv_sec <= 0)
44         r.t = t.tv_usec <= 0 ? 0 : t.tv_usec * OSSL_TIME_US;
45     else
46         r.t = ((uint64_t)t.tv_sec * 1000000 + t.tv_usec) * OSSL_TIME_US;
47 #endif  /* defined(_WIN32) */
48     return r;
49 }
50