Home | History | Annotate | Line # | Download | only in testutil
      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 
     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         ASN1_TIME_free(timestamp_asn1);
     42         return -1;
     43     }
     44 
     45     timestamp_tm = OPENSSL_malloc(sizeof(*timestamp_tm));
     46     if (timestamp_tm == NULL) {
     47         ASN1_TIME_free(timestamp_asn1);
     48         return -1;
     49     }
     50     if (!(ASN1_TIME_to_tm(timestamp_asn1, timestamp_tm))) {
     51         OPENSSL_free(timestamp_tm);
     52         ASN1_TIME_free(timestamp_asn1);
     53         return -1;
     54     }
     55     ASN1_TIME_free(timestamp_asn1);
     56 
     57 #if defined(__DJGPP__)
     58     /*
     59      * This is NOT thread-safe.  Do not use this method for platforms other
     60      * than djgpp.
     61      */
     62     tz = getenv("TZ");
     63     if (tz != NULL) {
     64         tz = OPENSSL_strdup(tz);
     65         if (tz == NULL) {
     66             OPENSSL_free(timestamp_tm);
     67             return -1;
     68         }
     69     }
     70     setenv("TZ", "UTC", 1);
     71 
     72     timestamp_utc = mktime(timestamp_tm);
     73 
     74     if (tz != NULL) {
     75         setenv("TZ", tz, 1);
     76         OPENSSL_free(tz);
     77     } else {
     78         unsetenv("TZ");
     79     }
     80 #elif defined(USE_TIMEGM)
     81     timestamp_utc = timegm(timestamp_tm);
     82 #else
     83     timestamp_local = mktime(timestamp_tm);
     84     timestamp_utc = timestamp_local - timezone;
     85 #endif
     86     OPENSSL_free(timestamp_tm);
     87 
     88     return timestamp_utc;
     89 }
     90