-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
74 lines (67 loc) · 2.15 KB
/
client.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
// Websocket is an extension package that makes the Teleport framework compatible
// with websocket protocol as specified in RFC 6455.
//
// Copyright 2018 HenryLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package websocket
import (
"net"
"path"
"strings"
tp "github.com/henrylee2cn/teleport"
"github.com/henrylee2cn/teleport/socket"
ws "github.com/henrylee2cn/tp-ext/mod-websocket/websocket"
)
// NewDialPlugin creates a websocket plugin for client.
func NewDialPlugin(pattern string) tp.Plugin {
pattern = path.Join("/", strings.TrimRight(pattern, "/"))
if pattern == "/" {
pattern = ""
}
return &clientPlugin{pattern}
}
type clientPlugin struct {
pattern string
}
var (
_ tp.PostDialPlugin = new(clientPlugin)
)
func (*clientPlugin) Name() string {
return "websocket"
}
func (c *clientPlugin) PostDial(sess tp.PreSession) *tp.Rerror {
var location, origin string
if sess.Peer().TlsConfig() == nil {
location = "ws://" + sess.RemoteAddr().String() + c.pattern
origin = "ws://" + sess.LocalAddr().String() + c.pattern
} else {
location = "wss://" + sess.RemoteAddr().String() + c.pattern
origin = "wss://" + sess.LocalAddr().String() + c.pattern
}
cfg, err := ws.NewConfig(location, origin)
if err != nil {
return tp.NewRerror(tp.CodeDialFailed, "upgrade to websocket failed", err.Error())
}
var rerr *tp.Rerror
sess.ModifySocket(func(conn net.Conn) (net.Conn, socket.ProtoFunc) {
conn, err := ws.NewClient(cfg, conn)
if err != nil {
rerr = tp.NewRerror(tp.CodeDialFailed, "upgrade to websocket failed", err.Error())
return nil, nil
}
return conn, NewWsProtoFunc(sess.GetProtoFunc())
})
return rerr
}