-
Notifications
You must be signed in to change notification settings - Fork 10
/
simple_server.go
101 lines (91 loc) · 1.98 KB
/
simple_server.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
package shadowsocks
import (
"context"
"fmt"
"net"
"net/url"
)
// SimpleServer is a simplified server, which can be configured as easily as client.
type SimpleServer struct {
Server
Listener net.Listener
Network string
Address string
}
// NewServer creates a new NewSimpleServer
func NewSimpleServer(addr string) (*SimpleServer, error) {
s := &SimpleServer{}
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
switch u.Scheme {
case "ss", "shadowsocks":
default:
return nil, fmt.Errorf("unsupported protocol '%s'", u.Scheme)
}
host := u.Host
port := u.Port()
if port == "" {
port = "8379"
hostname := u.Hostname()
host = net.JoinHostPort(hostname, port)
}
if u.User != nil {
s.Cipher, s.Password, err = GetCipherAndPasswordFromUserinfo(u.User)
if err != nil {
return nil, err
}
}
cipher, err := NewCipher(s.Cipher, s.Password)
if err != nil {
return nil, err
}
s.ConnCipher = cipher
s.Address = host
s.Network = "tcp"
return s, nil
}
// Run the server
func (s *SimpleServer) Run(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
return s.Serve(s.Listener)
}
// Start the server
func (s *SimpleServer) Start(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.Listener == nil {
listener, err := listenConfig.Listen(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.Listener = listener
}
s.Address = s.Listener.Addr().String()
go s.Serve(s.Listener)
return nil
}
// Close closes the listener
func (s *SimpleServer) Close() error {
if s.Listener == nil {
return nil
}
return s.Listener.Close()
}
// ProxyURL returns the URL of the proxy
func (s *SimpleServer) ProxyURL() string {
u := url.URL{
Scheme: "ss",
User: url.UserPassword(s.Cipher, s.Password),
Host: s.Address,
}
return u.String()
}