This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
115 lines (98 loc) · 2.2 KB
/
main.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
115
package main
import (
"flag"
"fmt"
"net"
"os"
"strconv"
"golang.org/x/net/context"
"time"
"io"
"strings"
socks5 "github.com/armon/go-socks5"
"github.com/aybabtme/iocontrol"
)
var (
rpool *iocontrol.ReaderPool
wpool *iocontrol.WriterPool
latency time.Duration
)
func main() {
var listen, ratekpbs, latencyms string
flag.StringVar(&listen, "listen", "", "address to listen on, e.g 127.0.0.1:8000 (required)")
flag.StringVar(&ratekpbs, "rate", "", "rate to limit to, in kpbs (required)")
flag.StringVar(&latencyms, "latency", "", "Latency to add to operations, in ms (required)")
flag.Parse()
verrs := []string{}
if listen == "" {
verrs = append(verrs, "listen is a required flag")
}
if ratekpbs == "" {
verrs = append(verrs, "rate is a required flag")
}
if latencyms == "" {
verrs = append(verrs, "latency is a required flag")
}
rate, err := strconv.Atoi(ratekpbs)
if err != nil {
verrs = append(verrs, "ratekbps needs to be numeric only")
}
latencyi, err := strconv.Atoi(latencyms)
if err != nil {
verrs = append(verrs, "latency needs to be numeric only")
}
latency = time.Duration(latencyi) * time.Millisecond
if len(verrs) > 0 {
flag.Usage()
fmt.Println("")
fmt.Println(strings.Join(verrs, "\n"))
os.Exit(2)
}
rpool = iocontrol.NewReaderPool(rate*iocontrol.KiB, 10*time.Millisecond)
wpool = iocontrol.NewWriterPool(rate*iocontrol.KiB, 10*time.Millisecond)
conf := &socks5.Config{
Dial: dial,
}
server, err := socks5.New(conf)
if err != nil {
panic(err)
}
if err := server.ListenAndServe("tcp", listen); err != nil {
panic(err)
}
}
type conn struct {
net.Conn
r io.Reader
relr func()
w io.Writer
relw func()
}
func (c *conn) Read(b []byte) (n int, err error) {
time.Sleep(latency)
return c.r.Read(b)
}
func (c *conn) Write(b []byte) (n int, err error) {
time.Sleep(latency)
return c.w.Write(b)
}
func (c *conn) Close() error {
c.relr()
c.relw()
return c.Conn.Close()
}
func dial(ctx context.Context, network, addr string) (net.Conn, error) {
c, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
r, relr := rpool.Get(c)
w, relw := wpool.Get(c)
return &conn{
Conn: c,
r: r,
relr: relr,
w: w,
relw: relw,
}, nil
}