helper.c 2.1 KB

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