forked from ginuerzh/gost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
114 lines (96 loc) · 2.48 KB
/
handler.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
package gost
import (
"bufio"
"crypto/tls"
"net"
"net/url"
"github.com/ginuerzh/gosocks4"
"github.com/ginuerzh/gosocks5"
"github.com/go-log/log"
)
// Handler is a proxy server handler
type Handler interface {
Handle(net.Conn)
}
// HandlerOptions describes the options for Handler.
type HandlerOptions struct {
Addr string
Chain *Chain
Users []*url.Userinfo
TLSConfig *tls.Config
Whitelist *Permissions
Blacklist *Permissions
}
// HandlerOption allows a common way to set handler options.
type HandlerOption func(opts *HandlerOptions)
// AddrHandlerOption sets the Addr option of HandlerOptions.
func AddrHandlerOption(addr string) HandlerOption {
return func(opts *HandlerOptions) {
opts.Addr = addr
}
}
// ChainHandlerOption sets the Chain option of HandlerOptions.
func ChainHandlerOption(chain *Chain) HandlerOption {
return func(opts *HandlerOptions) {
opts.Chain = chain
}
}
// UsersHandlerOption sets the Users option of HandlerOptions.
func UsersHandlerOption(users ...*url.Userinfo) HandlerOption {
return func(opts *HandlerOptions) {
opts.Users = users
}
}
// TLSConfigHandlerOption sets the TLSConfig option of HandlerOptions.
func TLSConfigHandlerOption(config *tls.Config) HandlerOption {
return func(opts *HandlerOptions) {
opts.TLSConfig = config
}
}
// WhitelistHandlerOption sets the Whitelist option of HandlerOptions.
func WhitelistHandlerOption(whitelist *Permissions) HandlerOption {
return func(opts *HandlerOptions) {
opts.Whitelist = whitelist
}
}
// BlacklistHandlerOption sets the Blacklist option of HandlerOptions.
func BlacklistHandlerOption(blacklist *Permissions) HandlerOption {
return func(opts *HandlerOptions) {
opts.Blacklist = blacklist
}
}
type autoHandler struct {
options []HandlerOption
}
// AutoHandler creates a server Handler for auto proxy server.
func AutoHandler(opts ...HandlerOption) Handler {
h := &autoHandler{
options: opts,
}
return h
}
func (h *autoHandler) Handle(conn net.Conn) {
defer conn.Close()
br := bufio.NewReader(conn)
b, err := br.Peek(1)
if err != nil {
log.Log(err)
return
}
cc := &bufferdConn{Conn: conn, br: br}
switch b[0] {
case gosocks4.Ver4:
return // SOCKS4(a) does not suppport authentication method, so we ignore it.
case gosocks5.Ver5:
SOCKS5Handler(h.options...).Handle(cc)
default: // http
HTTPHandler(h.options...).Handle(cc)
}
}
type bufferdConn struct {
net.Conn
br *bufio.Reader
}
func (c *bufferdConn) Read(b []byte) (int, error) {
return c.br.Read(b)
}