View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    * https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.pcap;
17  
18  import io.netty.buffer.ByteBuf;
19  
20  final class TCPPacket {
21  
22      /**
23       * Data Offset + Reserved Bits.
24       */
25      private static final short OFFSET = 0x5000;
26  
27      private TCPPacket() {
28          // Prevent outside initialization
29      }
30  
31      /**
32       * Write TCP Packet
33       *
34       * @param byteBuf ByteBuf where Packet data will be set
35       * @param payload Payload of this Packet
36       * @param srcPort Source Port
37       * @param dstPort Destination Port
38       */
39      static void writePacket(ByteBuf byteBuf, ByteBuf payload, int segmentNumber, int ackNumber, int srcPort,
40                              int dstPort, TCPFlag... tcpFlags) {
41  
42          byteBuf.writeShort(srcPort);     // Source Port
43          byteBuf.writeShort(dstPort);     // Destination Port
44          byteBuf.writeInt(segmentNumber); // Segment Number
45          byteBuf.writeInt(ackNumber);     // Acknowledgment Number
46          byteBuf.writeShort(OFFSET | TCPFlag.getFlag(tcpFlags)); // Flags
47          byteBuf.writeShort(65535);       // Window Size
48          byteBuf.writeShort(0x0001);      // Checksum
49          byteBuf.writeShort(0);           // Urgent Pointer
50  
51          if (payload != null) {
52              byteBuf.writeBytes(payload); //  Payload of Data
53          }
54      }
55  
56      enum TCPFlag {
57          FIN(1),
58          SYN(1 << 1),
59          RST(1 << 2),
60          PSH(1 << 3),
61          ACK(1 << 4),
62          URG(1 << 5),
63          ECE(1 << 6),
64          CWR(1 << 7);
65  
66          private final int value;
67  
68          TCPFlag(int value) {
69              this.value = value;
70          }
71  
72          static int getFlag(TCPFlag... tcpFlags) {
73              int flags = 0;
74  
75              for (TCPFlag tcpFlag : tcpFlags) {
76                  flags |= tcpFlag.value;
77              }
78  
79              return  flags;
80          }
81      }
82  }