-
Notifications
You must be signed in to change notification settings - Fork 124
/
gopee.go
315 lines (277 loc) · 8.21 KB
/
gopee.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package main
import (
"bytes"
"encoding/base64"
"errors"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
)
// GopeeEncPrefix - encoding prefix used while encoding urls
const GopeeEncPrefix = "xox"
// Pre-compile RegEx
var reBase = regexp.MustCompile(`base +href="(.*?)"`)
var reHTML = regexp.MustCompile(`\saction=["']?(.*?)["'\s]|\shref=["']?(.*?)["'\s]|\ssrc=["']?(.*?)["'\s]`)
var reCSS = regexp.MustCompile(`url\(["']?(.*?)["']?\)`)
var reBase64 = regexp.MustCompile("^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=)?$")
// Hop-by-hop headers
var hopHeaders = map[string]bool{
"connection": true,
"keep-alive": true,
"proxy-authenticate": true,
"proxy-authorization": true,
"te": true,
"trailers": true,
"transfer-encoding": true,
"upgrade": true,
}
// Headers that create problem handling response
// TODO: support gzip compressed response in future
var skipHeaders = map[string]bool{
"content-security-policy": true, // sent in response
"content-security-policy-report-only": true, // sent in response
"accept-encoding": true, // sent in request
"cookie": true, // sent in request
}
type proxyManager struct {
req *http.Request
uri *url.URL
resp *http.Response
}
var sessionManager *Manager
func encodeURL(plainURL []byte) string {
return GopeeEncPrefix + base64.URLEncoding.EncodeToString(plainURL)
}
func decodeURL(encodedURL string) (decodedURI *url.URL, err error) {
encodedURL = strings.TrimSpace(encodedURL)
if encodedURL == "" || !strings.HasPrefix(encodedURL, GopeeEncPrefix) {
err = errors.New("invalid path supplied to decode")
return nil, err
}
encodedURL = strings.TrimLeft(encodedURL, GopeeEncPrefix)
decoded, err := base64.URLEncoding.DecodeString(encodedURL)
if err != nil {
log.Println(err.Error(), " for url ", encodedURL)
return nil, err
}
decodedURI, err = url.Parse(string(decoded))
if err != nil {
log.Println("error parsing", string(decoded))
return nil, err
}
return decodedURI, err
}
// ProxyRequest creates a new request to be proxied
func ProxyRequest(r *http.Request, w http.ResponseWriter) {
var uri *url.URL
// Path can be of the form
// /base64-encoded-string
// /home/ajax.php
// http://thirdparty.com/resource.js
path := r.URL.Path[1:]
if decodedURL, err := decodeURL(path); err == nil {
// URL rewritten by GoPee
uri = decodedURL
} else {
// Might be a plain-text URL which was not rewritten
// AJAX request ?
path += "?" + r.URL.RawQuery
pathURI, err := url.Parse(path)
if err != nil {
log.Println("error parsing", path)
}
if pathURI.IsAbs() {
uri = pathURI
} else {
referer, err := url.Parse(r.Referer())
if err != nil {
log.Println("error parsing", r.Referer())
}
if baseURL, err := decodeURL(referer.Path[1:]); err == nil {
uri = baseURL.ResolveReference(pathURI)
}
}
}
// log.Println(uri.String())
if uri == nil {
// return a 404
http.NotFound(w, r)
} else {
// try fetching the url
proxyMan := &proxyManager{r, uri, nil}
proxyMan.Fetch(w)
}
}
// Fetch makes the actual request to server and writes data with rewritten URLs to response
func (pm *proxyManager) Fetch(w http.ResponseWriter) {
if pm.uri == nil {
http.Error(w, "No URI specified to fetch", http.StatusBadRequest)
return
}
// Get the http client assigned to this session
// If a session does not exist or is expired, create a new session
httpClient, err := sessionManager.Start(w, pm.req)
if err != nil {
http.Error(w, "Unable to start session", http.StatusInternalServerError)
return
}
req, _ := http.NewRequest(pm.req.Method, pm.uri.String(), pm.req.Body)
// Forward request headers to server
copyHeader(req.Header, pm.req.Header)
// Set http client protocol version
req.Proto = "HTTP/1.1"
req.ProtoMajor = 1
req.ProtoMinor = 1
pm.resp, err = httpClient.Do(req)
if err != nil {
log.Println("error fetching", pm.uri.String(), err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer pm.resp.Body.Close()
// In case there was a url redirect
// http -> https, non-www -> www, login page
if pm.uri.String() != pm.resp.Request.URL.String() {
pm.uri = pm.resp.Request.URL
http.Redirect(w, pm.req, "/"+encodeURL([]byte(pm.uri.String())), 302)
return
}
contentType := pm.resp.Header.Get("Content-Type")
// Forward response headers to client
copyHeader(w.Header(), pm.resp.Header)
w.WriteHeader(pm.resp.StatusCode)
// Rewrite all urls
if strings.Contains(contentType, "text/html") {
pm.rewriteHTML(w)
} else if strings.Contains(contentType, "text/css") {
pm.rewriteCSS(w)
} else {
io.Copy(w, pm.resp.Body)
}
}
func copyHeader(dst, src http.Header) {
// Copy Headers from src to dst
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
// Remove hop-by-hop headers and problem headers
for h, _ := range hopHeaders {
dst.Del(h)
}
for h, _ := range skipHeaders {
dst.Del(h)
}
}
func (pm *proxyManager) rewriteHTML(w http.ResponseWriter) {
body, _ := ioutil.ReadAll(pm.resp.Body)
// if there's a <base href> specified in the document
// use that as base to encode all URLs in the page
baseHrefMatch := reBase.FindSubmatch(body)
if len(baseHrefMatch) > 0 {
var err error
pm.uri, err = url.Parse(string(baseHrefMatch[1][:]))
if err != nil {
log.Println("Error Parsing " + string(baseHrefMatch[1][:]))
}
}
encodedBody := reHTML.ReplaceAllFunc(body, func(s []byte) []byte {
parts := reHTML.FindSubmatchIndex(s)
if parts != nil {
// replace src attribute
srcIndex := parts[2:4]
if srcIndex[0] != -1 {
return pm.rewriteURI(s, srcIndex[0], srcIndex[1])
}
// replace href attribute
hrefIndex := parts[4:6]
if hrefIndex[0] != -1 {
return pm.rewriteURI(s, hrefIndex[0], hrefIndex[1])
}
// replace form action attribute
actionIndex := parts[6:8]
if actionIndex[0] != -1 {
return pm.rewriteURI(s, actionIndex[0], actionIndex[1])
}
}
return s
})
w.Write(encodedBody)
}
func (pm *proxyManager) rewriteCSS(w http.ResponseWriter) {
body, _ := ioutil.ReadAll(pm.resp.Body)
encodedBody := reCSS.ReplaceAllFunc(body, func(s []byte) []byte {
parts := reCSS.FindSubmatchIndex(s)
if parts != nil {
// replace url attribute in css
pathIndex := parts[2:4]
if pathIndex[0] != -1 {
return pm.rewriteURI(s, pathIndex[0], pathIndex[1])
}
}
return s
})
w.Write(encodedBody)
}
func (pm *proxyManager) rewriteURI(src []byte, start int, end int) []byte {
relURL := string(src[start:end])
// keep anchor and javascript links intact
if relURL == "" || strings.HasPrefix(relURL, "#") || strings.HasPrefix(relURL, "javascript") || strings.HasPrefix(relURL, "data") {
return src
}
// Check if url is relative and make it absolute
if strings.Index(relURL, "http") != 0 {
relPath, err := url.Parse(relURL)
if err != nil {
return src
}
absURL := pm.uri.ResolveReference(relPath).String()
src = bytes.Replace(src, []byte(relURL), []byte(absURL), -1)
end = start + len(absURL)
}
encodedString := encodeURL(src[start:end])
return bytes.Replace(src, src[start:end], []byte(encodedString), -1)
}
// Cache templates
var templates = template.Must(template.ParseFiles("home.html"))
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path[1:] == "" {
r.ParseForm()
enteredURL := r.FormValue("url")
if enteredURL != "" {
// Check if url attribute is set in GET / POST
uri, _ := url.Parse(enteredURL)
// prepend http if not specified
if uri.Scheme == "" {
uri.Scheme = "http"
}
http.Redirect(w, r, "/"+encodeURL([]byte(uri.String())), 302)
return
}
templates.ExecuteTemplate(w, "home.html", nil)
} else {
ProxyRequest(r, w)
}
}
func main() {
httpHost := os.Getenv("HOST")
httpPort := os.Getenv("PORT")
if httpPort == "" {
httpPort = "8080"
}
sessionManager = NewManager("gopee", 600) // client session expiry set to 600s (10mins)
go sessionManager.GC()
http.HandleFunc("/", homeHandler)
http.HandleFunc("/assets/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
log.Printf("web proxy listening on %s:%s\n", httpHost, httpPort)
http.ListenAndServe(httpHost+":"+httpPort, nil)
}