-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathlisten.go
More file actions
188 lines (165 loc) · 4.68 KB
/
listen.go
File metadata and controls
188 lines (165 loc) · 4.68 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package peerbroker
import (
"context"
"errors"
"io"
"net"
"reflect"
"sync"
"github.com/pion/webrtc/v3"
"golang.org/x/xerrors"
"storj.io/drpc/drpcmux"
"storj.io/drpc/drpcserver"
"github.com/coder/coder/peer"
"github.com/coder/coder/peerbroker/proto"
)
// ICEServersFunc returns ICEServers when a new connection is requested.
type ICEServersFunc func(ctx context.Context) ([]webrtc.ICEServer, error)
// Listen consumes the transport as the server-side of the PeerBroker dRPC service.
// The Accept function must be serviced, or new connections will hang.
func Listen(connListener net.Listener, iceServersFunc ICEServersFunc, opts *peer.ConnOptions) (*Listener, error) {
if iceServersFunc == nil {
iceServersFunc = func(ctx context.Context) ([]webrtc.ICEServer, error) {
return []webrtc.ICEServer{}, nil
}
}
ctx, cancelFunc := context.WithCancel(context.Background())
listener := &Listener{
connectionChannel: make(chan *peer.Conn),
iceServersFunc: iceServersFunc,
closeFunc: cancelFunc,
closed: make(chan struct{}),
}
mux := drpcmux.New()
err := proto.DRPCRegisterPeerBroker(mux, &peerBrokerService{
connOptions: opts,
listener: listener,
})
if err != nil {
return nil, xerrors.Errorf("register peer broker: %w", err)
}
srv := drpcserver.New(mux)
go func() {
err := srv.Serve(ctx, connListener)
_ = listener.closeWithError(err)
}()
return listener, nil
}
type Listener struct {
connectionChannel chan *peer.Conn
iceServersFunc ICEServersFunc
closeFunc context.CancelFunc
closed chan struct{}
closeMutex sync.Mutex
closeError error
}
// Accept blocks until a connection arrives or the listener is closed.
func (l *Listener) Accept() (*peer.Conn, error) {
select {
case <-l.closed:
return nil, l.closeError
case conn := <-l.connectionChannel:
return conn, nil
}
}
// Close ends the listener. This will block all new WebRTC connections
// from establishing, but will not close active connections.
func (l *Listener) Close() error {
return l.closeWithError(io.EOF)
}
func (l *Listener) closeWithError(err error) error {
l.closeMutex.Lock()
defer l.closeMutex.Unlock()
if l.isClosed() {
return l.closeError
}
l.closeError = err
l.closeFunc()
close(l.closed)
return nil
}
func (l *Listener) isClosed() bool {
select {
case <-l.closed:
return true
default:
return false
}
}
// Implements the PeerBroker service protobuf definition.
type peerBrokerService struct {
listener *Listener
connOptions *peer.ConnOptions
}
// NegotiateConnection negotiates a WebRTC connection.
func (b *peerBrokerService) NegotiateConnection(stream proto.DRPCPeerBroker_NegotiateConnectionStream) error {
iceServers, err := b.listener.iceServersFunc(stream.Context())
if err != nil {
return xerrors.Errorf("get ice servers: %w", err)
}
// Start with no ICE servers. They can be sent by the client if provided.
peerConn, err := peer.Server(iceServers, b.connOptions)
if err != nil {
return xerrors.Errorf("create peer connection: %w", err)
}
select {
case <-b.listener.closed:
return peerConn.CloseWithError(b.listener.closeError)
case b.listener.connectionChannel <- peerConn:
}
go func() {
defer stream.Close()
for {
select {
case <-peerConn.Closed():
return
case sessionDescription := <-peerConn.LocalSessionDescription():
err = stream.Send(&proto.Exchange{
Message: &proto.Exchange_Sdp{
Sdp: &proto.WebRTCSessionDescription{
SdpType: int32(sessionDescription.Type),
Sdp: sessionDescription.SDP,
},
},
})
if err != nil {
_ = peerConn.CloseWithError(xerrors.Errorf("send local session description: %w", err))
return
}
case iceCandidate := <-peerConn.LocalCandidate():
err = stream.Send(&proto.Exchange{
Message: &proto.Exchange_IceCandidate{
IceCandidate: iceCandidate.Candidate,
},
})
if err != nil {
_ = peerConn.CloseWithError(xerrors.Errorf("send local candidate: %w", err))
return
}
}
}
}()
for {
clientToServerMessage, err := stream.Recv()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return peerConn.CloseWithError(xerrors.Errorf("recv: %w", err))
}
switch {
case clientToServerMessage.GetSdp() != nil:
peerConn.SetRemoteSessionDescription(webrtc.SessionDescription{
Type: webrtc.SDPType(clientToServerMessage.GetSdp().SdpType),
SDP: clientToServerMessage.GetSdp().Sdp,
})
case clientToServerMessage.GetIceCandidate() != "":
peerConn.AddRemoteCandidate(webrtc.ICECandidateInit{
Candidate: clientToServerMessage.GetIceCandidate(),
})
default:
return peerConn.CloseWithError(xerrors.Errorf("unhandled message: %s", reflect.TypeOf(clientToServerMessage).String()))
}
}
return nil
}