Merge pull request #5002 from BrzVlad/feature-sgen-modes
[mono.git] / mono / btls / btls-util.c
1 //
2 //  btls-util.c
3 //  MonoBtls
4 //
5 //  Created by Martin Baulig on 3/23/16.
6 //  Copyright © 2016 Xamarin. All rights reserved.
7 //
8
9 #include <btls-util.h>
10 #include <assert.h>
11 // #include <time.h>
12
13 extern int asn1_generalizedtime_to_tm (struct tm *tm, const ASN1_GENERALIZEDTIME *d);
14
15 extern int64_t btls_timegm64 (const struct tm *date);
16
17
18 MONO_API void
19 mono_btls_free (void *data)
20 {
21         OPENSSL_free (data);
22 }
23
24 int64_t
25 mono_btls_util_asn1_time_to_ticks (ASN1_TIME *time)
26 {
27         ASN1_GENERALIZEDTIME *gtime;
28         struct tm tm;
29         int64_t epoch;
30         int ret;
31         
32         memset (&tm, 0, sizeof (tm));
33
34         gtime = ASN1_TIME_to_generalizedtime (time, NULL);
35         ret = asn1_generalizedtime_to_tm (&tm, gtime);
36         ASN1_GENERALIZEDTIME_free (gtime);
37         epoch = btls_timegm64 (&tm);
38
39         return epoch;
40 }
41
42 // Copied from crypto/bio/printf.c, takes va_list
43 int
44 mono_btls_debug_printf (BIO *bio, const char *format, va_list args)
45 {
46         char buf[256], *out, out_malloced = 0;
47         int out_len, ret;
48
49         out_len = vsnprintf (buf, sizeof(buf), format, args);
50         if (out_len < 0) {
51                 return -1;
52         }
53
54         if ((size_t) out_len >= sizeof(buf)) {
55                 const int requested_len = out_len;
56                 /* The output was truncated. Note that vsnprintf's return value
57                  * does not include a trailing NUL, but the buffer must be sized
58                  * for it. */
59                 out = OPENSSL_malloc (requested_len + 1);
60                 out_malloced = 1;
61                 if (out == NULL) {
62                         OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
63                         return -1;
64                 }
65                 out_len = vsnprintf (out, requested_len + 1, format, args);
66                 assert(out_len == requested_len);
67         } else {
68                 out = buf;
69         }
70
71         ret = BIO_write(bio, out, out_len);
72         if (out_malloced) {
73                 OPENSSL_free(out);
74         }
75
76         return ret;
77 }