Check the return from OPENSSL_buf2hexstr()
[openssl.git] / crypto / err / err_prn.c
1 /*
2  * Copyright 1995-2019 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 /* TODO: When ERR_STATE becomes opaque, this musts be removed */
11 #define OSSL_FORCE_ERR_STATE
12
13 #include <stdio.h>
14 #include "internal/cryptlib.h"
15 #include <openssl/crypto.h>
16 #include <openssl/buffer.h>
17 #include <openssl/err.h>
18 #include "err_local.h"
19
20 void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
21                          void *u)
22 {
23     CRYPTO_THREAD_ID tid = CRYPTO_THREAD_get_current_id();
24     unsigned long l;
25     char buf[4096], *hex;
26     const char *lib, *reason;
27     const char *file, *data, *func;
28     int line, flags;
29
30     while ((l = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) {
31         lib = ERR_lib_error_string(l);
32         reason = ERR_reason_error_string(l);
33         if (func == NULL)
34             func = "unknown function";
35         if ((flags & ERR_TXT_STRING) == 0)
36             data = "";
37         hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
38         BIO_snprintf(buf, sizeof(buf), "%s:error:%s:%s:%s:%s:%d:%s\n",
39                      hex == NULL ? "<null>" : hex, lib, func, reason, file,
40                      line, data);
41         OPENSSL_free(hex);
42         if (cb(buf, strlen(buf), u) <= 0)
43             break;              /* abort outputting the error report */
44     }
45 }
46
47 static int print_bio(const char *str, size_t len, void *bp)
48 {
49     return BIO_write((BIO *)bp, str, len);
50 }
51
52 void ERR_print_errors(BIO *bp)
53 {
54     ERR_print_errors_cb(print_bio, bp);
55 }
56
57 #ifndef OPENSSL_NO_STDIO
58 void ERR_print_errors_fp(FILE *fp)
59 {
60     BIO *bio = BIO_new_fp(fp, BIO_NOCLOSE);
61     if (bio == NULL)
62         return;
63
64     ERR_print_errors_cb(print_bio, bio);
65     BIO_free(bio);
66 }
67 #endif