Add duplication APIs to ASN1_TIME and related types
[openssl.git] / crypto / asn1 / a_gentm.c
1 /*
2  * Copyright 1995-2017 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 /*
11  * GENERALIZEDTIME implementation. Based on UTCTIME
12  */
13
14 #include <stdio.h>
15 #include <time.h>
16 #include "internal/cryptlib.h"
17 #include <openssl/asn1.h>
18 #include "asn1_local.h"
19 #include <openssl/asn1t.h>
20
21 IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_GENERALIZEDTIME)
22
23 /* This is the primary function used to parse ASN1_GENERALIZEDTIME */
24 int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
25 {
26     /* wrapper around asn1_time_to_tm */
27     if (d->type != V_ASN1_GENERALIZEDTIME)
28         return 0;
29     return asn1_time_to_tm(tm, d);
30 }
31
32 int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d)
33 {
34     return asn1_generalizedtime_to_tm(NULL, d);
35 }
36
37 int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str)
38 {
39     ASN1_GENERALIZEDTIME t;
40
41     t.type = V_ASN1_GENERALIZEDTIME;
42     t.length = strlen(str);
43     t.data = (unsigned char *)str;
44     t.flags = 0;
45
46     if (!ASN1_GENERALIZEDTIME_check(&t))
47         return 0;
48
49     if (s != NULL && !ASN1_STRING_copy(s, &t))
50         return 0;
51
52     return 1;
53 }
54
55 ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
56                                                time_t t)
57 {
58     return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0);
59 }
60
61 ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
62                                                time_t t, int offset_day,
63                                                long offset_sec)
64 {
65     struct tm *ts;
66     struct tm data;
67
68     ts = OPENSSL_gmtime(&t, &data);
69     if (ts == NULL)
70         return NULL;
71
72     if (offset_day || offset_sec) {
73         if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
74             return NULL;
75     }
76
77     return asn1_time_from_tm(s, ts, V_ASN1_GENERALIZEDTIME);
78 }
79
80 int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm)
81 {
82     if (tm->type != V_ASN1_GENERALIZEDTIME)
83         return 0;
84     return ASN1_TIME_print(bp, tm);
85 }