1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.pcap;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.util.internal.logging.InternalLogger;
20 import io.netty.util.internal.logging.InternalLoggerFactory;
21
22 import java.io.Closeable;
23 import java.io.IOException;
24 import java.io.OutputStream;
25
26 final class PcapWriter implements Closeable {
27
28
29
30
31 private static final InternalLogger logger = InternalLoggerFactory.getInstance(PcapWriter.class);
32
33 private final PcapWriteHandler pcapWriteHandler;
34
35
36
37
38 private final OutputStream outputStream;
39
40
41
42
43
44
45 PcapWriter(PcapWriteHandler pcapWriteHandler) throws IOException {
46 this.pcapWriteHandler = pcapWriteHandler;
47 outputStream = pcapWriteHandler.outputStream();
48
49
50 if (!pcapWriteHandler.sharedOutputStream()) {
51 PcapHeaders.writeGlobalHeader(pcapWriteHandler.outputStream());
52 }
53 }
54
55
56
57
58
59
60
61
62 void writePacket(ByteBuf packetHeaderBuf, ByteBuf packet) throws IOException {
63 if (pcapWriteHandler.state() == State.CLOSED) {
64 logger.debug("Pcap Write attempted on closed PcapWriter");
65 }
66
67 long timestamp = System.currentTimeMillis();
68
69 PcapHeaders.writePacketHeader(
70 packetHeaderBuf,
71 (int) (timestamp / 1000L),
72 (int) (timestamp % 1000L * 1000L),
73 packet.readableBytes(),
74 packet.readableBytes()
75 );
76
77 if (pcapWriteHandler.sharedOutputStream()) {
78 synchronized (outputStream) {
79 packetHeaderBuf.readBytes(outputStream, packetHeaderBuf.readableBytes());
80 packet.readBytes(outputStream, packet.readableBytes());
81 }
82 } else {
83 packetHeaderBuf.readBytes(outputStream, packetHeaderBuf.readableBytes());
84 packet.readBytes(outputStream, packet.readableBytes());
85 }
86 }
87
88 @Override
89 public String toString() {
90 return "PcapWriter{" +
91 "outputStream=" + outputStream +
92 '}';
93 }
94
95 @Override
96 public void close() throws IOException {
97 if (pcapWriteHandler.state() == State.CLOSED) {
98 logger.debug("PcapWriter is already closed");
99 } else {
100 if (pcapWriteHandler.sharedOutputStream()) {
101 synchronized (outputStream) {
102 outputStream.flush();
103 }
104 } else {
105 outputStream.flush();
106 outputStream.close();
107 }
108 pcapWriteHandler.markClosed();
109 logger.debug("PcapWriter is now closed");
110 }
111 }
112 }