github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/tcpbits/tcp.go (about)

     1  // Copyright 2023 The Inspektor Gadget authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tcpbits
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  )
    21  
    22  // Names of the TCP states without the TCP_ prefix
    23  // from https://github.com/torvalds/linux/blob/v6.2/include/net/tcp_states.h#L12-L27
    24  var tcpstates = map[uint8]string{
    25  	1:  "ESTABLISHED",
    26  	2:  "SYN_SENT",
    27  	3:  "SYN_RECV",
    28  	4:  "FIN_WAIT1",
    29  	5:  "FIN_WAIT2",
    30  	6:  "TIME_WAIT",
    31  	7:  "CLOSE",
    32  	8:  "CLOSE_WAIT",
    33  	9:  "LAST_ACK",
    34  	10: "LISTEN",
    35  	11: "CLOSING",
    36  	12: "NEW_SYN_RECV",
    37  }
    38  
    39  // TCPState converts the state of a TCP connection to its name without the TCP_ prefix
    40  func TCPState(tcpstate uint8) string {
    41  	if ret, ok := tcpstates[tcpstate]; ok {
    42  		return ret
    43  	}
    44  	return fmt.Sprintf("UNKNOWN#%d", tcpstate)
    45  }
    46  
    47  // from https://github.com/torvalds/linux/blob/v6.2/include/net/tcp.h#L840-L847
    48  const (
    49  	tcphdrFin = 0x01
    50  	tcphdrSyn = 0x02
    51  	tcphdrRst = 0x04
    52  	tcphdrPsh = 0x08
    53  	tcphdrAck = 0x10
    54  	tcphdrUrg = 0x20
    55  	tcphdrEce = 0x40
    56  	tcphdrCwr = 0x80
    57  )
    58  
    59  // TCPFlags converts the flags of a TCP packet to a string
    60  func TCPFlags(flags uint8) string {
    61  	tcpFlagNames := []struct {
    62  		flag uint8
    63  		name string
    64  	}{
    65  		{tcphdrFin, "FIN"},
    66  		{tcphdrSyn, "SYN"},
    67  		{tcphdrRst, "RST"},
    68  		{tcphdrPsh, "PSH"},
    69  		{tcphdrAck, "ACK"},
    70  		{tcphdrUrg, "URG"},
    71  		{tcphdrEce, "ECE"},
    72  		{tcphdrCwr, "CWR"},
    73  	}
    74  
    75  	arr := []string{}
    76  	for _, v := range tcpFlagNames {
    77  		if flags&v.flag != 0 {
    78  			arr = append(arr, v.name)
    79  		}
    80  	}
    81  
    82  	return strings.Join(arr, "|")
    83  }