1package tcp
2
3import (
4	"os"
5	"strings"
6
7	"github.com/libp2p/go-reuseport"
8)
9
10// envReuseport is the env variable name used to turn off reuse port.
11// It default to true.
12const envReuseport = "LIBP2P_TCP_REUSEPORT"
13const deprecatedEnvReuseport = "IPFS_REUSEPORT"
14
15// envReuseportVal stores the value of envReuseport. defaults to true.
16var envReuseportVal = true
17
18func init() {
19	v := strings.ToLower(os.Getenv(envReuseport))
20	if v == "false" || v == "f" || v == "0" {
21		envReuseportVal = false
22		log.Infof("REUSEPORT disabled (LIBP2P_TCP_REUSEPORT=%s)", v)
23	}
24	v, exist := os.LookupEnv(deprecatedEnvReuseport)
25	if exist {
26		log.Warning("IPFS_REUSEPORT is deprecated, use LIBP2P_TCP_REUSEPORT instead")
27		if v == "false" || v == "f" || v == "0" {
28			envReuseportVal = false
29			log.Infof("REUSEPORT disabled (IPFS_REUSEPORT=%s)", v)
30		}
31	}
32}
33
34// reuseportIsAvailable returns whether reuseport is available to be used. This
35// is here because we want to be able to turn reuseport on and off selectively.
36// For now we use an ENV variable, as this handles our pressing need:
37//
38//   LIBP2P_TCP_REUSEPORT=false ipfs daemon
39//
40// If this becomes a sought after feature, we could add this to the config.
41// In the end, reuseport is a stop-gap.
42func ReuseportIsAvailable() bool {
43	return envReuseportVal && reuseport.Available()
44}
45