forked from koding/kite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
293 lines (230 loc) · 6.42 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Package tunnelproxy implements a reverse-proxy for kites behind firewall or NAT.
package tunnelproxy
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/koding/kite"
"github.com/koding/kite/config"
"gopkg.in/igm/sockjs-go.v2/sockjs"
)
const (
ProxyVersion = "0.0.2"
)
var (
DefaultPort = 3999
DefaultPublicHost = "localhost:3999"
)
type Proxy struct {
Kite *kite.Kite
listener net.Listener
TLSConfig *tls.Config
readyC chan bool // To signal when kite is ready to accept connections
closeC chan bool // To signal when kite is closed with Close()
// If givent it must match the domain in certificate.
PublicHost string
// For generating token tokens for tunnels.
pubKey string
privKey string
// Holds registered kites. Keys are kite IDs.
kites map[string]*PrivateKite
mux *http.ServeMux
RegisterToKontrol bool
url *url.URL
}
func New(conf *config.Config, version, pubKey, privKey string) *Proxy {
k := kite.New("tunnelproxy", version)
k.Config = conf
// Listen on 3999 by default
if k.Config.Port == 0 {
k.Config.Port = DefaultPort
}
p := &Proxy{
Kite: k,
readyC: make(chan bool),
closeC: make(chan bool),
pubKey: pubKey,
privKey: privKey,
kites: make(map[string]*PrivateKite),
mux: http.NewServeMux(),
RegisterToKontrol: true,
PublicHost: DefaultPublicHost,
}
p.Kite.HandleFunc("register", p.handleRegister)
p.mux.Handle("/", p.Kite)
p.mux.Handle("/proxy/", sockjsHandlerWithRequest("/proxy", sockjs.DefaultOptions, p.handleProxy)) // Handler for clients outside
p.mux.Handle("/tunnel/", sockjsHandlerWithRequest("/tunnel", sockjs.DefaultOptions, p.handleTunnel)) // Handler for kites behind
// Remove URL from the map when PrivateKite disconnects.
k.OnDisconnect(func(r *kite.Client) {
delete(p.kites, r.Kite.ID)
})
return p
}
// sockjsHandlerWithRequest is a wrapper around the sockjs.Handler that
// includes a *http.Request context.
func sockjsHandlerWithRequest(
prefix string,
opts sockjs.Options,
handleFunc func(sockjs.Session, *http.Request),
) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sockjs.NewHandler(prefix, opts, func(session sockjs.Session) {
handleFunc(session, r)
}).ServeHTTP(w, r)
})
}
func (s *Proxy) CloseNotify() chan bool {
return s.closeC
}
func (s *Proxy) ReadyNotify() chan bool {
return s.readyC
}
func (p *Proxy) Close() {
p.listener.Close()
for _, k := range p.kites {
k.Close()
for _, t := range k.tunnels {
t.Close()
}
}
}
func (p *Proxy) Start() {
go p.Run()
<-p.readyC
}
func (p *Proxy) Run() {
p.listenAndServe()
}
func (p *Proxy) listenAndServe() error {
var err error
p.listener, err = net.Listen("tcp", net.JoinHostPort(p.Kite.Config.IP, strconv.Itoa(p.Kite.Config.Port)))
if err != nil {
return err
}
p.Kite.Log.Info("Listening on: %s", p.listener.Addr().String())
close(p.readyC)
p.url = &url.URL{
Scheme: "ws",
Host: p.PublicHost,
Path: "/kite",
}
if p.RegisterToKontrol {
go p.Kite.RegisterForever(p.url)
}
defer close(p.closeC)
return http.Serve(p.listener, p.mux)
}
func (p *Proxy) handleRegister(r *kite.Request) (interface{}, error) {
p.kites[r.Client.ID] = newPrivateKite(r.Client)
proxyURL := url.URL{
Scheme: "http",
Host: p.url.Host,
Path: "proxy",
RawQuery: "kiteID=" + r.Client.ID,
}
return proxyURL.String(), nil
}
// handleProxy is the client side of the Tunnel (on public network).
func (p *Proxy) handleProxy(session sockjs.Session, req *http.Request) {
kiteID := req.URL.Query().Get("kiteID")
client, ok := p.kites[kiteID]
if !ok {
p.Kite.Log.Error("Remote kite is not found: %s", req.URL.String())
return
}
tunnel := client.newTunnel(session)
defer tunnel.Close()
token := jwt.New(jwt.GetSigningMethod("RS256"))
const ttl = time.Duration(1 * time.Hour)
const leeway = time.Duration(1 * time.Minute)
token.Claims = map[string]interface{}{
"sub": client.ID, // kite ID
"seq": tunnel.id, // tunnel number
"iat": time.Now().UTC().Unix(), // Issued At
"exp": time.Now().UTC().Add(ttl).Add(leeway).Unix(), // Expiration Time
"nbf": time.Now().UTC().Add(-leeway).Unix(), // Not Before
}
signed, err := token.SignedString([]byte(p.privKey))
if err != nil {
p.Kite.Log.Error("Cannot sign token: %s", err.Error())
return
}
tunnelURL := *p.url
tunnelURL.Path = "/tunnel" + strings.TrimPrefix(req.URL.Path, "/proxy")
tunnelURL.RawQuery = "token=" + signed
_, err = client.TellWithTimeout("kite.tunnel",
4*time.Second, map[string]string{"url": tunnelURL.String()})
if err != nil {
p.Kite.Log.Error("Cannot open tunnel to the kite: %s err: %s", client.Kite, err.Error())
return
}
select {
case <-tunnel.StartNotify():
<-tunnel.CloseNotify()
case <-time.After(1 * time.Minute):
p.Kite.Log.Error("timeout")
}
}
// handleTunnel is the PrivateKite side of the Tunnel (on private network).
func (p *Proxy) handleTunnel(session sockjs.Session, req *http.Request) {
tokenString := req.URL.Query().Get("token")
getPublicKey := func(token *jwt.Token) (interface{}, error) {
return []byte(p.pubKey), nil
}
token, err := jwt.Parse(tokenString, getPublicKey)
if err != nil {
p.Kite.Log.Error("Invalid token: \"%s\"", tokenString)
return
}
kiteID := token.Claims["sub"].(string)
seq := uint64(token.Claims["seq"].(float64))
client, ok := p.kites[kiteID]
if !ok {
p.Kite.Log.Error("Remote kite is not found: %s", kiteID)
return
}
tunnel, ok := client.tunnels[seq]
if !ok {
p.Kite.Log.Error("Tunnel not found: %d", seq)
}
go tunnel.Run(session)
<-tunnel.CloseNotify()
}
//
// PrivateKite
//
type PrivateKite struct {
*kite.Client
// Connections to kites behind the proxy. Keys are kite IDs.
tunnels map[uint64]*Tunnel
// Last tunnel number
seq uint64
}
func newPrivateKite(r *kite.Client) *PrivateKite {
return &PrivateKite{
Client: r,
tunnels: make(map[uint64]*Tunnel),
}
}
func (k *PrivateKite) newTunnel(local sockjs.Session) *Tunnel {
t := &Tunnel{
id: atomic.AddUint64(&k.seq, 1),
localConn: local,
startChan: make(chan bool),
closeChan: make(chan bool),
}
// Add to map.
k.tunnels[t.id] = t
// Delete from map on close.
go func() {
<-t.CloseNotify()
delete(k.tunnels, t.id)
}()
return t
}