a_utctm.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright 1995-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 "internal/cryptlib.h"
  12. #include <openssl/asn1.h>
  13. #include "asn1_local.h"
  14. #include <openssl/asn1t.h>
  15. IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_UTCTIME)
  16. /* This is the primary function used to parse ASN1_UTCTIME */
  17. int ossl_asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
  18. {
  19. /* wrapper around ossl_asn1_time_to_tm */
  20. if (d->type != V_ASN1_UTCTIME)
  21. return 0;
  22. return ossl_asn1_time_to_tm(tm, d);
  23. }
  24. int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
  25. {
  26. return ossl_asn1_utctime_to_tm(NULL, d);
  27. }
  28. /* Sets the string via simple copy without cleaning it up */
  29. int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
  30. {
  31. ASN1_UTCTIME t;
  32. t.type = V_ASN1_UTCTIME;
  33. t.length = strlen(str);
  34. t.data = (unsigned char *)str;
  35. t.flags = 0;
  36. if (!ASN1_UTCTIME_check(&t))
  37. return 0;
  38. if (s != NULL && !ASN1_STRING_copy(s, &t))
  39. return 0;
  40. return 1;
  41. }
  42. ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
  43. {
  44. return ASN1_UTCTIME_adj(s, t, 0, 0);
  45. }
  46. ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
  47. int offset_day, long offset_sec)
  48. {
  49. struct tm *ts;
  50. struct tm data;
  51. ts = OPENSSL_gmtime(&t, &data);
  52. if (ts == NULL)
  53. return NULL;
  54. if (offset_day || offset_sec) {
  55. if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
  56. return NULL;
  57. }
  58. return ossl_asn1_time_from_tm(s, ts, V_ASN1_UTCTIME);
  59. }
  60. int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
  61. {
  62. struct tm stm, ttm;
  63. int day, sec;
  64. if (!ossl_asn1_utctime_to_tm(&stm, s))
  65. return -2;
  66. if (OPENSSL_gmtime(&t, &ttm) == NULL)
  67. return -2;
  68. if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
  69. return -2;
  70. if (day > 0 || sec > 0)
  71. return 1;
  72. if (day < 0 || sec < 0)
  73. return -1;
  74. return 0;
  75. }
  76. int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm)
  77. {
  78. if (tm->type != V_ASN1_UTCTIME)
  79. return 0;
  80. return ASN1_TIME_print(bp, tm);
  81. }