1 /*
2  * Copyright 2020-2024 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 <stdio.h>
11 #include <time.h>
12 #include <openssl/asn1t.h>
13 #include "../testutil.h"
14 
15 /*
16  * tweak for Windows
17  */
18 #ifdef WIN32
19 # define timezone _timezone
20 #endif
21 
22 #if defined(__FreeBSD__) || defined(__wasi__) || \
23     (defined(__APPLE__) && !defined(OPENSSL_NO_APPLE_CRYPTO_RANDOM) && \
24      !(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
25 # define USE_TIMEGM
26 #endif
27 
test_asn1_string_to_time_t(const char * asn1_string)28 time_t test_asn1_string_to_time_t(const char *asn1_string)
29 {
30     ASN1_TIME *timestamp_asn1 = NULL;
31     struct tm *timestamp_tm = NULL;
32 #if defined(__DJGPP__)
33     char *tz = NULL;
34 #elif !defined(USE_TIMEGM)
35     time_t timestamp_local;
36 #endif
37     time_t timestamp_utc;
38 
39     timestamp_asn1 = ASN1_TIME_new();
40     if(timestamp_asn1 == NULL)
41         return -1;
42     if (!ASN1_TIME_set_string(timestamp_asn1, asn1_string))
43     {
44         ASN1_TIME_free(timestamp_asn1);
45         return -1;
46     }
47 
48     timestamp_tm = OPENSSL_malloc(sizeof(*timestamp_tm));
49     if (timestamp_tm == NULL) {
50         ASN1_TIME_free(timestamp_asn1);
51         return -1;
52     }
53     if (!(ASN1_TIME_to_tm(timestamp_asn1, timestamp_tm))) {
54         OPENSSL_free(timestamp_tm);
55         ASN1_TIME_free(timestamp_asn1);
56         return -1;
57     }
58     ASN1_TIME_free(timestamp_asn1);
59 
60 #if defined(__DJGPP__)
61     /*
62      * This is NOT thread-safe.  Do not use this method for platforms other
63      * than djgpp.
64      */
65     tz = getenv("TZ");
66     if (tz != NULL) {
67         tz = OPENSSL_strdup(tz);
68         if (tz == NULL) {
69             OPENSSL_free(timestamp_tm);
70             return -1;
71         }
72     }
73     setenv("TZ", "UTC", 1);
74 
75     timestamp_utc = mktime(timestamp_tm);
76 
77     if (tz != NULL) {
78         setenv("TZ", tz, 1);
79         OPENSSL_free(tz);
80     } else {
81         unsetenv("TZ");
82     }
83 #elif defined(USE_TIMEGM)
84     timestamp_utc = timegm(timestamp_tm);
85 #else
86     timestamp_local = mktime(timestamp_tm);
87     timestamp_utc = timestamp_local - timezone;
88 #endif
89     OPENSSL_free(timestamp_tm);
90 
91     return timestamp_utc;
92 }
93