snowflake.go 1.81 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package lib

import (
	"errors"
	"io"
	"log"
	"net"
	"sync"
)

const (
	ReconnectTimeout = 10
	SnowflakeTimeout = 30
)

16
// HandlerChan - When a connection handler starts, +1 is written to this channel; when it
17
18
19
20
21
22
23
24
25
26
27
28
29
// ends, -1 is written.
var HandlerChan = make(chan int)

// Given an accepted SOCKS connection, establish a WebRTC connection to the
// remote peer and exchange traffic.
func Handler(socks SocksConnector, snowflakes SnowflakeCollector) error {
	HandlerChan <- 1
	defer func() {
		HandlerChan <- -1
	}()
	// Obtain an available WebRTC remote. May block.
	snowflake := snowflakes.Pop()
	if nil == snowflake {
30
31
32
33
		if err := socks.Reject(); err != nil {
			log.Printf("socks.Reject returned error: %v", err)
		}

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
		return errors.New("handler: Received invalid Snowflake")
	}
	defer socks.Close()
	defer snowflake.Close()
	log.Println("---- Handler: snowflake assigned ----")
	err := socks.Grant(&net.TCPAddr{IP: net.IPv4zero, Port: 0})
	if err != nil {
		return err
	}

	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.)
func copyLoop(a, b io.ReadWriter) {
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
63
64
65
		if _, err := io.Copy(ORPort, WebRTC); err != nil {
			log.Printf("copying WebRTC to ORPort resulted in error: %v", err)
		}
66
67
68
		wg.Done()
	}()
	go func() {
69
70
71
		if _, err := io.Copy(WebRTC, ORPort); err != nil {
			log.Printf("copying ORPort to WebRTC resulted in error: %v", err)
		}
72
73
74
75
76
		wg.Done()
	}()
	wg.Wait()
	log.Println("copy loop ended")
}