11 "github.com/anacrolix/log"
12 "github.com/anacrolix/missinggo/v2/pproffd"
13 "github.com/pion/datachannel"
14 "github.com/pion/webrtc/v3"
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/codes"
18 "go.opentelemetry.io/otel/trace"
22 dataChannelLabel = "webrtc-datachannel"
26 metrics = expvar.NewMap("webtorrent")
27 api = func() *webrtc.API {
28 // Enable the detach API (since it's non-standard but more idiomatic).
29 s.DetachDataChannels()
30 return webrtc.NewAPI(webrtc.WithSettingEngine(s))
32 config = webrtc.Configuration{ICEServers: []webrtc.ICEServer{{URLs: []string{"stun:stun.l.google.com:19302"}}}}
33 newPeerConnectionMu sync.Mutex
36 type wrappedPeerConnection struct {
37 *webrtc.PeerConnection
44 func (me *wrappedPeerConnection) Close() error {
46 defer me.closeMu.Unlock()
47 err := me.CloseWrapper.Close()
52 func newPeerConnection(logger log.Logger) (*wrappedPeerConnection, error) {
53 newPeerConnectionMu.Lock()
54 defer newPeerConnectionMu.Unlock()
55 ctx, span := otel.Tracer(tracerName).Start(context.Background(), "PeerConnection")
56 pc, err := api.NewPeerConnection(config)
58 span.SetStatus(codes.Error, err.Error())
63 wpc := &wrappedPeerConnection{
65 CloseWrapper: pproffd.NewCloseWrapper(pc),
69 // If the state change handler intends to call Close, it should call it on the wrapper.
70 wpc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
71 logger.Levelf(log.Warning, "webrtc PeerConnection state changed to %v", state)
72 span.AddEvent("connection state changed", trace.WithAttributes(attribute.String("state", state.String())))
77 func setAndGatherLocalDescription(peerConnection *wrappedPeerConnection, sdp webrtc.SessionDescription) (_ webrtc.SessionDescription, err error) {
78 gatherComplete := webrtc.GatheringCompletePromise(peerConnection.PeerConnection)
79 peerConnection.span.AddEvent("setting local description")
80 err = peerConnection.SetLocalDescription(sdp)
82 err = fmt.Errorf("setting local description: %w", err)
86 peerConnection.span.AddEvent("gathering complete")
87 return *peerConnection.LocalDescription(), nil
90 // newOffer creates a transport and returns a WebRTC offer to be announced. See
91 // https://github.com/pion/webrtc/blob/master/examples/data-channels/jsfiddle/main.go for what this is modelled on.
92 func (tc *TrackerClient) newOffer(
97 peerConnection *wrappedPeerConnection,
98 dataChannel *webrtc.DataChannel,
99 offer webrtc.SessionDescription,
102 peerConnection, err = newPeerConnection(logger)
107 peerConnection.span.SetAttributes(attribute.String(webrtcConnTypeKey, "offer"))
109 dataChannel, err = peerConnection.CreateDataChannel(dataChannelLabel, nil)
111 err = fmt.Errorf("creating data channel: %w", err)
112 peerConnection.Close()
114 initDataChannel(dataChannel, peerConnection, func(dc datachannel.ReadWriteCloser, dcCtx context.Context, dcSpan trace.Span) {
115 metrics.Add("outbound offers answered with datachannel", 1)
117 tc.stats.ConvertedOutboundConns++
119 tc.OnConn(dc, DataChannelContext{
123 peerConnection: peerConnection,
129 offer, err = peerConnection.CreateOffer(nil)
132 peerConnection.Close()
136 offer, err = setAndGatherLocalDescription(peerConnection, offer)
139 peerConnection.Close()
144 type onDetachedDataChannelFunc func(detached datachannel.ReadWriteCloser, ctx context.Context, span trace.Span)
146 func (tc *TrackerClient) initAnsweringPeerConnection(
147 peerConn *wrappedPeerConnection,
148 offerContext offerContext,
149 ) (answer webrtc.SessionDescription, err error) {
150 peerConn.span.SetAttributes(attribute.String(webrtcConnTypeKey, "answer"))
152 timer := time.AfterFunc(30*time.Second, func() {
153 peerConn.span.SetStatus(codes.Error, "answer timeout")
154 metrics.Add("answering peer connections timed out", 1)
157 peerConn.OnDataChannel(func(d *webrtc.DataChannel) {
158 initDataChannel(d, peerConn, func(detached datachannel.ReadWriteCloser, ctx context.Context, span trace.Span) {
160 metrics.Add("answering peer connection conversions", 1)
162 tc.stats.ConvertedInboundConns++
164 tc.OnConn(detached, DataChannelContext{
165 OfferId: offerContext.Id,
167 InfoHash: offerContext.InfoHash,
168 peerConnection: peerConn,
175 err = peerConn.SetRemoteDescription(offerContext.SessDesc)
179 answer, err = peerConn.CreateAnswer(nil)
184 answer, err = setAndGatherLocalDescription(peerConn, answer)
188 // newAnsweringPeerConnection creates a transport from a WebRTC offer and returns a WebRTC answer to be announced.
189 func (tc *TrackerClient) newAnsweringPeerConnection(
190 offerContext offerContext,
192 peerConn *wrappedPeerConnection, answer webrtc.SessionDescription, err error,
194 peerConn, err = newPeerConnection(tc.Logger)
196 err = fmt.Errorf("failed to create new connection: %w", err)
199 answer, err = tc.initAnsweringPeerConnection(peerConn, offerContext)
201 peerConn.span.RecordError(err)
207 type datachannelReadWriter interface {
214 type ioCloserFunc func() error
216 func (me ioCloserFunc) Close() error {
220 func initDataChannel(
221 dc *webrtc.DataChannel,
222 pc *wrappedPeerConnection,
223 onOpen onDetachedDataChannelFunc,
230 pc.span.AddEvent("data channel opened")
231 var ctx context.Context
232 ctx, span = otel.Tracer(tracerName).Start(pc.ctx, "DataChannel")
233 raw, err := dc.Detach()
235 // This shouldn't happen if the API is configured correctly, and we call from OnOpen.
238 onOpen(hookDataChannelCloser(raw, pc, span, dc), ctx, span)
242 // Hooks the datachannel's Close to Close the owning PeerConnection. The datachannel takes ownership
243 // and responsibility for the PeerConnection.
244 func hookDataChannelCloser(
245 dcrwc datachannel.ReadWriteCloser,
246 pc *wrappedPeerConnection,
247 dataChannelSpan trace.Span,
248 originalDataChannel *webrtc.DataChannel,
249 ) datachannel.ReadWriteCloser {
251 datachannelReadWriter
255 ioCloserFunc(func() error {
258 originalDataChannel.Close()
259 dataChannelSpan.End()