-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathproxy.go
129 lines (106 loc) · 2.4 KB
/
proxy.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"fmt"
"io"
"net"
"net/http"
"os"
)
type Proxy struct {
done chan bool
daemon *Daemon
}
func (p *Proxy) cleanup() error {
_, err := os.Stat("/var/run/docker.sock")
if err == nil {
err = os.Remove("/var/run/docker.sock")
return err
}
return nil
}
func (p *Proxy) proxy(w http.ResponseWriter, r *http.Request) {
if p.daemon.VM == nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("The virtual machine has not been started"))
return
}
addr, err := p.daemon.VM.Address()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("Unable to locate the virtual machine"))
return
}
backend, err := net.DialTCP("tcp", nil, addr)
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("Unable to connect to the virtual machine"))
return
}
defer backend.Close()
r.URL.Scheme = "http"
r.URL.Host = fmt.Sprintf("%s:%d", addr.IP.String(), addr.Port)
hijacker, ok := w.(http.Hijacker)
if !ok {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("Unable to create hijacker"))
return
}
conn, _, err := hijacker.Hijack()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte("Unable to hijack connection"))
return
}
r.Write(backend)
finished := make(chan error, 1)
go func(backend *net.TCPConn, conn net.Conn, finished chan error) {
buf := make([]byte, 8092)
_, err := io.CopyBuffer(backend, conn, buf)
backend.CloseWrite()
finished <- err
}(backend, conn, finished)
go func(backend *net.TCPConn, conn net.Conn, finished chan error) {
buf := make([]byte, 8092)
_, err := io.CopyBuffer(conn, backend, buf)
conn.Close()
finished <- err
}(backend, conn, finished)
<-finished
<-finished
}
func (p *Proxy) Listen() error {
err := p.cleanup()
if err != nil {
return err
}
addr, err := net.ResolveUnixAddr("unix", "/var/run/docker.sock")
if err != nil {
return err
}
raw, err := net.ListenUnix("unix", addr)
if err != nil {
return err
}
listener := &unixListener{
UnixListener: raw,
done: p.done,
}
err = os.Chmod("/var/run/docker.sock", 0777)
if err != nil {
return err
}
server := http.Server{
Handler: http.HandlerFunc(p.proxy),
}
return server.Serve(listener)
}
func (p *Proxy) Stop() {
p.done <- true
p.cleanup()
}
func NewProxy(daemon *Daemon) *Proxy {
return &Proxy{
daemon: daemon,
done: make(chan bool),
}
}