1
1
package client
2
2
3
3
import (
4
+ "errors"
5
+ "fmt"
4
6
"log"
5
7
"net"
8
+ "net/url"
9
+ "regexp"
6
10
"strings"
7
11
8
12
"github.com/hashicorp/yamux"
@@ -15,47 +19,64 @@ type Client struct {
15
19
proxies []* Proxy
16
20
}
17
21
18
- func NewClient (auth , server string , remotes []string ) * Client {
22
+ func NewClient (auth , server string , remotes []string ) (* Client , error ) {
23
+
24
+ u , err := url .Parse (server )
25
+ if err != nil {
26
+ return nil , err
27
+ }
28
+
29
+ //apply default port
30
+ if ! regexp .MustCompile (`:\d+$` ).MatchString (u .Host ) {
31
+ if u .Scheme == "https" {
32
+ u .Host = u .Host + ":443"
33
+ } else {
34
+ u .Host = u .Host + ":80"
35
+ }
36
+ }
37
+
38
+ //use websockets scheme
39
+ u .Scheme = strings .Replace (u .Scheme , "http" , "ws" , 1 )
19
40
20
41
c := & chisel.Config {
21
42
Version : chisel .Version ,
22
43
Auth : auth ,
23
- Server : server ,
44
+ Server : u . String () ,
24
45
}
25
46
26
47
for _ , s := range remotes {
27
48
r , err := chisel .DecodeRemote (s )
28
49
if err != nil {
29
- log . Fatalf ("Failed to decode remote '%s': %s" , s , err )
50
+ return nil , fmt . Errorf ("Failed to decode remote '%s': %s" , s , err )
30
51
}
31
52
c .Remotes = append (c .Remotes , r )
32
53
}
33
54
34
- return & Client {config : c }
55
+ return & Client {config : c }, nil
35
56
}
36
57
37
- func (c * Client ) Start () {
58
+ func (c * Client ) Start () error {
38
59
encconfig , err := chisel .EncodeConfig (c .config )
39
60
if err != nil {
40
- log . Fatal ( err )
61
+ return err
41
62
}
42
63
43
- url := strings .Replace (c .config .Server , "http: " , "ws: " , 1 )
64
+ url := strings .Replace (c .config .Server , "http" , "ws" , 1 )
44
65
ws , err := websocket .Dial (url , encconfig , "http://localhost/" )
45
66
if err != nil {
46
- log . Fatal ( err )
67
+ return err
47
68
}
48
69
49
70
b := make ([]byte , 0xff )
50
71
n , _ := ws .Read (b )
51
72
if msg := string (b [:n ]); msg != "handshake-success" {
52
- log . Fatal (msg )
73
+ return errors . New (msg )
53
74
}
54
75
55
76
// Setup client side of yamux
56
77
session , err := yamux .Client (ws , nil )
57
78
if err != nil {
58
- log . Fatal ( err )
79
+ return err
59
80
}
60
81
61
82
markClosed := make (chan bool )
@@ -84,4 +105,5 @@ func (c *Client) Start() {
84
105
<- markClosed
85
106
isClosed = true
86
107
log .Printf ("Disconnected\n " )
108
+ return nil
87
109
}
0 commit comments