Merge pull request #3847 from rolfbjarne/btls-remove-unused-pinvokes
[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 #if defined(__ANDROID__) && !defined(__LP64__)
14 #include <time64.h>
15 extern time_t timegm (struct tm* const t);
16 #endif
17
18 extern int asn1_generalizedtime_to_tm (struct tm *tm, const ASN1_GENERALIZEDTIME *d);
19
20 MONO_API void
21 mono_btls_free (void *data)
22 {
23         OPENSSL_free (data);
24 }
25
26 long
27 mono_btls_util_asn1_time_to_ticks (ASN1_TIME *time)
28 {
29         ASN1_GENERALIZEDTIME *gtime;
30         struct tm tm;
31         time_t epoch;
32
33         gtime = ASN1_TIME_to_generalizedtime (time, NULL);
34         asn1_generalizedtime_to_tm (&tm, gtime);
35         ASN1_GENERALIZEDTIME_free (gtime);
36         epoch = timegm(&tm);
37
38         return epoch;
39 }
40
41 // Copied from crypto/bio/printf.c, takes va_list
42 int
43 mono_btls_debug_printf (BIO *bio, const char *format, va_list args)
44 {
45         char buf[256], *out, out_malloced = 0;
46         int out_len, ret;
47
48         out_len = vsnprintf (buf, sizeof(buf), format, args);
49         if (out_len < 0) {
50                 return -1;
51         }
52
53         if ((size_t) out_len >= sizeof(buf)) {
54                 const int requested_len = out_len;
55                 /* The output was truncated. Note that vsnprintf's return value
56                  * does not include a trailing NUL, but the buffer must be sized
57                  * for it. */
58                 out = OPENSSL_malloc (requested_len + 1);
59                 out_malloced = 1;
60                 if (out == NULL) {
61                         OPENSSL_PUT_ERROR(BIO, ERR_R_MALLOC_FAILURE);
62                         return -1;
63                 }
64                 out_len = vsnprintf (out, requested_len + 1, format, args);
65                 assert(out_len == requested_len);
66         } else {
67                 out = buf;
68         }
69
70         ret = BIO_write(bio, out, out_len);
71         if (out_malloced) {
72                 OPENSSL_free(out);
73         }
74
75         return ret;
76 }