forked from pufferffish/wireproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
210 lines (181 loc) · 4.45 KB
/
http.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
package awgproxy
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"regexp"
"strings"
"github.com/sourcegraph/conc"
)
const proxyAuthHeaderKey = "Proxy-Authorization"
type HTTPServer struct {
config *HTTPConfig
auth CredentialValidator
dial func(network, address string) (net.Conn, error)
authRequired bool
tlsRequired bool
routeRegex *regexp.Regexp
}
func (s *HTTPServer) needRoute(req *http.Request) bool {
hostname := req.URL.Hostname()
if s.routeRegex == nil {
s.routeRegex = regexp.MustCompile(`^([^\.]*)\.`)
}
for strings.Count(hostname, ".") > 0 {
if s.config.RouteHosts[hostname] {
log.Printf("route %s", hostname)
return true
}
hostname = s.routeRegex.ReplaceAllString(hostname, "")
}
return false
}
func (s *HTTPServer) authenticate(req *http.Request) (int, error) {
if !s.authRequired {
return 0, nil
}
auth := req.Header.Get(proxyAuthHeaderKey)
if auth == "" {
return http.StatusProxyAuthRequired, fmt.Errorf(http.StatusText(http.StatusProxyAuthRequired))
}
enc := strings.TrimPrefix(auth, "Basic ")
str, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return http.StatusNotAcceptable, fmt.Errorf("decode username and password failed: %w", err)
}
pairs := bytes.SplitN(str, []byte(":"), 2)
if len(pairs) != 2 {
return http.StatusLengthRequired, fmt.Errorf("username and password format invalid")
}
if s.auth.Valid(string(pairs[0]), string(pairs[1])) {
return 0, nil
}
return http.StatusUnauthorized, fmt.Errorf("username and password not matching")
}
func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn, err error) {
addr := req.Host
if !strings.Contains(addr, ":") {
port := "443"
addr = net.JoinHostPort(addr, port)
}
if s.needRoute(req) {
peer, err = s.dial("tcp", addr)
} else {
peer, err = net.Dial("tcp", addr)
}
if err != nil {
return peer, fmt.Errorf("tun tcp dial failed: %w", err)
}
_, err = conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
_ = peer.Close()
peer = nil
}
return
}
func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) {
addr := req.Host
if !strings.Contains(addr, ":") {
port := "80"
addr = net.JoinHostPort(addr, port)
}
if s.needRoute(req) {
peer, err = s.dial("tcp", addr)
} else {
peer, err = net.Dial("tcp", addr)
}
if err != nil {
return peer, fmt.Errorf("tun tcp dial failed: %w", err)
}
err = req.Write(peer)
if err != nil {
_ = peer.Close()
peer = nil
return peer, fmt.Errorf("conn write failed: %w", err)
}
return
}
func (s *HTTPServer) serve(conn net.Conn) {
var rd = bufio.NewReader(conn)
req, err := http.ReadRequest(rd)
if err != nil {
log.Printf("read request failed: %s\n", err)
return
}
code, err := s.authenticate(req)
if err != nil {
resp := responseWith(req, code)
if code == http.StatusProxyAuthRequired {
resp.Header.Set("Proxy-Authenticate", "Basic realm=\"Proxy\"")
}
_ = resp.Write(conn)
log.Println(err)
return
}
var peer net.Conn
switch req.Method {
case http.MethodConnect:
peer, err = s.handleConn(req, conn)
case http.MethodGet:
peer, err = s.handle(req)
default:
_ = responseWith(req, http.StatusMethodNotAllowed).Write(conn)
log.Printf("unsupported protocol: %s\n", req.Method)
return
}
if err != nil {
log.Printf("dial proxy failed: %s\n", err)
return
}
if peer == nil {
log.Println("dial proxy failed: peer nil")
return
}
go func() {
wg := conc.NewWaitGroup()
wg.Go(func() {
_, err = io.Copy(conn, peer)
_ = conn.Close()
})
wg.Go(func() {
_, err = io.Copy(peer, conn)
_ = peer.Close()
})
wg.Wait()
}()
}
func (s *HTTPServer) listen(network, addr string) (net.Listener, error) {
if s.tlsRequired {
cert, err := tls.LoadX509KeyPair(s.config.CertFile, s.config.KeyFile)
if err != nil {
return nil, err
}
return tls.Listen(network, addr, &tls.Config{Certificates: []tls.Certificate{cert}})
}
return net.Listen(network, addr)
}
// ListenAndServe is used to create a listener and serve on it
func (s *HTTPServer) ListenAndServe(network, addr string) error {
server, err := s.listen(network, addr)
if err != nil {
return fmt.Errorf("listen tcp failed: %w", err)
}
defer func(server net.Listener) {
_ = server.Close()
}(server)
for {
conn, err := server.Accept()
if err != nil {
return fmt.Errorf("accept request failed: %w", err)
}
go func(conn net.Conn) {
s.serve(conn)
}(conn)
}
}