xref: /freebsd/crypto/openssl/crypto/asn1/a_utctm.c (revision 7cc42f6d)
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 "internal/cryptlib.h"
13 #include <openssl/asn1.h>
14 #include "asn1_local.h"
15 
16 /* This is the primary function used to parse ASN1_UTCTIME */
17 int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
18 {
19     /* wrapper around ans1_time_to_tm */
20     if (d->type != V_ASN1_UTCTIME)
21         return 0;
22     return asn1_time_to_tm(tm, d);
23 }
24 
25 int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
26 {
27     return asn1_utctime_to_tm(NULL, d);
28 }
29 
30 /* Sets the string via simple copy without cleaning it up */
31 int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
32 {
33     ASN1_UTCTIME t;
34 
35     t.type = V_ASN1_UTCTIME;
36     t.length = strlen(str);
37     t.data = (unsigned char *)str;
38     t.flags = 0;
39 
40     if (!ASN1_UTCTIME_check(&t))
41         return 0;
42 
43     if (s != NULL && !ASN1_STRING_copy(s, &t))
44         return 0;
45 
46     return 1;
47 }
48 
49 ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
50 {
51     return ASN1_UTCTIME_adj(s, t, 0, 0);
52 }
53 
54 ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
55                                int offset_day, long offset_sec)
56 {
57     struct tm *ts;
58     struct tm data;
59 
60     ts = OPENSSL_gmtime(&t, &data);
61     if (ts == NULL)
62         return NULL;
63 
64     if (offset_day || offset_sec) {
65         if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
66             return NULL;
67     }
68 
69     return asn1_time_from_tm(s, ts, V_ASN1_UTCTIME);
70 }
71 
72 int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
73 {
74     struct tm stm, ttm;
75     int day, sec;
76 
77     if (!asn1_utctime_to_tm(&stm, s))
78         return -2;
79 
80     if (OPENSSL_gmtime(&t, &ttm) == NULL)
81         return -2;
82 
83     if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
84         return -2;
85 
86     if (day > 0 || sec > 0)
87         return 1;
88     if (day < 0 || sec < 0)
89         return -1;
90     return 0;
91 }
92 
93 int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm)
94 {
95     if (tm->type != V_ASN1_UTCTIME)
96         return 0;
97     return ASN1_TIME_print(bp, tm);
98 }
99