This repository has been archived by the owner on Apr 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpproxy.go
211 lines (184 loc) · 4.73 KB
/
httpproxy.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
package go_usbmuxd_device
import (
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"strconv"
"strings"
)
// HTTPProxy is our main struct for proxy releated attributes and methods
type HTTPProxy struct {
// The transport used to send proxy requests to actual server.
// If nil, http.DefaultTransport is used.
Transport http.RoundTripper
Credential string
Debug bool
}
// newHTTPProxy returns a new HTTPProxy object
func newHTTPProxy() *HTTPProxy {
return &HTTPProxy{}
}
func parseHostPort(addr string) (host string, port int) {
fields := strings.SplitN(addr, ":", 2)
if len(fields) == 1 {
return addr, 80
}
port, _ = strconv.Atoi(fields[1])
return fields[0], port
}
// NewUSBHTTPProxy used to proxy connection to iPhone
func NewUSBHTTPProxy(usbhub *USBHub) (*HTTPProxy, error) {
if usbhub == nil {
usbhub = NewUSBHub()
}
devCh, err := usbhub.deviceListenAttached()
if err != nil {
return nil, err
}
devIDs := make(map[string]int)
go func() {
for dev := range devCh {
devIDs[dev.SerialNumber] = dev.DeviceID
}
}()
// network always http
// addr is device UDID:PORT
dialDevice := func(network, addr string) (net.Conn, error) {
udid, port := parseHostPort(addr)
devID, ok := devIDs[udid]
if !ok {
return nil, fmt.Errorf("Device %s not connected", udid)
}
return usbhub.CreateConnect(devID, port)
}
return &HTTPProxy{
Transport: &http.Transport{
Dial: dialDevice,
},
}, nil
}
func (p *HTTPProxy) handleConnect(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
}
defer client.Close()
client.Write([]byte("HTTP/1.0 200 Connection Established\r\n\r\n"))
server, err := net.Dial("tcp", host)
if err != nil {
return
}
defer server.Close()
go io.Copy(server, client)
io.Copy(client, server)
}
// https://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81
func proxyBasicAuth(r *http.Request) (username, password string, ok bool) {
auth := r.Header.Get("Proxy-Authorization")
if auth == "" {
return
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return
}
return cs[:s], cs[s+1:], true
}
func (p *HTTPProxy) 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 *HTTPProxy) 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 *HTTPProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if !p.handleProxyAuth(rw, req) {
return
}
if p.Debug {
log.Printf("%s %s", req.Method, req.RequestURI)
}
if req.Method == "CONNECT" {
p.handleConnect(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)
rw.Write([]byte(err.Error()))
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)
// }