snowflake.go 1.44 KB
Newer Older
1
2
3
4
5
6
7
package lib

import (
	"errors"
	"io"
	"log"
	"net"
8
	"time"
9
10
11
)

const (
12
13
	ReconnectTimeout = 10 * time.Second
	SnowflakeTimeout = 30 * time.Second
14
15
16
17
)

// Given an accepted SOCKS connection, establish a WebRTC connection to the
// remote peer and exchange traffic.
18
func Handler(socks net.Conn, snowflakes SnowflakeCollector) error {
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
	// Obtain an available WebRTC remote. May block.
	snowflake := snowflakes.Pop()
	if nil == snowflake {
		return errors.New("handler: Received invalid Snowflake")
	}
	defer snowflake.Close()
	log.Println("---- Handler: snowflake assigned ----")

	go func() {
		// When WebRTC resets, close the SOCKS connection too.
		snowflake.WaitForReset()
		socks.Close()
	}()

	// Begin exchanging data. Either WebRTC or localhost SOCKS will close first.
	// In eithercase, this closes the handler and induces a new handler.
	copyLoop(socks, snowflake)
	log.Println("---- Handler: closed ---")
	return nil
}

// Exchanges bytes between two ReadWriters.
// (In this case, between a SOCKS and WebRTC connection.)
42
func copyLoop(socks, webRTC io.ReadWriter) {
43
	done := make(chan struct{}, 2)
44
	go func() {
45
		if _, err := io.Copy(socks, webRTC); err != nil {
46
			log.Printf("copying WebRTC to SOCKS resulted in error: %v", err)
47
		}
48
		done <- struct{}{}
49
50
	}()
	go func() {
51
		if _, err := io.Copy(webRTC, socks); err != nil {
52
			log.Printf("copying SOCKS to WebRTC resulted in error: %v", err)
53
		}
54
		done <- struct{}{}
55
	}()
56
	<-done
57
58
	log.Println("copy loop ended")
}