-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrewriter_addr.go
100 lines (83 loc) · 2.37 KB
/
rewriter_addr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"context"
"errors"
"fmt"
"net"
"strings"
"github.com/armon/go-socks5"
)
var ErrInvalidErrorRule = errors.New("Invalid format, should be (IP|FQDN):PORT[-PORT]:IP[:PORT]")
type RewriterAddr struct {
Rules map[string]RewriteDest
}
type RewriteDest struct {
IP net.IP
Port int
}
func NewRewriterAddr() *RewriterAddr {
return &RewriterAddr{
Rules: make(map[string]RewriteDest),
}
}
// AddRule parse and import a rule into the map
// Format: (IP|FQDN):PORT[-PORT]:IP[:PORT]
func (r *RewriterAddr) AddRule(rule string) error {
splittedRule := strings.Split(rule, ":")
if len(splittedRule) != 3 && len(splittedRule) != 4 {
return ErrInvalidErrorRule
}
// Parse source port (PORT[-PORT])
splittedSrcPort := strings.Split(splittedRule[1], "-")
if len(splittedSrcPort) != 1 && len(splittedSrcPort) != 2 {
return ErrInvalidErrorRule
}
srcPortBegin, err := ParseUint16(splittedSrcPort[0])
if err != nil {
return fmt.Errorf("Invalid source port %q: %s", splittedRule[1], err.Error())
}
srcPortEnd := srcPortBegin
if len(splittedSrcPort) == 2 {
port, err := ParseUint16(splittedSrcPort[1])
if err != nil {
return fmt.Errorf("Invalid end source port %q: %s", splittedRule[1], err.Error())
}
if srcPortBegin > port {
return fmt.Errorf("Invalid end source port %q: should be lower than %d", splittedRule[1], srcPortBegin)
}
srcPortEnd = uint16(port)
}
// Parse Destination
ip := net.ParseIP(splittedRule[2])
if ip == nil {
return fmt.Errorf("Invalid destination IP %q", splittedRule[2])
}
dstPortBegin := srcPortBegin
if len(splittedRule) == 4 {
port, err := ParseUint16(splittedRule[3])
if err != nil {
return fmt.Errorf("Invalid destination port %q: %s", splittedRule[3], err.Error())
}
dstPortBegin = port
}
for srcPort, dstPort := srcPortBegin, dstPortBegin; srcPort <= srcPortEnd; srcPort, dstPort = srcPort+1, dstPort+1 {
r.Rules[fmt.Sprintf("%s:%d", splittedRule[0], srcPort)] = RewriteDest{
IP: ip,
Port: int(dstPort),
}
}
return nil
}
func (r *RewriterAddr) Rewrite(ctx context.Context, request *socks5.Request, addr *socks5.AddrSpec) *socks5.AddrSpec {
var key string
if addr.FQDN != "" {
key = fmt.Sprintf("%s:%d", addr.FQDN, addr.Port)
} else {
key = fmt.Sprintf("%s:%d", addr.IP.String(), addr.Port)
}
if dest, ok := r.Rules[key]; ok {
addr.IP = dest.IP
addr.Port = dest.Port
}
return addr
}