Move retransmission checks to Conversation class.
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Conversation.java
1 package edu.uci.iotproject;
2
3 import org.pcap4j.core.PcapPacket;
4 import org.pcap4j.packet.IpV4Packet;
5 import org.pcap4j.packet.TcpPacket;
6
7 import java.util.*;
8
9 /**
10  * Models a (TCP) conversation/connection/session/flow (packet's belonging to the same session between a client and a
11  * server).
12  * Holds a list of {@link PcapPacket}s identified as pertaining to the flow. Note that this list is <em>not</em>
13  * considered when determining equality of two {@code Conversation} instances in order to allow for a
14  * {@code Conversation} to function as a key in data structures such as {@link java.util.Map} and {@link java.util.Set}.
15  * See {@link #equals(Object)} for the definition of equality.
16  *
17  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
18  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
19  */
20 public class Conversation {
21
22     /* Begin instance properties */
23     /**
24      * The IP of the host that is considered the client (i.e. the host that initiates the conversation)
25      * in this conversation.
26      */
27     private final String mClientIp;
28
29     /**
30      * The port number used by the host that is considered the client in this conversation.
31      */
32     private final int mClientPort;
33
34     /**
35      * The IP of the host that is considered the server (i.e. is the responder) in this conversation.
36      */
37     private final String mServerIp;
38
39     /**
40      * The port number used by the server in this conversation.
41      */
42     private final int mServerPort;
43
44     /**
45      * The list of packets pertaining to this conversation.
46      */
47     private final List<PcapPacket> mPackets;
48
49     /**
50      * Contains the sequence numbers seen so far for this {@code Conversation}.
51      * Used for filtering out retransmissions.
52      */
53     private final Set<Integer> mSeqNumbers;
54     /* End instance properties */
55
56     /**
57      * Constructs a new {@code Conversation}.
58      * @param clientIp The IP of the host that is considered the client (i.e. the host that initiates the conversation)
59      *                 in the conversation.
60      * @param clientPort The port number used by the client for the conversation.
61      * @param serverIp The IP of the host that is considered the server (i.e. is the responder) in the conversation.
62      * @param serverPort The port number used by the server for the conversation.
63      */
64     public Conversation(String clientIp, int clientPort, String serverIp, int serverPort) {
65         this.mClientIp = clientIp;
66         this.mClientPort = clientPort;
67         this.mServerIp = serverIp;
68         this.mServerPort = serverPort;
69         this.mPackets = new ArrayList<>();
70         this.mSeqNumbers = new HashSet<>();
71     }
72
73     /**
74      * Add a packet to the list of packets associated with this conversation.
75      * @param packet The packet that is to be added to (associated with) this conversation.
76      * @param ignoreRetransmissions Boolean value indicating if retransmissions should be ignored.
77      *                              If set to {@code true}, {@code packet} will <em>not</em> be added to the
78      *                              internal list of packets pertaining to this {@code Conversation}
79      *                              <em>iff</em> the sequence number of {@code packet} was already
80      *                              seen in a previous packet.
81      */
82     public void addPacket(PcapPacket packet, boolean ignoreRetransmissions) {
83         // Apply precondition to preserve class invariant: all packets in mPackets must match the 4 tuple that
84         // defines the conversation.
85         // ==== Precondition: verify that packet does indeed pertain to conversation. ====
86         IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
87         // For now we only support TCP flows.
88         TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
89         String ipSrc = ipPacket.getHeader().getSrcAddr().getHostAddress();
90         String ipDst = ipPacket.getHeader().getDstAddr().getHostAddress();
91         int srcPort = tcpPacket.getHeader().getSrcPort().valueAsInt();
92         int dstPort = tcpPacket.getHeader().getDstPort().valueAsInt();
93         String clientIp, serverIp;
94         int clientPort, serverPort;
95         if (ipSrc.equals(mClientIp)) {
96             clientIp = ipSrc;
97             clientPort = srcPort;
98             serverIp = ipDst;
99             serverPort = dstPort;
100         } else {
101             clientIp = ipDst;
102             clientPort = dstPort;
103             serverIp = ipSrc;
104             serverPort = srcPort;
105         }
106         if (!(clientIp.equals(mClientIp) && clientPort == mClientPort &&
107                 serverIp.equals(mServerIp) && serverPort == mServerPort)) {
108             throw new IllegalArgumentException(
109                     String.format("Attempt to add packet that does not pertain to %s",
110                             Conversation.class.getSimpleName()));
111         }
112         // ================================================================================
113         int seqNo = tcpPacket.getHeader().getSequenceNumber();
114         if (ignoreRetransmissions && mSeqNumbers.contains(seqNo)) {
115             // Packet is a retransmission. Ignore it.
116             return;
117         }
118         // Update set of sequence numbers seen so far with sequence number of new packet.
119         mSeqNumbers.add(seqNo);
120         // Finally add packet to list of packets pertaining to this conversation.
121         mPackets.add(packet);
122     }
123
124     /**
125      * Get a list of packets pertaining to this {@code Conversation}.
126      * The returned list is a read-only list.
127      * @return the list of packets pertaining to this {@code Conversation}.
128      */
129     public List<PcapPacket> getPackets() {
130         // Return read-only view to prevent external code from manipulating internal state (preserve invariant).
131         return Collections.unmodifiableList(mPackets);
132     }
133
134     // =========================================================================================================
135     // We simply reuse equals and hashCode methods of String.class to be able to use this class as a key
136     // in a Map.
137
138     /**
139      * <em>Note:</em> currently, equality is determined based on pairwise equality of the elements of the four tuple
140      * ({@link #mClientIp}, {@link #mClientPort}, {@link #mServerIp}, {@link #mServerPort}) for {@code this} and
141      * {@code obj}.
142      * @param obj The object to test for equality with {@code this}.
143      * @return {@code true} if {@code obj} is considered equal to {@code this} based on the definition of equality given above.
144      */
145     @Override
146     public boolean equals(Object obj) {
147         return obj instanceof Conversation && this.toString().equals(obj.toString());
148     }
149
150     @Override
151     public int hashCode() {
152         return toString().hashCode();
153     }
154     // =========================================================================================================
155
156     @Override
157     public String toString() {
158         return String.format("%s:%d %s:%d", mClientIp, mClientPort, mServerIp, mServerPort);
159     }
160 }