forked from txthinking/brook
-
Notifications
You must be signed in to change notification settings - Fork 1
/
white_httpmiddleman.go
67 lines (61 loc) · 1.51 KB
/
white_httpmiddleman.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
package brook
import (
"io"
"net"
"time"
"github.com/txthinking/pac/blackwhite"
)
// WhiteHTTPMiddleman is a HTTPMiddleman who only handle domain in white list
type WhiteHTTPMiddleman struct {
Timeout int
Deadline int
}
// NewWhiteHTTPMiddleman returns a WhiteHTTPMiddleman which can used to handle http proxy request
func NewWhiteHTTPMiddleman(timeout, deadline int) *WhiteHTTPMiddleman {
return &WhiteHTTPMiddleman{
Timeout: timeout,
Deadline: deadline,
}
}
// Handle handle http proxy request, if the domain is in the white list
func (w *WhiteHTTPMiddleman) Handle(method, addr string, request []byte, conn *net.TCPConn) (handled bool, err error) {
h, _, err := net.SplitHostPort(addr)
if err != nil {
return false, err
}
if !blackwhite.IsWhite(h) {
return false, nil
}
tmp, err := Dial.Dial("tcp", addr)
if err != nil {
return true, err
}
rc := tmp.(*net.TCPConn)
defer rc.Close()
if w.Timeout != 0 {
if err := rc.SetKeepAlivePeriod(time.Duration(w.Timeout) * time.Second); err != nil {
return true, err
}
}
if w.Deadline != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(w.Deadline) * time.Second)); err != nil {
return true, err
}
}
if method == "CONNECT" {
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
return true, err
}
}
if method != "CONNECT" {
if _, err := rc.Write(request); err != nil {
return true, err
}
}
go func() {
_, _ = io.Copy(rc, conn)
}()
_, _ = io.Copy(conn, rc)
return true, nil
}