-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpac_generator.go
100 lines (82 loc) · 2.05 KB
/
pac_generator.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 (
"bytes"
"fmt"
"text/template"
)
var pacTemplate = `
var hasOwnProperty = Object.hasOwnProperty;
{{range .Rules}}
var proxy_{{.Name}} = "{{if .Proxy}}PROXY {{.Proxy}};{{end}}{{if .SOCKS5}}SOCKS5 {{.SOCKS5}};{{end}}{{if .SOCKS4}}SOCKS4 {{.SOCKS4}};{{end}}DIRECT;";
var domains_{{.Name}} = {
{{.LocalRules}}
};
{{end}}
function FindProxyForURL(url, host) {
if (isPlainHostName(host) || host === '127.0.0.1' || host === 'localhost') {
return 'DIRECT';
}
var suffix;
var pos = host.lastIndexOf('.');
while(1) {
suffix = host.substring(pos + 1);
{{range .Rules}}
if (hasOwnProperty.call(domains_{{.Name}}, suffix)) {
return proxy_{{.Name}};
}
{{end}}
if (pos <= 0) {
break;
}
pos = host.lastIndexOf('.', pos - 1);
}
return 'DIRECT';
}
`
type PACGenerator struct {
filter map[string]int
Rules []PACRule
}
func NewPACGenerator(pacRules []PACRule) *PACGenerator {
rules := make([]PACRule, len(pacRules))
copy(rules, pacRules)
return &PACGenerator{
Rules: rules,
filter: make(map[string]int),
}
}
func (p *PACGenerator) Generate(index int, rules []string) ([]byte, error) {
for _, v := range rules {
if _, ok := p.filter[v]; !ok {
p.filter[v] = index
}
}
data := struct {
Rules []PACRule
}{
Rules: p.Rules,
}
for i := 0; i < len(data.Rules); i++ {
data.Rules[i].LocalRules = ""
}
for host, index := range p.filter {
data.Rules[index].LocalRules += fmt.Sprintf(",'%s' : 1", host)
}
for i := 0; i < len(data.Rules); i++ {
strlen := len(data.Rules[i].LocalRules)
if strlen > 0 {
data.Rules[i].LocalRules = data.Rules[i].LocalRules[1:strlen]
}
}
t, err := template.New("proxy.pac").Parse(pacTemplate)
if err != nil {
ErrLog.Println("failed to parse pacTempalte, err:", err)
}
buff := bytes.NewBuffer(nil)
err = t.Execute(buff, &data)
if err != nil {
InfoLog.Println(err)
return nil, err
}
return buff.Bytes(), nil
}