aboutsummaryrefslogtreecommitdiff
path: root/src/net/tcpconn_keepalive_posix_test.go
blob: f897e226bfcb47a89ad05a45e78d7931b396b253 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || windows

package net

import (
	"syscall"
	"testing"
	"time"
)

func getCurrentKeepAliveSettings(fd fdType) (cfg KeepAliveConfig, err error) {
	tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
	if err != nil {
		return
	}
	tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
	if err != nil {
		return
	}
	tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
	if err != nil {
		return
	}
	tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
	if err != nil {
		return
	}
	cfg = KeepAliveConfig{
		Enable:   tcpKeepAlive != 0,
		Idle:     time.Duration(tcpKeepAliveIdle) * time.Second,
		Interval: time.Duration(tcpKeepAliveInterval) * time.Second,
		Count:    tcpKeepAliveCount,
	}
	return
}

func verifyKeepAliveSettings(t *testing.T, fd fdType, oldCfg, cfg KeepAliveConfig) {
	if cfg.Idle == 0 {
		cfg.Idle = defaultTCPKeepAliveIdle
	}
	if cfg.Interval == 0 {
		cfg.Interval = defaultTCPKeepAliveInterval
	}
	if cfg.Count == 0 {
		cfg.Count = defaultTCPKeepAliveCount
	}
	if cfg.Idle == -1 {
		cfg.Idle = oldCfg.Idle
	}
	if cfg.Interval == -1 {
		cfg.Interval = oldCfg.Interval
	}
	if cfg.Count == -1 {
		cfg.Count = oldCfg.Count
	}

	tcpKeepAlive, err := syscall.GetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE)
	if err != nil {
		t.Fatal(err)
	}
	if (tcpKeepAlive != 0) != cfg.Enable {
		t.Fatalf("SO_KEEPALIVE: got %t; want %t", tcpKeepAlive != 0, cfg.Enable)
	}

	tcpKeepAliveIdle, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPIDLE)
	if err != nil {
		t.Fatal(err)
	}
	if time.Duration(tcpKeepAliveIdle)*time.Second != cfg.Idle {
		t.Fatalf("TCP_KEEPIDLE: got %ds; want %v", tcpKeepAliveIdle, cfg.Idle)
	}

	tcpKeepAliveInterval, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPINTVL)
	if err != nil {
		t.Fatal(err)
	}
	if time.Duration(tcpKeepAliveInterval)*time.Second != cfg.Interval {
		t.Fatalf("TCP_KEEPINTVL: got %ds; want %v", tcpKeepAliveInterval, cfg.Interval)
	}

	tcpKeepAliveCount, err := syscall.GetsockoptInt(fd, syscall.IPPROTO_TCP, syscall_TCP_KEEPCNT)
	if err != nil {
		t.Fatal(err)
	}
	if tcpKeepAliveCount != cfg.Count {
		t.Fatalf("TCP_KEEPCNT: got %d; want %d", tcpKeepAliveCount, cfg.Count)
	}
}