github.com/network-quality/goresponsiveness@v0.0.0-20240129151524-343954285090/l4s/unix.go (about)

     1  //go:build linux
     2  // +build linux
     3  
     4  /*
     5   * This file is part of Go Responsiveness.
     6   *
     7   * Go Responsiveness is free software: you can redistribute it and/or modify it under
     8   * the terms of the GNU General Public License as published by the Free Software Foundation,
     9   * either version 2 of the License, or (at your option) any later version.
    10   * Go Responsiveness is distributed in the hope that it will be useful, but WITHOUT ANY
    11   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    12   * PARTICULAR PURPOSE. See the GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License along
    15   * with Go Responsiveness. If not, see <https://www.gnu.org/licenses/>.
    16   */
    17  
    18  package l4s
    19  
    20  import (
    21  	"crypto/tls"
    22  	"fmt"
    23  	"net"
    24  	"syscall"
    25  )
    26  
    27  func SetL4S(conn net.Conn, algorithm *string) error {
    28  	if algorithm == nil {
    29  		panic("Attempting to set L4S congestion control without specifying a congestion control algorithm.")
    30  	}
    31  	tlsConn, ok := conn.(*tls.Conn)
    32  	if !ok {
    33  		return fmt.Errorf("when setting L4S congestion control algorithm, outermost connection is not a TLS connection")
    34  	}
    35  	tcpConn, ok := tlsConn.NetConn().(*net.TCPConn)
    36  	if !ok {
    37  		return fmt.Errorf("when setting L4S congestion control algorithm, could not get the underlying IP connection")
    38  	}
    39  	rawConn, err := tcpConn.SyscallConn()
    40  	if err != nil {
    41  		return fmt.Errorf("when setting L4S congestion control algorithm, could not get the underlying raw connection")
    42  	}
    43  	var sockoptError error = nil
    44  	rawConn.Control(func(fd uintptr) {
    45  		sockoptError = syscall.SetsockoptString(int(fd), syscall.IPPROTO_TCP, syscall.TCP_CONGESTION, *algorithm)
    46  	})
    47  	if sockoptError != nil {
    48  		return fmt.Errorf("when setting L4S congestion control algorithm, could not set the algorithm to %v: %v", *algorithm, sockoptError.Error())
    49  	}
    50  	return nil
    51  }