diff --git a/picoquic/picoquic_utils.h b/picoquic/picoquic_utils.h index c8a5c21e5..d082e27b2 100644 --- a/picoquic/picoquic_utils.h +++ b/picoquic/picoquic_utils.h @@ -65,6 +65,7 @@ extern "C" { void debug_set_stream(FILE *F); +void debug_set_callback(void (*cb)(const char *msg, void *argp), void *argp); void debug_printf(const char* fmt, ...); void debug_printf_push_stream(FILE* f); void debug_printf_pop_stream(void); diff --git a/picoquic/util.c b/picoquic/util.c index 7aa602f6e..95b369d04 100644 --- a/picoquic/util.c +++ b/picoquic/util.c @@ -111,35 +111,71 @@ char* picoquic_strip_endofline(char* buf, size_t bufmax, char const* line) } static FILE* debug_out = NULL; +void (*debug_callback)(const char *msg, void *arg) = NULL; +void *debug_callback_argp = NULL; static int debug_suspended = 0; void debug_set_stream(FILE *F) { debug_out = F; + debug_callback = NULL; + debug_callback_argp = NULL; +} + +void debug_set_callback(void (*cb)(const char *msg, void *argp), void *argp) +{ + debug_callback = cb; + debug_callback_argp = argp; + debug_out = NULL; } void debug_printf(const char* fmt, ...) { - if (debug_suspended == 0 && debug_out != NULL) { - va_list args; - va_start(args, fmt); - vfprintf(debug_out, fmt, args); - va_end(args); + if (debug_suspended == 0 && (debug_out != NULL || debug_callback != NULL)) { + if (debug_out) { + va_list args; + va_start(args, fmt); + vfprintf(debug_out, fmt, args); + va_end(args); + } else { + char message[1024]; + size_t message_length; + va_list args; + va_start(args, fmt); + vsnprintf(message, sizeof(message), fmt, args); + va_end(args); + message_length = strnlen(message, sizeof(message)); + if (message_length > 0) { + // Strip any trailing newline + if (message[message_length - 1] == '\n') { + message[message_length - 1] = '\0'; + } + } + debug_callback(message, debug_callback_argp); + } } } void debug_dump(const void * x, int len) { - if (debug_suspended == 0 && debug_out != NULL) { + if (debug_suspended == 0 && (debug_out != NULL || debug_callback != NULL)) { + char msg[64]; uint8_t * bytes = (uint8_t *)x; for (int i = 0; i < len;) { - fprintf(debug_out, "%04x: ", (int)i); + int mlen = 0; + snprintf(msg, sizeof(msg), "%04x: ", (int) i); + mlen = strnlen(msg, sizeof(msg)); for (int j = 0; j < 16 && i < len; j++, i++) { - fprintf(debug_out, "%02x ", bytes[i]); + snprintf(msg + mlen, sizeof(msg) - mlen, "%02x ", bytes[i]); + mlen = strnlen(msg, sizeof(msg)); + } + if (debug_out) { + fprintf(debug_out, "%s\n", msg); + } else { + debug_callback(msg, debug_callback_argp); } - fprintf(debug_out, "\n"); } } }