Skip to content

Commit

Permalink
Write PCAP header after we received a valid UUID (#57)
Browse files Browse the repository at this point in the history
* Write pcap header only after a uuid has been received

This makes sure no memory is allocated to instantiate a gzip.Writer.

* Write header before opening output stream
  • Loading branch information
robertodauria authored Oct 29, 2024
1 parent 0ec4d2a commit 70d4ff1
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions saver/tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ func (t *TCP) start(ctx context.Context, uuidDelay, duration time.Duration) {
func (t *TCP) savePackets(ctx context.Context, uuidDelay, duration time.Duration) {
pw := newPrebufferedWriter()

// Provide a buffer for packets that are captured before a corresponding UUID
// is received. This prevents us from allocating the pcapgo writer before we
// are sure that we are going to need it.
earlyPackets := make([]gopacket.Packet, 0)
zip := gzip.NewWriter(&pw)

// Write PCAP data to the buffer.
Expand Down Expand Up @@ -234,9 +238,8 @@ func (t *TCP) savePackets(ctx context.Context, uuidDelay, duration time.Duration
// overall packet size and then adding 60.
headerLen = len(p.Data()) - len(tl.LayerContents()) - len(tl.LayerPayload()) + 60
}
// Write out the header and the first packet.
w.WriteFileHeader(uint32(headerLen), layers.LinkTypeEthernet)
t.savePacket(w, p, headerLen)
// Store the first packet in the temporary buffer.
earlyPackets = append(earlyPackets, p)

t.state.Set("uuidwait")
// Read packets while waiting for uuid event, or until uuidCtx expires. The
Expand Down Expand Up @@ -273,7 +276,7 @@ uuidloop:
// the buffer.
case p, ok := <-t.pchanRead:
if ok {
t.savePacket(w, p, headerLen)
earlyPackets = append(earlyPackets, p)
}

// Once the UUID arrives, exit the loop.
Expand All @@ -292,6 +295,13 @@ uuidloop:
}

// uuidEvent is now set to a good value.
// Write the header and all the packets we have received so far.
w.WriteFileHeader(uint32(headerLen), layers.LinkTypeEthernet)
for _, earlyPacket := range earlyPackets {
t.savePacket(w, earlyPacket, headerLen)
}
earlyPackets = nil

// Create a file and directory based on the UUID and the time.
t.state.Set("dircreation")
dir, fname := filename(t.dir, uuidEvent)
Expand Down

0 comments on commit 70d4ff1

Please sign in to comment.