• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 1995-2016 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 <openssl/bio.h>
11 
12 #include <assert.h>
13 #include <stdarg.h>
14 #include <stdio.h>
15 
16 #include <openssl/err.h>
17 #include <openssl/mem.h>
18 
BIO_printf(BIO * bio,const char * format,...)19 int BIO_printf(BIO *bio, const char *format, ...) {
20   va_list args;
21   char buf[256], *out, out_malloced = 0;
22   int out_len, ret;
23 
24   va_start(args, format);
25   out_len = vsnprintf(buf, sizeof(buf), format, args);
26   va_end(args);
27   if (out_len < 0) {
28     return -1;
29   }
30 
31   if ((size_t)out_len >= sizeof(buf)) {
32     const size_t requested_len = (size_t)out_len;
33     // The output was truncated. Note that vsnprintf's return value does not
34     // include a trailing NUL, but the buffer must be sized for it.
35     out = reinterpret_cast<char *>(OPENSSL_malloc(requested_len + 1));
36     out_malloced = 1;
37     if (out == NULL) {
38       return -1;
39     }
40     va_start(args, format);
41     out_len = vsnprintf(out, requested_len + 1, format, args);
42     va_end(args);
43     assert(out_len == (int)requested_len);
44   } else {
45     out = buf;
46   }
47 
48   ret = BIO_write(bio, out, out_len);
49   if (out_malloced) {
50     OPENSSL_free(out);
51   }
52 
53   return ret;
54 }
55