-
Notifications
You must be signed in to change notification settings - Fork 10
/
simple_packet_server.go
103 lines (93 loc) · 2.17 KB
/
simple_packet_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
102
103
package shadowsocks
import (
"context"
"fmt"
"net"
"net/url"
)
// SimplePacketServer is a simplified server, which can be configured as easily as client.
type SimplePacketServer struct {
PacketServer
PacketConn net.PacketConn
Network string
Address string
}
// NewSimplePacketServer creates a new NewSimplePacketServer
func NewSimplePacketServer(addr string) (*SimplePacketServer, error) {
s := &SimplePacketServer{
PacketServer: *NewPacketServer(),
}
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 = "udp"
return s, nil
}
// Run the PacketServer
func (s *SimplePacketServer) Run(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.PacketConn == nil {
packetConn, err := listenConfig.ListenPacket(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.PacketConn = packetConn
}
s.Address = s.PacketConn.LocalAddr().String()
return s.ServePacket(s.PacketConn)
}
// Start the PacketServer
func (s *SimplePacketServer) Start(ctx context.Context) error {
var listenConfig net.ListenConfig
if s.PacketConn == nil {
packetConn, err := listenConfig.ListenPacket(ctx, s.Network, s.Address)
if err != nil {
return err
}
s.PacketConn = packetConn
}
s.Address = s.PacketConn.LocalAddr().String()
go s.ServePacket(s.PacketConn)
return nil
}
// Close closes the listener
func (s *SimplePacketServer) Close() error {
if s.PacketConn == nil {
return nil
}
return s.PacketConn.Close()
}
// ProxyURL returns the URL of the proxy
func (s *SimplePacketServer) ProxyURL() string {
u := url.URL{
Scheme: "ss",
User: url.UserPassword(s.Cipher, s.Password),
Host: s.Address,
}
return u.String()
}