blob: 7bbe3079f5b50d5f196622b40228c31aa5ba9c32 [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;
132
133 (void)pthread_mutex_lock(&fd_log_lock);
134
135 pthread_cleanup_push(fd_cleanup_mutex_silent, &fd_log_lock);
136
137 va_start(ap, format);
138 fd_logger(loglevel, format, ap);
139 va_end(ap);
140
141 pthread_cleanup_pop(0);
142
143 (void)pthread_mutex_unlock(&fd_log_lock);
144}
145
146/* Log a debug message */
147void fd_log_va ( int loglevel, const char * format, va_list args )
148{
149 (void)pthread_mutex_lock(&fd_log_lock);
150
151 pthread_cleanup_push(fd_cleanup_mutex_silent, &fd_log_lock);
152 fd_logger(loglevel, format, args);
153 pthread_cleanup_pop(0);
154
155 (void)pthread_mutex_unlock(&fd_log_lock);
156}
157
158/* Function to set the thread's friendly name */
159void fd_log_threadname ( const char * name )
160{
161 void * val = NULL;
162
163 TRACE_ENTRY("%p(%s)", name, name?:"/");
164
165 /* First, check if a value is already assigned to the current thread */
166 val = pthread_getspecific(fd_log_thname);
167 if (TRACE_BOOL(ANNOYING)) {
168 if (val) {
169 fd_log_debug("(Thread '%s' renamed to '%s')", (char *)val, name?:"(nil)");
170 } else {
171 fd_log_debug("(Thread %p named '%s')", (void *)pthread_self(), name?:"(nil)");
172 }
173 }
174 if (val != NULL) {
175 free(val);
176 }
177
178 /* Now create the new string */
179 if (name == NULL) {
180 CHECK_POSIX_DO( pthread_setspecific(fd_log_thname, NULL), /* continue */);
181 return;
182 }
183
184 CHECK_MALLOC_DO( val = strdup(name), return );
185
186 CHECK_POSIX_DO( pthread_setspecific(fd_log_thname, val), /* continue */);
187 return;
188}
189
190/* Write time into a buffer */
191char * fd_log_time ( struct timespec * ts, char * buf, size_t len, int incl_date, int incl_ms )
192{
193 int ret;
194 size_t offset = 0;
195 struct timespec tp;
196 struct tm tm;
197
198 /* Get current time */
199 if (!ts) {
200 ret = clock_gettime(CLOCK_REALTIME, &tp);
201 if (ret != 0) {
202 snprintf(buf, len, "%s", strerror(ret));
203 return buf;
204 }
205 ts = &tp;
206 }
207
208 offset += strftime(buf + offset, len - offset, incl_date?"%D,%T":"%T", localtime_r( &ts->tv_sec , &tm ));
209 if (incl_ms)
210 offset += snprintf(buf + offset, len - offset, ".%6.6ld", ts->tv_nsec / 1000);
211
212 return buf;
213}
214
215
216static size_t sys_mempagesz = 0;
217
218static size_t get_mempagesz(void) {
219 if (!sys_mempagesz) {
220 sys_mempagesz = sysconf(_SC_PAGESIZE); /* We alloc buffer by memory pages for efficiency. This can be readjusted if too memory consuming */
221 if (sys_mempagesz <= 0)
222 sys_mempagesz = 256; /* default size if above call failed */
223 }
224 return sys_mempagesz;
225}
226
227
228/* 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. */
229char * fd_dump_extend(char ** buf, size_t *len, size_t *offset, const char * format, ... )
230{
231 va_list ap;
232 int to_write;
233 size_t o = 0;
234 size_t mempagesz = get_mempagesz();
235
236 /* we do not TRACE_ENTRY this one on purpose */
237
238 CHECK_PARAMS_DO(buf && len, return NULL);
239
240 if (*buf == NULL) {
241 CHECK_MALLOC_DO(*buf = malloc(mempagesz), return NULL);
242 *len = mempagesz;
243 }
244
245 if (offset)
246 o = *offset;
247
248 va_start(ap, format);
249 to_write = vsnprintf(*buf + o, *len - o, format, ap);
250 va_end(ap);
251
252 if (to_write + o >= *len) {
253 /* There was no room in the buffer, we extend and redo */
254 size_t new_len = (((to_write + o) / mempagesz) + 1) * mempagesz;
255 CHECK_MALLOC_DO(*buf = realloc(*buf, new_len), return NULL);
256 *len = new_len;
257
258 va_start(ap, format);
259 to_write = vsnprintf(*buf + o, *len - o, format, ap);
260 va_end(ap);
261 }
262
263 if (offset)
264 *offset += to_write;
265
266 return *buf;
267}
268
269char * fd_dump_extend_hexdump(char ** buf, size_t *len, size_t *offset, uint8_t *data, size_t datalen, size_t trunc, size_t wrap )
270{
271 int truncated = 0;
272 size_t towrite = 0;
273 size_t o = 0;
274 int i;
275 char * p;
276 size_t mempagesz = get_mempagesz();
277#define TRUNK_MARK "[...]"
278
279 CHECK_PARAMS_DO(buf && len && data, return NULL);
280
281 if (trunc && (datalen > trunc)) {
282 datalen = trunc;
283 truncated = 1;
284 }
285
286 towrite = datalen * 2;
287
288 if (wrap)
289 towrite += datalen / wrap; /* add 1 '\n' every wrap byte */
290
291 if (truncated)
292 towrite += CONSTSTRLEN(TRUNK_MARK);
293
294
295 if (offset)
296 o = *offset;
297
298 if (*buf == NULL) {
299 /* Directly allocate the size we need */
300 *len = (((towrite + o) / mempagesz) + 1 ) * mempagesz;
301 CHECK_MALLOC_DO(*buf = malloc(*len), return NULL);
302 } else if ((towrite + o) >= *len) {
303 /* There is no room in the buffer, we extend and redo */
304 size_t new_len = (((towrite + o) / mempagesz) + 1) * mempagesz;
305 CHECK_MALLOC_DO(*buf = realloc(*buf, new_len), return NULL);
306 *len = new_len;
307 }
308
309 p = *buf + o;
310 for (i = 0; i < datalen; i++) {
311 sprintf(p, "%02hhX", data[i]);
312 p+=2;
313 if ((wrap) && ((i+1) % wrap == 0)) {
314 *p++='\n'; *p ='\0'; /* we want to ensure the buffer is always 0-terminated */
315 }
316 }
317
318 if (truncated)
319 memcpy(p, TRUNK_MARK, CONSTSTRLEN(TRUNK_MARK));
320
321 if (offset)
322 *offset += towrite;
323
324 return *buf;
325}