diff --git a/include/ipmitool/helper.h b/include/ipmitool/helper.h index b7ad628..41a3fa5 100644 --- a/include/ipmitool/helper.h +++ b/include/ipmitool/helper.h @@ -97,7 +97,9 @@ void print_valstr_2col(const struct valstr * vs, const char * title, int logleve uint16_t buf2short(uint8_t * buf); uint32_t buf2long(uint8_t * buf); -const char * buf2str(uint8_t * buf, int len); +#define BUF2STR_MAXIMUM_OUTPUT_SIZE (3*1024 + 1) +const char * buf2str_extended(const uint8_t *buf, int len, const char *sep); +const char * buf2str(const uint8_t *buf, int len); void printbuf(const uint8_t * buf, int len, const char * desc); uint8_t ipmi_csum(uint8_t * d, int s); FILE * ipmi_open_file(const char * file, int rw); diff --git a/lib/helper.c b/lib/helper.c index 022a9c9..04a5e0d 100644 --- a/lib/helper.c +++ b/lib/helper.c @@ -79,24 +79,67 @@ uint16_t buf2short(uint8_t * buf) return (uint16_t)(buf[1] << 8 | buf[0]); } -const char * buf2str(uint8_t * buf, int len) +/* buf2str_extended - convert sequence of bytes to hexadecimal string with + * optional separator + * + * @param buf - data to convert + * @param len - size of data + * @param sep - optional separator (can be NULL) + * + * @returns buf representation in hex, possibly truncated to fit + * allocated static memory + */ +const char * +buf2str_extended(const uint8_t *buf, int len, const char *sep) { - static char str[2049]; + static char str[BUF2STR_MAXIMUM_OUTPUT_SIZE]; + char *cur; int i; + int sz; + int left; + int sep_len; - if (len <= 0 || len > 1024) - return NULL; - - memset(str, 0, 2049); - - for (i=0; i"); + return (const char *)str; + } + cur = str; + left = sizeof(str); + if (sep) { + sep_len = strlen(sep); + } else { + sep_len = 0; + } + for (i = 0; i < len; i++) { + /* may return more than 2, depending on locale */ + sz = snprintf(cur, left, "%2.2x", buf[i]); + if (sz >= left) { + /* buffer overflow, truncate */ + break; + } + cur += sz; + left -= sz; + /* do not write separator after last byte */ + if (sep && i != (len - 1)) { + if (sep_len >= left) { + break; + } + strncpy(cur, sep, left - sz); + cur += sep_len; + left -= sep_len; + } + } + *cur = '\0'; return (const char *)str; } +const char * +buf2str(const uint8_t *buf, int len) +{ + return buf2str_extended(buf, len, NULL); +} + void printbuf(const uint8_t * buf, int len, const char * desc) { int i;