Include answer channel as part of the webRTCConn struct (#12)

This commit is contained in:
Serene Han 2016-02-17 20:41:33 -08:00
parent e35687b587
commit a1b7e01c54
2 changed files with 52 additions and 30 deletions

View file

@ -2,6 +2,7 @@ package main
import ( import (
"bytes" "bytes"
"github.com/keroserene/go-webrtc"
. "github.com/smartystreets/goconvey/convey" . "github.com/smartystreets/goconvey/convey"
"testing" "testing"
) )
@ -41,8 +42,9 @@ func TestConnect(t *testing.T) {
Convey("Receive answer fails on nil answer", func() { Convey("Receive answer fails on nil answer", func() {
c.reset = make(chan struct{}) c.reset = make(chan struct{})
c.answerChannel = make(chan *webrtc.SessionDescription)
c.ReceiveAnswer() c.ReceiveAnswer()
answerChannel <- nil c.answerChannel <- nil
<-c.reset <-c.reset
}) })

View file

@ -28,7 +28,6 @@ var frontDomain string
// When a connection handler starts, +1 is written to this channel; when it // When a connection handler starts, +1 is written to this channel; when it
// ends, -1 is written. // ends, -1 is written.
var handlerChan = make(chan int) var handlerChan = make(chan int)
var answerChannel = make(chan *webrtc.SessionDescription)
const ( const (
ReconnectTimeout = 5 ReconnectTimeout = 5
@ -37,7 +36,6 @@ const (
func copyLoop(a, b net.Conn) { func copyLoop(a, b net.Conn) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) wg.Add(2)
go func() { go func() {
io.Copy(b, a) io.Copy(b, a)
wg.Done() wg.Done()
@ -46,8 +44,8 @@ func copyLoop(a, b net.Conn) {
io.Copy(a, b) io.Copy(a, b)
wg.Done() wg.Done()
}() }()
wg.Wait() wg.Wait()
log.Println("copy loop ended")
} }
// Interface that matches both webrc.DataChannel and for testing. // Interface that matches both webrc.DataChannel and for testing.
@ -58,16 +56,17 @@ type SnowflakeChannel interface {
// Implements net.Conn interface // Implements net.Conn interface
type webRTCConn struct { type webRTCConn struct {
config *webrtc.Configuration config *webrtc.Configuration
pc *webrtc.PeerConnection pc *webrtc.PeerConnection
snowflake SnowflakeChannel // Interface holding the WebRTC DataChannel. snowflake SnowflakeChannel // Interface holding the WebRTC DataChannel.
broker *BrokerChannel broker *BrokerChannel
offerChannel chan *webrtc.SessionDescription offerChannel chan *webrtc.SessionDescription
errorChannel chan error answerChannel chan *webrtc.SessionDescription
recvPipe *io.PipeReader errorChannel chan error
writePipe *io.PipeWriter recvPipe *io.PipeReader
buffer bytes.Buffer writePipe *io.PipeWriter
reset chan struct{} buffer bytes.Buffer
reset chan struct{}
} }
var webrtcRemote *webRTCConn var webrtcRemote *webRTCConn
@ -164,6 +163,9 @@ func (c *webRTCConn) EstablishDataChannel() error {
} }
dc.OnOpen = func() { dc.OnOpen = func() {
log.Println("WebRTC: DataChannel.OnOpen") log.Println("WebRTC: DataChannel.OnOpen")
// if nil != c.snowflake {
// panic("PeerConnection snowflake already exists.")
// }
// Flush the buffer, then enable datachannel. // Flush the buffer, then enable datachannel.
// TODO: Make this more safe // TODO: Make this more safe
dc.Send(c.buffer.Bytes()) dc.Send(c.buffer.Bytes())
@ -175,14 +177,18 @@ func (c *webRTCConn) EstablishDataChannel() error {
// Disable the DataChannel as a write destination. // Disable the DataChannel as a write destination.
// Future writes will go to the buffer until a new DataChannel is available. // Future writes will go to the buffer until a new DataChannel is available.
log.Println("WebRTC: DataChannel.OnClose") log.Println("WebRTC: DataChannel.OnClose")
c.snowflake = nil if nil != c.snowflake {
c.reset <- struct{}{} // Attempt to negotiate a new datachannel.. c.snowflake = nil
// Only reset if this OnClose triggered
c.Reset()
}
} }
dc.OnMessage = func(msg []byte) { dc.OnMessage = func(msg []byte) {
log.Printf("OnMessage <--- %d bytes", len(msg)) log.Printf("OnMessage <--- %d bytes", len(msg))
n, err := c.writePipe.Write(msg) n, err := c.writePipe.Write(msg)
if err != nil { if err != nil {
// TODO: Maybe shouldn't actually close. // TODO: Maybe shouldn't actually close.
log.Println("Error writing to SOCKS pipe")
c.writePipe.CloseWithError(err) c.writePipe.CloseWithError(err)
} }
if n != len(msg) { if n != len(msg) {
@ -205,7 +211,7 @@ func (c *webRTCConn) SendOffer() error {
log.Printf("----------------") log.Printf("----------------")
return nil return nil
} }
// Use Broker... // Otherwise, use Broker.
go func() { go func() {
log.Println("Sending offer via BrokerChannel...\nTarget URL: ", brokerURL, log.Println("Sending offer via BrokerChannel...\nTarget URL: ", brokerURL,
"\nFront URL: ", frontDomain) "\nFront URL: ", frontDomain)
@ -214,7 +220,7 @@ func (c *webRTCConn) SendOffer() error {
log.Printf("BrokerChannel error: %s", err) log.Printf("BrokerChannel error: %s", err)
answer = nil answer = nil
} }
answerChannel <- answer c.answerChannel <- answer
}() }()
case err := <-c.errorChannel: case err := <-c.errorChannel:
c.pc.Close() c.pc.Close()
@ -225,11 +231,11 @@ func (c *webRTCConn) SendOffer() error {
func (c *webRTCConn) ReceiveAnswer() { func (c *webRTCConn) ReceiveAnswer() {
go func() { go func() {
answer, ok := <-answerChannel answer, ok := <-c.answerChannel
if !ok || nil == answer { if !ok || nil == answer {
log.Printf("Failed to retrieve answer. Retrying in %d seconds", ReconnectTimeout) log.Printf("Failed to retrieve answer. Retrying in %d seconds", ReconnectTimeout)
<-time.After(time.Second * ReconnectTimeout) <-time.After(time.Second * ReconnectTimeout)
c.reset <- struct{}{} c.Reset()
return return
} }
log.Printf("Received Answer:\n\n%s\n", answer.Sdp) log.Printf("Received Answer:\n\n%s\n", answer.Sdp)
@ -247,6 +253,12 @@ func (c *webRTCConn) sendData(data []byte) {
c.buffer.Write(data) c.buffer.Write(data)
return return
} }
// Otherwise, flush buffer if necessary.
for c.buffer.Len() > 0 {
c.snowflake.Send(c.buffer.Bytes())
log.Println("Flushed ", c.buffer.Len(), " bytes")
c.buffer.Reset()
}
log.Printf("Write %d bytes --> WebRTC", len(data)) log.Printf("Write %d bytes --> WebRTC", len(data))
c.snowflake.Send(data) c.snowflake.Send(data)
} }
@ -256,18 +268,25 @@ func (c *webRTCConn) ConnectLoop() {
for { for {
log.Println("Establishing WebRTC connection...") log.Println("Establishing WebRTC connection...")
// TODO: When go-webrtc is more stable, it's possible that a new // TODO: When go-webrtc is more stable, it's possible that a new
// PeerConnection won't need to be recreated each time. // PeerConnection won't need to be re-prepared each time.
// called once.
c.PreparePeerConnection() c.PreparePeerConnection()
c.EstablishDataChannel() err := c.EstablishDataChannel()
c.SendOffer() if err == nil {
c.ReceiveAnswer() c.SendOffer()
c.ReceiveAnswer()
<-c.reset <-c.reset
log.Println(" --- snowflake connection reset ---") log.Println(" --- snowflake connection reset ---")
}
} }
} }
func (c *webRTCConn) Reset() {
go func() {
c.reset <- struct{}{} // Attempt to negotiate a new datachannel..
log.Println("WebRTC resetting...")
}()
}
// Initialize a WebRTC Connection. // Initialize a WebRTC Connection.
func dialWebRTC(config *webrtc.Configuration, broker *BrokerChannel) ( func dialWebRTC(config *webrtc.Configuration, broker *BrokerChannel) (
*webRTCConn, error) { *webRTCConn, error) {
@ -275,6 +294,7 @@ func dialWebRTC(config *webrtc.Configuration, broker *BrokerChannel) (
connection.config = config connection.config = config
connection.broker = broker connection.broker = broker
connection.offerChannel = make(chan *webrtc.SessionDescription) connection.offerChannel = make(chan *webrtc.SessionDescription)
connection.answerChannel = make(chan *webrtc.SessionDescription)
connection.errorChannel = make(chan error) connection.errorChannel = make(chan error)
connection.reset = make(chan struct{}) connection.reset = make(chan struct{})
// Pipes remain the same even when DataChannel gets switched. // Pipes remain the same even when DataChannel gets switched.
@ -363,10 +383,10 @@ func readSignalingMessages(f *os.File) {
log.Printf("ignoring invalid signal message %+q", msg) log.Printf("ignoring invalid signal message %+q", msg)
continue continue
} }
answerChannel <- sdp webrtcRemote.answerChannel <- sdp
} }
log.Printf("close answerChannel") log.Printf("close answerChannel")
close(answerChannel) close(webrtcRemote.answerChannel)
if err := s.Err(); err != nil { if err := s.Err(); err != nil {
log.Printf("signal FIFO: %s", err) log.Printf("signal FIFO: %s", err)
} }