/
linker.go
307 lines (273 loc) · 7.96 KB
/
linker.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package roc
import (
"errors"
"log"
"net"
"net/http"
"fmt"
"github.com/Remote-Oculus-Controller/R.O.C-CONTROLS/misc"
"github.com/Remote-Oculus-Controller/proto"
"github.com/golang/protobuf/proto"
"github.com/gorilla/websocket"
)
//Linker is an encapsulation of Link and connection information
type Linker struct {
local, remote Link
lIP, rIP string
lT, rT bool
}
//Link are used as an element of a Linker. Contains all the connection structure and channel to communicate with.
// Use out channel to send packet and watch in for received packet.
//TODO clear TCP
type Link struct {
conn *net.TCPConn
ws *websocket.Conn
out, in chan *rocproto.Packet
}
//newLinker Create a new Linker.
//The Link channel are buffered to contains a maximum of a 100 packet
func newLinker(lS, rS string, lT, rT bool) *Linker {
l := Linker{local: Link{conn: nil, ws: nil, out: make(chan *rocproto.Packet, 100), in: make(chan *rocproto.Packet, 100)},
remote: Link{conn: nil, ws: nil, out: make(chan *rocproto.Packet, 1024), in: make(chan *rocproto.Packet, 1024)},
lIP: lS, lT: lT, rIP: rS, rT: rT}
return &l
}
//Start a Linker connection.
//
//If an local ip is specified a TCP connection will be setup. In all case a remote connection is attempted.
func (l *Linker) start() {
if l.lIP != "" {
log.Print("Staring local work")
go l.local.startConnTCP(l.lIP, l.lT, &l.remote, rocproto.Packet_CONTROL_SERVER|rocproto.Packet_VIDEO_SERVER)
}
log.Println("Starting remote work")
go l.startConnWS(l.rIP, l.rT, &l.local, rocproto.Packet_CONTROL_SERVER|rocproto.Packet_VIDEO_CLIENT)
}
//TODO timeout connection and try
func (l *Link) startConnTCP(s string, m bool, o *Link, t rocproto.Packet_Section) {
var listener *net.TCPListener
log.Println("Starting connection on ", s)
tcpAddr, err := net.ResolveTCPAddr("tcp", s)
misc.CheckError(err, "resolving address in linker.go/startConn", true)
for {
if m {
log.Println("Listening on", tcpAddr.String())
listener, err = net.ListenTCP("tcp", tcpAddr)
misc.CheckError(err, "listening in linker.go/startConn", true)
log.Println("Looking for a client...")
l.conn, err = listener.AcceptTCP()
misc.CheckError(err, "Accepting client in linker.go/startCnn", true)
log.Print("Connection acepted")
listener.Close()
} else {
log.Print("Dialing...")
l.conn, err = net.DialTCP("tcp", nil, tcpAddr)
misc.CheckError(err, "Dialing adresse in linker.go/startConn", true)
}
l.handleConn(o, t)
log.Println("Closing connection")
listener.Close()
l.conn.Close()
l.conn = nil
}
}
//TODO Insert buffer len and check
//Handle TCP connection
//
//The t parameters contain the section to which the handle is associated with Controls<=>Server Video / Controls<=>Client Videos
func (l *Link) handleConn(o *Link, t rocproto.Packet_Section) {
buff := make([]byte, 128)
quit := make(chan bool)
go func() {
defer func() { quit <- true }()
m := new(rocproto.Packet)
for {
i, err := l.conn.Read(buff[0:])
if misc.CheckError(err, "Receiving data from conn", false) != nil {
return
}
if err = checkBuffer(i, buff, m); err != nil {
e := NewError(rocproto.Error_Packet, err.Error(), int32(t&^rocproto.Packet_CONTROL_SERVER))
log.Println("Error : ", e)
l.out <- e
continue
}
log.Println("Received ==> ", m)
routPacket(m, l, o, t)
}
}()
for {
select {
case <-quit:
return
case m := <-l.out:
b, err := proto.Marshal(m)
if misc.CheckError(err, "linker.go/handleConn", false) != nil {
continue
}
_, err = l.conn.Write(b)
if misc.CheckError(err, "linker.go/handleConn", false) != nil {
return
}
}
}
}
//Start a websocket connection
// If m specified, a sever is created otherwise it will look to connect to the specified URL s
//
//In case of a server. A websocket http endpoint is created on localhost:port/controls
func (l *Linker) startConnWS(s string, m bool, o *Link, t rocproto.Packet_Section) {
log.Printf("Starting websocket on %v/controls\n", s)
if m {
http.HandleFunc("/controls", l.listenRemoteWS)
err := http.ListenAndServe(s, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
} else {
log.Fatalln("Websocket client not yet implemented")
}
}
func (l *Linker) listenRemoteWS(w http.ResponseWriter, r *http.Request) {
if l.remote.ws != nil {
er := "Remote connection already taken !!"
log.Println(er)
w.Write([]byte(er))
return
}
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
er := "Error upgrading to websocket"
log.Println(er)
w.Write([]byte(er))
return
}
log.Println("Client connected", r.RemoteAddr)
l.remote.ws = c
go l.remote.handleWS(&l.local, rocproto.Packet_CONTROL_SERVER|rocproto.Packet_VIDEO_CLIENT)
return
}
func (l *Linker) listenLocalWS(w http.ResponseWriter, r *http.Request) {
if l.local.ws != nil {
er := "Local connection already taken !!"
log.Println(er)
w.Write([]byte(er))
}
upgrader := websocket.Upgrader{}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
er := "Error upgrading to websocket"
log.Println(er)
w.Write([]byte(er))
return
}
log.Println("Client connected", r.RemoteAddr)
l.local.ws = c
go l.local.handleWS(&l.remote, rocproto.Packet_CONTROL_SERVER|rocproto.Packet_VIDEO_SERVER)
return
}
//Handle websocket connection
//
//The t parameters contain the section to which the handle is associated with Controls<=>Server Video / Controls<=>Client Videos
func (l *Link) handleWS(o *Link, t rocproto.Packet_Section) {
defer l.ws.Close()
defer func() { l.ws = nil }()
quit := make(chan bool)
go func() {
defer func() { quit <- true }()
for {
m := new(rocproto.Packet)
_, buff, err := l.ws.ReadMessage()
if misc.CheckError(err, "Receiving data from conn", false) != nil {
return
}
if err = checkBuffer(-1, buff, m); err != nil {
e := NewError(rocproto.Error_Packet, err.Error(), int32(t&^rocproto.Packet_CONTROL_SERVER))
log.Println("Error : ", e)
l.out <- e
continue
}
log.Println("Received ==> ", m)
log.Println(m.Header & uint32(t))
routPacket(m, l, o, t)
}
}()
for {
select {
case <-quit:
return
case m := <-l.out:
log.Printf("Sending ==> %v\n", m)
b, err := proto.Marshal(m)
if misc.CheckError(err, "linker.go/handleWS", false) != nil {
if m == nil {
return
}
continue
}
err = l.ws.WriteMessage(websocket.BinaryMessage, b)
if misc.CheckError(err, "linker.go/handleWS", false) != nil {
return
}
}
}
}
func checkBuffer(r int, buff []byte, m *rocproto.Packet) (err error) {
if r > -1 {
err = proto.Unmarshal(buff[0:r], m)
} else {
err = proto.Unmarshal(buff[0:], m)
}
if err != nil {
err = errors.New(fmt.Sprintln("Cannot Unmarshall packet : ", err.Error(),
"\nlength ==> ", r, "\nbuffer ==> ", buff[0:]))
log.Println(err.Error())
return err
}
if m.Magic != Magic {
log.Println("Wrong message format")
return errors.New("Wrong message packet")
}
return nil
}
func routPacket(m *rocproto.Packet, l, o *Link, t rocproto.Packet_Section) {
if m.Header&uint32(t) != 0 {
fmt.Println("Accepted", m)
l.in <- m
}
if (m.Header&uint32(rocproto.Packet_MASK_DEST))&^uint32(t) != 0 && (o.conn != nil || o.ws != nil) {
log.Println("Packet routed")
o.out <- m
}
}
//Stop and close all resources and connections associated with the linker
func (l *Linker) stop() {
log.Println("Linker stopping")
if l.remote.conn != nil {
l.remote.conn.Close()
}
if l.remote.ws != nil {
l.remote.ws.Close()
}
close(l.remote.in)
close(l.remote.out)
if l.local.conn != nil {
l.local.conn.Close()
}
if l.local.ws != nil {
l.local.ws.Close()
}
close(l.local.in)
close(l.local.out)
}
//Send packet on either remote or local outer channel
func (l *Linker) send(p *rocproto.Packet) error {
if (p.Header&uint32(rocproto.Packet_VIDEO_CLIENT)) != 0 && (l.remote.conn != nil || l.remote.ws != nil) {
l.remote.out <- p
}
if (p.Header&uint32(rocproto.Packet_VIDEO_SERVER)) != 0 && (l.local.conn != nil || l.local.ws != nil) {
l.local.out <- p
}
return nil
}