github.com/pawelgaczynski/gain@v0.4.0-alpha.0.20230821120126-41f1e60a18da/pkg/socket/sock_linux.go (about)

     1  // Copyright (c) 2017 Ma Weiwei, Max Riveiro
     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 socket
    16  
    17  import (
    18  	"bufio"
    19  	"os"
    20  	"strconv"
    21  	"strings"
    22  
    23  	"golang.org/x/sys/unix"
    24  )
    25  
    26  const (
    27  	maxUint16Value = 1<<16 - 1
    28  )
    29  
    30  func maxListenerBacklog() int {
    31  	fd, err := os.Open("/proc/sys/net/core/somaxconn")
    32  	if err != nil {
    33  		return unix.SOMAXCONN
    34  	}
    35  	defer fd.Close()
    36  
    37  	rd := bufio.NewReader(fd)
    38  
    39  	line, err := rd.ReadString('\n')
    40  	if err != nil {
    41  		return unix.SOMAXCONN
    42  	}
    43  
    44  	f := strings.Fields(line)
    45  	if len(f) < 1 {
    46  		return unix.SOMAXCONN
    47  	}
    48  
    49  	value, err := strconv.Atoi(f[0])
    50  	if err != nil || value == 0 {
    51  		return unix.SOMAXCONN
    52  	}
    53  
    54  	// Linux stores the backlog in a uint16.
    55  	// Truncate number to avoid wrapping.
    56  	// See issue 5030.
    57  	if value > maxUint16Value {
    58  		value = maxUint16Value
    59  	}
    60  
    61  	return value
    62  }