-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
290 lines (242 loc) · 5.73 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/darren/gpac"
)
var pacfile = flag.String("p", "wpad.dat", "pac file to load")
var addr = flag.String("l", "127.0.0.1:8080", "Listening address")
var refresh = flag.Duration("r", 0, "Time duration to refresh pac file")
// Server the proxy server
type Server struct {
http.Server
sync.Mutex
pacfile string
pac *gpac.Parser
refreshDuration time.Duration
}
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
s.handleConnect(w, r)
} else {
s.handleHTTP(w, r)
}
}
type peekedConn struct {
net.Conn
r io.Reader
}
// combine combines conn and peeked buffer
func combine(peeked io.Reader, conn net.Conn) *peekedConn {
r := io.MultiReader(peeked, conn)
return &peekedConn{conn, r}
}
func (p *peekedConn) Read(data []byte) (int, error) {
return p.r.Read(data)
}
// Copied from https://github.com/golang/go/blob/master/src/net/http/httputil/reverseproxy.go
// Hop-by-hop headers. These are removed when sent to the backend.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
var hopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te", // canonicalized version of "TE"
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
// removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
// See RFC 7230, section 6.1
func removeConnectionHeaders(h http.Header) {
if c := h.Get("Connection"); c != "" {
for _, f := range strings.Split(c, ",") {
if f = strings.TrimSpace(f); f != "" {
h.Del(f)
}
}
}
}
func removeHopHeaders(h http.Header) {
for _, k := range hopHeaders {
hv := h.Get(k)
if hv == "" {
continue
}
if k == "Te" && hv == "trailers" {
continue
}
h.Del(k)
}
}
// prune clean http header
func prune(h http.Header) {
removeConnectionHeaders(h)
removeHopHeaders(h)
}
func (s *Server) handleConnect(w http.ResponseWriter, r *http.Request) {
host, port, _ := net.SplitHostPort(r.Host)
var url string
if port == "443" {
url = fmt.Sprintf("https://%s/", host)
} else {
url = fmt.Sprintf("https://%s:%s/", host, port)
}
proxies, err := s.pac.FindProxy(url)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
ctx := context.Background()
var dst net.Conn
var proxy *gpac.Proxy
for _, proxy = range proxies {
dialer := proxy.Dialer()
dst, err = dialer(ctx, "tcp", r.Host)
if err != nil {
log.Println("Dial failed:", err)
continue
} else {
break
}
}
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
if proxy == nil {
http.Error(w, "No Proxy Available", http.StatusServiceUnavailable)
return
}
if proxy.IsDirect() || proxy.IsSOCKS() {
w.WriteHeader(http.StatusOK)
}
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
src, buf, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
src = combine(buf, src)
go pipe(dst, src)
go pipe(src, dst)
log.Printf("[%s] %s %v [%v]", r.RemoteAddr, r.Method, url, proxy)
}
func pipe(destination io.WriteCloser, source io.ReadCloser) {
defer destination.Close()
defer source.Close()
io.Copy(destination, source)
}
func (s *Server) handleHTTP(w http.ResponseWriter, req *http.Request) {
var perr error
proxies, err := s.pac.FindProxy(req.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
prune(req.Header)
for _, proxy := range proxies {
resp, err := proxy.Transport().RoundTrip(req)
perr = err
if err != nil {
continue
}
defer resp.Body.Close()
cloneHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
log.Printf("[%s] %s %v [%v]", req.RemoteAddr, req.Method, req.URL, proxy)
if err == nil {
return
}
}
if perr != nil {
log.Printf("[%s] %s %v FAILED: %v", req.RemoteAddr, req.Method, req.URL, perr)
http.Error(w, perr.Error(), http.StatusServiceUnavailable)
} else {
http.Error(w, "No proxy found", http.StatusServiceUnavailable)
}
}
func (s *Server) watch() {
for {
time.Sleep(s.refreshDuration)
log.Printf("Try reloading from %s", s.pacfile)
pac, err := gpac.From(s.pacfile)
if pac.Source() == s.pac.Source() {
log.Println("Pac file not changed")
continue
}
if err != nil {
log.Printf("Refresh pac failed: %v", err)
} else {
log.Println("Refresh pac succeeded")
}
s.Lock()
s.pac = pac
s.Unlock()
}
}
// Start starts the proxy server
func (s *Server) Start() error {
log.Printf("Start proxy on %s", s.Server.Addr)
if s.refreshDuration > 0 {
log.Printf("Start pac file watcher on: %s, refresh time: %v", s.pacfile, s.refreshDuration)
go s.watch()
}
s.Handler = http.HandlerFunc(s.handle)
return s.ListenAndServe()
}
// New create the proxy server
func New(addr string, pacf string, rintval time.Duration) (*Server, error) {
pac, err := gpac.From(pacf)
if os.IsNotExist(err) {
log.Print("Warn: using direct connection")
pac, _ = gpac.New(
`
function FindProxyForURL(url, host) {
return "DIRECT";
}
`,
)
} else if err != nil {
return nil, err
}
return &Server{
Server: http.Server{
Addr: addr,
},
pac: pac,
pacfile: pacf,
refreshDuration: rintval,
}, nil
}
func cloneHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.Parse()
server, err := New(*addr, *pacfile, *refresh)
if err != nil {
log.Fatal(err)
}
log.Fatal(server.Start())
}