2 * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
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
11 #include <openssl/opensslconf.h>
12 #include <openssl/trace.h>
14 #include "../testutil.h"
16 #ifndef OPENSSL_NO_TRACE
17 typedef struct tracedata_st {
19 unsigned int ingroup:1;
22 static size_t internal_trace_cb(const char *buf, size_t cnt,
23 int category, int cmd, void *vdata)
26 tracedata *trace_data = vdata;
27 char buffer[256], *hex;
31 case OSSL_TRACE_CTRL_BEGIN:
32 trace_data->ingroup = 1;
34 tid = CRYPTO_THREAD_get_current_id();
35 hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid));
36 BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ",
37 hex, OSSL_trace_get_category_name(category));
39 BIO_set_prefix(trace_data->bio, buffer);
41 case OSSL_TRACE_CTRL_WRITE:
42 ret = BIO_write(trace_data->bio, buf, cnt);
44 case OSSL_TRACE_CTRL_END:
45 trace_data->ingroup = 0;
47 BIO_set_prefix(trace_data->bio, NULL);
51 return ret < 0 ? 0 : ret;
54 DEFINE_STACK_OF(tracedata)
55 static STACK_OF(tracedata) *trace_data_stack;
57 static void tracedata_free(tracedata *data)
59 BIO_free_all(data->bio);
63 static STACK_OF(tracedata) *trace_data_stack;
65 static void cleanup_trace(void)
67 sk_tracedata_pop_free(trace_data_stack, tracedata_free);
70 static void setup_trace_category(int category)
73 tracedata *trace_data;
75 if (OSSL_trace_enabled(category))
78 channel = BIO_push(BIO_new(BIO_f_prefix()),
79 BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT));
80 trace_data = OPENSSL_zalloc(sizeof(*trace_data));
82 if (trace_data == NULL
83 || (trace_data->bio = channel) == NULL
84 || OSSL_trace_set_callback(category, internal_trace_cb,
86 || sk_tracedata_push(trace_data_stack, trace_data) == 0) {
89 "warning: unable to setup trace callback for category '%s'.\n",
90 OSSL_trace_get_category_name(category));
92 OSSL_trace_set_callback(category, NULL, NULL);
93 BIO_free_all(channel);
97 static void setup_trace(const char *str)
102 * We add this handler as early as possible to ensure it's executed
103 * as late as possible, i.e. after the TRACE code has done its cleanup
104 * (which happens last in OPENSSL_cleanup).
106 atexit(cleanup_trace);
108 trace_data_stack = sk_tracedata_new_null();
109 val = OPENSSL_strdup(str);
115 for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) {
116 int category = OSSL_trace_get_category_num(item);
118 if (category == OSSL_TRACE_CATEGORY_ALL) {
119 while (++category < OSSL_TRACE_CATEGORY_NUM)
120 setup_trace_category(category);
122 } else if (category > 0) {
123 setup_trace_category(category);
126 "warning: unknown trace category: '%s'.\n", item);
133 #endif /* OPENSSL_NO_TRACE */
135 int global_init(void)
137 #ifndef OPENSSL_NO_TRACE
138 setup_trace(getenv("OPENSSL_TRACE"));