-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtunnel.go
More file actions
85 lines (79 loc) · 2.41 KB
/
Copy pathtunnel.go
File metadata and controls
85 lines (79 loc) · 2.41 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
package main
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strconv"
"time"
)
// localtunnel.me exposes a local port to a public https URL. The protocol is
// simple: GET https://localtunnel.me/?new reserves a subdomain and returns a
// TCP port to connect relay agents to; each agent connection is bridged to the
// local server, and localtunnel multiplexes incoming requests across the pool.
const tunnelHost = "localtunnel.me"
type tunnelInfo struct {
ID string `json:"id"`
URL string `json:"url"`
Port int `json:"port"`
MaxConnCount int `json:"max_conn_count"`
}
// startLocalTunnel reserves a public URL and spawns the relay pool. It blocks
// only for the initial reservation request; on success the returned URL is
// live (workers reconnect on their own for the life of the process).
func startLocalTunnel(localPort int) (string, error) {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(fmt.Sprintf("https://%s/?new", tunnelHost))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%s returned %s", tunnelHost, resp.Status)
}
var info tunnelInfo
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return "", err
}
if info.URL == "" || info.Port == 0 {
return "", fmt.Errorf("unexpected response from %s", tunnelHost)
}
conns := info.MaxConnCount
if conns <= 0 {
conns = 10
}
for i := 0; i < conns; i++ {
go tunnelWorker(info.Port, localPort)
}
return info.URL, nil
}
// tunnelWorker keeps one relay connection alive: dial localtunnel, dial the
// local server, splice them, and reconnect when the pairing ends.
func tunnelWorker(remotePort, localPort int) {
remoteAddr := net.JoinHostPort(tunnelHost, strconv.Itoa(remotePort))
localAddr := net.JoinHostPort("127.0.0.1", strconv.Itoa(localPort))
for {
remote, err := net.DialTimeout("tcp", remoteAddr, 10*time.Second)
if err != nil {
time.Sleep(time.Second)
continue
}
local, err := net.Dial("tcp", localAddr)
if err != nil {
remote.Close()
time.Sleep(500 * time.Millisecond)
continue
}
splice(remote, local)
}
}
// splice copies bytes both ways until either side closes, then closes both.
func splice(a, b net.Conn) {
done := make(chan struct{}, 2)
go func() { io.Copy(a, b); done <- struct{}{} }()
go func() { io.Copy(b, a); done <- struct{}{} }()
<-done
a.Close()
b.Close()
}