...
1
2
3
4
5 package proxy
6
7 import (
8 "context"
9 "net"
10 "strings"
11 )
12
13
14
15 type PerHost struct {
16 def, bypass Dialer
17
18 bypassNetworks []*net.IPNet
19 bypassIPs []net.IP
20 bypassZones []string
21 bypassHosts []string
22 }
23
24
25
26
27 func NewPerHost(defaultDialer, bypass Dialer) *PerHost {
28 return &PerHost{
29 def: defaultDialer,
30 bypass: bypass,
31 }
32 }
33
34
35
36 func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) {
37 host, _, err := net.SplitHostPort(addr)
38 if err != nil {
39 return nil, err
40 }
41
42 return p.dialerForRequest(host).Dial(network, addr)
43 }
44
45
46
47 func (p *PerHost) DialContext(ctx context.Context, network, addr string) (c net.Conn, err error) {
48 host, _, err := net.SplitHostPort(addr)
49 if err != nil {
50 return nil, err
51 }
52 d := p.dialerForRequest(host)
53 if x, ok := d.(ContextDialer); ok {
54 return x.DialContext(ctx, network, addr)
55 }
56 return dialContext(ctx, d, network, addr)
57 }
58
59 func (p *PerHost) dialerForRequest(host string) Dialer {
60 if ip := net.ParseIP(host); ip != nil {
61 for _, net := range p.bypassNetworks {
62 if net.Contains(ip) {
63 return p.bypass
64 }
65 }
66 for _, bypassIP := range p.bypassIPs {
67 if bypassIP.Equal(ip) {
68 return p.bypass
69 }
70 }
71 return p.def
72 }
73
74 for _, zone := range p.bypassZones {
75 if strings.HasSuffix(host, zone) {
76 return p.bypass
77 }
78 if host == zone[1:] {
79
80
81 return p.bypass
82 }
83 }
84 for _, bypassHost := range p.bypassHosts {
85 if bypassHost == host {
86 return p.bypass
87 }
88 }
89 return p.def
90 }
91
92
93
94
95
96
97 func (p *PerHost) AddFromString(s string) {
98 hosts := strings.Split(s, ",")
99 for _, host := range hosts {
100 host = strings.TrimSpace(host)
101 if len(host) == 0 {
102 continue
103 }
104 if strings.Contains(host, "/") {
105
106 if _, net, err := net.ParseCIDR(host); err == nil {
107 p.AddNetwork(net)
108 }
109 continue
110 }
111 if ip := net.ParseIP(host); ip != nil {
112 p.AddIP(ip)
113 continue
114 }
115 if strings.HasPrefix(host, "*.") {
116 p.AddZone(host[1:])
117 continue
118 }
119 p.AddHost(host)
120 }
121 }
122
123
124
125
126 func (p *PerHost) AddIP(ip net.IP) {
127 p.bypassIPs = append(p.bypassIPs, ip)
128 }
129
130
131
132
133 func (p *PerHost) AddNetwork(net *net.IPNet) {
134 p.bypassNetworks = append(p.bypassNetworks, net)
135 }
136
137
138
139 func (p *PerHost) AddZone(zone string) {
140 if strings.HasSuffix(zone, ".") {
141 zone = zone[:len(zone)-1]
142 }
143 if !strings.HasPrefix(zone, ".") {
144 zone = "." + zone
145 }
146 p.bypassZones = append(p.bypassZones, zone)
147 }
148
149
150 func (p *PerHost) AddHost(host string) {
151 if strings.HasSuffix(host, ".") {
152 host = host[:len(host)-1]
153 }
154 p.bypassHosts = append(p.bypassHosts, host)
155 }
156
View as plain text