-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpxy.go
145 lines (124 loc) · 3.25 KB
/
pxy.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
package main
import (
"encoding/base64"
"flag"
"fmt"
"io"
"net"
"net/http"
"strings"
)
// Pxy is our main struct for proxy releated attributes and methods
type Pxy struct {
// The transport used to send proxy requests to actual server.
// If nil, http.DefaultTransport is used.
Transport http.RoundTripper
Credential string
}
// NewProxy returns a new Pxy object
func NewProxy() *Pxy {
return &Pxy{}
}
func (p *Pxy) handleTunnel(rw http.ResponseWriter, req *http.Request) {
host := req.URL.Host
hij, ok := rw.(http.Hijacker)
if !ok {
panic("HTTP Server does not support hijacking")
}
client, _, err := hij.Hijack()
if err != nil {
return
}
client.Write([]byte("HTTP/1.0 200 Connection Established\r\n\r\n"))
server, err := net.Dial("tcp", host)
if err != nil {
return
}
go io.Copy(server, client)
io.Copy(client, server)
}
// Reference:
// - https://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81
// - https://github.com/yangxikun/gsproxy
func (p *Pxy) proxyAuthCheck(r *http.Request) (ok bool) {
if p.Credential == "" { // no auth
return true
}
auth := r.Header.Get("Proxy-Authorization")
if auth == "" {
return
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
credential := auth[len(prefix):]
return credential == p.Credential
}
func (p *Pxy) handleProxyAuth(w http.ResponseWriter, r *http.Request) bool {
if p.proxyAuthCheck(r) {
return true
}
w.Header().Add("Proxy-Authenticate", "Basic realm=\"*\"")
w.WriteHeader(http.StatusProxyAuthRequired)
w.Write(nil)
return false
}
// ServeHTTP is the main handler for all requests.
func (p *Pxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !p.handleProxyAuth(rw, req) {
return
}
fmt.Printf("Received request %s %s %s\n",
req.Method,
req.Host,
req.RemoteAddr,
)
if req.Method == "CONNECT" {
p.handleTunnel(rw, req)
return
}
transport := p.Transport
if transport == nil {
transport = http.DefaultTransport
}
// copy the origin request, and modify according to proxy
// standard and user rules.
outReq := new(http.Request)
*outReq = *req // this only does shallow copies of maps
// Set `x-Forwarded-For` header.
// `X-Forwarded-For` contains a list of servers delimited by comma and space
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
if prior, ok := outReq.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
outReq.Header.Set("X-Forwarded-For", clientIP)
}
// send the modified request and get response
res, err := transport.RoundTrip(outReq)
if err != nil {
rw.WriteHeader(http.StatusBadGateway)
return
}
// write response back to client, including status code, header and body
for key, value := range res.Header {
// Some header item can contains many values
for _, v := range value {
rw.Header().Add(key, v)
}
}
rw.WriteHeader(res.StatusCode)
io.Copy(rw, res.Body)
res.Body.Close()
}
func main() {
addr := flag.String("addr", ":8080", "listen address")
auth := flag.String("auth", "", "http auth, eg: susan:hello-kitty")
flag.Parse()
proxy := NewProxy()
if *auth != "" {
proxy.Credential = base64.StdEncoding.EncodeToString([]byte(*auth))
}
fmt.Printf("listening on %s\n", *addr)
http.ListenAndServe(*addr, proxy)
}