blob: 0ea213010e82e7963d1d308aae51b12d46beccdb [file] [log] [blame]
Brian Waters13d96012017-12-08 16:53:31 -06001/*********************************************************************************************************
2* Software License Agreement (BSD License) *
3* Author: Sebastien Decugis <sdecugis@freediameter.net> *
4* *
5* Copyright (c) 2015, WIDE Project and NICT *
6* All rights reserved. *
7* *
8* Redistribution and use of this software in source and binary forms, with or without modification, are *
9* permitted provided that the following conditions are met: *
10* *
11* * Redistributions of source code must retain the above *
12* copyright notice, this list of conditions and the *
13* following disclaimer. *
14* *
15* * Redistributions in binary form must reproduce the above *
16* copyright notice, this list of conditions and the *
17* following disclaimer in the documentation and/or other *
18* materials provided with the distribution. *
19* *
20* * Neither the name of the WIDE Project or NICT nor the *
21* names of its contributors may be used to endorse or *
22* promote products derived from this software without *
23* specific prior written permission of WIDE Project and *
24* NICT. *
25* *
26* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED *
27* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
28* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
29* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
30* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *
31* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR *
32* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
33* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
34*********************************************************************************************************/
35
36#include "fdproto-internal.h"
37
38#include <stdarg.h>
39
40pthread_mutex_t fd_log_lock = PTHREAD_MUTEX_INITIALIZER;
41pthread_key_t fd_log_thname;
42int fd_g_debug_lvl = FD_LOG_NOTICE;
43
44static void fd_internal_logger( int, const char *, va_list );
45static int use_colors = 0; /* 0: not init, 1: yes, 2: no */
46
47/* These may be used to pass specific debug requests via the command-line parameters */
48char * fd_debug_one_function = NULL;
49char * fd_debug_one_file = NULL;
50
51/* Useless function, only to ease setting up a breakpoint in gdb (break fd_breakhere) -- use TRACE_HERE */
52int fd_breaks = 0;
53int fd_breakhere(void) { return ++fd_breaks; }
54
55/* Allow passing of the log and debug information from base stack to extensions */
56void (*fd_logger)( int loglevel, const char * format, va_list args ) = fd_internal_logger;
57
58/* Register an external call back for tracing and debug */
59int fd_log_handler_register( void (*logger)(int loglevel, const char * format, va_list args) )
60{
61 CHECK_PARAMS( logger );
62
63 if ( fd_logger != fd_internal_logger )
64 {
65 return EALREADY; /* only one registration allowed */
66 }
67 else
68 {
69 fd_logger = logger;
70 }
71
72 return 0;
73}
74
75/* Implement a simple reset function here */
76int fd_log_handler_unregister ( void )
77{
78 fd_logger = fd_internal_logger;
79 return 0; /* Successfull in all cases. */
80}
81
82static void fd_cleanup_mutex_silent( void * mutex )
83{
84 (void)pthread_mutex_unlock((pthread_mutex_t *)mutex);
85}
86
87
88static void fd_internal_logger( int printlevel, const char *format, va_list ap )
89{
90 char buf[25];
91
92 /* Do we need to trace this ? */
93 if (printlevel < fd_g_debug_lvl)
94 return;
95
96 /* add timestamp */
97 printf("%s ", fd_log_time(NULL, buf, sizeof(buf),
98#if (defined(DEBUG) && defined(DEBUG_WITH_META))
99 1, 1
100#else /* (defined(DEBUG) && defined(DEBUG_WITH_META)) */
101 0, 0
102#endif /* (defined(DEBUG) && defined(DEBUG_WITH_META)) */
103 ));
104 /* Use colors on stdout ? */
105 if (!use_colors) {
106 if (isatty(STDOUT_FILENO))
107 use_colors = 1;
108 else
109 use_colors = 2;
110 }
111
112 switch(printlevel) {
113 case FD_LOG_ANNOYING: printf("%s A ", (use_colors == 1) ? "\e[0;37m" : ""); break;
114 case FD_LOG_DEBUG: printf("%s DBG ", (use_colors == 1) ? "\e[0;37m" : ""); break;
115 case FD_LOG_NOTICE: printf("%sNOTI ", (use_colors == 1) ? "\e[1;37m" : ""); break;
116 case FD_LOG_ERROR: printf("%sERROR ", (use_colors == 1) ? "\e[0;31m" : ""); break;
117 case FD_LOG_FATAL: printf("%sFATAL! ", (use_colors == 1) ? "\e[0;31m" : ""); break;
118 default: printf("%s ??? ", (use_colors == 1) ? "\e[0;31m" : "");
119 }
120 vprintf(format, ap);
121 if (use_colors == 1)
122 printf("\e[00m");
123 printf("\n");
124
125 fflush(stdout);
126}
127
128/* Log a debug message */
129void fd_log ( int loglevel, const char * format, ... )
130{
131 va_list ap;
Javier Bravo Conde13b0e7d2018-07-09 17:08:51 -0500132
133 if (loglevel < fd_g_debug_lvl)
134 return;
Brian Waters13d96012017-12-08 16:53:31 -0600135
136 (void)pthread_mutex_lock(&fd_log_lock);
137
138 pthread_cleanup_push(fd_cleanup_mutex_silent, &fd_log_lock);
139
140 va_start(ap, format);
141 fd_logger(loglevel, format, ap);
142 va_end(ap);
143
144 pthread_cleanup_pop(0);
145
146 (void)pthread_mutex_unlock(&fd_log_lock);
147}
148
149/* Log a debug message */
150void fd_log_va ( int loglevel, const char * format, va_list args )
151{
152 (void)pthread_mutex_lock(&fd_log_lock);
153
154 pthread_cleanup_push(fd_cleanup_mutex_silent, &fd_log_lock);
155 fd_logger(loglevel, format, args);
156 pthread_cleanup_pop(0);
157
158 (void)pthread_mutex_unlock(&fd_log_lock);
159}
160
161/* Function to set the thread's friendly name */
162void fd_log_threadname ( const char * name )
163{
164 void * val = NULL;
165
166 TRACE_ENTRY("%p(%s)", name, name?:"/");
167
168 /* First, check if a value is already assigned to the current thread */
169 val = pthread_getspecific(fd_log_thname);
170 if (TRACE_BOOL(ANNOYING)) {
171 if (val) {
172 fd_log_debug("(Thread '%s' renamed to '%s')", (char *)val, name?:"(nil)");
173 } else {
174 fd_log_debug("(Thread %p named '%s')", (void *)pthread_self(), name?:"(nil)");
175 }
176 }
177 if (val != NULL) {
178 free(val);
179 }
180
181 /* Now create the new string */
182 if (name == NULL) {
183 CHECK_POSIX_DO( pthread_setspecific(fd_log_thname, NULL), /* continue */);
184 return;
185 }
186
187 CHECK_MALLOC_DO( val = strdup(name), return );
188
189 CHECK_POSIX_DO( pthread_setspecific(fd_log_thname, val), /* continue */);
190 return;
191}
192
193/* Write time into a buffer */
194char * fd_log_time ( struct timespec * ts, char * buf, size_t len, int incl_date, int incl_ms )
195{
196 int ret;
197 size_t offset = 0;
198 struct timespec tp;
199 struct tm tm;
200
201 /* Get current time */
202 if (!ts) {
203 ret = clock_gettime(CLOCK_REALTIME, &tp);
204 if (ret != 0) {
205 snprintf(buf, len, "%s", strerror(ret));
206 return buf;
207 }
208 ts = &tp;
209 }
210
211 offset += strftime(buf + offset, len - offset, incl_date?"%D,%T":"%T", localtime_r( &ts->tv_sec , &tm ));
212 if (incl_ms)
213 offset += snprintf(buf + offset, len - offset, ".%6.6ld", ts->tv_nsec / 1000);
214
215 return buf;
216}
217
218
219static size_t sys_mempagesz = 0;
220
221static size_t get_mempagesz(void) {
222 if (!sys_mempagesz) {
223 sys_mempagesz = sysconf(_SC_PAGESIZE); /* We alloc buffer by memory pages for efficiency. This can be readjusted if too memory consuming */
224 if (sys_mempagesz <= 0)
225 sys_mempagesz = 256; /* default size if above call failed */
226 }
227 return sys_mempagesz;
228}
229
230
231/* Helper function for fd_*_dump. Prints the format string from 'offset' into '*buf', extends if needed. The location of buf can be updated by this function. */
232char * fd_dump_extend(char ** buf, size_t *len, size_t *offset, const char * format, ... )
233{
234 va_list ap;
235 int to_write;
236 size_t o = 0;
237 size_t mempagesz = get_mempagesz();
238
239 /* we do not TRACE_ENTRY this one on purpose */
240
241 CHECK_PARAMS_DO(buf && len, return NULL);
242
243 if (*buf == NULL) {
244 CHECK_MALLOC_DO(*buf = malloc(mempagesz), return NULL);
245 *len = mempagesz;
246 }
247
248 if (offset)
249 o = *offset;
250
251 va_start(ap, format);
252 to_write = vsnprintf(*buf + o, *len - o, format, ap);
253 va_end(ap);
254
255 if (to_write + o >= *len) {
256 /* There was no room in the buffer, we extend and redo */
257 size_t new_len = (((to_write + o) / mempagesz) + 1) * mempagesz;
258 CHECK_MALLOC_DO(*buf = realloc(*buf, new_len), return NULL);
259 *len = new_len;
260
261 va_start(ap, format);
262 to_write = vsnprintf(*buf + o, *len - o, format, ap);
263 va_end(ap);
264 }
265
266 if (offset)
267 *offset += to_write;
268
269 return *buf;
270}
271
272char * fd_dump_extend_hexdump(char ** buf, size_t *len, size_t *offset, uint8_t *data, size_t datalen, size_t trunc, size_t wrap )
273{
274 int truncated = 0;
275 size_t towrite = 0;
276 size_t o = 0;
277 int i;
278 char * p;
279 size_t mempagesz = get_mempagesz();
280#define TRUNK_MARK "[...]"
281
282 CHECK_PARAMS_DO(buf && len && data, return NULL);
283
284 if (trunc && (datalen > trunc)) {
285 datalen = trunc;
286 truncated = 1;
287 }
288
289 towrite = datalen * 2;
290
291 if (wrap)
292 towrite += datalen / wrap; /* add 1 '\n' every wrap byte */
293
294 if (truncated)
295 towrite += CONSTSTRLEN(TRUNK_MARK);
296
297
298 if (offset)
299 o = *offset;
300
301 if (*buf == NULL) {
302 /* Directly allocate the size we need */
303 *len = (((towrite + o) / mempagesz) + 1 ) * mempagesz;
304 CHECK_MALLOC_DO(*buf = malloc(*len), return NULL);
305 } else if ((towrite + o) >= *len) {
306 /* There is no room in the buffer, we extend and redo */
307 size_t new_len = (((towrite + o) / mempagesz) + 1) * mempagesz;
308 CHECK_MALLOC_DO(*buf = realloc(*buf, new_len), return NULL);
309 *len = new_len;
310 }
311
312 p = *buf + o;
313 for (i = 0; i < datalen; i++) {
314 sprintf(p, "%02hhX", data[i]);
315 p+=2;
316 if ((wrap) && ((i+1) % wrap == 0)) {
317 *p++='\n'; *p ='\0'; /* we want to ensure the buffer is always 0-terminated */
318 }
319 }
320
321 if (truncated)
322 memcpy(p, TRUNK_MARK, CONSTSTRLEN(TRUNK_MARK));
323
324 if (offset)
325 *offset += towrite;
326
327 return *buf;
328}