forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 1
/
listener_tcp.go
95 lines (79 loc) · 2.36 KB
/
listener_tcp.go
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
93
94
95
package server
import (
"crypto/tls"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/hashicorp/vault/internalshared/configutil"
"github.com/hashicorp/vault/internalshared/listenerutil"
"github.com/hashicorp/vault/internalshared/reloadutil"
"github.com/mitchellh/cli"
)
func tcpListenerFactory(l *configutil.Listener, _ io.Writer, ui cli.Ui) (net.Listener, map[string]string, reloadutil.ReloadFunc, error) {
addr := l.Address
if addr == "" {
addr = "127.0.0.1:8200"
}
bindProto := "tcp"
// If they've passed 0.0.0.0, we only want to bind on IPv4
// rather than golang's dual stack default
if strings.HasPrefix(addr, "0.0.0.0:") {
bindProto = "tcp4"
}
ln, err := net.Listen(bindProto, addr)
if err != nil {
return nil, nil, nil, err
}
ln = TCPKeepAliveListener{ln.(*net.TCPListener)}
ln, err = listenerWrapProxy(ln, l)
if err != nil {
return nil, nil, nil, err
}
props := map[string]string{"addr": addr}
// X-Forwarded-For props
{
if len(l.XForwardedForAuthorizedAddrs) > 0 {
props["x_forwarded_for_authorized_addrs"] = fmt.Sprintf("%v", l.XForwardedForAuthorizedAddrs)
}
if l.XForwardedForHopSkips > 0 {
props["x_forwarded_for_hop_skips"] = fmt.Sprintf("%d", l.XForwardedForHopSkips)
} else if len(l.XForwardedForAuthorizedAddrs) > 0 {
props["x_forwarded_for_hop_skips"] = "0"
}
if len(l.XForwardedForAuthorizedAddrs) > 0 {
props["x_forwarded_for_reject_not_present"] = strconv.FormatBool(l.XForwardedForRejectNotPresent)
}
if len(l.XForwardedForAuthorizedAddrs) > 0 {
props["x_forwarded_for_reject_not_authorized"] = strconv.FormatBool(l.XForwardedForRejectNotAuthorized)
}
}
tlsConfig, reloadFunc, err := listenerutil.TLSConfig(l, props, ui)
if err != nil {
return nil, nil, nil, err
}
if tlsConfig != nil {
ln = tls.NewListener(ln, tlsConfig)
}
return ln, props, reloadFunc, nil
}
// TCPKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
//
// This is copied directly from the Go source code.
type TCPKeepAliveListener struct {
*net.TCPListener
}
func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}