forked from firefart/gosocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
85 lines (76 loc) · 1.64 KB
/
proxy.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
package socks
import (
"context"
"io"
"net"
"time"
)
// ProxyHandler is the interface for handling the proxy requests
type ProxyHandler interface {
Init(net.Addr, Request) (io.ReadWriteCloser, *Error)
ReadFromClient(context.Context, io.ReadCloser, io.WriteCloser) error
ReadFromRemote(context.Context, io.ReadCloser, io.WriteCloser) error
Close() error
}
// Proxy is the main struct
type Proxy struct {
ServerAddr string
Done chan struct{}
Proxyhandler ProxyHandler
Timeout time.Duration
Log Logger
}
func NewSimpleProxy(addr string, handler ProxyHandler) *Proxy {
return &Proxy{
ServerAddr: addr,
Proxyhandler: handler,
Timeout: time.Second * 60,
Log: nil,
Done: nil,
}
}
func NewProxy(addr string, handler ProxyHandler, done chan struct{}, timeout time.Duration, log Logger) *Proxy {
return &Proxy{
ServerAddr: addr,
Done: done,
Proxyhandler: handler,
Timeout: timeout,
Log: log,
}
}
// Start is the main function to start a proxy
func (p *Proxy) Start() error {
if p.Log == nil {
p.Log = &NilLogger{} // allow not to set logger
}
listener, err := net.Listen("tcp", p.ServerAddr)
if err != nil {
return err
}
go p.run(listener)
return nil
}
func (p *Proxy) run(listener net.Listener) {
for {
select {
case <-p.Done:
return
default:
connection, err := listener.Accept()
if err == nil {
go p.handle(connection)
} else {
p.Log.Errorf("Error accepting conn: %v", err)
}
}
}
}
// Stop stops the proxy
func (p *Proxy) Stop() {
p.Log.Warn("Stopping proxy")
if p.Done == nil {
return
}
close(p.Done)
p.Done = nil
}