1 // Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <openssl/bio.h>
16
17 #include <assert.h>
18 #include <stdarg.h>
19 #include <stdio.h>
20
21 #include <openssl/err.h>
22 #include <openssl/mem.h>
23
BIO_printf(BIO * bio,const char * format,...)24 int BIO_printf(BIO *bio, const char *format, ...) {
25 va_list args;
26 char buf[256], *out, out_malloced = 0;
27 int out_len, ret;
28
29 va_start(args, format);
30 out_len = vsnprintf(buf, sizeof(buf), format, args);
31 va_end(args);
32 if (out_len < 0) {
33 return -1;
34 }
35
36 if ((size_t)out_len >= sizeof(buf)) {
37 const size_t requested_len = (size_t)out_len;
38 // The output was truncated. Note that vsnprintf's return value does not
39 // include a trailing NUL, but the buffer must be sized for it.
40 out = reinterpret_cast<char *>(OPENSSL_malloc(requested_len + 1));
41 out_malloced = 1;
42 if (out == NULL) {
43 return -1;
44 }
45 va_start(args, format);
46 out_len = vsnprintf(out, requested_len + 1, format, args);
47 va_end(args);
48 assert(out_len == (int)requested_len);
49 } else {
50 out = buf;
51 }
52
53 ret = BIO_write(bio, out, out_len);
54 if (out_malloced) {
55 OPENSSL_free(out);
56 }
57
58 return ret;
59 }
60