-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyncserver.go
155 lines (125 loc) · 4.01 KB
/
syncserver.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
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"time"
)
func handleConn(conn net.Conn) {
// Socket initialization
tlsConn := conn.(*tls.Conn)
tlsConn.SetDeadline(time.Time{})
enc := json.NewEncoder(tlsConn)
dec := json.NewDecoder(tlsConn)
// Start TLS Connection
if err := tlsConn.Handshake(); err != nil {
fmt.Println("Error on TLS handshake:", err)
}
// Start decoding the received requests
var req Request
err := dec.Decode(&req)
if err != nil {
fmt.Println("Error decoding stuff:", err)
}
// First request should be an identifying connection attempt
if req.RequestType != RequestTypeConnectionAttempt {
logger.Printf("First request of %s was not a valid connection attempt (Type: %d)", req.OriginUUID, req.RequestType)
return
}
sha256Sum := SHA256FromTLSCert(tlsConn.ConnectionState().PeerCertificates[0])
// Now verify the identity
if !matchesAuthorizedKey(req.OriginUUID, sha256Sum) {
logger.Println("Info: SyncServer: Rejecting connection due to unauthorized key")
return
}
// Todo: Mutex
// Don't allow multiple connections with the same instance
var remote *RemoteInstance
for i, _ := range local.RemoteInstances {
if local.RemoteInstances[i].UUID == req.OriginUUID {
if local.RemoteInstances[i].connected {
// If we are already connected to this instance, we reject this connection
enc.Encode(Request{
RequestType: RequestTypeConnectionNACK,
OriginUUID: local.UUID,
Data: map[string]string{},
})
tlsConn.Close()
return
}
// If we weren't connected before, complete the existing instance by adding
// the required instances / data structures
local.RemoteInstances[i].tlsConn = tlsConn
local.RemoteInstances[i].connected = true
local.RemoteInstances[i].enc = enc
local.RemoteInstances[i].dec = dec
local.RemoteInstances[i].nextRequests = make(chan *Request, 2048)
remote = &local.RemoteInstances[i]
}
}
// If we didn't know this connection before, add it to our list
// (first time connection, UUID and Cert should already be in the authorizedKey file)
if remote == nil {
hostAddr, _, _ := net.SplitHostPort(tlsConn.RemoteAddr().String())
// Create a remoteInstance for this connection
remoteToAppend := RemoteInstance{
UUID: req.OriginUUID,
DisplayName: req.Data["DisplayName"],
RemoteAddress: hostAddr + ":8333",
SensorUUIDs: []string{},
sensors: []*Sensor{},
tlsConn: tlsConn,
connected: true,
enc: enc,
dec: dec,
nextRequests: make(chan *Request, 2048),
}
local.RemoteInstances = append(local.RemoteInstances, remoteToAppend)
remote = &local.RemoteInstances[len(local.RemoteInstances)-1]
// todo: mutex?
local.config.Set("RemoteInstances", local.RemoteInstances)
local.config.WriteConfig()
}
// Respond with ACK
remote.SendRequest(&Request{
RequestType: RequestTypeConnectionACK,
OriginUUID: local.UUID,
Data: map[string]string{"DisplayName": local.DisplayName},
})
/**
At this point we are messages are the connection is established,
encrypted, authenticated and the protocol is initialized.
Since we established connection, we can now
wait and handle duplex requests
*/
// Notify UI
WebAPIBroadcastRemoteInstances()
go remote.MultiplexRequests()
go remote.GeneratePeriodicRequests()
// Ask for sensor updates
remote.nextRequests <- &Request{
RequestType: RequestTypeGetSensorList,
OriginUUID: local.UUID,
Data: map[string]string{},
}
remote.HandleIncomingRequests()
}
func startSyncServer() {
tlsConfig := &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{local.keyPair}, ClientAuth: tls.RequireAnyClientCert}
listener, err := tls.Listen("tcp", ":8333", tlsConfig)
if err != nil {
panic(err)
}
logger.Println("Info: SyncServer: Listening on", listener.Addr().String(), "for incoming requests")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
}
go handleConn(conn)
}
}
func prepareForRemotes() {
//generateTLSCerts()
}