Skip to content

Commit

Permalink
Fix pcap's timeout for Unix.
Browse files Browse the repository at this point in the history
For PCAP, we should:

1) if we have a timeout, return an error when that timeout has been hit
and no packet received.
2) if we have a negative timeout, loop forever waiting for a packet,
checking every -timeout.
  • Loading branch information
gconnell committed Sep 12, 2017
1 parent de45615 commit 92028c3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
19 changes: 12 additions & 7 deletions pcap/pcap.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,8 @@ func (p *Handle) getNextBufPtrLocked(ci *gopacket.CaptureInfo) error {
// try to read a packet if one is immediately available
result := NextError(C.pcap_next_ex(p.cptr, &p.pkthdr, &p.bufptr))

if result == NextErrorOk {
switch result {
case NextErrorOk:
// got a packet, set capture info and return
sec := int64(p.pkthdr.ts.tv_sec)
// convert micros to nanos
Expand All @@ -369,16 +370,20 @@ func (p *Handle) getNextBufPtrLocked(ci *gopacket.CaptureInfo) error {
ci.InterfaceIndex = p.deviceIndex

return nil
} else if result == NextErrorNoMorePackets {
case NextErrorNoMorePackets:
// no more packets, return EOF rather than libpcap-specific error
return io.EOF
} else if result != NextErrorTimeoutExpired {
// we got a non-timeout error
case NextErrorTimeoutExpired:
// Negative timeout means to loop forever, instead of actually returning
// the timeout error.
if p.timeout < 0 {
// must have had a timeout... wait before trying again
p.waitForPacket()
continue
}
default:
return result
}

// must have had a timeout... wait before trying again
p.waitForPacket()
}

// stop must be set
Expand Down
5 changes: 0 additions & 5 deletions pcap/pcap_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,6 @@ func (p *Handle) openLive() error {

// waitForPacket waits for a packet or for the timeout to expire.
func (p *Handle) waitForPacket() {
if p.timeout == BlockForever {
C.pcap_wait(p.cptr, 0)
return
}

// need to wait less than the read timeout according to pcap documentation.
// timeoutMillis rounds up to at least one millisecond so we can safely
// subtract up to a millisecond.
Expand Down

0 comments on commit 92028c3

Please sign in to comment.