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
115
|
// Package client exposes a socks5 proxy that uses obfs4 to communicate with the server,
// with an optional kcp wire transport.
package client
import (
"errors"
"fmt"
"log"
"net"
"0xacab.org/leap/obfsvpn"
"github.com/kalikaneko/socks5"
"github.com/xtaci/kcp-go"
)
var (
ErrAlreadyRunning = errors.New("already initialized")
ErrNotRunning = errors.New("server not running")
)
type Client struct {
kcp bool
socksAddr string
obfs4Cert string
server *socks5.Server
EventLogger EventLogger
}
type EventLogger interface {
Log(state string, message string)
Error(message string)
}
func NewClient(kcp bool, socksAddr, obfs4Cert string) *Client {
return &Client{
kcp: kcp,
socksAddr: socksAddr,
obfs4Cert: obfs4Cert,
}
}
func (c *Client) Start() (bool, error) {
defer func() {
c.log("STOPPED", "", nil)
}
if c.IsStarted() {
c.error("Cannot start proxy server, already running")
return false, ErrAlreadyRunning
}
c.server = &socks5.Server{
Addr: c.socksAddr,
BindIP: "127.0.0.1",
}
dialer, err := obfsvpn.NewDialerFromCert(c.obfs4Cert)
if err != nil {
c.error("Error getting dialer: %v\n", err)
return false, err
}
if c.kcp {
dialer.DialFunc = func(network, address string) (net.Conn, error) {
c.log("RUNNING", "Dialing kcp://%s\n", address)
return kcp.Dial(address)
}
}
c.server.Dial = dialer.Dial
c.log("RUNNING", "[+] Starting socks5 proxy at %s\n", c.socksAddr)
if err := c.server.ListenAndServe(); err != nil {
c.error("error while listening: %v\n", err)
c.server = nil
return false, err
}
return true, nil
}
func (c *Client) Stop() (bool, error) {
if !c.IsStarted() {
return false, ErrNotRunning
}
if err := c.server.Close(); err != nil {
c.error("error while stopping: %v\n", err)
return false, err
}
c.server = nil
return true, nil
}
func (c *Client) log(state string, format string, a ...interface{}) {
if c.EventLogger != nil {
c.EventLogger.Log(state, fmt.Sprintf(format, a...))
return
}
log.Printf(format, a...)
}
func (c *Client) error(format string, a ...interface{}) {
if c.EventLogger != nil {
c.EventLogger.Error(fmt.Sprintf(format, a...))
return
}
log.Printf(format, a...)
}
func (c *Client) IsStarted() bool {
return c.server != nil
}
|