forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
143 lines (122 loc) · 3.91 KB
/
net.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Tamir Duberstein (tamird@gmail.com)
package util
import (
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"strings"
"sync"
"github.com/cockroachdb/cockroach/util/stop"
)
var _ net.Listener = listener{}
type listener struct {
addr net.Addr
net.Listener
}
func (ln listener) Addr() net.Addr {
return ln.addr
}
// ListenAndServe creates a listener and serves handler on it, closing
// the listener when signalled by the stopper.
func ListenAndServe(stopper *stop.Stopper, handler http.Handler, addr net.Addr, config *tls.Config) (net.Listener, error) {
ln, err := net.Listen(addr.Network(), addr.String())
if err != nil {
return nil, err
}
newAddr, err := updatedAddr(addr, ln.Addr())
if err != nil {
return nil, err
}
if config != nil {
ln = tls.NewListener(ln, config)
}
stopper.RunWorker(func() {
var mu sync.Mutex
activeConns := make(map[net.Conn]struct{})
httpServer := http.Server{
Handler: handler,
ConnState: func(conn net.Conn, state http.ConnState) {
mu.Lock()
switch state {
case http.StateNew:
activeConns[conn] = struct{}{}
case http.StateClosed:
delete(activeConns, conn)
}
mu.Unlock()
},
}
if err := httpServer.Serve(ln); err != nil && !IsClosedConnection(err) {
log.Fatal(err)
}
mu.Lock()
for conn := range activeConns {
conn.Close()
}
mu.Unlock()
})
stopper.RunWorker(func() {
<-stopper.ShouldStop()
// Some unit tests manually close `ln`, so it may already be closed
// when we get here.
if err := ln.Close(); err != nil && !IsClosedConnection(err) {
log.Fatal(err)
}
})
return listener{newAddr, ln}, nil
}
// IsClosedConnection returns true if err is the net package's errClosed.
func IsClosedConnection(err error) bool {
return strings.HasSuffix(err.Error(), "use of closed network connection")
}
// updatedAddr returns our "official" address based on the address we asked for
// (oldAddr) and the address we successfully bound to (newAddr). It's kind of
// hacky, but necessary to make TLS work.
func updatedAddr(oldAddr, newAddr net.Addr) (net.Addr, error) {
oldAddrStr := oldAddr.String()
newAddrStr := newAddr.String()
switch network := oldAddr.Network(); network {
case "tcp", "tcp4", "tcp6":
// After binding, it's possible that our host and/or port will be
// different from what we requested. If the hostname is different, we
// want to keep the original one since it's more likely to match our
// TLS certificate. But if the port is different, it should be because
// we asked for ":0" and got an arbitrary unused port; that needs to be
// reflected in our addr.
host, oldPort, err := net.SplitHostPort(EnsureHostPort(oldAddrStr))
if err != nil {
return nil, fmt.Errorf("unable to parse original addr '%s': %v", oldAddrStr, err)
}
_, newPort, err := net.SplitHostPort(newAddrStr)
if err != nil {
return nil, fmt.Errorf("unable to parse new addr '%s': %v", newAddrStr, err)
}
if newPort != oldPort && oldPort != "0" {
return nil, fmt.Errorf("asked for port %s, got %s", oldPort, newPort)
}
return MakeUnresolvedAddr(network, net.JoinHostPort(host, newPort)), nil
case "unix":
if oldAddrStr != newAddrStr {
return nil, fmt.Errorf("asked for unix addr %s, got %s", oldAddr, newAddr)
}
return newAddr, nil
default:
return nil, fmt.Errorf("unexpected network type: %s", network)
}
}