diff --git a/CMakeLists.txt b/CMakeLists.txt index 84a507fd8..6f9af1f6e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -242,6 +242,7 @@ set(SRCS src/fmt/regex.c src/fmt/str.c src/fmt/str_error.c + src/fmt/text2pcap.c src/fmt/time.c src/fmt/unicode.c diff --git a/include/re_fmt.h b/include/re_fmt.h index af4cd1841..245e10218 100644 --- a/include/re_fmt.h +++ b/include/re_fmt.h @@ -202,3 +202,13 @@ void fmt_param_apply(const struct pl *pl, fmt_param_h *ph, void *arg); int utf8_encode(struct re_printf *pf, const char *str); int utf8_decode(struct re_printf *pf, const struct pl *pl); size_t utf8_byteseq(char u[4], unsigned cp); + + +/* text2pcap */ +struct re_text2pcap { + bool in; + const struct mbuf *mb; + char *id; +}; + +int re_text2pcap(struct re_printf *pf, struct re_text2pcap *pcap); diff --git a/src/fmt/text2pcap.c b/src/fmt/text2pcap.c new file mode 100644 index 000000000..a3a4708ce --- /dev/null +++ b/src/fmt/text2pcap.c @@ -0,0 +1,37 @@ +#include +#include + +#include +#include +#include + + +int re_text2pcap(struct re_printf *pf, struct re_text2pcap *pcap) +{ + struct timeval tv; + time_t t = time(NULL); + struct tm *tm = localtime(&t); + char ts[10] = {0}; + + if (!pcap) + return EINVAL; + + uint8_t *buf = mbuf_buf(pcap->mb); + if (!buf) + return EINVAL; + + gettimeofday(&tv, NULL); + strftime(ts, sizeof(ts), "%H:%M:%S", tm); + + re_hprintf(pf, "%s %s.%06ld 000000", pcap->in ? "I" : "O", ts, + tv.tv_usec); + + size_t sz = mbuf_get_left(pcap->mb); + for (size_t i = 0; i < sz; i++) { + re_hprintf(pf, " %02x", buf[i]); + } + + re_hprintf(pf, " %s\r\n", pcap->id); + + return 0; +} diff --git a/test/fmt.c b/test/fmt.c index 7b82deebb..33b7e89d3 100644 --- a/test/fmt.c +++ b/test/fmt.c @@ -1158,3 +1158,30 @@ int test_fmt_hexdump(void) return 0; } + + +int test_text2pcap(void) +{ + char test[64]; + struct mbuf *mb; + int err = 0; + + mb = mbuf_alloc(1); + if (!mb) + return ENOMEM; + + mbuf_write_u8(mb, 42); + mbuf_write_u8(mb, 23); + + mbuf_set_pos(mb, 0); + + struct re_text2pcap pcap = {.id = "test", .in = true, .mb = mb}; + + int ret = re_snprintf(test, sizeof(test), "%H", re_text2pcap, &pcap); + + TEST_EQUALS(37, ret); + +out: + mem_deref(mb); + return err; +} diff --git a/test/test.c b/test/test.c index 261c1d96f..6bfc024f9 100644 --- a/test/test.c +++ b/test/test.c @@ -214,6 +214,7 @@ static const struct test tests[] = { TEST(test_sys_getenv), TEST(test_tcp), TEST(test_telev), + TEST(test_text2pcap), #ifdef USE_TLS TEST(test_tls), TEST(test_tls_ec), diff --git a/test/test.h b/test/test.h index 68a681e2c..cee4a3401 100644 --- a/test/test.h +++ b/test/test.h @@ -330,6 +330,7 @@ int test_sys_fs_fopen(void); int test_sys_getenv(void); int test_tcp(void); int test_telev(void); +int test_text2pcap(void); int test_thread(void); int test_thread_cnd_timedwait(void); int test_tmr_jiffies(void);