Skip to content

Commit

Permalink
pcapfile: make sure nanosecond timestamp resolution is retained
Browse files Browse the repository at this point in the history
Previously, we were using trace_get_timeval() to get the
timestamp for a packet that is to be written, but obviously
this timestamp is only at microsecond resolution. Changed to
use trace_get_timespec() instead and the resulting nanosecs
are only then divided by 1000 if the output trace is going
to also use microsecond resolution.
  • Loading branch information
salcock committed Jun 18, 2024
1 parent 72c6882 commit 24b5363
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions lib/format_pcapfile.c
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,12 @@ static int pcapfile_read_packet(libtrace_t *libtrace, libtrace_packet_t *packet)
return sizeof(libtrace_pcapfile_pkt_hdr_t) + bytes_to_read;
}

#define IS_PCAP_NANOSECS(packet) \
(packet->trace && packet->trace->format && ( \
packet->trace->format->type == TRACE_FORMAT_PCAPFILE) && \
DATA(packet->trace) && \
trace_in_nanoseconds(&DATA(packet->trace)->header))

static int pcapfile_write_packet(libtrace_out_t *out, libtrace_packet_t *packet)
{

Expand All @@ -479,7 +485,7 @@ static int pcapfile_write_packet(libtrace_out_t *out, libtrace_packet_t *packet)
}

struct libtrace_pcapfile_pkt_hdr_t hdr;
struct timeval tv = trace_get_timeval(packet);
struct timespec ts = trace_get_timespec(packet);
int numbytes;
int ret;
void *ptr;
Expand Down Expand Up @@ -516,9 +522,8 @@ static int pcapfile_write_packet(libtrace_out_t *out, libtrace_packet_t *packet)
return -1;
}

if (packet->trace && packet->trace->format && (
packet->trace->format->type == TRACE_FORMAT_PCAPFILE) &&
trace_in_nanoseconds(&DATA(packet->trace)->header)) {

if (IS_PCAP_NANOSECS(packet)) {
pcaphdr.magic_number = MAGIC2;
} else {
pcaphdr.magic_number = MAGIC1;
Expand All @@ -533,8 +538,13 @@ static int pcapfile_write_packet(libtrace_out_t *out, libtrace_packet_t *packet)
wandio_wwrite(DATAOUT(out)->file, &pcaphdr, sizeof(pcaphdr));
}

hdr.ts_sec = (uint32_t)tv.tv_sec;
hdr.ts_usec = (uint32_t)tv.tv_usec;
hdr.ts_sec = (uint32_t)ts.tv_sec;
if (IS_PCAP_NANOSECS(packet)) {
hdr.ts_usec = (uint32_t)ts.tv_nsec;
} else {
hdr.ts_usec = (uint32_t)ts.tv_nsec / 1000;
}

hdr.caplen = trace_get_capture_length(packet);
if (hdr.caplen >= LIBTRACE_PACKET_BUFSIZE) {
trace_set_err_out(out, TRACE_ERR_BAD_PACKET,
Expand Down

0 comments on commit 24b5363

Please sign in to comment.