/
tcp.go
148 lines (119 loc) · 4.11 KB
/
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
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
144
145
146
147
148
package dslvm
import (
"context"
"net"
"sync"
"time"
"github.com/ooni/probe-engine/pkg/logx"
"github.com/ooni/probe-engine/pkg/model"
"github.com/ooni/probe-engine/pkg/netxlite"
)
// TCPConnectStage is a [Stage] that creates [*TCPConnection].
type TCPConnectStage struct {
// Input contains the MANDATORY channel from which to read endpoints. We
// assume that this channel will be closed when done.
Input <-chan string
// Output is the MANDATORY channel emitting [*TCPConnection]. We will close this
// channel when the Input channel has been closed.
Output chan<- *TCPConnection
// Tags contains OPTIONAL tags to add to the endpoint observations.
Tags []string
}
// TCPConnection is a TCP connection.
type TCPConnection struct {
Conn net.Conn
tx Trace
}
var _ HTTPConnection = &TCPConnection{}
// AsSingleUseTransport implements HTTPConnection.
func (c *TCPConnection) AsSingleUseTransport(logger model.Logger) model.HTTPTransport {
return netxlite.NewHTTPTransport(logger, netxlite.NewSingleUseDialer(c.Conn), netxlite.NewNullTLSDialer())
}
// Close implements HTTPConnection.
func (c *TCPConnection) Close(logger model.Logger) error {
ol := logx.NewOperationLogger(logger, "[#%d] TCPClose %s", c.tx.Index(), c.RemoteAddress())
err := c.Conn.Close()
ol.Stop(err)
return err
}
// Network implements HTTPConnection.
func (c *TCPConnection) Network() string {
return "tcp"
}
// RemoteAddress implements HTTPConnection.
func (c *TCPConnection) RemoteAddress() (addr string) {
if v := c.Conn.RemoteAddr(); v != nil {
addr = v.String()
}
return
}
// Scheme implements HTTPConnection.
func (c *TCPConnection) Scheme() string {
return "http"
}
// TLSNegotiatedProtocol implements HTTPConnection.
func (c *TCPConnection) TLSNegotiatedProtocol() string {
return ""
}
// Trace implements HTTPConnection.
func (c *TCPConnection) Trace() Trace {
return c.tx
}
var _ Stage = &TCPConnectStage{}
// Run reads endpoints from Input and streams on the Output channel the [*TCPConnection]
// that it could successfully establish. Note that this function honors the [Semaphore] returned
// by the [Runtime] ActiveConnections that controls how many connections we can measure in
// parallel. When given the permission to run, this function spawns a background goroutine that
// attempts to establish a connection. The [*TCPConnection] returned by this stage MUST
// eventually feed into a [*CloseStage], so that the code can notify the above mentioned
// [Semaphore] and so that we close the open connection. This function will close the Output
// channel when Inputs have been closed and there are no pending connection attempts. In
// case of failure, the code will automatically notify the [Semaphore].
func (sx *TCPConnectStage) Run(ctx context.Context, rtx Runtime) {
// make sure we close the output channel
defer close(sx.Output)
// track the number of running goroutines
waitGroup := &sync.WaitGroup{}
for endpoint := range sx.Input {
// wait for authorization to process a connection
rtx.ActiveConnections().Wait()
// process connection in a background goroutine
waitGroup.Add(1)
go func(endpoint string) {
defer waitGroup.Done()
sx.connect(ctx, rtx, endpoint)
}(endpoint)
}
// wait for pending work to finish
waitGroup.Wait()
}
func (sx *TCPConnectStage) connect(ctx context.Context, rtx Runtime, endpoint string) {
// create trace
trace := rtx.NewTrace(rtx.IDGenerator().Add(1), rtx.ZeroTime(), sx.Tags...)
// start operation logger
ol := logx.NewOperationLogger(
rtx.Logger(),
"[#%d] TCPConnect %s",
trace.Index(),
endpoint,
)
// setup
const timeout = 15 * time.Second
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// obtain the dialer to use
dialer := trace.NewDialerWithoutResolver(rtx.Logger())
// connect
conn, err := dialer.DialContext(ctx, "tcp", endpoint)
// stop the operation logger
ol.Stop(err)
// save the observations
rtx.SaveObservations(maybeTraceToObservations(trace)...)
// handle error case
if err != nil {
rtx.ActiveConnections().Signal() // make sure we release the semaphore
return
}
// handle success
sx.Output <- &TCPConnection{Conn: conn, tx: trace}
}