-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
80 lines (72 loc) · 1.7 KB
/
handler.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
package main
import (
"bufio"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"net/http"
)
func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) {
hj, ok := w.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("Failed to cast writer to hijacker.")
}
conn, bufrw, err := hj.Hijack()
if err != nil {
return nil, nil, err
}
if len := bufrw.Reader.Buffered(); len > 0 {
buf, _ := bufrw.Peek(len)
log.Printf("Non empty bufrw: \"%s\"", string(buf))
}
return conn, bufrw, nil
}
func handleRegularRequest(w http.ResponseWriter, req *http.Request) {
if req.URL.Scheme == "" {
req.URL.Scheme = "https"
req.URL.Host = req.Host
go scanURL("https://" + req.Host + req.RequestURI)
} else {
go scanURL(req.RequestURI)
}
req.RequestURI = ""
resp, err := (&http.Client{}).Do(req)
if err != nil {
log.Print(err)
return
}
for key, values := range resp.Header {
w.Header().Set(key, values[0])
for _, value := range values[1:] {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func handleConnectRequest(w http.ResponseWriter, req *http.Request) {
ln := &listener{0, make(chan net.Conn), make(chan bool)}
srv := &http.Server{
Handler: http.HandlerFunc(handleRequest),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{*generateCert(req.Host)},
},
}
go srv.Serve(tls.NewListener(ln, srv.TLSConfig))
conn, _, err := hijack(w)
if err != nil {
log.Print(err)
return
}
conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
ln.port <- conn
}
func handleRequest(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodConnect {
handleConnectRequest(w, req)
} else {
handleRegularRequest(w, req)
}
}