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