1 /*
2  *  Message Processing Stack, Trace module
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #include "common.h"
9 
10 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
11 
12 #include "mps_common.h"
13 
14 #if defined(MBEDTLS_MPS_ENABLE_TRACE)
15 
16 #include "mps_trace.h"
17 #include <stdarg.h>
18 
19 static int trace_depth = 0;
20 
21 #define color_default  "\x1B[0m"
22 #define color_red      "\x1B[1;31m"
23 #define color_green    "\x1B[1;32m"
24 #define color_yellow   "\x1B[1;33m"
25 #define color_blue     "\x1B[1;34m"
26 #define color_magenta  "\x1B[1;35m"
27 #define color_cyan     "\x1B[1;36m"
28 #define color_white    "\x1B[1;37m"
29 
30 static char const *colors[] =
31 {
32     color_default,
33     color_green,
34     color_yellow,
35     color_magenta,
36     color_cyan,
37     color_blue,
38     color_white
39 };
40 
41 #define MPS_TRACE_BUF_SIZE 100
42 
mbedtls_mps_trace_print_msg(int id,int line,const char * format,...)43 void mbedtls_mps_trace_print_msg(int id, int line, const char *format, ...)
44 {
45     int ret;
46     char str[MPS_TRACE_BUF_SIZE];
47     va_list argp;
48     va_start(argp, format);
49     ret = mbedtls_vsnprintf(str, MPS_TRACE_BUF_SIZE, format, argp);
50     va_end(argp);
51 
52     if (ret >= 0 && ret < MPS_TRACE_BUF_SIZE) {
53         str[ret] = '\0';
54         mbedtls_printf("[%d|L%d]: %s\n", id, line, str);
55     }
56 }
57 
mbedtls_mps_trace_get_depth()58 int mbedtls_mps_trace_get_depth()
59 {
60     return trace_depth;
61 }
mbedtls_mps_trace_dec_depth()62 void mbedtls_mps_trace_dec_depth()
63 {
64     trace_depth--;
65 }
mbedtls_mps_trace_inc_depth()66 void mbedtls_mps_trace_inc_depth()
67 {
68     trace_depth++;
69 }
70 
mbedtls_mps_trace_color(int id)71 void mbedtls_mps_trace_color(int id)
72 {
73     if (id > (int) (sizeof(colors) / sizeof(*colors))) {
74         return;
75     }
76     printf("%s", colors[id]);
77 }
78 
mbedtls_mps_trace_indent(int level,mbedtls_mps_trace_type ty)79 void mbedtls_mps_trace_indent(int level, mbedtls_mps_trace_type ty)
80 {
81     if (level > 0) {
82         while (--level) {
83             printf("|  ");
84         }
85 
86         printf("|  ");
87     }
88 
89     switch (ty) {
90         case MBEDTLS_MPS_TRACE_TYPE_COMMENT:
91             mbedtls_printf("@ ");
92             break;
93 
94         case MBEDTLS_MPS_TRACE_TYPE_CALL:
95             mbedtls_printf("+--> ");
96             break;
97 
98         case MBEDTLS_MPS_TRACE_TYPE_ERROR:
99             mbedtls_printf("E ");
100             break;
101 
102         case MBEDTLS_MPS_TRACE_TYPE_RETURN:
103             mbedtls_printf("< ");
104             break;
105 
106         default:
107             break;
108     }
109 }
110 
111 #endif /* MBEDTLS_MPS_ENABLE_TRACE */
112 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
113