-
Notifications
You must be signed in to change notification settings - Fork 12
/
proxy.go
229 lines (175 loc) · 5.31 KB
/
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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package networkwebsockets
import (
"errors"
"fmt"
"time"
"github.com/richtr/websocket"
)
type Proxy struct {
// Inherit attributes from Peer struct
base Peer
// Discovered proxy connection's base64 hash value
// empty unless set via .setHash_Base64()
Hash_Base64 string
// List of connection ids that this proxy connection 'owns'
peerIds map[string]bool
// Whether this proxy connection is writeable
writeable bool
}
type ProxyMessageHandler struct {
proxy *Proxy
}
func (handler *ProxyMessageHandler) Read(buf []byte) error {
proxy := handler.proxy
if proxy == nil {
return errors.New("ProxyMessageHandler requires an attached Proxy object")
}
message, err := decodeWireMessage(buf)
if err != nil {
return err
}
switch message.Action {
case "connect":
proxy.peerIds[message.Target] = true
// Inform all local peer connections that this proxy owns this peer connection
for _, peer := range proxy.base.channel.peers {
if wireData, err := encodeWireMessage("connect", peer.id, message.Target, ""); err == nil {
peer.transport.Write(wireData)
}
}
return nil
case "disconnect":
delete(proxy.peerIds, message.Target)
// Inform all local peer connections that this proxy no longer owns this peer connection
for _, peer := range proxy.base.channel.peers {
if wireData, err := encodeWireMessage("disconnect", peer.id, message.Target, ""); err == nil {
peer.transport.Write(wireData)
}
}
return nil
case "broadcast":
// broadcast message on to given target
wsBroadcast := &WireMessage{
Action: "broadcast",
Source: message.Source,
Target: "", // target all connections
Payload: message.Payload,
fromProxy: true,
}
proxy.base.channel.broadcastBuffer <- wsBroadcast
return nil
case "message":
messageSent := false
// Relay message to channel peer that matches target
for _, peer := range proxy.base.channel.peers {
if peer.id == message.Target {
if wireData, err := encodeWireMessage("message", message.Source, message.Target, message.Payload); err == nil {
peer.transport.Write(wireData)
}
messageSent = true
break
}
}
if !messageSent {
fmt.Errorf("P2P message target could not be found. Not sent.")
}
return nil
}
return errors.New("Could not find target for message")
}
func (handler *ProxyMessageHandler) Write(buf []byte) error {
proxy := handler.proxy
if proxy == nil {
return errors.New("ProxyMessageHandler requires an attached Proxy object")
}
if !proxy.base.active {
return errors.New("Proxy is not active")
}
proxy.base.transport.conn.SetWriteDeadline(time.Now().Add(writeWait))
proxy.base.transport.conn.WriteMessage(websocket.TextMessage, buf)
return nil
}
func NewProxy(conn *websocket.Conn, isWriteable bool) *Proxy {
proxyConn := &Proxy{
base: Peer{
id: GenerateId(),
},
Hash_Base64: "",
writeable: isWriteable,
peerIds: make(map[string]bool),
}
// Create a new peer socket message handler
handler := &ProxyMessageHandler{proxyConn}
// Create a new peer socket transporter
transport := NewTransport(conn, handler)
// Attach peer transport to peer object
proxyConn.base.transport = transport
return proxyConn
}
func (proxy *Proxy) Start(channel *Channel) error {
if channel == nil {
return errors.New("Proxy requires a channel to start")
}
if proxy.base.active {
return errors.New("Proxy is already started")
}
proxy.base.channel = channel
// Start connection read/write pumps
proxy.base.transport.Start()
go func() {
<-proxy.base.transport.StopNotify()
proxy.Stop()
}()
proxy.base.active = true
// Add reference to this proxy connection to channel
proxy.addConnection()
return nil
}
func (proxy *Proxy) Stop() error {
if !proxy.base.active {
return errors.New("Proxy cannot be stopped because it is not currently active")
}
// Remove references to this proxy connection from channel
proxy.removeConnection()
// Close underlying websocket connection
proxy.base.transport.Stop()
// If no more local peers are connected then remove the current Network Web Socket service
if len(proxy.base.channel.peers) == 0 {
proxy.base.channel.Stop()
}
proxy.base.active = false
return nil
}
func (proxy *Proxy) setHash_Base64(hash string) {
proxy.Hash_Base64 = hash
}
// Set up a new Channel connection instance
func (proxy *Proxy) addConnection() {
proxy.base.channel.proxies = append(proxy.base.channel.proxies, proxy)
if proxy.writeable {
// Inform this proxy of all the peer connections we own
for _, peer := range proxy.base.channel.peers {
if wireData, err := encodeWireMessage("connect", proxy.base.id, peer.id, ""); err == nil {
proxy.base.transport.Write(wireData)
}
}
}
}
// Tear down an existing Channel connection instance
func (proxy *Proxy) removeConnection() {
for i, conn := range proxy.base.channel.proxies {
if proxy.base.id == conn.base.id {
proxy.base.channel.proxies[i] = nil // allow to be garbage-collected
proxy.base.channel.proxies = append(proxy.base.channel.proxies[:i], proxy.base.channel.proxies[i+1:]...)
break
}
}
if proxy.writeable {
// Inform this proxy of all the peer connections we no longer own
for _, peer := range proxy.base.channel.peers {
if wireData, err := encodeWireMessage("disconnect", proxy.base.id, peer.id, ""); err == nil {
proxy.base.transport.Write(wireData)
}
}
}
}