xref: /openssl/test/testutil/helper.c (revision 7ed6de99)
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 # define USE_TIMEGM
24 #endif
25 
test_asn1_string_to_time_t(const char * asn1_string)26 time_t test_asn1_string_to_time_t(const char *asn1_string)
27 {
28     ASN1_TIME *timestamp_asn1 = NULL;
29     struct tm *timestamp_tm = NULL;
30 #if defined(__DJGPP__)
31     char *tz = NULL;
32 #elif !defined(USE_TIMEGM)
33     time_t timestamp_local;
34 #endif
35     time_t timestamp_utc;
36 
37     timestamp_asn1 = ASN1_TIME_new();
38     if(timestamp_asn1 == NULL)
39         return -1;
40     if (!ASN1_TIME_set_string(timestamp_asn1, asn1_string))
41     {
42         ASN1_TIME_free(timestamp_asn1);
43         return -1;
44     }
45 
46     timestamp_tm = OPENSSL_malloc(sizeof(*timestamp_tm));
47     if (timestamp_tm == NULL) {
48         ASN1_TIME_free(timestamp_asn1);
49         return -1;
50     }
51     if (!(ASN1_TIME_to_tm(timestamp_asn1, timestamp_tm))) {
52         OPENSSL_free(timestamp_tm);
53         ASN1_TIME_free(timestamp_asn1);
54         return -1;
55     }
56     ASN1_TIME_free(timestamp_asn1);
57 
58 #if defined(__DJGPP__)
59     /*
60      * This is NOT thread-safe.  Do not use this method for platforms other
61      * than djgpp.
62      */
63     tz = getenv("TZ");
64     if (tz != NULL) {
65         tz = OPENSSL_strdup(tz);
66         if (tz == NULL) {
67             OPENSSL_free(timestamp_tm);
68             return -1;
69         }
70     }
71     setenv("TZ", "UTC", 1);
72 
73     timestamp_utc = mktime(timestamp_tm);
74 
75     if (tz != NULL) {
76         setenv("TZ", tz, 1);
77         OPENSSL_free(tz);
78     } else {
79         unsetenv("TZ");
80     }
81 #elif defined(USE_TIMEGM)
82     timestamp_utc = timegm(timestamp_tm);
83 #else
84     timestamp_local = mktime(timestamp_tm);
85     timestamp_utc = timestamp_local - timezone;
86 #endif
87     OPENSSL_free(timestamp_tm);
88 
89     return timestamp_utc;
90 }
91