-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdefault_proxy.go
54 lines (45 loc) · 1014 Bytes
/
default_proxy.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
package cproxy
import (
"io"
"sync"
)
type defaultProxy struct {
client Socket
server Socket
waiter *sync.WaitGroup
}
func newProxy(client, server Socket) *defaultProxy {
waiter := &sync.WaitGroup{}
waiter.Add(2) // wait on both client->server and server->client streams
return &defaultProxy{
waiter: waiter,
client: client,
server: server,
}
}
func (this *defaultProxy) Proxy() {
go this.streamAndClose(this.client, this.server)
go this.streamAndClose(this.server, this.client)
this.closeSockets()
}
func (this *defaultProxy) streamAndClose(reader, writer Socket) {
_, _ = io.Copy(writer, reader)
tryCloseRead(reader)
tryCloseWrite(writer)
this.waiter.Done()
}
func tryCloseRead(socket Socket) {
if tcp, ok := socket.(tcpSocket); ok {
_ = tcp.CloseRead()
}
}
func tryCloseWrite(socket Socket) {
if tcp, ok := socket.(tcpSocket); ok {
_ = tcp.CloseWrite()
}
}
func (this *defaultProxy) closeSockets() {
this.waiter.Wait()
_ = this.client.Close()
_ = this.server.Close()
}