-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdummyserver.go
More file actions
124 lines (104 loc) · 2.51 KB
/
dummyserver.go
File metadata and controls
124 lines (104 loc) · 2.51 KB
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
package main
import (
"bufio"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
)
func tryClosingWriteSide(conn net.Conn) bool {
connWriter, isCloseWriter := conn.(interface{ CloseWrite() error })
if isCloseWriter {
connWriter.CloseWrite()
} else {
conn.Close()
}
return isCloseWriter
}
func tryClosingReadSide(conn net.Conn) bool {
connWriter, isCloseRead := conn.(interface{ CloseRead() error })
if isCloseRead {
connWriter.CloseRead()
} else {
conn.Close()
}
return isCloseRead
}
// startDummyServer is a dummy server that just dials to the outside internet
func startDummyServer(addr net.Addr) {
ln, err := net.Listen(addr.Network(), addr.String())
if err != nil {
fatal(err)
}
wg := &sync.WaitGroup{}
defer wg.Wait()
for {
conn, err := ln.Accept()
if err != nil {
fatal(err)
}
wg.Go(func() {
defer conn.Close()
wg := &sync.WaitGroup{}
defer wg.Wait()
reader := bufio.NewReader(conn)
req, err := http.ReadRequest(reader)
if err != nil {
log.Println("Can't read request:", err)
return
}
if req.Method != http.MethodConnect {
errRes := (&http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: http.StatusMethodNotAllowed,
}).Write(conn)
if errRes != nil {
log.Println("Error writing response:", errRes)
}
log.Println("Error HTTP method is not connect:", req.Method)
return
}
destinationAddr := req.Host
dialer := net.Dialer{}
if req.Header.Get("X-Tls-Sni") != "" {
// Just a hack to test that it works...
if addr, found := strings.CutSuffix(destinationAddr, ":443"); found {
destinationAddr = addr + ":80"
}
}
originConn, err := dialer.Dial("tcp", destinationAddr)
response := http.Response{
ProtoMajor: 1,
ProtoMinor: 1,
}
if err != nil {
response.StatusCode = http.StatusBadRequest
if err := response.Write(conn); err != nil {
log.Println("Error writing back the response:", err)
}
log.Println("Error dialing the origin connection", destinationAddr, err)
return
}
response.StatusCode = http.StatusOK
if err := response.Write(conn); err != nil {
log.Println("Error writing back the OK response:", err)
return
}
// client -> origin
wg.Go(func() {
defer tryClosingWriteSide(originConn)
defer tryClosingReadSide(conn)
io.Copy(originConn, reader)
})
// origin -> client
wg.Go(func() {
defer tryClosingWriteSide(conn)
defer tryClosingReadSide(originConn)
io.Copy(conn, originConn)
})
})
}
}