├── .github
├── PULL_REQUEST_TEMPLATE
├── CONTRIBUTING.md
└── ISSUE_TEMPLATE
│ ├── discussion.md
│ ├── Question.md
│ ├── question.md
│ ├── feature_request.md
│ └── bug_report.md
├── scripts
├── iproute.sh
└── iptables.sh
├── .travis.yml
├── sskey_test.go
├── init.go
├── run_notlinux.go
├── run_linux.go
├── cli
└── brook
│ ├── .gitignore
│ ├── buildAll.sh
│ └── main.go
├── qr.go
├── sskey.go
├── sysproxy
├── system_darwin_test.go
├── system_linux.go
├── system_darwin.go
└── system_windows.go
├── util.go
├── plugin
├── middleman.go
└── middleman
│ └── blackwhite
│ └── blackwhite.go
├── vpn_linux.go
├── vpn_darwin.go
├── cipher.go
├── vpn_windows.go
├── tproxy
├── tcp.go
└── udp.go
├── vpn.go
├── encrypt.go
├── socks5tohttp.go
├── run.go
├── relay.go
├── server.go
├── socks5.go
├── tunnel.go
├── tproxy_linux.go
├── ssserver.go
├── README.md
├── ssclient.go
├── client.go
├── OPENSOURCELICENSES
└── LICENSE
/.github/PULL_REQUEST_TEMPLATE:
--------------------------------------------------------------------------------
1 | Fixes # .
2 |
3 | Changes proposed in this pull request:
4 | -
5 | -
6 | -
7 |
8 | @mentions
9 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ### I want to create a PR.
2 |
3 | 1. Please create a issue first
4 | 1. Please create PR on `develop` branch
5 |
--------------------------------------------------------------------------------
/scripts/iproute.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | sudo ip rule add fwmark 1 lookup 100
4 | sudo ip route add local 0.0.0.0/0 dev lo table 100
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 | sudo: false
3 | go:
4 | install:
5 | - go get -t -v .
6 | script:
7 | - go test -v .
8 | - cd cli/brook && go get -t -v . && go build .
9 |
--------------------------------------------------------------------------------
/sskey_test.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import "testing"
4 |
5 | func TestMakeSSKey(t *testing.T) {
6 | key := MakeSSKey("a")
7 | t.Log(len(key))
8 | t.Log(key)
9 | }
10 |
--------------------------------------------------------------------------------
/init.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "github.com/txthinking/socks5"
5 | "github.com/txthinking/x"
6 | )
7 |
8 | var Dial x.Dialer = x.DefaultDial
9 |
10 | // EnableDebug
11 | func EnableDebug() {
12 | socks5.Debug = true
13 | }
14 |
--------------------------------------------------------------------------------
/run_notlinux.go:
--------------------------------------------------------------------------------
1 | // +build !linux
2 |
3 | package brook
4 |
5 | import "errors"
6 |
7 | func RunTproxy(address, server, password string, tcpTimeout, tcpDeadline, udpDeadline int) error {
8 | return errors.New("Only works on Linux")
9 | }
10 |
--------------------------------------------------------------------------------
/run_linux.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | // RunTproxy used to start a tproxy
4 | func RunTproxy(address, server, password string, tcpTimeout, tcpDeadline, udpDeadline int) error {
5 | c, err := NewTproxy(address, server, password, tcpTimeout, tcpDeadline, udpDeadline)
6 | if err != nil {
7 | return err
8 | }
9 | return c.ListenAndServe()
10 | }
11 |
--------------------------------------------------------------------------------
/cli/brook/.gitignore:
--------------------------------------------------------------------------------
1 | main
2 | brook
3 | brook_linux_386
4 | brook_linux_arm64
5 | brook_linux_arm7
6 | brook_linux_arm6
7 | brook_linux_arm5
8 | brook_macos_amd64
9 | brook_windows_amd64.exe
10 | brook_windows_386.exe
11 | brook_linux_mips
12 | brook_linux_mipsle
13 | brook_linux_mips64
14 | brook_linux_mips64le
15 | brook_linux_ppc64
16 | brook_linux_ppc64le
17 |
--------------------------------------------------------------------------------
/qr.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "net/url"
5 | "os"
6 |
7 | "github.com/mdp/qrterminal"
8 | )
9 |
10 | // QR generate and print QR code
11 | func QR(server, password string) {
12 | // TODO
13 | t := "default"
14 | s := t + " " + server + " " + password
15 | s = "brook://" + url.PathEscape(s)
16 | qrterminal.Generate(s, qrterminal.H, os.Stdout)
17 | }
18 |
--------------------------------------------------------------------------------
/sskey.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import "crypto/md5"
4 |
5 | // MakeSSKey used to make shadowsocks aes-256-cfb key
6 | func MakeSSKey(password string) []byte {
7 | h := md5.New()
8 | h.Write([]byte(password))
9 | tmp := h.Sum(nil) // 16 len
10 |
11 | h = md5.New()
12 | h.Write(tmp)
13 | h.Write([]byte(password))
14 | tmp1 := h.Sum(nil) // 16 len
15 |
16 | return append(tmp, tmp1...) // 32 len
17 | }
18 |
--------------------------------------------------------------------------------
/sysproxy/system_darwin_test.go:
--------------------------------------------------------------------------------
1 | // +build darwin
2 | // +build amd64 386
3 |
4 | package sysproxy
5 |
6 | import "testing"
7 |
8 | func TestGetNetworkServices(t *testing.T) {
9 | nss, err := getNetworkServices()
10 | if err != nil {
11 | t.Fatal(err)
12 | }
13 | for _, v := range nss {
14 | t.Log("|" + v + "|")
15 | }
16 | }
17 |
18 | func TestSetDNSServer(t *testing.T) {
19 | err := SetDNSServer("8.8.4.4")
20 | if err != nil {
21 | t.Fatal(err)
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/discussion.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Discussion
3 | about: Want to discuss a topic about Brook?
4 | title: ''
5 | labels: discussion
6 | assignees: ''
7 |
8 | ---
9 |
10 | ### Prerequisites
11 |
12 | * [ ] Did you check the [wiki](https://github.com/txthinking/brook/wiki)?
13 | * [ ] Did you search in [issues](https://github.com/txthinking/brook/issues)?
14 | * [ ] Are you running the latest version?
15 | * [ ] I will write this according to this template.
16 | * [ ] I will write this in English.
17 |
18 | ### Discussion
19 |
20 |
--------------------------------------------------------------------------------
/util.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "net"
5 |
6 | "github.com/txthinking/socks5"
7 | )
8 |
9 | func ErrorReply(r *socks5.Request, c *net.TCPConn, e error) error {
10 | var p *socks5.Reply
11 | if r.Atyp == socks5.ATYPIPv4 || r.Atyp == socks5.ATYPDomain {
12 | p = socks5.NewReply(socks5.RepConnectionRefused, socks5.ATYPIPv4, net.IPv4zero, []byte{0x00, 0x00})
13 | } else {
14 | p = socks5.NewReply(socks5.RepConnectionRefused, socks5.ATYPIPv6, net.IPv6zero, []byte{0x00, 0x00})
15 | }
16 | if err := p.WriteTo(c); err != nil {
17 | return err
18 | }
19 | return e
20 | }
21 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Question.md:
--------------------------------------------------------------------------------
1 | ```
2 | name: Question
3 | labels: question
4 | about: Have any questions regarding how to use brook?
5 | ```
6 |
7 | ### Prerequisites
8 |
9 | * [ ] Did you check the [wiki](https://github.com/txthinking/brook/wiki)?
10 | * [ ] Did you search in [issues](https://github.com/txthinking/brook/issues)?
11 | * [ ] I will write this according to this template.
12 | * [ ] I will write this in English.
13 |
14 | ### Environment
15 |
16 | * Brook Version:
17 | * Operating System:
18 | * Operating System Version:
19 | * Operation System Language:
20 |
21 | ### Question
22 |
23 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/question.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Question
3 | about: Have any questions regarding how to use Brook?
4 | title: ''
5 | labels: question
6 | assignees: ''
7 |
8 | ---
9 |
10 | ### Prerequisites
11 |
12 | * [ ] Did you check the [wiki](https://github.com/txthinking/brook/wiki)?
13 | * [ ] Did you search in [issues](https://github.com/txthinking/brook/issues)?
14 | * [ ] Are you running the latest version?
15 | * [ ] I will write this according to this template.
16 | * [ ] I will write this in English.
17 |
18 | ### Environment
19 |
20 | * Brook Version:
21 | * Server Operating System:
22 | * Server Operating System Version:
23 | * Server Operation System Language:
24 | * Client Operating System:
25 | * Client Operating System Version:
26 | * Client Operation System Language:
27 |
28 | ### Expected Behavior
29 |
30 | ### Current Behavior
31 |
32 | ### Detailed Description
33 |
34 | ### Possible Solution
35 |
36 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Want us to add something to Brook?
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | ### Prerequisites
11 |
12 | * [ ] Did you check the [wiki](https://github.com/txthinking/brook/wiki)?
13 | * [ ] Did you search in [issues](https://github.com/txthinking/brook/issues)?
14 | * [ ] Are you running the latest version?
15 | * [ ] I will write this according to this template.
16 | * [ ] I will write this in English.
17 |
18 | ### Environment
19 |
20 | * Brook Version:
21 | * Server Operating System:
22 | * Server Operating System Version:
23 | * Server Operation System Language:
24 | * Client Operating System:
25 | * Client Operating System Version:
26 | * Client Operation System Language:
27 |
28 | ### Expected Behavior
29 |
30 | ### Current Behavior
31 |
32 | ### Detailed Description
33 |
34 | ### Possible Solution
35 |
36 |
--------------------------------------------------------------------------------
/cli/brook/buildAll.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GOOS=linux GOARCH=amd64 go build -o brook .
4 | GOOS=linux GOARCH=386 go build -o brook_linux_386 .
5 | GOOS=linux GOARCH=arm64 go build -o brook_linux_arm64 .
6 | GOOS=linux GOARCH=arm GOARM=7 go build -o brook_linux_arm7 .
7 | GOOS=linux GOARCH=arm GOARM=6 go build -o brook_linux_arm6 .
8 | GOOS=linux GOARCH=arm GOARM=5 go build -o brook_linux_arm5 .
9 | GOOS=linux GOARCH=mips go build -o brook_linux_mips .
10 | GOOS=linux GOARCH=mipsle go build -o brook_linux_mipsle .
11 | GOOS=linux GOARCH=mips64 go build -o brook_linux_mips64 .
12 | GOOS=linux GOARCH=mips64le go build -o brook_linux_mips64le .
13 | GOOS=linux GOARCH=ppc64 go build -o brook_linux_ppc64 .
14 | GOOS=linux GOARCH=ppc64le go build -o brook_linux_ppc64le .
15 | GOOS=darwin GOARCH=amd64 go build -o brook_darwin_amd64 .
16 | GOOS=windows GOARCH=amd64 go build -o brook_windows_amd64.exe .
17 | GOOS=windows GOARCH=386 go build -o brook_windows_386.exe .
18 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Did something not work as expected?
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | ### Prerequisites
11 |
12 | * [ ] Did you check the [wiki](https://github.com/txthinking/brook/wiki)?
13 | * [ ] Did you search in [issues](https://github.com/txthinking/brook/issues)?
14 | * [ ] Are you running the latest version?
15 | * [ ] I will write this according to this template.
16 | * [ ] I will write this in English.
17 |
18 | ### Environment
19 |
20 | * Brook Version:
21 | * Server Operating System:
22 | * Server Operating System Version:
23 | * Server Operation System Language:
24 | * Client Operating System:
25 | * Client Operating System Version:
26 | * Client Operation System Language:
27 |
28 | ### Expected Behavior
29 |
30 | ### Current Behavior
31 |
32 | ### Steps to Reproduce
33 |
34 | 1.
35 | 2.
36 | 3.
37 |
38 | ### Detailed Description
39 |
40 | ### Possible Solution
41 |
42 |
--------------------------------------------------------------------------------
/plugin/middleman.go:
--------------------------------------------------------------------------------
1 | package plugin
2 |
3 | import (
4 | "net"
5 |
6 | "github.com/txthinking/socks5"
7 | )
8 |
9 | // Socks5Middleman is a middleman who can intercept and handle request
10 | type Socks5Middleman interface {
11 | // TCPRequestHandle does not need to close conn,
12 | // if return true that means the request has been handled
13 | TCPHandle(*socks5.Server, *net.TCPConn, *socks5.Request) (bool, error)
14 |
15 | // UDPPacketHandle handles udp packet.
16 | // If return true that means the request has been handled.
17 | UDPHandle(*socks5.Server, *net.UDPAddr, *socks5.Datagram) (bool, error)
18 | }
19 |
20 | // HTTPMiddleman is a middleman who can intercept and handle request
21 | type HTTPMiddleman interface {
22 | // Addr is the absoluteURI, RFC 2396.
23 | // Request is the http header, don't guarantee it is complete, but contains the host line
24 | // Has not written anything to conn.
25 | // Handle does not need to close conn.
26 | // If handled is true or err is not nil that means the request has been handled
27 | Handle(method, addr string, request []byte, conn *net.TCPConn) (handled bool, err error)
28 | }
29 |
--------------------------------------------------------------------------------
/scripts/iptables.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | sudo sysctl -w net.ipv4.ip_forward=1
4 | sudo sysctl -w net.ipv6.conf.all.forwarding=1
5 |
6 | sudo iptables -t mangle -F
7 | sudo iptables -t mangle -X
8 |
9 | sudo iptables -t mangle -A PREROUTING -d 0.0.0.0/8 -j RETURN
10 | sudo iptables -t mangle -A PREROUTING -d 10.0.0.0/8 -j RETURN
11 | sudo iptables -t mangle -A PREROUTING -d 127.0.0.0/8 -j RETURN
12 | sudo iptables -t mangle -A PREROUTING -d 169.254.0.0/16 -j RETURN
13 | sudo iptables -t mangle -A PREROUTING -d 172.16.0.0/12 -j RETURN
14 | sudo iptables -t mangle -A PREROUTING -d 192.168.0.0/16 -j RETURN
15 | sudo iptables -t mangle -A PREROUTING -d 224.0.0.0/4 -j RETURN
16 | sudo iptables -t mangle -A PREROUTING -d 240.0.0.0/4 -j RETURN
17 | sudo iptables -t mangle -A PREROUTING -d BROOK_SERVER_IP -j RETURN
18 |
19 | sudo iptables -t mangle -A PREROUTING -p tcp -m socket -j MARK --set-mark 1
20 | sudo iptables -t mangle -A PREROUTING -p tcp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 1080
21 | sudo iptables -t mangle -A PREROUTING -p udp -m socket -j MARK --set-mark 1
22 | sudo iptables -t mangle -A PREROUTING -p udp -j TPROXY --tproxy-mark 0x1/0x1 --on-port 1080
23 |
--------------------------------------------------------------------------------
/sysproxy/system_linux.go:
--------------------------------------------------------------------------------
1 | package sysproxy
2 |
3 | import (
4 | "errors"
5 | "os"
6 | "os/exec"
7 | "regexp"
8 | )
9 |
10 | // GetNetworkInterfaces returns interface list
11 | func GetNetworkInterfaces() ([]string, error) {
12 | return []string{}, nil
13 | }
14 |
15 | func TurnOnSystemProxy(pac string) error {
16 | return nil
17 | }
18 |
19 | func TurnOffSystemProxy() error {
20 | return nil
21 | }
22 |
23 | // SetDNSServer used to set system DNS server
24 | func SetDNSServer(server string) error {
25 | f, err := os.OpenFile("/etc/resolv.conf", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
26 | if err != nil {
27 | return err
28 | }
29 | defer f.Close()
30 | _, err = f.WriteString("nameserver " + server)
31 | if err != nil {
32 | return err
33 | }
34 | return nil
35 | }
36 |
37 | // GetDefaultGateway returns default gateway
38 | func GetDefaultGateway() (string, error) {
39 | c := exec.Command("ip", "route")
40 | out, err := c.CombinedOutput()
41 | if err != nil {
42 | return "", errors.New(string(out) + err.Error())
43 | }
44 | r, err := regexp.Compile(`default.*?(\d+.\d+\.\d+\.\d+)`)
45 | if err != nil {
46 | return "", err
47 | }
48 | ss := r.FindStringSubmatch(string(out))
49 | if len(ss) == 0 {
50 | return "", errors.New("Can not find default gateway")
51 | }
52 | return ss[1], nil
53 | }
54 |
--------------------------------------------------------------------------------
/vpn_linux.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "os/exec"
6 |
7 | "github.com/txthinking/brook/sysproxy"
8 | )
9 |
10 | // AddRoutes adds routes
11 | func (v *VPN) AddRoutes() error {
12 | c := exec.Command("ip", "route", "add", "0.0.0.0/1", "via", v.TunGateway)
13 | if out, err := c.CombinedOutput(); err != nil {
14 | return errors.New(string(out) + err.Error())
15 | }
16 | c = exec.Command("ip", "route", "add", "128.0.0.0/1", "via", v.TunGateway)
17 | if out, err := c.CombinedOutput(); err != nil {
18 | return errors.New(string(out) + err.Error())
19 | }
20 | gw, err := sysproxy.GetDefaultGateway()
21 | if err != nil {
22 | return err
23 | }
24 | c = exec.Command("ip", "route", "add", v.ServerIP, "via", gw)
25 | if out, err := c.CombinedOutput(); err != nil {
26 | return errors.New(string(out) + err.Error())
27 | }
28 | return nil
29 | }
30 |
31 | // DeleteRoutes deletes routes
32 | func (v *VPN) DeleteRoutes() error {
33 | c := exec.Command("ip", "route", "del", "0.0.0.0/1", "via", v.TunGateway)
34 | if out, err := c.CombinedOutput(); err != nil {
35 | return errors.New(string(out) + err.Error())
36 | }
37 | c = exec.Command("ip", "route", "del", "128.0.0.0/1", "via", v.TunGateway)
38 | if out, err := c.CombinedOutput(); err != nil {
39 | return errors.New(string(out) + err.Error())
40 | }
41 | gw, err := sysproxy.GetDefaultGateway()
42 | if err != nil {
43 | return err
44 | }
45 | c = exec.Command("ip", "route", "del", v.ServerIP, "via", gw)
46 | if out, err := c.CombinedOutput(); err != nil {
47 | return errors.New(string(out) + err.Error())
48 | }
49 | return nil
50 | }
51 |
--------------------------------------------------------------------------------
/vpn_darwin.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "os/exec"
6 |
7 | "github.com/txthinking/brook/sysproxy"
8 | )
9 |
10 | // AddRoutes adds routes
11 | func (v *VPN) AddRoutes() error {
12 | c := exec.Command("route", "add", "-net", "0.0.0.0", v.TunGateway, "-netmask", "128.0.0.0")
13 | if out, err := c.CombinedOutput(); err != nil {
14 | return errors.New(string(out) + err.Error())
15 | }
16 | c = exec.Command("route", "add", "-net", "128.0.0.0", v.TunGateway, "-netmask", "128.0.0.0")
17 | if out, err := c.CombinedOutput(); err != nil {
18 | return errors.New(string(out) + err.Error())
19 | }
20 | gw, err := sysproxy.GetDefaultGateway()
21 | if err != nil {
22 | return err
23 | }
24 | c = exec.Command("route", "add", "-host", v.ServerIP, gw, "-netmask", "255.255.255.255")
25 | if out, err := c.CombinedOutput(); err != nil {
26 | return errors.New(string(out) + err.Error())
27 | }
28 | return nil
29 | }
30 |
31 | // DeleteRoutes deletes routes
32 | func (v *VPN) DeleteRoutes() error {
33 | c := exec.Command("route", "delete", "-net", "0.0.0.0", v.TunGateway, "-netmask", "128.0.0.0")
34 | if out, err := c.CombinedOutput(); err != nil {
35 | return errors.New(string(out) + err.Error())
36 | }
37 | c = exec.Command("route", "delete", "-net", "128.0.0.0", v.TunGateway, "-netmask", "128.0.0.0")
38 | if out, err := c.CombinedOutput(); err != nil {
39 | return errors.New(string(out) + err.Error())
40 | }
41 | gw, err := sysproxy.GetDefaultGateway()
42 | if err != nil {
43 | return err
44 | }
45 | c = exec.Command("route", "delete", "-host", v.ServerIP, gw, "-netmask", "255.255.255.255")
46 | if out, err := c.CombinedOutput(); err != nil {
47 | return errors.New(string(out) + err.Error())
48 | }
49 | return nil
50 | }
51 |
--------------------------------------------------------------------------------
/cipher.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "errors"
7 | "net"
8 | "time"
9 |
10 | "github.com/txthinking/x"
11 | )
12 |
13 | // CipherConn is the encrypted connection
14 | type CipherConn struct {
15 | c net.Conn
16 | sr cipher.StreamReader
17 | sw cipher.StreamWriter
18 | }
19 |
20 | // NewCipherConn returns a new CipherConn, iv length must be equal aes.BlockSize
21 | func NewCipherConn(c net.Conn, key []byte, iv []byte) (*CipherConn, error) {
22 | if len(iv) != aes.BlockSize {
23 | return nil, errors.New("Invalid IV length")
24 | }
25 | block, err := aes.NewCipher(x.AESMake256Key(key))
26 | if err != nil {
27 | return nil, err
28 | }
29 | return &CipherConn{
30 | c: c,
31 | sr: cipher.StreamReader{
32 | S: cipher.NewCFBDecrypter(block, iv),
33 | R: c,
34 | },
35 | sw: cipher.StreamWriter{
36 | S: cipher.NewCFBEncrypter(block, iv),
37 | W: c,
38 | },
39 | }, nil
40 | }
41 |
42 | // Read is just like net.Conn interface
43 | func (c *CipherConn) Read(b []byte) (n int, err error) {
44 | return c.sr.Read(b)
45 | }
46 |
47 | // Write is just like net.Conn interface
48 | func (c *CipherConn) Write(b []byte) (n int, err error) {
49 | return c.sw.Write(b)
50 | }
51 |
52 | // Close is just like net.Conn interface
53 | func (c *CipherConn) Close() error {
54 | return c.c.Close()
55 | }
56 |
57 | // LocalAddr is just like net.Conn interface
58 | func (c *CipherConn) LocalAddr() net.Addr {
59 | return c.c.LocalAddr()
60 | }
61 |
62 | // RemoteAddr is just like net.Conn interface
63 | func (c *CipherConn) RemoteAddr() net.Addr {
64 | return c.c.RemoteAddr()
65 | }
66 |
67 | // SetDeadline is just like net.Conn interface
68 | func (c *CipherConn) SetDeadline(t time.Time) error {
69 | return c.c.SetDeadline(t)
70 | }
71 |
72 | // SetReadDeadline is just like net.Conn interface
73 | func (c *CipherConn) SetReadDeadline(t time.Time) error {
74 | return c.c.SetReadDeadline(t)
75 | }
76 |
77 | // SetWriteDeadline is just like net.Conn interface
78 | func (c *CipherConn) SetWriteDeadline(t time.Time) error {
79 | return c.c.SetWriteDeadline(t)
80 | }
81 |
--------------------------------------------------------------------------------
/vpn_windows.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "os/exec"
6 | "syscall"
7 |
8 | "github.com/txthinking/brook/sysproxy"
9 | )
10 |
11 | // AddRoutes adds routes
12 | func (v *VPN) AddRoutes() error {
13 | c := exec.Command("route", "add", "0.0.0.0", "mask", "128.0.0.0", v.TunGateway)
14 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
15 | if out, err := c.CombinedOutput(); err != nil {
16 | return errors.New(string(out) + err.Error())
17 | }
18 | c = exec.Command("route", "add", "128.0.0.0", "mask", "128.0.0.0", v.TunGateway)
19 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
20 | if out, err := c.CombinedOutput(); err != nil {
21 | return errors.New(string(out) + err.Error())
22 | }
23 | if v.DefaultGateway == "" {
24 | var err error
25 | v.DefaultGateway, err = sysproxy.GetDefaultGateway()
26 | if err != nil {
27 | return err
28 | }
29 | }
30 | c = exec.Command("route", "add", v.ServerIP, "mask", "255.255.255.255", v.DefaultGateway, "metric", "1")
31 | if out, err := c.CombinedOutput(); err != nil {
32 | return errors.New(string(out) + err.Error())
33 | }
34 | return nil
35 | }
36 |
37 | // DeleteRoutes deletes routes
38 | func (v *VPN) DeleteRoutes() error {
39 | c := exec.Command("route", "delete", "0.0.0.0", "mask", "128.0.0.0", v.TunGateway)
40 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
41 | if out, err := c.CombinedOutput(); err != nil {
42 | return errors.New(string(out) + err.Error())
43 | }
44 | c = exec.Command("route", "delete", "128.0.0.0", "mask", "128.0.0.0", v.TunGateway)
45 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
46 | if out, err := c.CombinedOutput(); err != nil {
47 | return errors.New(string(out) + err.Error())
48 | }
49 | if v.DefaultGateway == "" {
50 | var err error
51 | v.DefaultGateway, err = sysproxy.GetDefaultGateway()
52 | if err != nil {
53 | return err
54 | }
55 | }
56 | c = exec.Command("route", "delete", v.ServerIP, "mask", "255.255.255.255", v.DefaultGateway, "metric", "1")
57 | if out, err := c.CombinedOutput(); err != nil {
58 | return errors.New(string(out) + err.Error())
59 | }
60 | return nil
61 | }
62 |
--------------------------------------------------------------------------------
/sysproxy/system_darwin.go:
--------------------------------------------------------------------------------
1 | package sysproxy
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "os/exec"
7 | "regexp"
8 | )
9 |
10 | // GetNetworkInterfaces returns interface list
11 | func GetNetworkInterfaces() ([]string, error) {
12 | c := exec.Command("networksetup", "-listallnetworkservices")
13 | out, err := c.CombinedOutput()
14 | if err != nil {
15 | return nil, errors.New(string(out) + err.Error())
16 | }
17 | nss := make([]string, 0)
18 | reg := regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)
19 | for _, v := range bytes.Split(bytes.TrimSpace(out), []byte("\n")) {
20 | // An asterisk (*) denotes that a network service is disabled.
21 | if bytes.Contains(v, []byte("*")) {
22 | continue
23 | }
24 | ns := string(bytes.TrimSpace(v))
25 | c := exec.Command("networksetup", "-getinfo", ns)
26 | out, err := c.CombinedOutput()
27 | if err != nil {
28 | return nil, errors.New(string(out) + err.Error())
29 | }
30 | if !reg.MatchString(string(out)) {
31 | continue
32 | }
33 | nss = append(nss, ns)
34 | }
35 | if len(nss) == 0 {
36 | return nil, errors.New("no available network service")
37 | }
38 | return nss, nil
39 | }
40 |
41 | // TurnOnSystemProxy used to enable system pac proxy, pac is a URL.
42 | func TurnOnSystemProxy(pac string) error {
43 | nss, err := GetNetworkInterfaces()
44 | if err != nil {
45 | return err
46 | }
47 | for _, v := range nss {
48 | c := exec.Command("networksetup", "-setautoproxyurl", v, pac)
49 | if out, err := c.CombinedOutput(); err != nil {
50 | return errors.New(string(out) + err.Error())
51 | }
52 | c = exec.Command("networksetup", "-setautoproxystate", v, "on")
53 | if out, err := c.CombinedOutput(); err != nil {
54 | return errors.New(string(out) + err.Error())
55 | }
56 | }
57 | return nil
58 | }
59 |
60 | // TurnOffSystemProxy used to disable system pac proxy
61 | func TurnOffSystemProxy() error {
62 | nss, err := GetNetworkInterfaces()
63 | if err != nil {
64 | return err
65 | }
66 | for _, v := range nss {
67 | c := exec.Command("networksetup", "-setautoproxystate", v, "off")
68 | if out, err := c.CombinedOutput(); err != nil {
69 | return errors.New(string(out) + err.Error())
70 | }
71 | }
72 | return nil
73 | }
74 |
75 | // SetDNSServer used to set system DNS server
76 | func SetDNSServer(server string) error {
77 | nis, err := GetNetworkInterfaces()
78 | if err != nil {
79 | return err
80 | }
81 | for _, v := range nis {
82 | c := exec.Command("networksetup", "-setdnsservers", v, server)
83 | if out, err := c.CombinedOutput(); err != nil {
84 | return errors.New(string(out) + err.Error())
85 | }
86 | }
87 | return nil
88 | }
89 |
90 | // GetDefaultGateway returns default gateway
91 | func GetDefaultGateway() (string, error) {
92 | c := exec.Command("sh", "-c", "route get default | grep gateway | awk '{print $2}'")
93 | out, err := c.CombinedOutput()
94 | if err != nil {
95 | return "", errors.New(string(out) + err.Error())
96 | }
97 | return string(out), nil
98 | }
99 |
--------------------------------------------------------------------------------
/tproxy/tcp.go:
--------------------------------------------------------------------------------
1 | package tproxy
2 |
3 | import (
4 | "net"
5 | "os"
6 | "strconv"
7 | "strings"
8 | "syscall"
9 |
10 | "github.com/txthinking/x"
11 | )
12 |
13 | func ListenTCP(network string, laddr *net.TCPAddr) (*net.TCPListener, error) {
14 | l, err := net.ListenTCP(network, laddr)
15 | if err != nil {
16 | return nil, err
17 | }
18 | defer l.Close()
19 |
20 | f, err := l.File()
21 | if err != nil {
22 | return nil, err
23 | }
24 | defer f.Close()
25 | fd := int(f.Fd())
26 | if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
27 | return nil, err
28 | }
29 | tmp, err := net.FileListener(f)
30 | if err != nil {
31 | return nil, err
32 | }
33 | return tmp.(*net.TCPListener), nil
34 | }
35 |
36 | func DialTCP(network, addr string) (net.Conn, error) {
37 | taddr, err := net.ResolveTCPAddr("tcp", addr)
38 | if err != nil {
39 | return nil, err
40 | }
41 | saddr, err := tcpAddrToSocketAddr(taddr)
42 | if err != nil {
43 | return nil, err
44 | }
45 | fd, err := syscall.Socket(tcpAddrFamily("tcp", taddr, nil), syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
46 | if err != nil {
47 | return nil, err
48 | }
49 | if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
50 | syscall.Close(fd)
51 | return nil, err
52 | }
53 | if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
54 | syscall.Close(fd)
55 | return nil, err
56 | }
57 | if err := syscall.SetNonblock(fd, true); err != nil {
58 | syscall.Close(fd)
59 | return nil, err
60 | }
61 | if err = syscall.Connect(fd, saddr); err != nil && !strings.Contains(err.Error(), "operation now in progress") {
62 | syscall.Close(fd)
63 | return nil, err
64 | }
65 |
66 | f := os.NewFile(uintptr(fd), string(x.RandomNumber()))
67 | defer f.Close()
68 |
69 | c, err := net.FileConn(f)
70 | if err != nil {
71 | syscall.Close(fd)
72 | return nil, err
73 | }
74 | return c, nil
75 | }
76 |
77 | func tcpAddrToSocketAddr(addr *net.TCPAddr) (syscall.Sockaddr, error) {
78 | switch {
79 | case addr.IP.To4() != nil:
80 | ip := [4]byte{}
81 | copy(ip[:], addr.IP.To4())
82 |
83 | return &syscall.SockaddrInet4{Addr: ip, Port: addr.Port}, nil
84 |
85 | default:
86 | ip := [16]byte{}
87 | copy(ip[:], addr.IP.To16())
88 |
89 | zoneID, err := strconv.ParseUint(addr.Zone, 10, 32)
90 | if err != nil {
91 | return nil, err
92 | }
93 |
94 | return &syscall.SockaddrInet6{Addr: ip, Port: addr.Port, ZoneId: uint32(zoneID)}, nil
95 | }
96 | }
97 |
98 | func tcpAddrFamily(net string, laddr, raddr *net.TCPAddr) int {
99 | switch net[len(net)-1] {
100 | case '4':
101 | return syscall.AF_INET
102 | case '6':
103 | return syscall.AF_INET6
104 | }
105 |
106 | if (laddr == nil || laddr.IP.To4() != nil) &&
107 | (raddr == nil || raddr.IP.To4() != nil) {
108 | return syscall.AF_INET
109 | }
110 | return syscall.AF_INET6
111 | }
112 |
--------------------------------------------------------------------------------
/vpn.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "log"
7 | "net"
8 | "os"
9 | "os/signal"
10 | "syscall"
11 |
12 | "github.com/txthinking/brook/sysproxy"
13 | "github.com/txthinking/gotun2socks"
14 | "github.com/txthinking/gotun2socks/tun"
15 | )
16 |
17 | // VPN
18 | type VPN struct {
19 | Client *Client
20 | Tunnel *Tunnel
21 | Tun *gotun2socks.Tun2Socks
22 | ServerIP string
23 | TunGateway string
24 | DefaultGateway string
25 | }
26 |
27 | // NewVPN
28 | func NewVPN(addr, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int, tunDevice, tunIP, tunGateway, tunMask, defaultGateway string) (*VPN, error) {
29 | h, _, err := net.SplitHostPort(addr)
30 | if err != nil {
31 | return nil, err
32 | }
33 | if h != "127.0.0.1" {
34 | return nil, errors.New("Must listen on 127.0.0.1")
35 | }
36 | h, p, err := net.SplitHostPort(server)
37 | if err != nil {
38 | return nil, err
39 | }
40 | l, err := net.LookupIP(h)
41 | if err != nil {
42 | return nil, err
43 | }
44 | s := ""
45 | for _, v := range l {
46 | if v.To4() == nil {
47 | continue
48 | }
49 | s = v.String()
50 | break
51 | }
52 | if s == "" {
53 | return nil, errors.New("Can not find server v4 IP")
54 | }
55 | server = net.JoinHostPort(s, p)
56 |
57 | c, err := NewClient(addr, "127.0.0.1", server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
58 | if err != nil {
59 | return nil, err
60 | }
61 | tl, err := NewTunnel("127.0.0.1:53", "8.8.8.8:53", server, password, tcpTimeout, tcpDeadline, udpDeadline)
62 | if err != nil {
63 | return nil, err
64 | }
65 | f, err := tun.OpenTunDevice(tunDevice, tunIP, tunGateway, tunMask, []string{"8.8.8.8"})
66 | if err != nil {
67 | return nil, err
68 | }
69 | t := gotun2socks.New(f, addr, []string{"8.8.8.8"}, true, true)
70 | return &VPN{
71 | Client: c,
72 | Tunnel: tl,
73 | Tun: t,
74 | ServerIP: s,
75 | TunGateway: tunGateway,
76 | DefaultGateway: defaultGateway,
77 | }, nil
78 | }
79 |
80 | // ListenAndServe starts to run VPN
81 | func (v *VPN) ListenAndServe() error {
82 | if err := sysproxy.SetDNSServer("127.0.0.1"); err != nil {
83 | return err
84 | }
85 | if err := v.AddRoutes(); err != nil {
86 | return err
87 | }
88 |
89 | errch := make(chan error)
90 | go func() {
91 | errch <- v.Client.ListenAndServe()
92 | }()
93 | go func() {
94 | errch <- v.Tunnel.ListenAndServe()
95 | }()
96 | go func() {
97 | v.Tun.Run()
98 | }()
99 | go func() {
100 | sigs := make(chan os.Signal, 1)
101 | signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
102 | <-sigs
103 | errch <- nil
104 | }()
105 | fmt.Println("Ctrl-C to quit")
106 |
107 | err := <-errch
108 | if err := v.Shutdown(); err != nil {
109 | return err
110 | }
111 | return err
112 | }
113 |
114 | // Shutdown stops VPN
115 | func (v *VPN) Shutdown() error {
116 | fmt.Println("Quitting...")
117 | if err := sysproxy.SetDNSServer("8.8.8.8"); err != nil {
118 | log.Println(err)
119 | }
120 | if err := v.DeleteRoutes(); err != nil {
121 | log.Println(err)
122 | }
123 | if v.Client != nil {
124 | if err := v.Client.Shutdown(); err != nil {
125 | log.Println(err)
126 | }
127 | }
128 | if v.Tunnel != nil {
129 | if err := v.Tunnel.Shutdown(); err != nil {
130 | log.Println(err)
131 | }
132 | }
133 | if v.Tun != nil {
134 | // v.Tun.Stop()
135 | }
136 | return nil
137 | }
138 |
--------------------------------------------------------------------------------
/encrypt.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "errors"
7 | "io"
8 | "net"
9 | "strconv"
10 | "time"
11 |
12 | "github.com/txthinking/socks5"
13 | "github.com/txthinking/x"
14 | )
15 |
16 | // IncrementNonce loves your compute to use Litter Endian
17 | func IncrementNonce(n []byte) []byte {
18 | i := int(binary.LittleEndian.Uint16(n))
19 | i += 1
20 | n = make([]byte, 12)
21 | binary.LittleEndian.PutUint16(n, uint16(i))
22 | return n
23 | }
24 |
25 | // ReadFrom
26 | func ReadFrom(c *net.TCPConn, k, n []byte, hasTime bool) ([]byte, []byte, error) {
27 | b := make([]byte, 18)
28 | if _, err := io.ReadFull(c, b); err != nil {
29 | return nil, nil, err
30 | }
31 | n = IncrementNonce(n)
32 | d, err := x.AESGCMDecrypt(b, k, n)
33 | if err != nil {
34 | return nil, nil, err
35 | }
36 |
37 | l := int(binary.BigEndian.Uint16(d))
38 | b = make([]byte, l)
39 | if _, err := io.ReadFull(c, b); err != nil {
40 | return nil, nil, err
41 | }
42 | n = IncrementNonce(n)
43 | d, err = x.AESGCMDecrypt(b, k, n)
44 | if err != nil {
45 | return nil, nil, err
46 | }
47 |
48 | if hasTime {
49 | i, err := strconv.Atoi(string(d[0:10]))
50 | if err != nil {
51 | return nil, nil, err
52 | }
53 | if time.Now().Unix()-int64(i) > 90 {
54 | time.Sleep(time.Duration(x.Random(1, 60*10)) * time.Second)
55 | return nil, nil, errors.New("Expired request")
56 | }
57 | d = d[10:]
58 | }
59 | return d, n, nil
60 | }
61 |
62 | // WriteTo
63 | func WriteTo(c *net.TCPConn, d, k, n []byte, needTime bool) ([]byte, error) {
64 | if needTime {
65 | d = append(bytes.NewBufferString(strconv.Itoa(int(time.Now().Unix()))).Bytes(), d...)
66 | }
67 |
68 | i := len(d) + 16
69 | bb := make([]byte, 2)
70 | binary.BigEndian.PutUint16(bb, uint16(i))
71 | n = IncrementNonce(n)
72 | b, err := x.AESGCMEncrypt(bb, k, n)
73 | if err != nil {
74 | return nil, err
75 | }
76 | if _, err := c.Write(b); err != nil {
77 | return nil, err
78 | }
79 |
80 | n = IncrementNonce(n)
81 | b, err = x.AESGCMEncrypt(d, k, n)
82 | if err != nil {
83 | return nil, err
84 | }
85 | if _, err := c.Write(b); err != nil {
86 | return nil, err
87 | }
88 | return n, nil
89 | }
90 |
91 | // PrepareKey
92 | func PrepareKey(p []byte) ([]byte, []byte, error) {
93 | return x.HkdfSha256RandomSalt(p, []byte{0x62, 0x72, 0x6f, 0x6f, 0x6b}, 12)
94 | }
95 |
96 | // GetKey
97 | func GetKey(p, n []byte) ([]byte, error) {
98 | return x.HkdfSha256WithSalt(p, n, []byte{0x62, 0x72, 0x6f, 0x6f, 0x6b})
99 | }
100 |
101 | // Encrypt data
102 | func Encrypt(p, b []byte) ([]byte, error) {
103 | b = append(bytes.NewBufferString(strconv.Itoa(int(time.Now().Unix()))).Bytes(), b...)
104 | k, n, err := PrepareKey(p)
105 | if err != nil {
106 | return nil, err
107 | }
108 | b, err = x.AESGCMEncrypt(b, k, n)
109 | if err != nil {
110 | return nil, err
111 | }
112 | b = append(n, b...)
113 | return b, nil
114 | }
115 |
116 | // Decrypt data
117 | func Decrypt(p, b []byte) (a byte, addr, port, data []byte, err error) {
118 | err = errors.New("Data length error")
119 | if len(b) <= 12+16 {
120 | return
121 | }
122 | k, err := GetKey(p, b[0:12])
123 | bb, err := x.AESGCMDecrypt(b[12:], k, b[0:12])
124 | if err != nil {
125 | return
126 | }
127 | i, err := strconv.Atoi(string(bb[0:10]))
128 | if err != nil {
129 | return
130 | }
131 | if time.Now().Unix()-int64(i) > 90 {
132 | time.Sleep(time.Duration(x.Random(1, 60*10)) * time.Second)
133 | err = errors.New("Expired request")
134 | return
135 | }
136 | bb = bb[10:]
137 | a = bb[0]
138 | if a == socks5.ATYPIPv4 {
139 | addr = bb[1:5]
140 | port = bb[5:7]
141 | data = bb[7:]
142 | } else if a == socks5.ATYPIPv6 {
143 | addr = bb[1:17]
144 | port = bb[17:19]
145 | data = bb[19:]
146 | } else if a == socks5.ATYPDomain {
147 | l := int(bb[1])
148 | addr = bb[1 : 1+l]
149 | port = bb[1+l : 1+l+2]
150 | data = bb[1+l+2:]
151 | } else {
152 | return
153 | }
154 | err = nil
155 | return
156 | }
157 |
--------------------------------------------------------------------------------
/sysproxy/system_windows.go:
--------------------------------------------------------------------------------
1 | package sysproxy
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "net"
7 | "os/exec"
8 | "regexp"
9 | "syscall"
10 | )
11 |
12 | // TurnOnSystemProxy used to enable system pac proxy, pac is a URL.
13 | func TurnOnSystemProxy(pac string) error {
14 | c := exec.Command(`reg`, `add`, `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`, `/v`, `AutoConfigURL`, `/t`, `REG_SZ`, `/d`, pac, `/f`)
15 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
16 | if out, err := c.CombinedOutput(); err != nil {
17 | return errors.New(string(out) + err.Error())
18 | }
19 | c = exec.Command(`reg`, `add`, `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`, `/v`, `ProxyEnable`, `/t`, `REG_DWORD`, `/d`, `0`, `/f`)
20 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
21 | if out, err := c.CombinedOutput(); err != nil {
22 | return errors.New(string(out) + err.Error())
23 | }
24 | if err := reloadWinProxy(); err != nil {
25 | return err
26 | }
27 | return nil
28 | }
29 |
30 | // TurnOffSystemProxy used to disable system pac proxy
31 | func TurnOffSystemProxy() error {
32 | c := exec.Command(`reg`, `query`, `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`)
33 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
34 | out, err := c.CombinedOutput()
35 | if err != nil {
36 | return errors.New("Can not query proxy settings: " + err.Error())
37 | }
38 | if bytes.Contains(bytes.ToLower(out), []byte("autoconfigurl")) {
39 | c := exec.Command(`reg`, `delete`, `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`, `/v`, `AutoConfigURL`, `/f`)
40 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
41 | if out, err := c.CombinedOutput(); err != nil {
42 | return errors.New(string(out) + err.Error())
43 | }
44 | }
45 | if err := reloadWinProxy(); err != nil {
46 | return err
47 | }
48 | return nil
49 | }
50 |
51 | func reloadWinProxy() error {
52 | h, err := syscall.LoadLibrary("wininet.dll")
53 | if err != nil {
54 | return err
55 | }
56 | f, err := syscall.GetProcAddress(h, "InternetSetOptionW")
57 | if err != nil {
58 | return err
59 | }
60 | ret, _, errno := syscall.Syscall6(uintptr(f), 4, 0, 39, 0, 0, 0, 0)
61 | if ret != 1 {
62 | return errors.New(errno.Error())
63 | }
64 | ret, _, errno = syscall.Syscall6(uintptr(f), 4, 0, 37, 0, 0, 0, 0)
65 | if ret != 1 {
66 | return errors.New(errno.Error())
67 | }
68 | return nil
69 | }
70 |
71 | // GetNetworkInterfaces returns interface list
72 | func GetNetworkInterfaces() ([]string, error) {
73 | is, err := net.Interfaces()
74 | if err != nil {
75 | return nil, err
76 | }
77 | nss := make([]string, 0)
78 | for _, v := range is {
79 | nss = append(nss, v.Name)
80 | }
81 | if len(nss) == 0 {
82 | return nil, errors.New("no available network service")
83 | }
84 | return nss, nil
85 | }
86 |
87 | // SetDNSServer used to set system DNS server
88 | func SetDNSServer(server string) error {
89 | nis, err := GetNetworkInterfaces()
90 | if err != nil {
91 | return err
92 | }
93 | for _, v := range nis {
94 | c := exec.Command("netsh", "interface", "ip", "set", "dnsservers", v, "static", server, "primary")
95 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
96 | if out, err := c.CombinedOutput(); err != nil {
97 | return errors.New(string(out) + err.Error())
98 | }
99 | }
100 | return nil
101 | }
102 |
103 | // GetDefaultGateway returns default gateway
104 | func GetDefaultGateway() (string, error) {
105 | c := exec.Command("netsh", "interface", "ipv4", "show", "address")
106 | c.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
107 | out, err := c.CombinedOutput()
108 | if err != nil {
109 | return "", errors.New(string(out) + err.Error())
110 | }
111 | r, err := regexp.Compile(`Default Gateway.*?(\d+.\d+\.\d+\.\d+)`)
112 | if err != nil {
113 | return "", err
114 | }
115 | ss := r.FindStringSubmatch(string(out))
116 | if len(ss) == 0 {
117 | return "", errors.New("Can not find default gateway")
118 | }
119 | return ss[1], nil
120 | }
121 |
--------------------------------------------------------------------------------
/socks5tohttp.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "io"
7 | "log"
8 | "net"
9 | "time"
10 |
11 | "github.com/txthinking/brook/plugin"
12 | "github.com/txthinking/x"
13 | "golang.org/x/net/proxy"
14 | )
15 |
16 | type Socks5ToHTTP struct {
17 | Addr *net.TCPAddr
18 | Socks5Address string
19 | Dial proxy.Dialer
20 | Timeout int
21 | Deadline int
22 | Listen *net.TCPListener
23 | HTTPMiddleman plugin.HTTPMiddleman
24 | }
25 |
26 | func NewSocks5ToHTTP(addr, socks5addr string, timeout, deadline int) (*Socks5ToHTTP, error) {
27 | dial, err := proxy.SOCKS5("tcp", socks5addr, nil, &net.Dialer{
28 | Timeout: time.Duration(deadline) * time.Second,
29 | KeepAlive: time.Duration(timeout) * time.Second,
30 | })
31 | if err != nil {
32 | return nil, err
33 | }
34 | ta, err := net.ResolveTCPAddr("tcp", addr)
35 | if err != nil {
36 | return nil, err
37 | }
38 | return &Socks5ToHTTP{
39 | Addr: ta,
40 | Socks5Address: socks5addr,
41 | Dial: dial,
42 | Timeout: timeout,
43 | Deadline: deadline,
44 | }, nil
45 | }
46 |
47 | // SetHTTPMiddleman sets httpmiddleman plugin
48 | func (s *Socks5ToHTTP) SetHTTPMiddleman(m plugin.HTTPMiddleman) {
49 | s.HTTPMiddleman = m
50 | }
51 |
52 | func (s *Socks5ToHTTP) ListenAndServe() error {
53 | l, err := net.ListenTCP("tcp", s.Addr)
54 | if err != nil {
55 | return err
56 | }
57 | defer l.Close()
58 | s.Listen = l
59 | for {
60 | c, err := l.AcceptTCP()
61 | if err != nil {
62 | return err
63 | }
64 | go func(c *net.TCPConn) {
65 | defer c.Close()
66 | if s.Timeout != 0 {
67 | if err := c.SetKeepAlivePeriod(time.Duration(s.Timeout) * time.Second); err != nil {
68 | log.Println(err)
69 | return
70 | }
71 | }
72 | if s.Deadline != 0 {
73 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.Deadline) * time.Second)); err != nil {
74 | log.Println(err)
75 | return
76 | }
77 | }
78 | if err := s.Handle(c); err != nil {
79 | log.Println(err)
80 | return
81 | }
82 | }(c)
83 | }
84 | }
85 |
86 | func (s *Socks5ToHTTP) Handle(c *net.TCPConn) error {
87 | b := make([]byte, 0, 1024)
88 | for {
89 | var b1 [1024]byte
90 | n, err := c.Read(b1[:])
91 | if err != nil {
92 | return err
93 | }
94 | b = append(b, b1[:n]...)
95 | if bytes.Contains(b, []byte{0x0d, 0x0a, 0x0d, 0x0a}) {
96 | break
97 | }
98 | if len(b) >= 2083+18 {
99 | return errors.New("HTTP header too long")
100 | }
101 | }
102 |
103 | bb := bytes.SplitN(b, []byte(" "), 3)
104 | if len(bb) != 3 {
105 | return errors.New("Invalid Request")
106 | }
107 | method, address := string(bb[0]), string(bb[1])
108 | var addr string
109 | if method == "CONNECT" {
110 | addr = address
111 | }
112 | if method != "CONNECT" {
113 | var err error
114 | addr, err = x.GetAddressFromURL(address)
115 | if err != nil {
116 | return err
117 | }
118 | }
119 |
120 | if s.HTTPMiddleman != nil {
121 | if done, err := s.HTTPMiddleman.Handle(method, addr, b, c); err != nil || done {
122 | return err
123 | }
124 | }
125 |
126 | tmp, err := s.Dial.Dial("tcp", addr)
127 | if err != nil {
128 | return err
129 | }
130 | rc := tmp.(*net.TCPConn)
131 | defer rc.Close()
132 | if s.Timeout != 0 {
133 | if err := rc.SetKeepAlivePeriod(time.Duration(s.Timeout) * time.Second); err != nil {
134 | return err
135 | }
136 | }
137 | if s.Deadline != 0 {
138 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.Deadline) * time.Second)); err != nil {
139 | return err
140 | }
141 | }
142 | if method == "CONNECT" {
143 | _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
144 | if err != nil {
145 | return err
146 | }
147 | }
148 | if method != "CONNECT" {
149 | if _, err := rc.Write(b); err != nil {
150 | return err
151 | }
152 | }
153 | // TODO
154 | go func() {
155 | _, _ = io.Copy(rc, c)
156 | }()
157 | _, _ = io.Copy(c, rc)
158 | return nil
159 | }
160 |
161 | func (s *Socks5ToHTTP) Shutdown() error {
162 | if s.Listen == nil {
163 | return nil
164 | }
165 | return s.Listen.Close()
166 | }
167 |
--------------------------------------------------------------------------------
/run.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "github.com/txthinking/brook/sysproxy"
5 | )
6 |
7 | // RunServer used to make a new Server and start to listen
8 | func RunServer(address, password string, tcpTimeout, tcpDeadline, udpDeadline int) error {
9 | s, err := NewServer(address, password, tcpTimeout, tcpDeadline, udpDeadline)
10 | if err != nil {
11 | return err
12 | }
13 | return s.ListenAndServe()
14 | }
15 |
16 | // RunClient used to make a new Client and start a socks5 proxy to listen
17 | func RunClient(address, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) error {
18 | c, err := NewClient(address, ip, server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
19 | if err != nil {
20 | return err
21 | }
22 | return c.ListenAndServe()
23 | }
24 |
25 | // RunClientAsHTTP used to make a new Client and start a http proxy to listen
26 | func RunClientAsHTTP(address, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) error {
27 | c, err := NewClient(address, ip, server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
28 | if err != nil {
29 | return err
30 | }
31 | return c.ListenAndServeHTTP()
32 | }
33 |
34 | // RunTunnel used to start a tunnel
35 | func RunTunnel(address, to, server, password string, tcpTimeout, tcpDeadline, udpDeadline int) error {
36 | c, err := NewTunnel(address, to, server, password, tcpTimeout, tcpDeadline, udpDeadline)
37 | if err != nil {
38 | return err
39 | }
40 | return c.ListenAndServe()
41 | }
42 |
43 | // RunSSServer used to make a new Server and start to listen
44 | func RunSSServer(address, password string, tcpTimeout, tcpDeadline, udpDeadline int) error {
45 | s, err := NewSSServer(address, password, tcpTimeout, tcpDeadline, udpDeadline)
46 | if err != nil {
47 | return err
48 | }
49 | return s.ListenAndServe()
50 | }
51 |
52 | // RunSSClient used to make a new Client and start a socks5 proxy to listen
53 | func RunSSClient(address, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) error {
54 | c, err := NewSSClient(address, ip, server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
55 | if err != nil {
56 | return err
57 | }
58 | return c.ListenAndServe()
59 | }
60 |
61 | // RunSSClientAsHTTP used to make a new Client and start a http proxy to listen
62 | func RunSSClientAsHTTP(address, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) error {
63 | c, err := NewSSClient(address, ip, server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
64 | if err != nil {
65 | return err
66 | }
67 | return c.ListenAndServeHTTP()
68 | }
69 |
70 | // RunRelay used to make a new Relay and start to listen
71 | func RunRelay(address, remote string, tcpTimeout, tcpDeadline, udpDeadline int) error {
72 | r, err := NewRelay(address, remote, tcpTimeout, tcpDeadline, udpDeadline)
73 | if err != nil {
74 | return err
75 | }
76 | return r.ListenAndServe()
77 | }
78 |
79 | // RunSocks5Server used to make a new Socks5Server and start a raw socks5 proxy to listen
80 | func RunSocks5Server(address, ip, username, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) error {
81 | s, err := NewSocks5Server(address, ip, username, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
82 | if err != nil {
83 | return err
84 | }
85 | return s.ListenAndServe()
86 | }
87 |
88 | // RunSocks5ToHTTP used to make a new Socks5ToHTTP and start a http proxy to listen
89 | func RunSocks5ToHTTP(address, socks5 string, timeout, deadline int) error {
90 | s, err := NewSocks5ToHTTP(address, socks5, timeout, deadline)
91 | if err != nil {
92 | return err
93 | }
94 | return s.ListenAndServe()
95 | }
96 |
97 | // RunSystemProxy used to set/remove system proxy
98 | func RunSystemProxy(remove bool, pac string) error {
99 | if remove {
100 | if err := sysproxy.TurnOffSystemProxy(); err != nil {
101 | return err
102 | }
103 | return nil
104 | }
105 | if err := sysproxy.TurnOnSystemProxy(pac); err != nil {
106 | return err
107 | }
108 | return nil
109 | }
110 |
111 | // RunVPN used to make a new VPN and start
112 | func RunVPN(address, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int, tunDevice, tunIP, tunGateway, tunMask, defaultGateway string) error {
113 | v, err := NewVPN(address, server, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime, tunDevice, tunIP, tunGateway, tunMask, defaultGateway)
114 | if err != nil {
115 | return err
116 | }
117 | return v.ListenAndServe()
118 | }
119 |
--------------------------------------------------------------------------------
/tproxy/udp.go:
--------------------------------------------------------------------------------
1 | package tproxy
2 |
3 | import (
4 | "bytes"
5 | "encoding/binary"
6 | "net"
7 | "os"
8 | "strconv"
9 | "syscall"
10 | "unsafe"
11 |
12 | "github.com/txthinking/x"
13 | )
14 |
15 | func ListenUDP(network string, laddr *net.UDPAddr) (*net.UDPConn, error) {
16 | c, err := net.ListenUDP(network, laddr)
17 | if err != nil {
18 | return nil, err
19 | }
20 | defer c.Close()
21 |
22 | f, err := c.File()
23 | if err != nil {
24 | return nil, err
25 | }
26 | defer f.Close()
27 |
28 | fd := int(f.Fd())
29 | if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
30 | return nil, err
31 | }
32 | if err = syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1); err != nil {
33 | return nil, err
34 | }
35 | tmp, err := net.FileConn(f)
36 | if err != nil {
37 | return nil, err
38 | }
39 | return tmp.(*net.UDPConn), nil
40 | }
41 |
42 | func ReadFromUDP(conn *net.UDPConn, b []byte) (int, *net.UDPAddr, *net.UDPAddr, error) {
43 | oob := make([]byte, 1024)
44 | n, oobn, _, addr, err := conn.ReadMsgUDP(b, oob)
45 | if err != nil {
46 | return 0, nil, nil, err
47 | }
48 |
49 | msgs, err := syscall.ParseSocketControlMessage(oob[:oobn])
50 | if err != nil {
51 | return 0, nil, nil, err
52 | }
53 |
54 | var originalDst *net.UDPAddr
55 | for _, msg := range msgs {
56 | if msg.Header.Level != syscall.SOL_IP || msg.Header.Type != syscall.IP_RECVORIGDSTADDR {
57 | continue
58 | }
59 | originalDstRaw := &syscall.RawSockaddrInet4{}
60 | if err := binary.Read(bytes.NewReader(msg.Data), binary.LittleEndian, originalDstRaw); err != nil {
61 | return 0, nil, nil, err
62 | }
63 |
64 | switch originalDstRaw.Family {
65 | case syscall.AF_INET:
66 | pp := (*syscall.RawSockaddrInet4)(unsafe.Pointer(originalDstRaw))
67 | p := (*[2]byte)(unsafe.Pointer(&pp.Port))
68 | originalDst = &net.UDPAddr{
69 | IP: net.IPv4(pp.Addr[0], pp.Addr[1], pp.Addr[2], pp.Addr[3]),
70 | Port: int(p[0])<<8 + int(p[1]),
71 | }
72 | case syscall.AF_INET6:
73 | pp := (*syscall.RawSockaddrInet6)(unsafe.Pointer(originalDstRaw))
74 | p := (*[2]byte)(unsafe.Pointer(&pp.Port))
75 | originalDst = &net.UDPAddr{
76 | IP: net.IP(pp.Addr[:]),
77 | Port: int(p[0])<<8 + int(p[1]),
78 | Zone: strconv.Itoa(int(pp.Scope_id)),
79 | }
80 | default:
81 | return 0, nil, nil, nil
82 | }
83 | }
84 | if originalDst == nil {
85 | return 0, nil, nil, nil
86 | }
87 | return n, addr, originalDst, nil
88 | }
89 |
90 | func DialUDP(network string, laddr *net.UDPAddr, raddr *net.UDPAddr) (*net.UDPConn, error) {
91 | remoteSocketAddress, err := udpAddrToSocketAddr(raddr)
92 | if err != nil {
93 | return nil, err
94 | }
95 |
96 | localSocketAddress, err := udpAddrToSocketAddr(laddr)
97 | if err != nil {
98 | return nil, err
99 | }
100 |
101 | fd, err := syscall.Socket(udpAddrFamily(network, laddr, raddr), syscall.SOCK_DGRAM, 0)
102 | if err != nil {
103 | return nil, err
104 | }
105 |
106 | if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
107 | syscall.Close(fd)
108 | return nil, err
109 | }
110 |
111 | if err := syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
112 | syscall.Close(fd)
113 | return nil, err
114 | }
115 |
116 | if err := syscall.Bind(fd, localSocketAddress); err != nil {
117 | syscall.Close(fd)
118 | return nil, err
119 | }
120 |
121 | if err := syscall.Connect(fd, remoteSocketAddress); err != nil {
122 | syscall.Close(fd)
123 | return nil, err
124 | }
125 |
126 | f := os.NewFile(uintptr(fd), string(x.RandomNumber()))
127 | defer f.Close()
128 |
129 | c, err := net.FileConn(f)
130 | if err != nil {
131 | return nil, err
132 | }
133 | return c.(*net.UDPConn), nil
134 | }
135 |
136 | func udpAddrToSocketAddr(addr *net.UDPAddr) (syscall.Sockaddr, error) {
137 | switch {
138 | case addr.IP.To4() != nil:
139 | ip := [4]byte{}
140 | copy(ip[:], addr.IP.To4())
141 |
142 | return &syscall.SockaddrInet4{Addr: ip, Port: addr.Port}, nil
143 |
144 | default:
145 | ip := [16]byte{}
146 | copy(ip[:], addr.IP.To16())
147 |
148 | zoneID, err := strconv.ParseUint(addr.Zone, 10, 32)
149 | if err != nil {
150 | return nil, err
151 | }
152 |
153 | return &syscall.SockaddrInet6{Addr: ip, Port: addr.Port, ZoneId: uint32(zoneID)}, nil
154 | }
155 | }
156 |
157 | func udpAddrFamily(net string, laddr, raddr *net.UDPAddr) int {
158 | switch net[len(net)-1] {
159 | case '4':
160 | return syscall.AF_INET
161 | case '6':
162 | return syscall.AF_INET6
163 | }
164 |
165 | if (laddr == nil || laddr.IP.To4() != nil) &&
166 | (raddr == nil || raddr.IP.To4() != nil) {
167 | return syscall.AF_INET
168 | }
169 | return syscall.AF_INET6
170 | }
171 |
--------------------------------------------------------------------------------
/relay.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "io"
5 | "log"
6 | "net"
7 | "time"
8 |
9 | cache "github.com/patrickmn/go-cache"
10 | "github.com/txthinking/socks5"
11 | )
12 |
13 | // Relay is stream relay server
14 | type Relay struct {
15 | TCPAddr *net.TCPAddr
16 | UDPAddr *net.UDPAddr
17 | RemoteTCPAddr *net.TCPAddr
18 | RemoteUDPAddr *net.UDPAddr
19 | TCPListen *net.TCPListener
20 | UDPConn *net.UDPConn
21 | UDPExchanges *cache.Cache
22 | TCPDeadline int
23 | TCPTimeout int
24 | UDPDeadline int
25 | }
26 |
27 | // NewRelay
28 | func NewRelay(addr, remote string, tcpTimeout, tcpDeadline, udpDeadline int) (*Relay, error) {
29 | taddr, err := net.ResolveTCPAddr("tcp", addr)
30 | if err != nil {
31 | return nil, err
32 | }
33 | uaddr, err := net.ResolveUDPAddr("udp", addr)
34 | if err != nil {
35 | return nil, err
36 | }
37 | rtaddr, err := net.ResolveTCPAddr("tcp", remote)
38 | if err != nil {
39 | return nil, err
40 | }
41 | ruaddr, err := net.ResolveUDPAddr("udp", remote)
42 | if err != nil {
43 | return nil, err
44 | }
45 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
46 | s := &Relay{
47 | TCPAddr: taddr,
48 | UDPAddr: uaddr,
49 | RemoteTCPAddr: rtaddr,
50 | RemoteUDPAddr: ruaddr,
51 | UDPExchanges: cs,
52 | TCPTimeout: tcpTimeout,
53 | TCPDeadline: tcpDeadline,
54 | UDPDeadline: udpDeadline,
55 | }
56 | return s, nil
57 | }
58 |
59 | // Run server
60 | func (s *Relay) ListenAndServe() error {
61 | errch := make(chan error)
62 | go func() {
63 | errch <- s.RunTCPServer()
64 | }()
65 | go func() {
66 | errch <- s.RunUDPServer()
67 | }()
68 | return <-errch
69 | }
70 |
71 | // RunTCPServer starts tcp server
72 | func (s *Relay) RunTCPServer() error {
73 | var err error
74 | s.TCPListen, err = net.ListenTCP("tcp", s.TCPAddr)
75 | if err != nil {
76 | return err
77 | }
78 | defer s.TCPListen.Close()
79 | for {
80 | c, err := s.TCPListen.AcceptTCP()
81 | if err != nil {
82 | return err
83 | }
84 | go func(c *net.TCPConn) {
85 | defer c.Close()
86 | if s.TCPTimeout != 0 {
87 | if err := c.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
88 | log.Println(err)
89 | return
90 | }
91 | }
92 | if s.TCPDeadline != 0 {
93 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
94 | log.Println(err)
95 | return
96 | }
97 | }
98 | if err := s.TCPHandle(c); err != nil {
99 | log.Println(err)
100 | }
101 | }(c)
102 | }
103 | return nil
104 | }
105 |
106 | // RunUDPServer starts udp server
107 | func (s *Relay) RunUDPServer() error {
108 | var err error
109 | s.UDPConn, err = net.ListenUDP("udp", s.UDPAddr)
110 | if err != nil {
111 | return err
112 | }
113 | defer s.UDPConn.Close()
114 | for {
115 | b := make([]byte, 65536)
116 | n, addr, err := s.UDPConn.ReadFromUDP(b)
117 | if err != nil {
118 | return err
119 | }
120 | go func(addr *net.UDPAddr, b []byte) {
121 | if err := s.UDPHandle(addr, b); err != nil {
122 | log.Println(err)
123 | return
124 | }
125 | }(addr, b[0:n])
126 | }
127 | return nil
128 | }
129 |
130 | // Shutdown server
131 | func (s *Relay) Shutdown() error {
132 | var err, err1 error
133 | if s.TCPListen != nil {
134 | err = s.TCPListen.Close()
135 | }
136 | if s.UDPConn != nil {
137 | err1 = s.UDPConn.Close()
138 | }
139 | if err != nil {
140 | return err
141 | }
142 | return err1
143 | }
144 |
145 | // TCPHandle handle request
146 | func (s *Relay) TCPHandle(c *net.TCPConn) error {
147 | tmp, err := Dial.Dial("tcp", s.RemoteTCPAddr.String())
148 | if err != nil {
149 | return err
150 | }
151 | rc := tmp.(*net.TCPConn)
152 | defer rc.Close()
153 | if s.TCPTimeout != 0 {
154 | if err := rc.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
155 | return err
156 | }
157 | }
158 | if s.TCPDeadline != 0 {
159 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
160 | return err
161 | }
162 | }
163 |
164 | // TODO
165 | go func() {
166 | _, _ = io.Copy(c, rc)
167 | }()
168 | _, _ = io.Copy(rc, c)
169 | return nil
170 | }
171 |
172 | // UDPHandle handle packet
173 | func (s *Relay) UDPHandle(addr *net.UDPAddr, b []byte) error {
174 | send := func(ue *socks5.UDPExchange, data []byte) error {
175 | _, err := ue.RemoteConn.Write(data)
176 | if err != nil {
177 | return err
178 | }
179 | return nil
180 | }
181 |
182 | var ue *socks5.UDPExchange
183 | iue, ok := s.UDPExchanges.Get(addr.String())
184 | if ok {
185 | ue = iue.(*socks5.UDPExchange)
186 | return send(ue, b)
187 | }
188 |
189 | tmp, err := Dial.Dial("udp", s.RemoteUDPAddr.String())
190 | if err != nil {
191 | return err
192 | }
193 | rc := tmp.(*net.UDPConn)
194 | ue = &socks5.UDPExchange{
195 | ClientAddr: addr,
196 | RemoteConn: rc,
197 | }
198 | if err := send(ue, b); err != nil {
199 | ue.RemoteConn.Close()
200 | return err
201 | }
202 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
203 | go func(ue *socks5.UDPExchange) {
204 | defer func() {
205 | s.UDPExchanges.Delete(ue.ClientAddr.String())
206 | ue.RemoteConn.Close()
207 | }()
208 | var b [65536]byte
209 | for {
210 | if s.UDPDeadline != 0 {
211 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
212 | log.Println(err)
213 | break
214 | }
215 | }
216 | n, err := ue.RemoteConn.Read(b[:])
217 | if err != nil {
218 | log.Println(err)
219 | break
220 | }
221 | if _, err := s.UDPConn.WriteToUDP(b[0:n], ue.ClientAddr); err != nil {
222 | log.Println(err)
223 | break
224 | }
225 | }
226 | }(ue)
227 | return nil
228 | }
229 |
--------------------------------------------------------------------------------
/server.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "io"
5 | "log"
6 | "net"
7 | "time"
8 |
9 | cache "github.com/patrickmn/go-cache"
10 | "github.com/txthinking/socks5"
11 | )
12 |
13 | // Server
14 | type Server struct {
15 | Password []byte
16 | TCPAddr *net.TCPAddr
17 | UDPAddr *net.UDPAddr
18 | TCPListen *net.TCPListener
19 | UDPConn *net.UDPConn
20 | UDPExchanges *cache.Cache
21 | TCPDeadline int
22 | TCPTimeout int
23 | UDPDeadline int
24 | }
25 |
26 | // NewServer
27 | func NewServer(addr, password string, tcpTimeout, tcpDeadline, udpDeadline int) (*Server, error) {
28 | taddr, err := net.ResolveTCPAddr("tcp", addr)
29 | if err != nil {
30 | return nil, err
31 | }
32 | uaddr, err := net.ResolveUDPAddr("udp", addr)
33 | if err != nil {
34 | return nil, err
35 | }
36 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
37 | s := &Server{
38 | Password: []byte(password),
39 | TCPAddr: taddr,
40 | UDPAddr: uaddr,
41 | UDPExchanges: cs,
42 | TCPTimeout: tcpTimeout,
43 | TCPDeadline: tcpDeadline,
44 | UDPDeadline: udpDeadline,
45 | }
46 | return s, nil
47 | }
48 |
49 | // Run server
50 | func (s *Server) ListenAndServe() error {
51 | errch := make(chan error)
52 | go func() {
53 | errch <- s.RunTCPServer()
54 | }()
55 | go func() {
56 | errch <- s.RunUDPServer()
57 | }()
58 | return <-errch
59 | }
60 |
61 | // RunTCPServer starts tcp server
62 | func (s *Server) RunTCPServer() error {
63 | var err error
64 | s.TCPListen, err = net.ListenTCP("tcp", s.TCPAddr)
65 | if err != nil {
66 | return err
67 | }
68 | defer s.TCPListen.Close()
69 | for {
70 | c, err := s.TCPListen.AcceptTCP()
71 | if err != nil {
72 | return err
73 | }
74 | go func(c *net.TCPConn) {
75 | defer c.Close()
76 | if s.TCPTimeout != 0 {
77 | if err := c.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
78 | log.Println(err)
79 | return
80 | }
81 | }
82 | if s.TCPDeadline != 0 {
83 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
84 | log.Println(err)
85 | return
86 | }
87 | }
88 | if err := s.TCPHandle(c); err != nil {
89 | log.Println(err)
90 | }
91 | }(c)
92 | }
93 | return nil
94 | }
95 |
96 | // RunUDPServer starts udp server
97 | func (s *Server) RunUDPServer() error {
98 | var err error
99 | s.UDPConn, err = net.ListenUDP("udp", s.UDPAddr)
100 | if err != nil {
101 | return err
102 | }
103 | defer s.UDPConn.Close()
104 | for {
105 | b := make([]byte, 65536)
106 | n, addr, err := s.UDPConn.ReadFromUDP(b)
107 | if err != nil {
108 | return err
109 | }
110 | go func(addr *net.UDPAddr, b []byte) {
111 | if err := s.UDPHandle(addr, b); err != nil {
112 | log.Println(err)
113 | return
114 | }
115 | }(addr, b[0:n])
116 | }
117 | return nil
118 | }
119 |
120 | // TCPHandle handle request
121 | func (s *Server) TCPHandle(c *net.TCPConn) error {
122 | cn := make([]byte, 12)
123 | if _, err := io.ReadFull(c, cn); err != nil {
124 | return err
125 | }
126 | ck, err := GetKey(s.Password, cn)
127 | if err != nil {
128 | return err
129 | }
130 | var b []byte
131 | b, cn, err = ReadFrom(c, ck, cn, true)
132 | if err != nil {
133 | return err
134 | }
135 | address := socks5.ToAddress(b[0], b[1:len(b)-2], b[len(b)-2:])
136 | tmp, err := Dial.Dial("tcp", address)
137 | if err != nil {
138 | return err
139 | }
140 | rc := tmp.(*net.TCPConn)
141 | defer rc.Close()
142 | if s.TCPTimeout != 0 {
143 | if err := rc.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
144 | return err
145 | }
146 | }
147 | if s.TCPDeadline != 0 {
148 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
149 | return err
150 | }
151 | }
152 |
153 | go func() {
154 | k, n, err := PrepareKey(s.Password)
155 | if err != nil {
156 | log.Println(err)
157 | return
158 | }
159 | if _, err := c.Write(n); err != nil {
160 | return
161 | }
162 | var b [1024 * 2]byte
163 | for {
164 | if s.TCPDeadline != 0 {
165 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
166 | return
167 | }
168 | }
169 | i, err := rc.Read(b[:])
170 | if err != nil {
171 | return
172 | }
173 | n, err = WriteTo(c, b[0:i], k, n, false)
174 | if err != nil {
175 | return
176 | }
177 | }
178 | }()
179 |
180 | for {
181 | if s.TCPDeadline != 0 {
182 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
183 | return nil
184 | }
185 | }
186 | b, cn, err = ReadFrom(c, ck, cn, false)
187 | if err != nil {
188 | return nil
189 | }
190 | if _, err := rc.Write(b); err != nil {
191 | return nil
192 | }
193 | }
194 | return nil
195 | }
196 |
197 | // UDPHandle handle packet
198 | func (s *Server) UDPHandle(addr *net.UDPAddr, b []byte) error {
199 | a, h, p, data, err := Decrypt(s.Password, b)
200 | if err != nil {
201 | return err
202 | }
203 | send := func(ue *socks5.UDPExchange, data []byte) error {
204 | _, err := ue.RemoteConn.Write(data)
205 | if err != nil {
206 | return err
207 | }
208 | return nil
209 | }
210 |
211 | var ue *socks5.UDPExchange
212 | iue, ok := s.UDPExchanges.Get(addr.String())
213 | if ok {
214 | ue = iue.(*socks5.UDPExchange)
215 | return send(ue, data)
216 | }
217 | address := socks5.ToAddress(a, h, p)
218 |
219 | c, err := Dial.Dial("udp", address)
220 | if err != nil {
221 | return err
222 | }
223 | rc := c.(*net.UDPConn)
224 | ue = &socks5.UDPExchange{
225 | ClientAddr: addr,
226 | RemoteConn: rc,
227 | }
228 | if err := send(ue, data); err != nil {
229 | ue.RemoteConn.Close()
230 | return err
231 | }
232 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
233 | go func(ue *socks5.UDPExchange) {
234 | defer func() {
235 | s.UDPExchanges.Delete(ue.ClientAddr.String())
236 | ue.RemoteConn.Close()
237 | }()
238 | var b [65536]byte
239 | for {
240 | if s.UDPDeadline != 0 {
241 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
242 | break
243 | }
244 | }
245 | n, err := ue.RemoteConn.Read(b[:])
246 | if err != nil {
247 | break
248 | }
249 | a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
250 | if err != nil {
251 | log.Println(err)
252 | break
253 | }
254 | d := make([]byte, 0, 7)
255 | d = append(d, a)
256 | d = append(d, addr...)
257 | d = append(d, port...)
258 | d = append(d, b[0:n]...)
259 | cd, err := Encrypt(s.Password, d)
260 | if err != nil {
261 | log.Println(err)
262 | break
263 | }
264 | if _, err := s.UDPConn.WriteToUDP(cd, ue.ClientAddr); err != nil {
265 | break
266 | }
267 | }
268 | }(ue)
269 | return nil
270 | }
271 |
272 | // Shutdown server
273 | func (s *Server) Shutdown() error {
274 | var err, err1 error
275 | if s.TCPListen != nil {
276 | err = s.TCPListen.Close()
277 | }
278 | if s.UDPConn != nil {
279 | err1 = s.UDPConn.Close()
280 | }
281 | if err != nil {
282 | return err
283 | }
284 | return err1
285 | }
286 |
--------------------------------------------------------------------------------
/socks5.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "io"
6 | "log"
7 | "net"
8 | "time"
9 |
10 | cache "github.com/patrickmn/go-cache"
11 | "github.com/txthinking/brook/plugin"
12 | "github.com/txthinking/socks5"
13 | )
14 |
15 | // Socks5Server is the client of raw socks5 protocol
16 | type Socks5Server struct {
17 | Server *socks5.Server
18 | Socks5Middleman plugin.Socks5Middleman
19 | TCPTimeout int
20 | TCPDeadline int // not refreshed
21 | UDPDeadline int
22 | UDPSessionTime int
23 | ForwardAddress string
24 | ForwardUserName string
25 | ForwardPassword string
26 | Cache *cache.Cache
27 | }
28 |
29 | // NewSocks5Server returns a new Socks5Server
30 | func NewSocks5Server(addr, ip, userName, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) (*Socks5Server, error) {
31 | s5, err := socks5.NewClassicServer(addr, ip, userName, password, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
32 | if err != nil {
33 | return nil, err
34 | }
35 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
36 | x := &Socks5Server{
37 | Server: s5,
38 | TCPTimeout: tcpTimeout,
39 | TCPDeadline: tcpDeadline,
40 | UDPDeadline: udpDeadline,
41 | UDPSessionTime: udpSessionTime,
42 | Cache: cs,
43 | }
44 | return x, nil
45 | }
46 |
47 | // SetSocks5Middleman sets socks5middleman plugin
48 | func (x *Socks5Server) SetSocks5Middleman(m plugin.Socks5Middleman) {
49 | x.Socks5Middleman = m
50 | }
51 |
52 | // ListenAndServe will let client start to listen and serve, sm can be nil
53 | func (x *Socks5Server) ListenAndServe() error {
54 | return x.Server.Run(nil)
55 | }
56 |
57 | // ListenAndForward will let client start a proxy to listen and forward to another socks5,
58 | // sm can be nil
59 | func (x *Socks5Server) ListenAndForward(addr, username, password string) error {
60 | x.ForwardAddress = addr
61 | x.ForwardUserName = username
62 | x.ForwardPassword = password
63 | return x.Server.Run(x)
64 | }
65 |
66 | // TCPHandle handles tcp request
67 | func (x *Socks5Server) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
68 | if x.Socks5Middleman != nil {
69 | done, err := x.Socks5Middleman.TCPHandle(s, c, r)
70 | if err != nil {
71 | if done {
72 | return err
73 | }
74 | return ErrorReply(r, c, err)
75 | }
76 | if done {
77 | return nil
78 | }
79 | }
80 |
81 | client, err := socks5.NewClient(x.ForwardAddress, x.ForwardUserName, x.ForwardPassword, x.TCPTimeout, x.TCPDeadline, x.UDPDeadline)
82 | if err != nil {
83 | return err
84 | }
85 | if err := client.Negotiate(); err != nil {
86 | return ErrorReply(r, c, err)
87 | }
88 | defer client.TCPConn.Close()
89 |
90 | if r.Cmd == socks5.CmdUDP {
91 | // TODO If client's udp address is not 0, then prepare a local udp address
92 | if r.Atyp == socks5.ATYPIPv4 || r.Atyp == socks5.ATYPDomain {
93 | r.DstAddr = net.IPv4zero
94 | } else {
95 | r.DstAddr = net.IPv6zero
96 | }
97 | r.DstPort = []byte{0x00, 0x00}
98 | }
99 | rp, err := client.Request(r)
100 | if err != nil {
101 | return ErrorReply(r, c, err)
102 | }
103 |
104 | // reply ok and choose address according to cmd or something wrong
105 | if r.Cmd == socks5.CmdConnect {
106 | a, address, port, err := socks5.ParseAddress(client.TCPConn.LocalAddr().String())
107 | if err != nil {
108 | return ErrorReply(r, c, err)
109 | }
110 | rp.Atyp = a
111 | rp.BndAddr = address
112 | rp.BndPort = port
113 | if err := rp.WriteTo(c); err != nil {
114 | return err
115 | }
116 | // TODO
117 | go func() {
118 | _, _ = io.Copy(c, client.TCPConn)
119 | }()
120 | _, _ = io.Copy(client.TCPConn, c)
121 | return nil
122 | }
123 | if r.Cmd == socks5.CmdUDP {
124 | caddr, err := r.UDP(c, x.Server.ServerAddr)
125 | if err != nil {
126 | return err
127 | }
128 | // Because we always send zero:0 to remote
129 | _, ok := x.Cache.Get("RUA")
130 | if !ok {
131 | x.Cache.Set("RUA", rp.Address(), cache.DefaultExpiration)
132 | }
133 | _, p, err := net.SplitHostPort(caddr.String())
134 | if err != nil {
135 | return err
136 | }
137 | if p == "0" {
138 | time.Sleep(time.Duration(x.Server.UDPSessionTime) * time.Second)
139 | return nil
140 | }
141 | ch := make(chan byte)
142 | x.Server.TCPUDPAssociate.Set(caddr.String(), ch, cache.DefaultExpiration)
143 | <-ch
144 | return nil
145 | }
146 | return ErrorReply(r, c, socks5.ErrUnsupportCmd)
147 | }
148 |
149 | // UDPHandle handles udp request
150 | func (x *Socks5Server) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
151 | if x.Socks5Middleman != nil {
152 | if done, err := x.Socks5Middleman.UDPHandle(s, addr, d); err != nil || done {
153 | return err
154 | }
155 | }
156 |
157 | send := func(ue *socks5.UDPExchange, data []byte) error {
158 | _, err := ue.RemoteConn.Write(data)
159 | if err != nil {
160 | return err
161 | }
162 | return nil
163 | }
164 |
165 | var ue *socks5.UDPExchange
166 | iue, ok := s.UDPExchanges.Get(addr.String())
167 | if ok {
168 | ue = iue.(*socks5.UDPExchange)
169 | return send(ue, d.Bytes())
170 | }
171 |
172 | raddr, ok := x.Cache.Get("RUA")
173 | if !ok {
174 | return errors.New("Can not find remote udp address.")
175 | }
176 | tmp, err := Dial.Dial("udp", raddr.(string))
177 | if err != nil {
178 | v, ok := s.TCPUDPAssociate.Get(addr.String())
179 | if ok {
180 | ch := v.(chan byte)
181 | ch <- 0x00
182 | s.TCPUDPAssociate.Delete(addr.String())
183 | }
184 | return err
185 | }
186 | rc := tmp.(*net.UDPConn)
187 | ue = &socks5.UDPExchange{
188 | ClientAddr: addr,
189 | RemoteConn: rc,
190 | }
191 | if err := send(ue, d.Bytes()); err != nil {
192 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
193 | if ok {
194 | ch := v.(chan byte)
195 | ch <- 0x00
196 | }
197 | ue.RemoteConn.Close()
198 | return err
199 | }
200 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
201 | go func(ue *socks5.UDPExchange) {
202 | defer func() {
203 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
204 | if ok {
205 | ch := v.(chan byte)
206 | ch <- 0x00
207 | }
208 | s.UDPExchanges.Delete(ue.ClientAddr.String())
209 | ue.RemoteConn.Close()
210 | }()
211 | var b [65536]byte
212 | for {
213 | if s.UDPDeadline != 0 {
214 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
215 | log.Println(err)
216 | break
217 | }
218 | }
219 | n, err := ue.RemoteConn.Read(b[:])
220 | if err != nil {
221 | log.Println(err)
222 | break
223 | }
224 | d1, err := socks5.NewDatagramFromBytes(b[0:n])
225 | if err != nil {
226 | log.Println(err)
227 | break
228 | }
229 | a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
230 | if err != nil {
231 | log.Println(err)
232 | break
233 | }
234 | d1 = socks5.NewDatagram(a, addr, port, d1.Data)
235 | if _, err := s.UDPConn.WriteToUDP(d1.Bytes(), ue.ClientAddr); err != nil {
236 | log.Println(err)
237 | break
238 | }
239 | }
240 | }(ue)
241 | return nil
242 | }
243 |
244 | // Shutdown used to stop the client
245 | func (x *Socks5Server) Shutdown() error {
246 | return x.Server.Stop()
247 | }
248 |
--------------------------------------------------------------------------------
/tunnel.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "io"
5 | "log"
6 | "net"
7 | "time"
8 |
9 | cache "github.com/patrickmn/go-cache"
10 | "github.com/txthinking/socks5"
11 | )
12 |
13 | // Tunnel
14 | type Tunnel struct {
15 | TCPAddr *net.TCPAddr
16 | UDPAddr *net.UDPAddr
17 | ToAddr string
18 | RemoteTCPAddr *net.TCPAddr
19 | RemoteUDPAddr *net.UDPAddr
20 | Password []byte
21 | TCPListen *net.TCPListener
22 | UDPConn *net.UDPConn
23 | UDPExchanges *cache.Cache
24 | TCPDeadline int
25 | TCPTimeout int
26 | UDPDeadline int
27 | }
28 |
29 | // NewTunnel
30 | func NewTunnel(addr, to, remote, password string, tcpTimeout, tcpDeadline, udpDeadline int) (*Tunnel, error) {
31 | taddr, err := net.ResolveTCPAddr("tcp", addr)
32 | if err != nil {
33 | return nil, err
34 | }
35 | uaddr, err := net.ResolveUDPAddr("udp", addr)
36 | if err != nil {
37 | return nil, err
38 | }
39 | rtaddr, err := net.ResolveTCPAddr("tcp", remote)
40 | if err != nil {
41 | return nil, err
42 | }
43 | ruaddr, err := net.ResolveUDPAddr("udp", remote)
44 | if err != nil {
45 | return nil, err
46 | }
47 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
48 | s := &Tunnel{
49 | ToAddr: to,
50 | Password: []byte(password),
51 | TCPAddr: taddr,
52 | UDPAddr: uaddr,
53 | RemoteTCPAddr: rtaddr,
54 | RemoteUDPAddr: ruaddr,
55 | UDPExchanges: cs,
56 | TCPTimeout: tcpTimeout,
57 | TCPDeadline: tcpDeadline,
58 | UDPDeadline: udpDeadline,
59 | }
60 | return s, nil
61 | }
62 |
63 | // Run server
64 | func (s *Tunnel) ListenAndServe() error {
65 | errch := make(chan error)
66 | go func() {
67 | errch <- s.RunTCPServer()
68 | }()
69 | go func() {
70 | errch <- s.RunUDPServer()
71 | }()
72 | return <-errch
73 | }
74 |
75 | // RunTCPServer starts tcp server
76 | func (s *Tunnel) RunTCPServer() error {
77 | var err error
78 | s.TCPListen, err = net.ListenTCP("tcp", s.TCPAddr)
79 | if err != nil {
80 | return err
81 | }
82 | defer s.TCPListen.Close()
83 | for {
84 | c, err := s.TCPListen.AcceptTCP()
85 | if err != nil {
86 | return err
87 | }
88 | go func(c *net.TCPConn) {
89 | defer c.Close()
90 | if s.TCPTimeout != 0 {
91 | if err := c.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
92 | log.Println(err)
93 | return
94 | }
95 | }
96 | if s.TCPDeadline != 0 {
97 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
98 | log.Println(err)
99 | return
100 | }
101 | }
102 | if err := s.TCPHandle(c); err != nil {
103 | log.Println(err)
104 | }
105 | }(c)
106 | }
107 | return nil
108 | }
109 |
110 | // RunUDPServer starts udp server
111 | func (s *Tunnel) RunUDPServer() error {
112 | var err error
113 | s.UDPConn, err = net.ListenUDP("udp", s.UDPAddr)
114 | if err != nil {
115 | return err
116 | }
117 | defer s.UDPConn.Close()
118 | for {
119 | b := make([]byte, 65536)
120 | n, addr, err := s.UDPConn.ReadFromUDP(b)
121 | if err != nil {
122 | return err
123 | }
124 | go func(addr *net.UDPAddr, b []byte) {
125 | if err := s.UDPHandle(addr, b); err != nil {
126 | log.Println(err)
127 | return
128 | }
129 | }(addr, b[0:n])
130 | }
131 | return nil
132 | }
133 |
134 | // Shutdown server
135 | func (s *Tunnel) Shutdown() error {
136 | var err, err1 error
137 | if s.TCPListen != nil {
138 | err = s.TCPListen.Close()
139 | }
140 | if s.UDPConn != nil {
141 | err1 = s.UDPConn.Close()
142 | }
143 | if err != nil {
144 | return err
145 | }
146 | return err1
147 | }
148 |
149 | // TCPHandle handle request
150 | func (s *Tunnel) TCPHandle(c *net.TCPConn) error {
151 | tmp, err := Dial.Dial("tcp", s.RemoteTCPAddr.String())
152 | if err != nil {
153 | return err
154 | }
155 | rc := tmp.(*net.TCPConn)
156 | defer rc.Close()
157 | if s.TCPTimeout != 0 {
158 | if err := rc.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
159 | return err
160 | }
161 | }
162 | if s.TCPDeadline != 0 {
163 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
164 | return err
165 | }
166 | }
167 |
168 | k, n, err := PrepareKey(s.Password)
169 | if err != nil {
170 | return err
171 | }
172 | if _, err := rc.Write(n); err != nil {
173 | return err
174 | }
175 |
176 | a, address, port, err := socks5.ParseAddress(s.ToAddr)
177 | if err != nil {
178 | return err
179 | }
180 | rawaddr := make([]byte, 0, 7)
181 | rawaddr = append(rawaddr, a)
182 | rawaddr = append(rawaddr, address...)
183 | rawaddr = append(rawaddr, port...)
184 | n, err = WriteTo(rc, rawaddr, k, n, true)
185 | if err != nil {
186 | return err
187 | }
188 |
189 | go func() {
190 | n := make([]byte, 12)
191 | if _, err := io.ReadFull(rc, n); err != nil {
192 | return
193 | }
194 | k, err := GetKey(s.Password, n)
195 | if err != nil {
196 | log.Println(err)
197 | return
198 | }
199 | var b []byte
200 | for {
201 | if s.TCPDeadline != 0 {
202 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
203 | return
204 | }
205 | }
206 | b, n, err = ReadFrom(rc, k, n, false)
207 | if err != nil {
208 | return
209 | }
210 | if _, err := c.Write(b); err != nil {
211 | return
212 | }
213 | }
214 | }()
215 |
216 | var b [1024 * 2]byte
217 | for {
218 | if s.TCPDeadline != 0 {
219 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
220 | return nil
221 | }
222 | }
223 | i, err := c.Read(b[:])
224 | if err != nil {
225 | return nil
226 | }
227 | n, err = WriteTo(rc, b[0:i], k, n, false)
228 | if err != nil {
229 | return nil
230 | }
231 | }
232 | return nil
233 | }
234 |
235 | // UDPHandle handle packet
236 | func (s *Tunnel) UDPHandle(addr *net.UDPAddr, b []byte) error {
237 | a, address, port, err := socks5.ParseAddress(s.ToAddr)
238 | if err != nil {
239 | return err
240 | }
241 | rawaddr := make([]byte, 0, 7)
242 | rawaddr = append(rawaddr, a)
243 | rawaddr = append(rawaddr, address...)
244 | rawaddr = append(rawaddr, port...)
245 | b = append(rawaddr, b...)
246 |
247 | send := func(ue *socks5.UDPExchange, data []byte) error {
248 | cd, err := Encrypt(s.Password, data)
249 | if err != nil {
250 | return err
251 | }
252 | _, err = ue.RemoteConn.Write(cd)
253 | if err != nil {
254 | return err
255 | }
256 | return nil
257 | }
258 |
259 | var ue *socks5.UDPExchange
260 | iue, ok := s.UDPExchanges.Get(addr.String())
261 | if ok {
262 | ue = iue.(*socks5.UDPExchange)
263 | return send(ue, b)
264 | }
265 |
266 | c, err := Dial.Dial("udp", s.RemoteUDPAddr.String())
267 | if err != nil {
268 | return err
269 | }
270 | rc := c.(*net.UDPConn)
271 | ue = &socks5.UDPExchange{
272 | ClientAddr: addr,
273 | RemoteConn: rc,
274 | }
275 | if err := send(ue, b); err != nil {
276 | ue.RemoteConn.Close()
277 | return err
278 | }
279 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
280 | go func(ue *socks5.UDPExchange) {
281 | defer func() {
282 | s.UDPExchanges.Delete(ue.ClientAddr.String())
283 | ue.RemoteConn.Close()
284 | }()
285 | var b [65536]byte
286 | for {
287 | if s.UDPDeadline != 0 {
288 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
289 | break
290 | }
291 | }
292 | n, err := ue.RemoteConn.Read(b[:])
293 | if err != nil {
294 | break
295 | }
296 | _, _, _, data, err := Decrypt(s.Password, b[0:n])
297 | if err != nil {
298 | log.Println(err)
299 | break
300 | }
301 | if _, err := s.UDPConn.WriteToUDP(data, ue.ClientAddr); err != nil {
302 | break
303 | }
304 | }
305 | }(ue)
306 | return nil
307 | }
308 |
--------------------------------------------------------------------------------
/plugin/middleman/blackwhite/blackwhite.go:
--------------------------------------------------------------------------------
1 | package blackwhite
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "io"
7 | "io/ioutil"
8 | "net"
9 | "net/http"
10 | "strings"
11 | "time"
12 |
13 | "github.com/miekg/dns"
14 | "github.com/txthinking/socks5"
15 | "github.com/txthinking/x"
16 | )
17 |
18 | var Dial x.Dialer = x.DefaultDial
19 |
20 | // BlackWhite is a middleman
21 | type BlackWhite struct {
22 | Mode string // mode is white or black
23 | Domains map[string]byte
24 | Nets []*net.IPNet
25 | Timeout int
26 | Deadline int
27 | Socks5Handle *socks5.DefaultHandle
28 | BlackDNS string
29 | WhiteDNS string
30 | }
31 |
32 | // NewBlackWhite returns a BlackWhite
33 | func NewBlackWhite(mode, domainURL, cidrURL, blackDNS, whiteDNS string, timeout, deadline int) (*BlackWhite, error) {
34 | ds := make(map[string]byte)
35 | ns := make([]*net.IPNet, 0)
36 | if domainURL != "" {
37 | data, err := readData(domainURL)
38 | if err != nil {
39 | return nil, err
40 | }
41 | data = bytes.TrimSpace(data)
42 | data = bytes.Replace(data, []byte{0x20}, []byte{}, -1)
43 | data = bytes.Replace(data, []byte{0x0d, 0x0a}, []byte{0x0a}, -1)
44 | ss := strings.Split(string(data), "\n")
45 | for _, v := range ss {
46 | ds[v] = 0
47 | }
48 | }
49 | if cidrURL != "" {
50 | data, err := readData(cidrURL)
51 | if err != nil {
52 | return nil, err
53 | }
54 | data = bytes.TrimSpace(data)
55 | data = bytes.Replace(data, []byte{0x20}, []byte{}, -1)
56 | data = bytes.Replace(data, []byte{0x0d, 0x0a}, []byte{0x0a}, -1)
57 | ss := strings.Split(string(data), "\n")
58 | ns = make([]*net.IPNet, 0, len(ss))
59 | for _, v := range ss {
60 | _, in, err := net.ParseCIDR(v)
61 | if err != nil {
62 | return nil, err
63 | }
64 | ns = append(ns, in)
65 | }
66 | }
67 | return &BlackWhite{
68 | Mode: mode,
69 | Domains: ds,
70 | Nets: ns,
71 | Timeout: timeout,
72 | Deadline: deadline,
73 | Socks5Handle: &socks5.DefaultHandle{},
74 | WhiteDNS: whiteDNS,
75 | BlackDNS: blackDNS,
76 | }, nil
77 | }
78 |
79 | // Has domain or IP
80 | func (b *BlackWhite) Has(host string) bool {
81 | ip := net.ParseIP(host)
82 | if ip != nil {
83 | for _, v := range b.Nets {
84 | if v.Contains(ip) {
85 | return true
86 | }
87 | }
88 | return false
89 | }
90 | ss := strings.Split(host, ".")
91 | var s string
92 | for i := len(ss) - 1; i >= 0; i-- {
93 | if s == "" {
94 | s = ss[i]
95 | } else {
96 | s = ss[i] + "." + s
97 | }
98 | if _, ok := b.Domains[s]; ok {
99 | return true
100 | }
101 | }
102 | return false
103 | }
104 |
105 | // TCPHandle handles tcp request
106 | func (b *BlackWhite) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) (bool, error) {
107 | if r.Cmd == socks5.CmdConnect {
108 | h, _, err := net.SplitHostPort(r.Address())
109 | if err != nil {
110 | return false, err
111 | }
112 | if b.Mode == "white" && !b.Has(h) {
113 | return false, nil
114 | }
115 | if b.Mode == "black" && b.Has(h) {
116 | return false, nil
117 | }
118 | if err := b.Socks5Handle.TCPHandle(s, c, r); err != nil {
119 | return true, err
120 | }
121 | return true, nil
122 | }
123 | if r.Cmd == socks5.CmdUDP {
124 | return false, nil
125 | }
126 | return false, socks5.ErrUnsupportCmd
127 | }
128 |
129 | // UDPHandle handles udp packet
130 | func (b *BlackWhite) UDPHandle(s *socks5.Server, ca *net.UDPAddr, d *socks5.Datagram) (bool, error) {
131 | if d.Address() == b.BlackDNS {
132 | done, err := b.DNSHandle(s, ca, d)
133 | if err != nil || done {
134 | return done, err
135 | }
136 | }
137 | h, _, err := net.SplitHostPort(d.Address())
138 | if err != nil {
139 | return false, err
140 | }
141 | if b.Mode == "white" && !b.Has(h) {
142 | return false, nil
143 | }
144 | if b.Mode == "black" && b.Has(h) {
145 | return false, nil
146 | }
147 | if err := b.Socks5Handle.UDPHandle(s, ca, d); err != nil {
148 | return true, err
149 | }
150 | return true, nil
151 | }
152 |
153 | // DNSHandle handles DNS query
154 | func (b *BlackWhite) DNSHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) (bool, error) {
155 | bye := func() {
156 | v, ok := s.TCPUDPAssociate.Get(addr.String())
157 | if ok {
158 | ch := v.(chan byte)
159 | ch <- 0x00
160 | s.TCPUDPAssociate.Delete(addr.String())
161 | }
162 | }
163 | m := &dns.Msg{}
164 | if err := m.Unpack(d.Data); err != nil {
165 | bye()
166 | return true, err
167 | }
168 | white := false
169 | for _, v := range m.Question {
170 | if len(v.Name) > 0 && b.Mode == "white" && b.Has(v.Name[0:len(v.Name)-1]) {
171 | white = true
172 | break
173 | }
174 | if len(v.Name) > 0 && b.Mode == "black" && !b.Has(v.Name[0:len(v.Name)-1]) {
175 | white = true
176 | break
177 | }
178 | }
179 | if !white {
180 | return false, nil
181 | }
182 |
183 | conn, err := Dial.Dial("udp", b.WhiteDNS)
184 | if err != nil {
185 | bye()
186 | return true, err
187 | }
188 | defer conn.Close()
189 | co := &dns.Conn{Conn: conn}
190 | if err := co.WriteMsg(m); err != nil {
191 | bye()
192 | return true, err
193 | }
194 | m1, err := co.ReadMsg()
195 | if err != nil {
196 | bye()
197 | return true, err
198 | }
199 | if m1.MsgHdr.Truncated {
200 | conn, err := Dial.Dial("tcp", b.WhiteDNS)
201 | if err != nil {
202 | bye()
203 | return true, err
204 | }
205 | defer conn.Close()
206 | co := &dns.Conn{Conn: conn}
207 | if err := co.WriteMsg(m); err != nil {
208 | bye()
209 | return true, err
210 | }
211 | m1, err = co.ReadMsg()
212 | if err != nil {
213 | bye()
214 | return true, err
215 | }
216 | }
217 | m1b, err := m1.Pack()
218 | if err != nil {
219 | bye()
220 | return true, err
221 | }
222 |
223 | a, ad, port, err := socks5.ParseAddress(addr.String())
224 | if err != nil {
225 | bye()
226 | return true, err
227 | }
228 | d = socks5.NewDatagram(a, ad, port, m1b)
229 | if _, err := s.UDPConn.WriteToUDP(d.Bytes(), addr); err != nil {
230 | bye()
231 | return true, err
232 | }
233 | bye()
234 | return true, nil
235 | }
236 |
237 | // Handle handles http proxy request, if the domain is in the white list
238 | func (b *BlackWhite) Handle(method, addr string, request []byte, conn *net.TCPConn) (handled bool, err error) {
239 | h, _, err := net.SplitHostPort(addr)
240 | if err != nil {
241 | return false, err
242 | }
243 | if b.Mode == "white" && !b.Has(h) {
244 | return false, nil
245 | }
246 | if b.Mode == "black" && b.Has(h) {
247 | return false, nil
248 | }
249 |
250 | tmp, err := Dial.Dial("tcp", addr)
251 | if err != nil {
252 | return true, err
253 | }
254 | rc := tmp.(*net.TCPConn)
255 | defer rc.Close()
256 | if b.Timeout != 0 {
257 | if err := rc.SetKeepAlivePeriod(time.Duration(b.Timeout) * time.Second); err != nil {
258 | return true, err
259 | }
260 | }
261 | if b.Deadline != 0 {
262 | if err := rc.SetDeadline(time.Now().Add(time.Duration(b.Deadline) * time.Second)); err != nil {
263 | return true, err
264 | }
265 | }
266 | if method == "CONNECT" {
267 | _, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
268 | if err != nil {
269 | return true, err
270 | }
271 | }
272 | if method != "CONNECT" {
273 | if _, err := rc.Write(request); err != nil {
274 | return true, err
275 | }
276 | }
277 | // TODO
278 | go func() {
279 | _, _ = io.Copy(rc, conn)
280 | }()
281 | _, _ = io.Copy(conn, rc)
282 | return true, nil
283 | }
284 |
285 | func readData(url string) ([]byte, error) {
286 | if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
287 | c := &http.Client{
288 | Timeout: 9 * time.Second,
289 | }
290 | r, err := c.Get(url)
291 | if err != nil {
292 | return nil, err
293 | }
294 | defer r.Body.Close()
295 | data, err := ioutil.ReadAll(r.Body)
296 | if err != nil {
297 | return nil, err
298 | }
299 | return data, nil
300 | }
301 | if strings.HasPrefix(url, "file://") {
302 | data, err := ioutil.ReadFile(url)
303 | if err != nil {
304 | return nil, err
305 | }
306 | return data, nil
307 | }
308 | return nil, errors.New("Unsupport URL")
309 | }
310 |
--------------------------------------------------------------------------------
/tproxy_linux.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "io"
7 | "log"
8 | "net"
9 | "time"
10 |
11 | cache "github.com/patrickmn/go-cache"
12 | "github.com/txthinking/brook/tproxy"
13 | "github.com/txthinking/socks5"
14 | )
15 |
16 | // Tproxy
17 | type Tproxy struct {
18 | TCPAddr *net.TCPAddr
19 | UDPAddr *net.UDPAddr
20 | RemoteTCPAddr *net.TCPAddr
21 | RemoteUDPAddr *net.UDPAddr
22 | Password []byte
23 | TCPListen *net.TCPListener
24 | UDPConn *net.UDPConn
25 | UDPExchanges *cache.Cache
26 | TCPDeadline int
27 | TCPTimeout int
28 | UDPDeadline int
29 | }
30 |
31 | // NewTproxy
32 | func NewTproxy(addr, remote, password string, tcpTimeout, tcpDeadline, udpDeadline int) (*Tproxy, error) {
33 | taddr, err := net.ResolveTCPAddr("tcp", addr)
34 | if err != nil {
35 | return nil, err
36 | }
37 | uaddr, err := net.ResolveUDPAddr("udp", addr)
38 | if err != nil {
39 | return nil, err
40 | }
41 | rtaddr, err := net.ResolveTCPAddr("tcp", remote)
42 | if err != nil {
43 | return nil, err
44 | }
45 | ruaddr, err := net.ResolveUDPAddr("udp", remote)
46 | if err != nil {
47 | return nil, err
48 | }
49 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
50 | s := &Tproxy{
51 | Password: []byte(password),
52 | TCPAddr: taddr,
53 | UDPAddr: uaddr,
54 | RemoteTCPAddr: rtaddr,
55 | RemoteUDPAddr: ruaddr,
56 | UDPExchanges: cs,
57 | TCPTimeout: tcpTimeout,
58 | TCPDeadline: tcpDeadline,
59 | UDPDeadline: udpDeadline,
60 | }
61 | return s, nil
62 | }
63 |
64 | // Run server
65 | func (s *Tproxy) ListenAndServe() error {
66 | errch := make(chan error)
67 | go func() {
68 | errch <- s.RunTCPServer()
69 | }()
70 | go func() {
71 | errch <- s.RunUDPServer()
72 | }()
73 | return <-errch
74 | }
75 |
76 | // RunTCPServer starts tcp server
77 | func (s *Tproxy) RunTCPServer() error {
78 | var err error
79 | s.TCPListen, err = tproxy.ListenTCP("tcp", s.TCPAddr)
80 | if err != nil {
81 | return err
82 | }
83 | defer s.TCPListen.Close()
84 | for {
85 | c, err := s.TCPListen.AcceptTCP()
86 | if err != nil {
87 | return err
88 | }
89 | go func(c *net.TCPConn) {
90 | defer c.Close()
91 | if s.TCPTimeout != 0 {
92 | if err := c.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
93 | log.Println(err)
94 | return
95 | }
96 | }
97 | if s.TCPDeadline != 0 {
98 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
99 | log.Println(err)
100 | return
101 | }
102 | }
103 | if err := s.TCPHandle(c); err != nil {
104 | log.Println(err)
105 | }
106 | }(c)
107 | }
108 | return nil
109 | }
110 |
111 | // RunUDPServer starts udp server
112 | func (s *Tproxy) RunUDPServer() error {
113 | var err error
114 | s.UDPConn, err = tproxy.ListenUDP("udp", s.UDPAddr)
115 | if err != nil {
116 | return err
117 | }
118 | defer s.UDPConn.Close()
119 | for {
120 | b := make([]byte, 65536)
121 | n, saddr, daddr, err := tproxy.ReadFromUDP(s.UDPConn, b)
122 | if err != nil {
123 | return err
124 | }
125 | if n == 0 {
126 | continue
127 | }
128 | go func(saddr, daddr *net.UDPAddr, b []byte) {
129 | if err := s.UDPHandle(saddr, daddr, b); err != nil {
130 | log.Println(err)
131 | return
132 | }
133 | }(saddr, daddr, b[0:n])
134 | }
135 | return nil
136 | }
137 |
138 | // Shutdown server
139 | func (s *Tproxy) Shutdown() error {
140 | var err, err1 error
141 | if s.TCPListen != nil {
142 | err = s.TCPListen.Close()
143 | }
144 | if s.UDPConn != nil {
145 | err1 = s.UDPConn.Close()
146 | }
147 | if err != nil {
148 | return err
149 | }
150 | return err1
151 | }
152 |
153 | // TCPHandle handle request
154 | func (s *Tproxy) TCPHandle(c *net.TCPConn) error {
155 | tmp, err := tproxy.DialTCP("tcp", s.RemoteTCPAddr.String())
156 | if err != nil {
157 | return err
158 | }
159 | rc := tmp.(*net.TCPConn)
160 | defer rc.Close()
161 | if s.TCPTimeout != 0 {
162 | if err := rc.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
163 | return err
164 | }
165 | }
166 | if s.TCPDeadline != 0 {
167 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
168 | return err
169 | }
170 | }
171 |
172 | k, n, err := PrepareKey(s.Password)
173 | if err != nil {
174 | return err
175 | }
176 | if _, err := rc.Write(n); err != nil {
177 | return err
178 | }
179 |
180 | a, address, port, err := socks5.ParseAddress(c.LocalAddr().String())
181 | if err != nil {
182 | return err
183 | }
184 | rawaddr := make([]byte, 0, 7)
185 | rawaddr = append(rawaddr, a)
186 | rawaddr = append(rawaddr, address...)
187 | rawaddr = append(rawaddr, port...)
188 | n, err = WriteTo(rc, rawaddr, k, n, true)
189 | if err != nil {
190 | return err
191 | }
192 |
193 | go func() {
194 | n := make([]byte, 12)
195 | if _, err := io.ReadFull(rc, n); err != nil {
196 | return
197 | }
198 | k, err := GetKey(s.Password, n)
199 | if err != nil {
200 | log.Println(err)
201 | return
202 | }
203 | var b []byte
204 | for {
205 | if s.TCPDeadline != 0 {
206 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
207 | return
208 | }
209 | }
210 | b, n, err = ReadFrom(rc, k, n, false)
211 | if err != nil {
212 | return
213 | }
214 | if _, err := c.Write(b); err != nil {
215 | return
216 | }
217 | }
218 | }()
219 |
220 | var b [1024 * 2]byte
221 | for {
222 | if s.TCPDeadline != 0 {
223 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
224 | return nil
225 | }
226 | }
227 | i, err := c.Read(b[:])
228 | if err != nil {
229 | return nil
230 | }
231 | n, err = WriteTo(rc, b[0:i], k, n, false)
232 | if err != nil {
233 | return nil
234 | }
235 | }
236 | return nil
237 | }
238 |
239 | type UDPExchange struct {
240 | RemoteConn *net.UDPConn
241 | LocalConn *net.UDPConn
242 | }
243 |
244 | func (s *Tproxy) UDPHandle(addr, daddr *net.UDPAddr, b []byte) error {
245 | a, address, port, err := socks5.ParseAddress(daddr.String())
246 | if err != nil {
247 | return err
248 | }
249 | rawaddr := make([]byte, 0, 7)
250 | rawaddr = append(rawaddr, a)
251 | rawaddr = append(rawaddr, address...)
252 | rawaddr = append(rawaddr, port...)
253 | b = append(rawaddr, b...)
254 |
255 | send := func(ue *UDPExchange, data []byte) error {
256 | cd, err := Encrypt(s.Password, data)
257 | if err != nil {
258 | return err
259 | }
260 | _, err = ue.RemoteConn.Write(cd)
261 | if err != nil {
262 | return err
263 | }
264 | return nil
265 | }
266 |
267 | var ue *UDPExchange
268 | iue, ok := s.UDPExchanges.Get(addr.String())
269 | if ok {
270 | ue = iue.(*UDPExchange)
271 | return send(ue, b)
272 | }
273 |
274 | rc, err := tproxy.DialUDP("udp", &net.UDPAddr{
275 | IP: net.IPv4zero,
276 | Port: 0,
277 | }, s.RemoteUDPAddr)
278 | if err != nil {
279 | return err
280 | }
281 | c, err := tproxy.DialUDP("udp", daddr, addr)
282 | if err != nil {
283 | rc.Close()
284 | return errors.New(fmt.Sprintf("src: %s dst: %s %s", daddr.String(), addr.String(), err.Error()))
285 | }
286 | ue = &UDPExchange{
287 | RemoteConn: rc,
288 | LocalConn: c,
289 | }
290 | if err := send(ue, b); err != nil {
291 | ue.RemoteConn.Close()
292 | ue.LocalConn.Close()
293 | return err
294 | }
295 | s.UDPExchanges.Set(ue.LocalConn.RemoteAddr().String(), ue, cache.DefaultExpiration)
296 | go func(ue *UDPExchange) {
297 | defer func() {
298 | s.UDPExchanges.Delete(ue.LocalConn.RemoteAddr().String())
299 | ue.RemoteConn.Close()
300 | ue.LocalConn.Close()
301 | }()
302 | var b [65536]byte
303 | for {
304 | if s.UDPDeadline != 0 {
305 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
306 | break
307 | }
308 | }
309 | n, err := ue.RemoteConn.Read(b[:])
310 | if err != nil {
311 | break
312 | }
313 | _, _, _, data, err := Decrypt(s.Password, b[0:n])
314 | if err != nil {
315 | break
316 | }
317 | if _, err := ue.LocalConn.Write(data); err != nil {
318 | break
319 | }
320 | }
321 | }(ue)
322 | return nil
323 | }
324 |
--------------------------------------------------------------------------------
/ssserver.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/rand"
6 | "errors"
7 | "io"
8 | "log"
9 | "net"
10 | "time"
11 |
12 | cache "github.com/patrickmn/go-cache"
13 | "github.com/txthinking/socks5"
14 | "github.com/txthinking/x"
15 | )
16 |
17 | // SSServer
18 | type SSServer struct {
19 | Password []byte
20 | TCPAddr *net.TCPAddr
21 | UDPAddr *net.UDPAddr
22 | TCPListen *net.TCPListener
23 | UDPConn *net.UDPConn
24 | UDPExchanges *cache.Cache
25 | TCPDeadline int
26 | TCPTimeout int
27 | UDPDeadline int
28 | }
29 |
30 | // NewSSServer
31 | func NewSSServer(addr, password string, tcpTimeout, tcpDeadline, udpDeadline int) (*SSServer, error) {
32 | taddr, err := net.ResolveTCPAddr("tcp", addr)
33 | if err != nil {
34 | return nil, err
35 | }
36 | uaddr, err := net.ResolveUDPAddr("udp", addr)
37 | if err != nil {
38 | return nil, err
39 | }
40 | cs := cache.New(cache.NoExpiration, cache.NoExpiration)
41 | s := &SSServer{
42 | Password: MakeSSKey(password),
43 | TCPAddr: taddr,
44 | UDPAddr: uaddr,
45 | UDPExchanges: cs,
46 | TCPTimeout: tcpTimeout,
47 | TCPDeadline: tcpDeadline,
48 | UDPDeadline: udpDeadline,
49 | }
50 | return s, nil
51 | }
52 |
53 | // ListenAndServe server
54 | func (s *SSServer) ListenAndServe() error {
55 | errch := make(chan error)
56 | go func() {
57 | errch <- s.RunTCPServer()
58 | }()
59 | go func() {
60 | errch <- s.RunUDPServer()
61 | }()
62 | return <-errch
63 | }
64 |
65 | // RunTCPServer starts tcp server
66 | func (s *SSServer) RunTCPServer() error {
67 | var err error
68 | s.TCPListen, err = net.ListenTCP("tcp", s.TCPAddr)
69 | if err != nil {
70 | return err
71 | }
72 | defer s.TCPListen.Close()
73 | for {
74 | c, err := s.TCPListen.AcceptTCP()
75 | if err != nil {
76 | return err
77 | }
78 | go func(c *net.TCPConn) {
79 | defer c.Close()
80 | if s.TCPTimeout != 0 {
81 | if err := c.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
82 | log.Println(err)
83 | return
84 | }
85 | }
86 | if s.TCPDeadline != 0 {
87 | if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
88 | log.Println(err)
89 | return
90 | }
91 | }
92 | if err := s.TCPHandle(c); err != nil {
93 | log.Println(err)
94 | }
95 | }(c)
96 | }
97 | return nil
98 | }
99 |
100 | // RunUDPServer starts udp server
101 | func (s *SSServer) RunUDPServer() error {
102 | var err error
103 | s.UDPConn, err = net.ListenUDP("udp", s.UDPAddr)
104 | if err != nil {
105 | return err
106 | }
107 | defer s.UDPConn.Close()
108 | for {
109 | b := make([]byte, 65536)
110 | n, addr, err := s.UDPConn.ReadFromUDP(b)
111 | if err != nil {
112 | return err
113 | }
114 | go func(addr *net.UDPAddr, b []byte) {
115 | if err := s.UDPHandle(addr, b); err != nil {
116 | log.Println(err)
117 | return
118 | }
119 | }(addr, b[0:n])
120 | }
121 | return nil
122 | }
123 |
124 | // TCPHandle handle request
125 | func (s *SSServer) TCPHandle(c *net.TCPConn) error {
126 | cc, err := s.WrapCipherConn(c)
127 | if err != nil {
128 | return err
129 | }
130 | bb := make([]byte, 1)
131 | if _, err := io.ReadFull(cc, bb); err != nil {
132 | return err
133 | }
134 | var addr []byte
135 | if bb[0] == socks5.ATYPIPv4 {
136 | addr = make([]byte, 4)
137 | if _, err := io.ReadFull(cc, addr); err != nil {
138 | return err
139 | }
140 | } else if bb[0] == socks5.ATYPIPv6 {
141 | addr = make([]byte, 16)
142 | if _, err := io.ReadFull(cc, addr); err != nil {
143 | return err
144 | }
145 | } else if bb[0] == socks5.ATYPDomain {
146 | dal := make([]byte, 1)
147 | if _, err := io.ReadFull(cc, dal); err != nil {
148 | return err
149 | }
150 | if dal[0] == 0 {
151 | return err
152 | }
153 | addr = make([]byte, int(dal[0]))
154 | if _, err := io.ReadFull(cc, addr); err != nil {
155 | return err
156 | }
157 | addr = append(dal, addr...)
158 | } else {
159 | return errors.New("Unknown address type")
160 | }
161 | port := make([]byte, 2)
162 | if _, err := io.ReadFull(cc, port); err != nil {
163 | return err
164 | }
165 | address := socks5.ToAddress(bb[0], addr, port)
166 |
167 | tmp, err := Dial.Dial("tcp", address)
168 | if err != nil {
169 | return err
170 | }
171 | rc := tmp.(*net.TCPConn)
172 | defer rc.Close()
173 | if s.TCPTimeout != 0 {
174 | if err := rc.SetKeepAlivePeriod(time.Duration(s.TCPTimeout) * time.Second); err != nil {
175 | return err
176 | }
177 | }
178 | if s.TCPDeadline != 0 {
179 | if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPDeadline) * time.Second)); err != nil {
180 | return err
181 | }
182 | }
183 |
184 | // TODO
185 | go func() {
186 | iv := make([]byte, aes.BlockSize)
187 | if _, err := io.ReadFull(rand.Reader, iv); err != nil {
188 | log.Println(err)
189 | return
190 | }
191 | if _, err := cc.Write(iv); err != nil {
192 | log.Println(err)
193 | return
194 | }
195 | _, _ = io.Copy(cc, rc)
196 | }()
197 | _, _ = io.Copy(rc, cc)
198 | return nil
199 | }
200 |
201 | // UDPHandle handle packet
202 | func (s *SSServer) UDPHandle(addr *net.UDPAddr, b []byte) error {
203 | a, h, p, data, err := s.Decrypt(b)
204 | if err != nil {
205 | return err
206 | }
207 | send := func(ue *socks5.UDPExchange, data []byte) error {
208 | _, err := ue.RemoteConn.Write(data)
209 | if err != nil {
210 | return err
211 | }
212 | return nil
213 | }
214 |
215 | var ue *socks5.UDPExchange
216 | iue, ok := s.UDPExchanges.Get(addr.String())
217 | if ok {
218 | ue = iue.(*socks5.UDPExchange)
219 | return send(ue, data)
220 | }
221 | address := socks5.ToAddress(a, h, p)
222 |
223 | c, err := Dial.Dial("udp", address)
224 | if err != nil {
225 | return err
226 | }
227 | rc := c.(*net.UDPConn)
228 | ue = &socks5.UDPExchange{
229 | ClientAddr: addr,
230 | RemoteConn: rc,
231 | }
232 | if err := send(ue, data); err != nil {
233 | ue.RemoteConn.Close()
234 | return err
235 | }
236 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
237 | go func(ue *socks5.UDPExchange) {
238 | defer func() {
239 | s.UDPExchanges.Delete(ue.ClientAddr.String())
240 | ue.RemoteConn.Close()
241 | }()
242 | var b [65536]byte
243 | for {
244 | if s.UDPDeadline != 0 {
245 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
246 | log.Println(err)
247 | break
248 | }
249 | }
250 | n, err := ue.RemoteConn.Read(b[:])
251 | if err != nil {
252 | log.Println(err)
253 | break
254 | }
255 | a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
256 | if err != nil {
257 | log.Println(err)
258 | break
259 | }
260 | cd, err := s.Encrypt(a, addr, port, b[0:n])
261 | if err != nil {
262 | log.Println(err)
263 | break
264 | }
265 | if _, err := s.UDPConn.WriteToUDP(cd, ue.ClientAddr); err != nil {
266 | log.Println(err)
267 | break
268 | }
269 | }
270 | }(ue)
271 | return nil
272 | }
273 |
274 | // WrapChiperConn make a chiper conn
275 | func (s *SSServer) WrapCipherConn(conn net.Conn) (*CipherConn, error) {
276 | iv := make([]byte, aes.BlockSize)
277 | if _, err := io.ReadFull(conn, iv); err != nil {
278 | return nil, err
279 | }
280 | return NewCipherConn(conn, s.Password, iv)
281 | }
282 |
283 | // Encrypt data
284 | func (s *SSServer) Encrypt(a byte, h, p, d []byte) ([]byte, error) {
285 | b := make([]byte, 0, 7)
286 | b = append(b, a)
287 | b = append(b, h...)
288 | b = append(b, p...)
289 | b = append(b, d...)
290 | return x.AESCFBEncrypt(b, s.Password)
291 | }
292 |
293 | // Decrypt data
294 | func (s *SSServer) Decrypt(cd []byte) (a byte, addr, port, data []byte, err error) {
295 | var bb []byte
296 | bb, err = x.AESCFBDecrypt(cd, s.Password)
297 | if err != nil {
298 | return
299 | }
300 | err = errors.New("Data length error")
301 | n := len(bb)
302 | minl := 1
303 | if n < minl {
304 | return
305 | }
306 | if bb[0] == socks5.ATYPIPv4 {
307 | minl += 4
308 | if n < minl {
309 | return
310 | }
311 | addr = bb[minl-4 : minl]
312 | } else if bb[0] == socks5.ATYPIPv6 {
313 | minl += 16
314 | if n < minl {
315 | return
316 | }
317 | addr = bb[minl-16 : minl]
318 | } else if bb[0] == socks5.ATYPDomain {
319 | minl += 1
320 | if n < minl {
321 | return
322 | }
323 | l := bb[1]
324 | if l == 0 {
325 | return
326 | }
327 | minl += int(l)
328 | if n < minl {
329 | return
330 | }
331 | addr = bb[minl-int(l) : minl]
332 | addr = append([]byte{l}, addr...)
333 | } else {
334 | return
335 | }
336 | minl += 2
337 | if n <= minl {
338 | return
339 | }
340 | a = bb[0]
341 | port = bb[minl-2 : minl]
342 | data = bb[minl:]
343 | err = nil
344 | return
345 | }
346 |
347 | // Shutdown server
348 | func (s *SSServer) Shutdown() error {
349 | var err, err1 error
350 | if s.TCPListen != nil {
351 | err = s.TCPListen.Close()
352 | }
353 | if s.UDPConn != nil {
354 | err1 = s.UDPConn.Close()
355 | }
356 | if err != nil {
357 | return err
358 | }
359 | return err1
360 | }
361 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Brook
2 |
3 | [](https://travis-ci.org/txthinking/brook) [](https://goreportcard.com/report/github.com/txthinking/brook) [](http://www.gnu.org/licenses/gpl-3.0) [](https://github.com/txthinking/brook/wiki)
4 |
5 |
6 |
7 |
8 |
9 | ---
10 |
11 | ### v20181212
12 |
13 | * Uninstall/Delete the old client on MacOS or Windows
14 | * On MacOS, you need to System Preferences -> Security & Privacy, click Open Anyway, when you open Brook
15 | * No longer support the snap package
16 |
17 | ---
18 |
19 | ### Table of Contents
20 |
21 | * [What is Brook](#what-is-brook)
22 | * [Download](#download)
23 | * [Packages](#packages)
24 | * [**Server**](#server)
25 | * [**Client (CLI)**](#client-cli)
26 | * [**Client (GUI)**](#client-gui)
27 | * [Tunnel](#tunnel)
28 | * [Tproxy](#tproxy)
29 | * [VPN](#vpn)
30 | * [Relay](#relay)
31 | * [Socks5](#socks5)
32 | * [Socks5 to HTTP](#socks5-to-http)
33 | * [Shadowsocks](#shadowsocks)
34 | * [Contributing](#contributing)
35 | * [License](#license)
36 |
37 | ## What is Brook
38 |
39 | Brook is a cross-platform proxy/vpn software.
40 | Brook's goal is to keep it simple, stupid and not detectable.
41 |
42 | ## Download
43 |
44 | | Download | Server/Client | OS | Arch | Remark |
45 | | --- | --- | --- | --- | --- |
46 | | [brook](https://github.com/txthinking/brook/releases/download/v20181212/brook) | Server & Client | Linux | amd64 | CLI |
47 | | [brook_linux_386](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_386) | Server & Client | Linux | 386 | CLI |
48 | | [brook_linux_arm64](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_arm64) | Server & Client | Linux | arm64 | CLI |
49 | | [brook_linux_arm5](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_arm5) | Server & Client | Linux | arm5 | CLI |
50 | | [brook_linux_arm6](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_arm6) | Server & Client | Linux | arm6 | CLI |
51 | | [brook_linux_arm7](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_arm7) | Server & Client | Linux | arm7 | CLI |
52 | | [brook_linux_mips](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_mips) | Server & Client | Linux | mips | CLI |
53 | | [brook_linux_mipsle](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_mipsle) | Server & Client | Linux | mipsle | CLI |
54 | | [brook_linux_mips64](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_mips64) | Server & Client | Linux | mips64 | CLI |
55 | | [brook_linux_mips64le](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_mips64le) | Server & Client | Linux | mips64le | CLI |
56 | | [brook_linux_ppc64](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_ppc64) | Server & Client | Linux | ppc64 | CLI |
57 | | [brook_linux_ppc64le](https://github.com/txthinking/brook/releases/download/v20181212/brook_linux_ppc64le) | Server & Client | Linux | ppc64le | CLI |
58 | | [brook_darwin_amd64](https://github.com/txthinking/brook/releases/download/v20181212/brook_darwin_amd64) | Server & Client | MacOS | amd64 | CLI |
59 | | [brook_windows_amd64.exe](https://github.com/txthinking/brook/releases/download/v20181212/brook_windows_amd64.exe) | Server & Client | Windows | amd64 | CLI |
60 | | [brook_windows_386.exe](https://github.com/txthinking/brook/releases/download/v20181212/brook_windows_386.exe) | Server & Client | Windows | 386 | CLI |
61 | | [Brook.dmg](https://github.com/txthinking/brook/releases/download/v20181212/Brook.dmg) | Client | MacOS | amd64 | GUI |
62 | | [Brook.exe](https://github.com/txthinking/brook/releases/download/v20181212/Brook.exe) | Client | Windows | amd64 | GUI |
63 | | [App Store](https://itunes.apple.com/us/app/brook-brook-shadowsocks-vpn-proxy/id1216002642) | Client | iOS | - | GUI |
64 | | [Brook.apk](https://github.com/txthinking/brook/releases/download/v20181212/Brook.apk)(No Google Play) | Client | Android | - | GUI |
65 |
66 | **See [wiki](https://github.com/txthinking/brook/wiki) for more tutorials**
67 |
68 | ## Packages
69 |
70 | ### ArchLinux
71 |
72 | ```
73 | sudo pacman -S brook
74 | ```
75 |
76 | ### MacOS(GUI)
77 |
78 | ```
79 | brew cask install brook
80 | ```
81 |
82 | ## Brook
83 |
84 | ```
85 | NAME:
86 | Brook - A Cross-Platform Proxy/VPN Software
87 |
88 | USAGE:
89 | brook [global options] command [command options] [arguments...]
90 |
91 | VERSION:
92 | 20181212
93 |
94 | AUTHOR:
95 | Cloud
96 |
97 | COMMANDS:
98 | server Run as server mode
99 | servers Run as multiple servers mode
100 | client Run as client mode
101 | tunnel Run as tunnel mode on client-side
102 | tproxy Run as tproxy mode on client-side, transparent proxy, only works on Linux
103 | vpn Run as VPN mode on client-side
104 | ssserver Run as shadowsocks server mode, fixed method is aes-256-cfb
105 | ssservers Run as shadowsocks multiple servers mode, fixed method is aes-256-cfb
106 | ssclient Run as shadowsocks client mode, fixed method is aes-256-cfb
107 | socks5 Run as raw socks5 server
108 | relay Run as relay mode
109 | relays Run as multiple relays mode
110 | qr Print brook server QR code
111 | socks5tohttp Convert socks5 to http proxy
112 | systemproxy Set system proxy with pac url, or remove, only works on MacOS/Windows
113 | help, h Shows a list of commands or help for one command
114 |
115 | GLOBAL OPTIONS:
116 | --debug, -d Enable debug
117 | --listen value, -l value Listen address for debug (default: ":6060")
118 | --help, -h show help
119 | --version, -v print the version
120 | ```
121 |
122 | ### Server
123 |
124 | ```
125 | # Run as a brook server
126 | $ brook server -l :9999 -p password
127 | ```
128 |
129 | ```
130 | # Run as multiple brook servers
131 | $ brook servers -l ":9999 password" -l ":8888 password"
132 | ```
133 |
134 | > If you run a public/shared server, do not forget this parameter --tcpDeadline
135 |
136 | ### Client (CLI)
137 |
138 | ```
139 | # Run as brook client, start a socks5 proxy socks5://127.0.0.1:1080
140 | $ brook client -l 127.0.0.1:1080 -i 127.0.0.1 -s server_address:port -p password
141 | ```
142 |
143 | ```
144 | # Run as brook client, start a http(s) proxy http(s)://127.0.0.1:8080
145 | $ brook client -l 127.0.0.1:8080 -i 127.0.0.1 -s server_address:port -p password --http
146 | ```
147 |
148 | ### Client (GUI)
149 |
150 | See [wiki](https://github.com/txthinking/brook/wiki)
151 |
152 | #### Tunnel
153 |
154 | ```
155 | # Run as tunnel 127.0.0.1:5 to 1.2.3.4:5
156 | $ brook tunnel -l 127.0.0.1:5 -t 1.2.3.4:5 -s server_address:port -p password
157 | ```
158 |
159 | #### Tproxy (usually used on Linux router box)
160 |
161 | See [wiki](https://github.com/txthinking/brook/wiki/How-to-run-transparent-proxy-on-Linux%3F)
162 |
163 | #### VPN
164 |
165 | ```
166 | # Run as VPN to proxy all TCP/UDP. [ROOT privileges required].
167 | $ sudo brook vpn -l 127.0.0.1:1080 -s server_address:port -p password
168 | ```
169 |
170 | **See [wiki](https://github.com/txthinking/brook/wiki/How-to-run-VPN-on-Linux,-MacOS-and-Windows%3F) for more tutorials**
171 |
172 | #### Relay
173 |
174 | ```
175 | # Run as relay to 1.2.3.4:5
176 | $ brook relay -l :5 -r 1.2.3.4:5
177 | ```
178 |
179 | #### Socks5
180 |
181 | ```
182 | # Run as a raw socks5 server 1.2.3.4:1080
183 | $ brook socks5 -l :1080 -i 1.2.3.4
184 | ```
185 |
186 | #### Socks5 to HTTP
187 |
188 | ```
189 | # Convert socks5://127.0.0.1:1080 to http(s)://127.0.0.1:8080 proxy
190 | $ brook socks5tohttp -l 127.0.0.1:8080 -s 127.0.0.1:1080
191 | ```
192 |
193 | #### Shadowsocks
194 |
195 | ```
196 | # Run as a shadowsocks server
197 | $ brook ssserver -l :9999 -p password
198 | ```
199 |
200 | ```
201 | # Run as multiple shadowsocks servers
202 | $ brook ssservers -l ":9999 password" -l ":8888 password"
203 | ```
204 |
205 | > If you run a public/shared server, do not forget this parameter --tcpDeadline
206 |
207 | ```
208 | # Run as shadowsocks client, start a socks5 proxy socks5://127.0.0.1:1080
209 | $ brook ssclient -l 127.0.0.1:1080 -i 127.0.0.1 -s server_address:port -p password
210 | ```
211 |
212 | ```
213 | # Run as shadowsocks client, start a http(s) proxy http(s)://127.0.0.1:8080
214 | $ brook ssclient -l 127.0.0.1:8080 -i 127.0.0.1 -s server_address:port -p password --http
215 | ```
216 |
217 | > Fixed method is aes-256-cfb
218 |
219 | **See [wiki](https://github.com/txthinking/brook/wiki) for more tutorials**
220 |
221 | ## Contributing
222 |
223 | Please read [CONTRIBUTING.md](https://github.com/txthinking/brook/blob/master/.github/CONTRIBUTING.md) first
224 |
225 | ## License
226 |
227 | Licensed under The GPLv3 License
228 |
--------------------------------------------------------------------------------
/ssclient.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "bytes"
5 | "crypto/aes"
6 | "crypto/rand"
7 | "errors"
8 | "io"
9 | "log"
10 | "net"
11 | "time"
12 |
13 | cache "github.com/patrickmn/go-cache"
14 | "github.com/txthinking/brook/plugin"
15 | "github.com/txthinking/socks5"
16 | xx "github.com/txthinking/x"
17 | )
18 |
19 | // SSClient
20 | type SSClient struct {
21 | Server *socks5.Server
22 | RemoteAddr string
23 | Password []byte
24 | TCPTimeout int
25 | TCPDeadline int // Not refreshed
26 | UDPDeadline int
27 | TCPListen *net.TCPListener
28 | Socks5Middleman plugin.Socks5Middleman
29 | HTTPMiddleman plugin.HTTPMiddleman
30 | }
31 |
32 | // NewSSClient returns a new SSClient
33 | func NewSSClient(addr, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) (*SSClient, error) {
34 | s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
35 | if err != nil {
36 | return nil, err
37 | }
38 | x := &SSClient{
39 | RemoteAddr: server,
40 | Server: s5,
41 | Password: MakeSSKey(password),
42 | TCPTimeout: tcpTimeout,
43 | TCPDeadline: tcpDeadline,
44 | UDPDeadline: udpDeadline,
45 | }
46 | return x, nil
47 | }
48 |
49 | // SetSocks5Middleman sets socks5middleman plugin
50 | func (x *SSClient) SetSocks5Middleman(m plugin.Socks5Middleman) {
51 | x.Socks5Middleman = m
52 | }
53 |
54 | // SetHTTPMiddleman sets httpmiddleman plugin
55 | func (x *SSClient) SetHTTPMiddleman(m plugin.HTTPMiddleman) {
56 | x.HTTPMiddleman = m
57 | }
58 |
59 | // ListenAndServe will let client start a socks5 proxy
60 | // sm can be nil
61 | func (x *SSClient) ListenAndServe() error {
62 | return x.Server.Run(x)
63 | }
64 |
65 | // TCPHandle handles tcp request
66 | func (x *SSClient) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
67 | if x.Socks5Middleman != nil {
68 | done, err := x.Socks5Middleman.TCPHandle(s, c, r)
69 | if err != nil {
70 | if done {
71 | return err
72 | }
73 | return ErrorReply(r, c, err)
74 | }
75 | if done {
76 | return nil
77 | }
78 | }
79 |
80 | if r.Cmd == socks5.CmdConnect {
81 | tmp, err := Dial.Dial("tcp", x.RemoteAddr)
82 | if err != nil {
83 | return ErrorReply(r, c, err)
84 | }
85 | rc := tmp.(*net.TCPConn)
86 | defer rc.Close()
87 | if x.TCPTimeout != 0 {
88 | if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
89 | return ErrorReply(r, c, err)
90 | }
91 | }
92 | if x.TCPDeadline != 0 {
93 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
94 | return ErrorReply(r, c, err)
95 | }
96 | }
97 | crc, err := x.WrapCipherConn(rc)
98 | if err != nil {
99 | return ErrorReply(r, c, err)
100 | }
101 | rawaddr := make([]byte, 0, 7)
102 | rawaddr = append(rawaddr, r.Atyp)
103 | rawaddr = append(rawaddr, r.DstAddr...)
104 | rawaddr = append(rawaddr, r.DstPort...)
105 | if _, err := crc.Write(rawaddr); err != nil {
106 | return ErrorReply(r, c, err)
107 | }
108 | a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
109 | if err != nil {
110 | return ErrorReply(r, c, err)
111 | }
112 |
113 | rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
114 | if err := rp.WriteTo(c); err != nil {
115 | return err
116 | }
117 |
118 | // TODO
119 | go func() {
120 | iv := make([]byte, aes.BlockSize)
121 | if _, err := io.ReadFull(crc, iv); err != nil {
122 | log.Println(err)
123 | return
124 | }
125 | _, _ = io.Copy(c, crc)
126 | }()
127 | _, _ = io.Copy(crc, c)
128 | return nil
129 | }
130 | if r.Cmd == socks5.CmdUDP {
131 | caddr, err := r.UDP(c, x.Server.ServerAddr)
132 | if err != nil {
133 | return err
134 | }
135 | _, p, err := net.SplitHostPort(caddr.String())
136 | if err != nil {
137 | return err
138 | }
139 | if p == "0" {
140 | time.Sleep(time.Duration(x.Server.UDPSessionTime) * time.Second)
141 | return nil
142 | }
143 | ch := make(chan byte)
144 | x.Server.TCPUDPAssociate.Set(caddr.String(), ch, cache.DefaultExpiration)
145 | <-ch
146 | return nil
147 | }
148 | return socks5.ErrUnsupportCmd
149 | }
150 |
151 | // UDPHandle handles udp request
152 | func (x *SSClient) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
153 | if x.Socks5Middleman != nil {
154 | if done, err := x.Socks5Middleman.UDPHandle(s, addr, d); err != nil || done {
155 | return err
156 | }
157 | }
158 |
159 | send := func(ue *socks5.UDPExchange, data []byte) error {
160 | cd, err := x.Encrypt(data)
161 | if err != nil {
162 | return err
163 | }
164 | _, err = ue.RemoteConn.Write(cd)
165 | if err != nil {
166 | return err
167 | }
168 | return nil
169 | }
170 |
171 | var ue *socks5.UDPExchange
172 | iue, ok := s.UDPExchanges.Get(addr.String())
173 | if ok {
174 | ue = iue.(*socks5.UDPExchange)
175 | return send(ue, d.Bytes()[3:])
176 | }
177 |
178 | c, err := Dial.Dial("udp", x.RemoteAddr)
179 | if err != nil {
180 | v, ok := s.TCPUDPAssociate.Get(addr.String())
181 | if ok {
182 | ch := v.(chan byte)
183 | ch <- 0x00
184 | }
185 | return err
186 | }
187 | rc := c.(*net.UDPConn)
188 | ue = &socks5.UDPExchange{
189 | ClientAddr: addr,
190 | RemoteConn: rc,
191 | }
192 | if err := send(ue, d.Bytes()[3:]); err != nil {
193 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
194 | if ok {
195 | ch := v.(chan byte)
196 | ch <- 0x00
197 | }
198 | ue.RemoteConn.Close()
199 | return err
200 | }
201 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
202 | go func(ue *socks5.UDPExchange) {
203 | defer func() {
204 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
205 | if ok {
206 | ch := v.(chan byte)
207 | ch <- 0x00
208 | }
209 | s.UDPExchanges.Delete(ue.ClientAddr.String())
210 | ue.RemoteConn.Close()
211 | }()
212 | var b [65536]byte
213 | for {
214 | if s.UDPDeadline != 0 {
215 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
216 | log.Println(err)
217 | break
218 | }
219 | }
220 | n, err := ue.RemoteConn.Read(b[:])
221 | if err != nil {
222 | log.Println(err)
223 | break
224 | }
225 | _, _, _, data, err := x.Decrypt(b[0:n])
226 | if err != nil {
227 | log.Println(err)
228 | break
229 | }
230 | a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
231 | if err != nil {
232 | log.Println(err)
233 | break
234 | }
235 | d1 := socks5.NewDatagram(a, addr, port, data)
236 | if _, err := s.UDPConn.WriteToUDP(d1.Bytes(), ue.ClientAddr); err != nil {
237 | log.Println(err)
238 | break
239 | }
240 | }
241 | }(ue)
242 | return nil
243 | }
244 |
245 | // ListenAndServeHTTP will let client start a http proxy
246 | // m can be nil
247 | func (x *SSClient) ListenAndServeHTTP() error {
248 | var err error
249 | x.TCPListen, err = net.ListenTCP("tcp", x.Server.TCPAddr)
250 | if err != nil {
251 | return nil
252 | }
253 | for {
254 | c, err := x.TCPListen.AcceptTCP()
255 | if err != nil {
256 | return err
257 | }
258 | go func(c *net.TCPConn) {
259 | defer c.Close()
260 | if x.TCPTimeout != 0 {
261 | if err := c.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
262 | log.Println(err)
263 | return
264 | }
265 | }
266 | if x.TCPDeadline != 0 {
267 | if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
268 | log.Println(err)
269 | return
270 | }
271 | }
272 | if err := x.HTTPHandle(c); err != nil {
273 | log.Println(err)
274 | return
275 | }
276 | }(c)
277 | }
278 | }
279 |
280 | // HTTPHandle handle http request
281 | func (x *SSClient) HTTPHandle(c *net.TCPConn) error {
282 | b := make([]byte, 0, 1024)
283 | for {
284 | var b1 [1024]byte
285 | n, err := c.Read(b1[:])
286 | if err != nil {
287 | return err
288 | }
289 | b = append(b, b1[:n]...)
290 | if bytes.Contains(b, []byte{0x0d, 0x0a, 0x0d, 0x0a}) {
291 | break
292 | }
293 | if len(b) >= 2083+18 {
294 | return errors.New("HTTP header too long")
295 | }
296 | }
297 | bb := bytes.SplitN(b, []byte(" "), 3)
298 | if len(bb) != 3 {
299 | return errors.New("Invalid Request")
300 | }
301 | method, aoru := string(bb[0]), string(bb[1])
302 | var addr string
303 | if method == "CONNECT" {
304 | addr = aoru
305 | }
306 | if method != "CONNECT" {
307 | var err error
308 | addr, err = xx.GetAddressFromURL(aoru)
309 | if err != nil {
310 | return err
311 | }
312 | }
313 |
314 | if x.HTTPMiddleman != nil {
315 | if done, err := x.HTTPMiddleman.Handle(method, addr, b, c); err != nil || done {
316 | return err
317 | }
318 | }
319 |
320 | a, h, p, err := socks5.ParseAddress(addr)
321 | if err != nil {
322 | return err
323 | }
324 | tmp, err := Dial.Dial("tcp", x.RemoteAddr)
325 | if err != nil {
326 | return err
327 | }
328 | rc := tmp.(*net.TCPConn)
329 | defer rc.Close()
330 | if x.TCPTimeout != 0 {
331 | if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
332 | return err
333 | }
334 | }
335 | if x.TCPDeadline != 0 {
336 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
337 | return err
338 | }
339 | }
340 | crc, err := x.WrapCipherConn(rc)
341 | if err != nil {
342 | return err
343 | }
344 |
345 | rawaddr := make([]byte, 0)
346 | rawaddr = append(rawaddr, a)
347 | rawaddr = append(rawaddr, h...)
348 | rawaddr = append(rawaddr, p...)
349 | if _, err := crc.Write(rawaddr); err != nil {
350 | return err
351 | }
352 | if method == "CONNECT" {
353 | _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
354 | if err != nil {
355 | return err
356 | }
357 | }
358 | if method != "CONNECT" {
359 | if _, err := crc.Write(b); err != nil {
360 | return err
361 | }
362 | }
363 |
364 | // TODO
365 | go func() {
366 | iv := make([]byte, aes.BlockSize)
367 | if _, err := io.ReadFull(crc, iv); err != nil {
368 | log.Println(err)
369 | return
370 | }
371 | _, _ = io.Copy(c, crc)
372 | }()
373 | _, _ = io.Copy(crc, c)
374 | return nil
375 | }
376 |
377 | // WrapChiperConn make a chiper conn
378 | func (x *SSClient) WrapCipherConn(conn *net.TCPConn) (*CipherConn, error) {
379 | iv := make([]byte, aes.BlockSize)
380 | if _, err := io.ReadFull(rand.Reader, iv); err != nil {
381 | return nil, err
382 | }
383 | if _, err := conn.Write(iv); err != nil {
384 | return nil, err
385 | }
386 | return NewCipherConn(conn, x.Password, iv)
387 | }
388 |
389 | // Encrypt data
390 | func (x *SSClient) Encrypt(rawdata []byte) ([]byte, error) {
391 | return xx.AESCFBEncrypt(rawdata, x.Password)
392 | }
393 |
394 | // Decrypt data
395 | func (x *SSClient) Decrypt(cd []byte) (a byte, addr, port, data []byte, err error) {
396 | var bb []byte
397 | bb, err = xx.AESCFBDecrypt(cd, x.Password)
398 | if err != nil {
399 | return
400 | }
401 | err = errors.New("Data length error")
402 | n := len(bb)
403 | minl := 1
404 | if n < minl {
405 | return
406 | }
407 | if bb[0] == socks5.ATYPIPv4 {
408 | minl += 4
409 | if n < minl {
410 | return
411 | }
412 | addr = bb[minl-4 : minl]
413 | } else if bb[0] == socks5.ATYPIPv6 {
414 | minl += 16
415 | if n < minl {
416 | return
417 | }
418 | addr = bb[minl-16 : minl]
419 | } else if bb[0] == socks5.ATYPDomain {
420 | minl += 1
421 | if n < minl {
422 | return
423 | }
424 | l := bb[1]
425 | if l == 0 {
426 | return
427 | }
428 | minl += int(l)
429 | if n < minl {
430 | return
431 | }
432 | addr = bb[minl-int(l) : minl]
433 | addr = append([]byte{l}, addr...)
434 | } else {
435 | return
436 | }
437 | minl += 2
438 | if n <= minl {
439 | return
440 | }
441 | a = bb[0]
442 | port = bb[minl-2 : minl]
443 | data = bb[minl:]
444 | err = nil
445 | return
446 | }
447 |
448 | // Shutdown used to stop the client
449 | func (x *SSClient) Shutdown() error {
450 | return x.Server.Stop()
451 | }
452 |
--------------------------------------------------------------------------------
/client.go:
--------------------------------------------------------------------------------
1 | package brook
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "io"
7 | "log"
8 | "net"
9 | "time"
10 |
11 | cache "github.com/patrickmn/go-cache"
12 | "github.com/txthinking/brook/plugin"
13 | "github.com/txthinking/socks5"
14 | xx "github.com/txthinking/x"
15 | )
16 |
17 | // Client
18 | type Client struct {
19 | Server *socks5.Server
20 | RemoteAddr string
21 | Password []byte
22 | TCPTimeout int
23 | TCPDeadline int
24 | UDPDeadline int
25 | TCPListen *net.TCPListener
26 | Socks5Middleman plugin.Socks5Middleman
27 | HTTPMiddleman plugin.HTTPMiddleman
28 | }
29 |
30 | // NewClient returns a new Client
31 | func NewClient(addr, ip, server, password string, tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime int) (*Client, error) {
32 | s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, tcpDeadline, udpDeadline, udpSessionTime)
33 | if err != nil {
34 | return nil, err
35 | }
36 | x := &Client{
37 | RemoteAddr: server,
38 | Server: s5,
39 | Password: []byte(password),
40 | TCPTimeout: tcpTimeout,
41 | TCPDeadline: tcpDeadline,
42 | UDPDeadline: udpDeadline,
43 | }
44 | return x, nil
45 | }
46 |
47 | // SetSocks5Middleman sets socks5middleman plugin
48 | func (x *Client) SetSocks5Middleman(m plugin.Socks5Middleman) {
49 | x.Socks5Middleman = m
50 | }
51 |
52 | // SetHTTPMiddleman sets httpmiddleman plugin
53 | func (x *Client) SetHTTPMiddleman(m plugin.HTTPMiddleman) {
54 | x.HTTPMiddleman = m
55 | }
56 |
57 | // ListenAndServe will let client start a socks5 proxy
58 | // sm can be nil
59 | func (x *Client) ListenAndServe() error {
60 | return x.Server.Run(x)
61 | }
62 |
63 | // TCPHandle handles tcp request
64 | func (x *Client) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
65 | if x.Socks5Middleman != nil {
66 | done, err := x.Socks5Middleman.TCPHandle(s, c, r)
67 | if err != nil {
68 | if done {
69 | return err
70 | }
71 | return ErrorReply(r, c, err)
72 | }
73 | if done {
74 | return nil
75 | }
76 | }
77 |
78 | if r.Cmd == socks5.CmdConnect {
79 | tmp, err := Dial.Dial("tcp", x.RemoteAddr)
80 | if err != nil {
81 | return ErrorReply(r, c, err)
82 | }
83 | rc := tmp.(*net.TCPConn)
84 | defer rc.Close()
85 | if x.TCPTimeout != 0 {
86 | if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
87 | return ErrorReply(r, c, err)
88 | }
89 | }
90 | if x.TCPDeadline != 0 {
91 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
92 | return ErrorReply(r, c, err)
93 | }
94 | }
95 |
96 | k, n, err := PrepareKey(x.Password)
97 | if err != nil {
98 | return ErrorReply(r, c, err)
99 | }
100 | if _, err := rc.Write(n); err != nil {
101 | return ErrorReply(r, c, err)
102 | }
103 |
104 | rawaddr := make([]byte, 0, 7)
105 | rawaddr = append(rawaddr, r.Atyp)
106 | rawaddr = append(rawaddr, r.DstAddr...)
107 | rawaddr = append(rawaddr, r.DstPort...)
108 | n, err = WriteTo(rc, rawaddr, k, n, true)
109 | if err != nil {
110 | return ErrorReply(r, c, err)
111 | }
112 |
113 | a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
114 | if err != nil {
115 | return ErrorReply(r, c, err)
116 | }
117 | rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
118 | if err := rp.WriteTo(c); err != nil {
119 | return err
120 | }
121 |
122 | go func() {
123 | n := make([]byte, 12)
124 | if _, err := io.ReadFull(rc, n); err != nil {
125 | return
126 | }
127 | k, err := GetKey(x.Password, n)
128 | if err != nil {
129 | log.Println(err)
130 | return
131 | }
132 | var b []byte
133 | for {
134 | if x.TCPDeadline != 0 {
135 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
136 | return
137 | }
138 | }
139 | b, n, err = ReadFrom(rc, k, n, false)
140 | if err != nil {
141 | return
142 | }
143 | if _, err := c.Write(b); err != nil {
144 | return
145 | }
146 | }
147 | }()
148 |
149 | var b [1024 * 2]byte
150 | for {
151 | if x.TCPDeadline != 0 {
152 | if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
153 | return nil
154 | }
155 | }
156 | i, err := c.Read(b[:])
157 | if err != nil {
158 | return nil
159 | }
160 | n, err = WriteTo(rc, b[0:i], k, n, false)
161 | if err != nil {
162 | return nil
163 | }
164 | }
165 | return nil
166 | }
167 | if r.Cmd == socks5.CmdUDP {
168 | caddr, err := r.UDP(c, x.Server.ServerAddr)
169 | if err != nil {
170 | return err
171 | }
172 | _, p, err := net.SplitHostPort(caddr.String())
173 | if err != nil {
174 | return err
175 | }
176 | if p == "0" {
177 | time.Sleep(time.Duration(x.Server.UDPSessionTime) * time.Second)
178 | return nil
179 | }
180 | ch := make(chan byte)
181 | x.Server.TCPUDPAssociate.Set(caddr.String(), ch, cache.DefaultExpiration)
182 | <-ch
183 | return nil
184 | }
185 | return socks5.ErrUnsupportCmd
186 | }
187 |
188 | // UDPHandle handles udp request
189 | func (x *Client) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
190 | if x.Socks5Middleman != nil {
191 | if done, err := x.Socks5Middleman.UDPHandle(s, addr, d); err != nil || done {
192 | return err
193 | }
194 | }
195 |
196 | send := func(ue *socks5.UDPExchange, data []byte) error {
197 | cd, err := Encrypt(x.Password, data)
198 | if err != nil {
199 | return err
200 | }
201 | _, err = ue.RemoteConn.Write(cd)
202 | if err != nil {
203 | return err
204 | }
205 | return nil
206 | }
207 |
208 | var ue *socks5.UDPExchange
209 | iue, ok := s.UDPExchanges.Get(addr.String())
210 | if ok {
211 | ue = iue.(*socks5.UDPExchange)
212 | return send(ue, d.Bytes()[3:])
213 | }
214 |
215 | c, err := Dial.Dial("udp", x.RemoteAddr)
216 | if err != nil {
217 | v, ok := s.TCPUDPAssociate.Get(addr.String())
218 | if ok {
219 | ch := v.(chan byte)
220 | ch <- 0x00
221 | s.TCPUDPAssociate.Delete(addr.String())
222 | }
223 | return err
224 | }
225 | rc := c.(*net.UDPConn)
226 | ue = &socks5.UDPExchange{
227 | ClientAddr: addr,
228 | RemoteConn: rc,
229 | }
230 | if err := send(ue, d.Bytes()[3:]); err != nil {
231 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
232 | if ok {
233 | ch := v.(chan byte)
234 | ch <- 0x00
235 | s.TCPUDPAssociate.Delete(ue.ClientAddr.String())
236 | }
237 | ue.RemoteConn.Close()
238 | return err
239 | }
240 | s.UDPExchanges.Set(ue.ClientAddr.String(), ue, cache.DefaultExpiration)
241 | go func(ue *socks5.UDPExchange) {
242 | defer func() {
243 | v, ok := s.TCPUDPAssociate.Get(ue.ClientAddr.String())
244 | if ok {
245 | ch := v.(chan byte)
246 | ch <- 0x00
247 | }
248 | s.UDPExchanges.Delete(ue.ClientAddr.String())
249 | ue.RemoteConn.Close()
250 | }()
251 | var b [65536]byte
252 | for {
253 | if s.UDPDeadline != 0 {
254 | if err := ue.RemoteConn.SetDeadline(time.Now().Add(time.Duration(s.UDPDeadline) * time.Second)); err != nil {
255 | break
256 | }
257 | }
258 | n, err := ue.RemoteConn.Read(b[:])
259 | if err != nil {
260 | break
261 | }
262 | _, _, _, data, err := Decrypt(x.Password, b[0:n])
263 | if err != nil {
264 | log.Println(err)
265 | break
266 | }
267 | a, addr, port, err := socks5.ParseAddress(ue.ClientAddr.String())
268 | if err != nil {
269 | log.Println(err)
270 | break
271 | }
272 | d1 := socks5.NewDatagram(a, addr, port, data)
273 | if _, err := s.UDPConn.WriteToUDP(d1.Bytes(), ue.ClientAddr); err != nil {
274 | break
275 | }
276 | }
277 | }(ue)
278 | return nil
279 | }
280 |
281 | // ListenAndServeHTTP will let client start a http proxy
282 | func (x *Client) ListenAndServeHTTP() error {
283 | var err error
284 | x.TCPListen, err = net.ListenTCP("tcp", x.Server.TCPAddr)
285 | if err != nil {
286 | return nil
287 | }
288 | for {
289 | c, err := x.TCPListen.AcceptTCP()
290 | if err != nil {
291 | return err
292 | }
293 | go func(c *net.TCPConn) {
294 | defer c.Close()
295 | if x.TCPTimeout != 0 {
296 | if err := c.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
297 | log.Println(err)
298 | return
299 | }
300 | }
301 | if x.TCPDeadline != 0 {
302 | if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
303 | log.Println(err)
304 | return
305 | }
306 | }
307 | if err := x.HTTPHandle(c); err != nil {
308 | log.Println(err)
309 | return
310 | }
311 | }(c)
312 | }
313 | }
314 |
315 | // HTTPHandle handle http request
316 | func (x *Client) HTTPHandle(c *net.TCPConn) error {
317 | b := make([]byte, 0, 1024)
318 | for {
319 | var b1 [1024]byte
320 | n, err := c.Read(b1[:])
321 | if err != nil {
322 | return err
323 | }
324 | b = append(b, b1[:n]...)
325 | if bytes.Contains(b, []byte{0x0d, 0x0a, 0x0d, 0x0a}) {
326 | break
327 | }
328 | if len(b) >= 2083+18 {
329 | return errors.New("HTTP header too long")
330 | }
331 | }
332 | bb := bytes.SplitN(b, []byte(" "), 3)
333 | if len(bb) != 3 {
334 | return errors.New("Invalid Request")
335 | }
336 | method, aoru := string(bb[0]), string(bb[1])
337 | var addr string
338 | if method == "CONNECT" {
339 | addr = aoru
340 | }
341 | if method != "CONNECT" {
342 | var err error
343 | addr, err = xx.GetAddressFromURL(aoru)
344 | if err != nil {
345 | return err
346 | }
347 | }
348 |
349 | if x.HTTPMiddleman != nil {
350 | if done, err := x.HTTPMiddleman.Handle(method, addr, b, c); err != nil || done {
351 | return err
352 | }
353 | }
354 |
355 | tmp, err := Dial.Dial("tcp", x.RemoteAddr)
356 | if err != nil {
357 | return err
358 | }
359 | rc := tmp.(*net.TCPConn)
360 | defer rc.Close()
361 | if x.TCPTimeout != 0 {
362 | if err := rc.SetKeepAlivePeriod(time.Duration(x.TCPTimeout) * time.Second); err != nil {
363 | return err
364 | }
365 | }
366 | if x.TCPDeadline != 0 {
367 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
368 | return err
369 | }
370 | }
371 |
372 | k, n, err := PrepareKey(x.Password)
373 | if err != nil {
374 | return err
375 | }
376 | if _, err := rc.Write(n); err != nil {
377 | return err
378 | }
379 |
380 | a, h, p, err := socks5.ParseAddress(addr)
381 | if err != nil {
382 | return err
383 | }
384 | rawaddr := make([]byte, 0, 7)
385 | rawaddr = append(rawaddr, a)
386 | rawaddr = append(rawaddr, h...)
387 | rawaddr = append(rawaddr, p...)
388 | n, err = WriteTo(rc, rawaddr, k, n, true)
389 | if err != nil {
390 | return err
391 | }
392 |
393 | if method == "CONNECT" {
394 | _, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
395 | if err != nil {
396 | return err
397 | }
398 | }
399 | if method != "CONNECT" {
400 | n, err = WriteTo(rc, b, k, n, false)
401 | if err != nil {
402 | return err
403 | }
404 | }
405 |
406 | go func() {
407 | n := make([]byte, 12)
408 | if _, err := io.ReadFull(rc, n); err != nil {
409 | return
410 | }
411 | k, err := GetKey(x.Password, n)
412 | if err != nil {
413 | log.Println(err)
414 | return
415 | }
416 | var b []byte
417 | for {
418 | if x.TCPDeadline != 0 {
419 | if err := rc.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
420 | return
421 | }
422 | }
423 | b, n, err = ReadFrom(rc, k, n, false)
424 | if err != nil {
425 | return
426 | }
427 | if _, err := c.Write(b); err != nil {
428 | return
429 | }
430 | }
431 | }()
432 |
433 | var bf [1024 * 2]byte
434 | for {
435 | if x.TCPDeadline != 0 {
436 | if err := c.SetDeadline(time.Now().Add(time.Duration(x.TCPDeadline) * time.Second)); err != nil {
437 | return nil
438 | }
439 | }
440 | i, err := c.Read(bf[:])
441 | if err != nil {
442 | return nil
443 | }
444 | n, err = WriteTo(rc, bf[0:i], k, n, false)
445 | if err != nil {
446 | return nil
447 | }
448 | }
449 | return nil
450 | }
451 |
452 | // Shutdown used to stop the client
453 | func (x *Client) Shutdown() error {
454 | return x.Server.Stop()
455 | }
456 |
--------------------------------------------------------------------------------
/cli/brook/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "log"
6 | "os"
7 | "strings"
8 |
9 | "net/http"
10 | _ "net/http/pprof"
11 |
12 | "github.com/txthinking/brook"
13 | "github.com/urfave/cli"
14 | )
15 |
16 | var debug bool
17 | var debugAddress string
18 |
19 | func main() {
20 | app := cli.NewApp()
21 | app.Name = "Brook"
22 | app.Version = "20181212"
23 | app.Usage = "A Cross-Platform Proxy/VPN Software"
24 | app.Author = "Cloud"
25 | app.Email = "cloud@txthinking.com"
26 | app.Flags = []cli.Flag{
27 | cli.BoolFlag{
28 | Name: "debug, d",
29 | Usage: "Enable debug",
30 | Destination: &debug,
31 | },
32 | cli.StringFlag{
33 | Name: "listen, l",
34 | Usage: "Listen address for debug",
35 | Value: ":6060",
36 | Destination: &debugAddress,
37 | },
38 | }
39 | app.Commands = []cli.Command{
40 | cli.Command{
41 | Name: "server",
42 | Usage: "Run as server mode",
43 | Flags: []cli.Flag{
44 | cli.StringFlag{
45 | Name: "listen, l",
46 | Usage: "Server listen address, like: 0.0.0.0:1080",
47 | },
48 | cli.StringFlag{
49 | Name: "password, p",
50 | Usage: "Server password",
51 | },
52 | cli.IntFlag{
53 | Name: "tcpTimeout",
54 | Value: 60,
55 | Usage: "connection tcp keepalive timeout (s)",
56 | },
57 | cli.IntFlag{
58 | Name: "tcpDeadline",
59 | Value: 0,
60 | Usage: "connection deadline time (s)",
61 | },
62 | cli.IntFlag{
63 | Name: "udpDeadline",
64 | Value: 60,
65 | Usage: "connection deadline time (s)",
66 | },
67 | },
68 | Action: func(c *cli.Context) error {
69 | if c.String("listen") == "" || c.String("password") == "" {
70 | cli.ShowCommandHelp(c, "server")
71 | return nil
72 | }
73 | if debug {
74 | enableDebug()
75 | }
76 | return brook.RunServer(c.String("listen"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
77 | },
78 | },
79 | cli.Command{
80 | Name: "servers",
81 | Usage: "Run as multiple servers mode",
82 | Flags: []cli.Flag{
83 | cli.StringSliceFlag{
84 | Name: "listenpassword, l",
85 | Usage: "server and password, like '0.0.0.0:1080 password'",
86 | },
87 | cli.IntFlag{
88 | Name: "tcpTimeout",
89 | Value: 60,
90 | Usage: "connection tcp keepalive timeout (s)",
91 | },
92 | cli.IntFlag{
93 | Name: "tcpDeadline",
94 | Value: 0,
95 | Usage: "connection deadline time (s)",
96 | },
97 | cli.IntFlag{
98 | Name: "udpDeadline",
99 | Value: 60,
100 | Usage: "connection deadline time (s)",
101 | },
102 | },
103 | Action: func(c *cli.Context) error {
104 | if len(c.StringSlice("listenpassword")) == 0 {
105 | cli.ShowCommandHelp(c, "servers")
106 | return nil
107 | }
108 | if debug {
109 | enableDebug()
110 | }
111 | errch := make(chan error)
112 | go func() {
113 | for _, v := range c.StringSlice("listenpassword") {
114 | ss := strings.Split(v, " ")
115 | if len(ss) != 2 {
116 | errch <- errors.New("Invalid listenpassword")
117 | return
118 | }
119 | go func() {
120 | errch <- brook.RunServer(ss[0], ss[1], c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
121 | }()
122 | }
123 | }()
124 | return <-errch
125 | },
126 | },
127 | cli.Command{
128 | Name: "client",
129 | Usage: "Run as client mode",
130 | Flags: []cli.Flag{
131 | cli.StringFlag{
132 | Name: "listen, l",
133 | Usage: "Client listen address, like: 127.0.0.1:1080",
134 | },
135 | cli.StringFlag{
136 | Name: "ip, i",
137 | Usage: "Client IP address, like: 127.0.0.1",
138 | },
139 | cli.StringFlag{
140 | Name: "server, s",
141 | Usage: "Server address, like: 1.2.3.4:1080",
142 | },
143 | cli.StringFlag{
144 | Name: "password, p",
145 | Usage: "Server password",
146 | },
147 | cli.IntFlag{
148 | Name: "tcpTimeout",
149 | Value: 60,
150 | Usage: "connection tcp keepalive timeout (s)",
151 | },
152 | cli.IntFlag{
153 | Name: "tcpDeadline",
154 | Value: 0,
155 | Usage: "connection deadline time (s)",
156 | },
157 | cli.IntFlag{
158 | Name: "udpDeadline",
159 | Value: 60,
160 | Usage: "connection deadline time (s)",
161 | },
162 | cli.IntFlag{
163 | Name: "udpSessionTime",
164 | Value: 60,
165 | Usage: "udp session time (s), in most cases need this",
166 | },
167 | cli.BoolFlag{
168 | Name: "http",
169 | Usage: "If true, client start a http(s) proxy. default socks5",
170 | },
171 | },
172 | Action: func(c *cli.Context) error {
173 | if c.String("listen") == "" || c.String("ip") == "" || c.String("server") == "" || c.String("password") == "" {
174 | cli.ShowCommandHelp(c, "client")
175 | return nil
176 | }
177 | if debug {
178 | enableDebug()
179 | }
180 | if c.Bool("http") {
181 | return brook.RunClientAsHTTP(c.String("listen"), c.String("ip"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"))
182 | }
183 | return brook.RunClient(c.String("listen"), c.String("ip"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"))
184 | },
185 | },
186 | cli.Command{
187 | Name: "tunnel",
188 | Usage: "Run as tunnel mode on client-site",
189 | Flags: []cli.Flag{
190 | cli.StringFlag{
191 | Name: "listen, l",
192 | Usage: "Client listen address, like: 127.0.0.1:1080",
193 | },
194 | cli.StringFlag{
195 | Name: "to, t",
196 | Usage: "Tunnel to where, like: 8.8.8.8:53",
197 | },
198 | cli.StringFlag{
199 | Name: "server, s",
200 | Usage: "Server address, like: 1.2.3.4:1080",
201 | },
202 | cli.StringFlag{
203 | Name: "password, p",
204 | Usage: "Server password",
205 | },
206 | cli.IntFlag{
207 | Name: "tcpTimeout",
208 | Value: 60,
209 | Usage: "connection tcp keepalive timeout (s)",
210 | },
211 | cli.IntFlag{
212 | Name: "tcpDeadline",
213 | Value: 0,
214 | Usage: "connection deadline time (s)",
215 | },
216 | cli.IntFlag{
217 | Name: "udpDeadline",
218 | Value: 60,
219 | Usage: "connection deadline time (s)",
220 | },
221 | },
222 | Action: func(c *cli.Context) error {
223 | if c.String("listen") == "" || c.String("to") == "" || c.String("server") == "" || c.String("password") == "" {
224 | cli.ShowCommandHelp(c, "tunnel")
225 | return nil
226 | }
227 | if debug {
228 | enableDebug()
229 | }
230 | return brook.RunTunnel(c.String("listen"), c.String("to"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
231 | },
232 | },
233 | cli.Command{
234 | Name: "tproxy",
235 | Usage: "Run as tproxy mode on client-site, transparent proxy, only works on Linux",
236 | Flags: []cli.Flag{
237 | cli.StringFlag{
238 | Name: "listen, l",
239 | Usage: "Client listen address, like: 127.0.0.1:1080",
240 | },
241 | cli.StringFlag{
242 | Name: "server, s",
243 | Usage: "Server address, like: 1.2.3.4:1080",
244 | },
245 | cli.StringFlag{
246 | Name: "password, p",
247 | Usage: "Server password",
248 | },
249 | cli.IntFlag{
250 | Name: "tcpTimeout",
251 | Value: 60,
252 | Usage: "connection tcp keepalive timeout (s)",
253 | },
254 | cli.IntFlag{
255 | Name: "tcpDeadline",
256 | Value: 0,
257 | Usage: "connection deadline time (s)",
258 | },
259 | cli.IntFlag{
260 | Name: "udpDeadline",
261 | Value: 60,
262 | Usage: "connection deadline time (s)",
263 | },
264 | },
265 | Action: func(c *cli.Context) error {
266 | if c.String("listen") == "" || c.String("server") == "" || c.String("password") == "" {
267 | cli.ShowCommandHelp(c, "tproxy")
268 | return nil
269 | }
270 | if debug {
271 | enableDebug()
272 | }
273 | return brook.RunTproxy(c.String("listen"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
274 | },
275 | },
276 | cli.Command{
277 | Name: "vpn",
278 | Usage: "Run as VPN mode on client-site",
279 | Flags: []cli.Flag{
280 | cli.StringFlag{
281 | Name: "listen, l",
282 | Usage: "Client listen address, must use 127.0.0.1, like: 127.0.0.1:1080",
283 | },
284 | cli.StringFlag{
285 | Name: "server, s",
286 | Usage: "Server address, must use IP, like: 1.2.3.4:1080",
287 | },
288 | cli.StringFlag{
289 | Name: "password, p",
290 | Usage: "Server password",
291 | },
292 | cli.IntFlag{
293 | Name: "tcpTimeout",
294 | Value: 60,
295 | Usage: "connection tcp keepalive timeout (s)",
296 | },
297 | cli.IntFlag{
298 | Name: "tcpDeadline",
299 | Value: 0,
300 | Usage: "connection deadline time (s)",
301 | },
302 | cli.IntFlag{
303 | Name: "udpDeadline",
304 | Value: 60,
305 | Usage: "connection deadline time (s)",
306 | },
307 | cli.IntFlag{
308 | Name: "udpSessionTime",
309 | Value: 60,
310 | Usage: "udp session time (s), in most cases need this",
311 | },
312 | cli.StringFlag{
313 | Name: "tunDevice",
314 | Usage: "tun name",
315 | Value: "tun0",
316 | },
317 | cli.StringFlag{
318 | Name: "tunIP",
319 | Usage: "tun IP",
320 | Value: "10.9.9.2",
321 | },
322 | cli.StringFlag{
323 | Name: "tunGateway",
324 | Usage: "tun gateway",
325 | Value: "10.9.9.1",
326 | },
327 | cli.StringFlag{
328 | Name: "tunMask",
329 | Usage: "tun mask",
330 | Value: "255.255.255.0",
331 | },
332 | cli.StringFlag{
333 | Name: "defaultGateway",
334 | Usage: "Your default gateway, Only needed on windows that are not utf8 encoded.",
335 | },
336 | },
337 | Action: func(c *cli.Context) error {
338 | if c.String("listen") == "" || c.String("server") == "" || c.String("password") == "" {
339 | cli.ShowCommandHelp(c, "vpn")
340 | return nil
341 | }
342 | if debug {
343 | enableDebug()
344 | }
345 | return brook.RunVPN(c.String("listen"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"), c.String("tunDevice"), c.String("tunIP"), c.String("tunGateway"), c.String("tunMask"), c.String("defaultGateway"))
346 | },
347 | },
348 | cli.Command{
349 | Name: "ssserver",
350 | Usage: "Run as shadowsocks server mode, fixed method is aes-256-cfb",
351 | Flags: []cli.Flag{
352 | cli.StringFlag{
353 | Name: "listen, l",
354 | Usage: "Server listen address, like: 0.0.0.0:1080",
355 | },
356 | cli.StringFlag{
357 | Name: "password, p",
358 | Usage: "Server password",
359 | },
360 | cli.IntFlag{
361 | Name: "tcpTimeout",
362 | Value: 60,
363 | Usage: "connection tcp keepalive timeout (s)",
364 | },
365 | cli.IntFlag{
366 | Name: "tcpDeadline",
367 | Value: 0,
368 | Usage: "connection deadline time (s)",
369 | },
370 | cli.IntFlag{
371 | Name: "udpDeadline",
372 | Value: 60,
373 | Usage: "connection deadline time (s)",
374 | },
375 | },
376 | Action: func(c *cli.Context) error {
377 | if c.String("listen") == "" || c.String("password") == "" {
378 | cli.ShowCommandHelp(c, "ssserver")
379 | return nil
380 | }
381 | if debug {
382 | enableDebug()
383 | }
384 | return brook.RunSSServer(c.String("listen"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
385 | },
386 | },
387 | cli.Command{
388 | Name: "ssservers",
389 | Usage: "Run as shadowsocks multiple servers mode, fixed method is aes-256-cfb",
390 | Flags: []cli.Flag{
391 | cli.StringSliceFlag{
392 | Name: "listenpassword, l",
393 | Usage: "server address and password, like '0.0.0.0:1080 password'",
394 | },
395 | cli.IntFlag{
396 | Name: "tcpTimeout",
397 | Value: 60,
398 | Usage: "connection tcp keepalive timeout (s)",
399 | },
400 | cli.IntFlag{
401 | Name: "tcpDeadline",
402 | Value: 0,
403 | Usage: "connection deadline time (s)",
404 | },
405 | cli.IntFlag{
406 | Name: "udpDeadline",
407 | Value: 60,
408 | Usage: "connection deadline time (s)",
409 | },
410 | },
411 | Action: func(c *cli.Context) error {
412 | if len(c.StringSlice("listenpassword")) == 0 {
413 | cli.ShowCommandHelp(c, "ssservers")
414 | return nil
415 | }
416 | if debug {
417 | enableDebug()
418 | }
419 | errch := make(chan error)
420 | go func() {
421 | for _, v := range c.StringSlice("listenpassword") {
422 | ss := strings.Split(v, " ")
423 | if len(ss) != 2 {
424 | errch <- errors.New("Invalid listenpassword")
425 | return
426 | }
427 | go func() {
428 | errch <- brook.RunSSServer(ss[0], ss[1], c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
429 | }()
430 | }
431 | }()
432 | return <-errch
433 | },
434 | },
435 | cli.Command{
436 | Name: "ssclient",
437 | Usage: "Run as shadowsocks client mode, fixed method is aes-256-cfb",
438 | Flags: []cli.Flag{
439 | cli.StringFlag{
440 | Name: "listen, l",
441 | Usage: "Client listen address, like: 127.0.0.1:1080",
442 | },
443 | cli.StringFlag{
444 | Name: "ip, i",
445 | Usage: "Client IP address, like: 127.0.0.1",
446 | },
447 | cli.StringFlag{
448 | Name: "server, s",
449 | Usage: "Server address, like: 1.2.3.4:1080",
450 | },
451 | cli.StringFlag{
452 | Name: "password, p",
453 | Usage: "Server password",
454 | },
455 | cli.IntFlag{
456 | Name: "tcpTimeout",
457 | Value: 60,
458 | Usage: "connection tcp keepalive timeout (s)",
459 | },
460 | cli.IntFlag{
461 | Name: "tcpDeadline",
462 | Value: 0,
463 | Usage: "connection deadline time (s)",
464 | },
465 | cli.IntFlag{
466 | Name: "udpDeadline",
467 | Value: 60,
468 | Usage: "connection deadline time (s)",
469 | },
470 | cli.IntFlag{
471 | Name: "udpSessionTime",
472 | Value: 60,
473 | Usage: "udp session time (s), in most cases need this",
474 | },
475 | cli.BoolFlag{
476 | Name: "http",
477 | Usage: "If true, client start a http(s) proxy. default socks5",
478 | },
479 | },
480 | Action: func(c *cli.Context) error {
481 | if c.String("listen") == "" || c.String("ip") == "" || c.String("server") == "" || c.String("password") == "" {
482 | cli.ShowCommandHelp(c, "ssclient")
483 | return nil
484 | }
485 | if debug {
486 | enableDebug()
487 | }
488 | if c.Bool("http") {
489 | return brook.RunSSClientAsHTTP(c.String("listen"), c.String("ip"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"))
490 | }
491 | return brook.RunSSClient(c.String("listen"), c.String("ip"), c.String("server"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"))
492 | },
493 | },
494 | cli.Command{
495 | Name: "socks5",
496 | Usage: "Run as raw socks5 server",
497 | Flags: []cli.Flag{
498 | cli.StringFlag{
499 | Name: "listen, l",
500 | Usage: "Client listen address, like: 127.0.0.1:1080",
501 | },
502 | cli.StringFlag{
503 | Name: "ip, i",
504 | Usage: "Client IP address, like: 127.0.0.1",
505 | },
506 | cli.StringFlag{
507 | Name: "username",
508 | Usage: "User name, optional",
509 | },
510 | cli.StringFlag{
511 | Name: "password",
512 | Usage: "Password, optional",
513 | },
514 | cli.IntFlag{
515 | Name: "tcpTimeout",
516 | Value: 60,
517 | Usage: "connection tcp keepalive timeout (s)",
518 | },
519 | cli.IntFlag{
520 | Name: "tcpDeadline",
521 | Value: 0,
522 | Usage: "connection deadline time (s)",
523 | },
524 | cli.IntFlag{
525 | Name: "udpDeadline",
526 | Value: 60,
527 | Usage: "connection deadline time (s)",
528 | },
529 | cli.IntFlag{
530 | Name: "udpSessionTime",
531 | Value: 60,
532 | Usage: "udp session time (s), in most cases need this",
533 | },
534 | },
535 | Action: func(c *cli.Context) error {
536 | if c.String("listen") == "" || c.String("ip") == "" {
537 | cli.ShowCommandHelp(c, "socks5")
538 | return nil
539 | }
540 | if debug {
541 | enableDebug()
542 | }
543 | return brook.RunSocks5Server(c.String("listen"), c.String("ip"), c.String("username"), c.String("password"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"), c.Int("udpSessionTime"))
544 | },
545 | },
546 | cli.Command{
547 | Name: "relay",
548 | Usage: "Run as relay mode",
549 | Flags: []cli.Flag{
550 | cli.StringFlag{
551 | Name: "listen, l",
552 | Usage: "Relay server address: 0.0.0.0:1080",
553 | },
554 | cli.StringFlag{
555 | Name: "remote, r",
556 | Usage: "Server address, like: 1.2.3.4:1080",
557 | },
558 | cli.IntFlag{
559 | Name: "tcpTimeout",
560 | Value: 60,
561 | Usage: "connection tcp keepalive timeout (s)",
562 | },
563 | cli.IntFlag{
564 | Name: "tcpDeadline",
565 | Value: 0,
566 | Usage: "connection deadline time (s)",
567 | },
568 | cli.IntFlag{
569 | Name: "udpDeadline",
570 | Value: 60,
571 | Usage: "connection deadline time (s)",
572 | },
573 | },
574 | Action: func(c *cli.Context) error {
575 | if c.String("listen") == "" || c.String("remote") == "" {
576 | cli.ShowCommandHelp(c, "relay")
577 | return nil
578 | }
579 | if debug {
580 | enableDebug()
581 | }
582 | return brook.RunRelay(c.String("listen"), c.String("remote"), c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
583 | },
584 | },
585 | cli.Command{
586 | Name: "relays",
587 | Usage: "Run as multiple relays mode",
588 | Flags: []cli.Flag{
589 | cli.StringSliceFlag{
590 | Name: "listenremote, l",
591 | Usage: "listen address and server address, like '0.0.0.0:1080 1.2.3.4:1080'",
592 | },
593 | cli.IntFlag{
594 | Name: "tcpTimeout",
595 | Value: 60,
596 | Usage: "connection tcp keepalive timeout (s)",
597 | },
598 | cli.IntFlag{
599 | Name: "tcpDeadline",
600 | Value: 0,
601 | Usage: "connection deadline time (s)",
602 | },
603 | cli.IntFlag{
604 | Name: "udpDeadline",
605 | Value: 60,
606 | Usage: "connection deadline time (s)",
607 | },
608 | },
609 | Action: func(c *cli.Context) error {
610 | if len(c.StringSlice("listenremote")) == 0 {
611 | cli.ShowCommandHelp(c, "relays")
612 | return nil
613 | }
614 | if debug {
615 | enableDebug()
616 | }
617 | errch := make(chan error)
618 | go func() {
619 | for _, v := range c.StringSlice("listenremote") {
620 | ss := strings.Split(v, " ")
621 | if len(ss) != 2 {
622 | errch <- errors.New("Invalid listenremote")
623 | return
624 | }
625 | go func() {
626 | errch <- brook.RunRelay(ss[0], ss[1], c.Int("tcpTimeout"), c.Int("tcpDeadline"), c.Int("udpDeadline"))
627 | }()
628 | }
629 | }()
630 | return <-errch
631 | },
632 | },
633 | cli.Command{
634 | Name: "qr",
635 | Usage: "Print brook server QR code",
636 | Flags: []cli.Flag{
637 | cli.StringFlag{
638 | Name: "server, s",
639 | Usage: "Server address, like: 1.2.3.4:1080",
640 | },
641 | cli.StringFlag{
642 | Name: "password, p",
643 | Usage: "Server password",
644 | },
645 | },
646 | Action: func(c *cli.Context) error {
647 | if c.String("server") == "" || c.String("password") == "" {
648 | cli.ShowCommandHelp(c, "qr")
649 | return nil
650 | }
651 | brook.QR(c.String("server"), c.String("password"))
652 | return nil
653 | },
654 | },
655 | cli.Command{
656 | Name: "socks5tohttp",
657 | Usage: "Convert socks5 to http proxy",
658 | Flags: []cli.Flag{
659 | cli.StringFlag{
660 | Name: "listen, l",
661 | Usage: "Client listen address: like: 127.0.0.1:8080",
662 | },
663 | cli.StringFlag{
664 | Name: "socks5, s",
665 | Usage: "Socks5 address",
666 | },
667 | cli.IntFlag{
668 | Name: "timeout",
669 | Value: 60,
670 | Usage: "connection tcp keepalive timeout (s)",
671 | },
672 | cli.IntFlag{
673 | Name: "deadline",
674 | Value: 0,
675 | Usage: "connection deadline time (s)",
676 | },
677 | },
678 | Action: func(c *cli.Context) error {
679 | if c.String("listen") == "" || c.String("socks5") == "" {
680 | cli.ShowCommandHelp(c, "socks5tohttp")
681 | return nil
682 | }
683 | if debug {
684 | enableDebug()
685 | }
686 | return brook.RunSocks5ToHTTP(c.String("listen"), c.String("socks5"), c.Int("timeout"), c.Int("deadline"))
687 | },
688 | },
689 | cli.Command{
690 | Name: "systemproxy",
691 | Usage: "Set system proxy with pac url, or remove, only works on MacOS/Windows",
692 | Flags: []cli.Flag{
693 | cli.StringFlag{
694 | Name: "url, u",
695 | Usage: "Pac address: like: http://127.0.0.1/pac",
696 | },
697 | cli.BoolFlag{
698 | Name: "remove, r",
699 | Usage: "Remove pac url from system proxy",
700 | },
701 | },
702 | Action: func(c *cli.Context) error {
703 | if !c.Bool("remove") && c.String("url") == "" {
704 | cli.ShowCommandHelp(c, "systemproxy")
705 | return nil
706 | }
707 | return brook.RunSystemProxy(c.Bool("remove"), c.String("url"))
708 | },
709 | },
710 | }
711 | if err := app.Run(os.Args); err != nil {
712 | log.Fatal(err)
713 | }
714 | }
715 |
716 | func enableDebug() {
717 | go func() {
718 | log.Println(http.ListenAndServe(debugAddress, nil))
719 | }()
720 | brook.EnableDebug()
721 | }
722 |
--------------------------------------------------------------------------------
/OPENSOURCELICENSES:
--------------------------------------------------------------------------------
1 | ### addr-to-ip-port
2 |
3 | https://github.com/webtorrent/addr-to-ip-port
4 |
5 | The MIT License (MIT)
6 |
7 | Copyright (c) Feross Aboukhadijeh and WebTorrent, LLC
8 |
9 | Permission is hereby granted, free of charge, to any person obtaining a copy of
10 | this software and associated documentation files (the "Software"), to deal in
11 | the Software without restriction, including without limitation the rights to
12 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
13 | the Software, and to permit persons to whom the Software is furnished to do so,
14 | subject to the following conditions:
15 |
16 | The above copyright notice and this permission notice shall be included in all
17 | copies or substantial portions of the Software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
21 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
22 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
23 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 |
26 | ### x
27 |
28 | https://github.com/txthinking/x
29 |
30 | The MIT License (MIT)
31 |
32 | Copyright (c) 2013-present Cloud https://www.txthinking.com
33 |
34 | Permission is hereby granted, free of charge, to any person obtaining a copy of
35 | this software and associated documentation files (the "Software"), to deal in
36 | the Software without restriction, including without limitation the rights to
37 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
38 | the Software, and to permit persons to whom the Software is furnished to do so,
39 | subject to the following conditions:
40 |
41 | The above copyright notice and this permission notice shall be included in all
42 | copies or substantial portions of the Software.
43 |
44 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
46 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
47 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
48 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
49 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
50 |
51 | ### cli
52 |
53 | https://github.com/urfave/cli
54 |
55 | MIT License
56 |
57 | Copyright (c) 2016 Jeremy Saenz & Contributors
58 |
59 | Permission is hereby granted, free of charge, to any person obtaining a copy
60 | of this software and associated documentation files (the "Software"), to deal
61 | in the Software without restriction, including without limitation the rights
62 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
63 | copies of the Software, and to permit persons to whom the Software is
64 | furnished to do so, subject to the following conditions:
65 |
66 | The above copyright notice and this permission notice shall be included in all
67 | copies or substantial portions of the Software.
68 |
69 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
70 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
71 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
72 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
73 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
74 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
75 | SOFTWARE.
76 |
77 | ### electron
78 |
79 | https://github.com/electron/electron
80 |
81 | Copyright (c) 2013-2018 GitHub Inc.
82 |
83 | Permission is hereby granted, free of charge, to any person obtaining
84 | a copy of this software and associated documentation files (the
85 | "Software"), to deal in the Software without restriction, including
86 | without limitation the rights to use, copy, modify, merge, publish,
87 | distribute, sublicense, and/or sell copies of the Software, and to
88 | permit persons to whom the Software is furnished to do so, subject to
89 | the following conditions:
90 |
91 | The above copyright notice and this permission notice shall be
92 | included in all copies or substantial portions of the Software.
93 |
94 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
95 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
96 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
97 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
98 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
99 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
100 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
101 |
102 | ### electron-builder
103 |
104 | https://github.com/electron-userland/electron-builder
105 |
106 | The MIT License (MIT)
107 |
108 | Copyright (c) 2015 Loopline Systems
109 |
110 | Permission is hereby granted, free of charge, to any person obtaining a copy
111 | of this software and associated documentation files (the "Software"), to deal
112 | in the Software without restriction, including without limitation the rights
113 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
114 | copies of the Software, and to permit persons to whom the Software is
115 | furnished to do so, subject to the following conditions:
116 |
117 | The above copyright notice and this permission notice shall be included in all
118 | copies or substantial portions of the Software.
119 |
120 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
121 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
122 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
123 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
124 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
125 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
126 | SOFTWARE.
127 |
128 | ### electron-vue
129 |
130 | https://github.com/SimulatedGREG/electron-vue
131 |
132 | The MIT License (MIT)
133 |
134 | Copyright (c) 2016 Greg Holguin
135 |
136 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
137 |
138 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
139 |
140 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
141 |
142 | ### go-cache
143 |
144 | https://github.com/patrickmn/go-cache
145 |
146 | Copyright (c) 2012-2017 Patrick Mylund Nielsen and the go-cache contributors
147 |
148 | Permission is hereby granted, free of charge, to any person obtaining a copy
149 | of this software and associated documentation files (the "Software"), to deal
150 | in the Software without restriction, including without limitation the rights
151 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
152 | copies of the Software, and to permit persons to whom the Software is
153 | furnished to do so, subject to the following conditions:
154 |
155 | The above copyright notice and this permission notice shall be included in
156 | all copies or substantial portions of the Software.
157 |
158 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
159 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
160 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
161 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
162 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
163 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
164 | THE SOFTWARE.
165 |
166 | ### go-tproxy
167 |
168 | https://github.com/LiamHaworth/go-tproxy
169 |
170 | MIT License
171 |
172 | Copyright (c) 2017 Liam R. Haworth
173 |
174 | Permission is hereby granted, free of charge, to any person obtaining a copy
175 | of this software and associated documentation files (the "Software"), to deal
176 | in the Software without restriction, including without limitation the rights
177 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
178 | copies of the Software, and to permit persons to whom the Software is
179 | furnished to do so, subject to the following conditions:
180 |
181 | The above copyright notice and this permission notice shall be included in all
182 | copies or substantial portions of the Software.
183 |
184 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
185 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
186 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
187 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
188 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
189 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
190 | SOFTWARE.
191 |
192 | ### gotun2socks
193 |
194 | https://github.com/yinghuocho/gotun2socks
195 |
196 | Copyright (c) 2016, yinghuocho
197 | All rights reserved.
198 |
199 | Redistribution and use in source and binary forms, with or without
200 | modification, are permitted provided that the following conditions are met:
201 |
202 | * Redistributions of source code must retain the above copyright notice, this
203 | list of conditions and the following disclaimer.
204 |
205 | * Redistributions in binary form must reproduce the above copyright notice,
206 | this list of conditions and the following disclaimer in the documentation
207 | and/or other materials provided with the distribution.
208 |
209 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
210 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
211 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
212 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
213 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
214 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
215 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
216 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
217 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
218 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
219 |
220 | ### mux
221 |
222 | https://github.com/gorilla/mux
223 |
224 | Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
225 |
226 | Redistribution and use in source and binary forms, with or without
227 | modification, are permitted provided that the following conditions are
228 | met:
229 |
230 | * Redistributions of source code must retain the above copyright
231 | notice, this list of conditions and the following disclaimer.
232 | * Redistributions in binary form must reproduce the above
233 | copyright notice, this list of conditions and the following disclaimer
234 | in the documentation and/or other materials provided with the
235 | distribution.
236 | * Neither the name of Google Inc. nor the names of its
237 | contributors may be used to endorse or promote products derived from
238 | this software without specific prior written permission.
239 |
240 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
241 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
242 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
243 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
244 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
245 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
246 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
247 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
248 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
249 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
250 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251 |
252 | ### negroni
253 |
254 | https://github.com/urfave/negroni
255 |
256 | The MIT License (MIT)
257 |
258 | Copyright (c) 2014 Jeremy Saenz
259 |
260 | Permission is hereby granted, free of charge, to any person obtaining a copy
261 | of this software and associated documentation files (the "Software"), to deal
262 | in the Software without restriction, including without limitation the rights
263 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
264 | copies of the Software, and to permit persons to whom the Software is
265 | furnished to do so, subject to the following conditions:
266 |
267 | The above copyright notice and this permission notice shall be included in all
268 | copies or substantial portions of the Software.
269 |
270 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
271 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
272 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
273 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
274 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
275 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
276 | SOFTWARE.
277 |
278 | ### net
279 |
280 | https://github.com/golang/net
281 |
282 | Copyright (c) 2009 The Go Authors. All rights reserved.
283 |
284 | Redistribution and use in source and binary forms, with or without
285 | modification, are permitted provided that the following conditions are
286 | met:
287 |
288 | * Redistributions of source code must retain the above copyright
289 | notice, this list of conditions and the following disclaimer.
290 | * Redistributions in binary form must reproduce the above
291 | copyright notice, this list of conditions and the following disclaimer
292 | in the documentation and/or other materials provided with the
293 | distribution.
294 | * Neither the name of Google Inc. nor the names of its
295 | contributors may be used to endorse or promote products derived from
296 | this software without specific prior written permission.
297 |
298 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
299 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
300 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
301 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
302 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
303 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
304 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
305 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
306 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
307 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
308 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
309 |
310 | ### open-golang
311 |
312 | https://github.com/skratchdot/open-golang
313 |
314 | Copyright (c) 2013 skratchdot
315 |
316 | Permission is hereby granted, free of charge, to any person
317 | obtaining a copy of this software and associated documentation
318 | files (the "Software"), to deal in the Software without
319 | restriction, including without limitation the rights to use,
320 | copy, modify, merge, publish, distribute, sublicense, and/or sell
321 | copies of the Software, and to permit persons to whom the
322 | Software is furnished to do so, subject to the following
323 | conditions:
324 |
325 | The above copyright notice and this permission notice shall be
326 | included in all copies or substantial portions of the Software.
327 |
328 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
329 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
330 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
331 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
332 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
333 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
334 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
335 | OTHER DEALINGS IN THE SOFTWARE.
336 |
337 | ### pac
338 |
339 | https://github.com/txthinking/pac
340 |
341 | The MIT License (MIT)
342 |
343 | Copyright (c) 2013 Cloud http://www.txthinking.com
344 |
345 | Permission is hereby granted, free of charge, to any person obtaining a copy of
346 | this software and associated documentation files (the "Software"), to deal in
347 | the Software without restriction, including without limitation the rights to
348 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
349 | the Software, and to permit persons to whom the Software is furnished to do so,
350 | subject to the following conditions:
351 |
352 | The above copyright notice and this permission notice shall be included in all
353 | copies or substantial portions of the Software.
354 |
355 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
356 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
357 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
358 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
359 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
360 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
361 |
362 | ### socks5
363 |
364 | https://github.com/txthinking/socks5
365 |
366 | MIT License
367 |
368 | Copyright (c) 2015-present Cloud https://www.txthinking.com
369 |
370 | Permission is hereby granted, free of charge, to any person obtaining a copy
371 | of this software and associated documentation files (the "Software"), to deal
372 | in the Software without restriction, including without limitation the rights
373 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
374 | copies of the Software, and to permit persons to whom the Software is
375 | furnished to do so, subject to the following conditions:
376 |
377 | The above copyright notice and this permission notice shall be included in all
378 | copies or substantial portions of the Software.
379 |
380 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
381 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
382 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
383 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
384 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
385 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
386 | SOFTWARE.
387 |
388 | ### vue
389 |
390 | https://github.com/vuejs/vue
391 |
392 | The MIT License (MIT)
393 |
394 | Copyright (c) 2013-present, Yuxi (Evan) You
395 |
396 | Permission is hereby granted, free of charge, to any person obtaining a copy
397 | of this software and associated documentation files (the "Software"), to deal
398 | in the Software without restriction, including without limitation the rights
399 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
400 | copies of the Software, and to permit persons to whom the Software is
401 | furnished to do so, subject to the following conditions:
402 |
403 | The above copyright notice and this permission notice shall be included in
404 | all copies or substantial portions of the Software.
405 |
406 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
407 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
408 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
409 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
410 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
411 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
412 | THE SOFTWARE.
413 |
414 | ### vue-router
415 |
416 | https://github.com/vuejs/vue-router
417 |
418 | MIT License
419 |
420 | Copyright (c) 2013-present Evan You
421 |
422 | Permission is hereby granted, free of charge, to any person obtaining a copy
423 | of this software and associated documentation files (the "Software"), to deal
424 | in the Software without restriction, including without limitation the rights
425 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
426 | copies of the Software, and to permit persons to whom the Software is
427 | furnished to do so, subject to the following conditions:
428 |
429 | The above copyright notice and this permission notice shall be included in all
430 | copies or substantial portions of the Software.
431 |
432 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
433 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
434 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
435 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
436 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
437 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
438 | SOFTWARE.
439 |
440 | ### vuetify
441 |
442 | https://github.com/vuetifyjs/vuetify
443 |
444 | The MIT License (MIT)
445 |
446 | Copyright (c) 2016 John Jeremy Leider
447 |
448 | Permission is hereby granted, free of charge, to any person obtaining a copy
449 | of this software and associated documentation files (the "Software"), to deal
450 | in the Software without restriction, including without limitation the rights
451 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
452 | copies of the Software, and to permit persons to whom the Software is
453 | furnished to do so, subject to the following conditions:
454 |
455 | The above copyright notice and this permission notice shall be included in
456 | all copies or substantial portions of the Software.
457 |
458 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
459 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
460 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
461 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
462 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
463 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
464 | THE SOFTWARE.
465 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------