-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.go
More file actions
583 lines (464 loc) · 15.2 KB
/
Server.go
File metadata and controls
583 lines (464 loc) · 15.2 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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package main
import (
"crypto/sha256"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-vgo/robotgo"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type Server struct {
port int
devices []*Device
sessionDevices map[string]*Device
sessionInputs map[string]*InputDispatcher
sessionNonces map[string]bool
sessionTimestamps map[string]time.Time
httpServer *http.Server
mutex *sync.Mutex
}
type Result struct {
Data string `json:"result"`
}
func (server *Server) authorizeRequest(w http.ResponseWriter, clientAuth string) bool {
// Computer will have an auth code later on
if clientAuth == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return false
}
clientComponents := strings.Split(clientAuth, ",")
if len(clientComponents) != 2 {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return false
}
nonce := clientComponents[0]
server.mutex.Lock()
if server.sessionNonces[nonce] == true {
server.mutex.Unlock()
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return false
}
server.sessionNonces[nonce] = true
server.mutex.Unlock()
hashContent := nonce + "," + GetString("serverSecret")
hash := sha256.Sum256([]byte(hashContent))
hashSlice := hash[:]
hashStr := b64.StdEncoding.EncodeToString(hashSlice)
serverAuth := nonce + "," + hashStr
return serverAuth == clientAuth
}
func (server *Server) allowDevice(device *Device) {
device.SessionId = generateRandomStr(16)
server.mutex.Lock()
server.sessionDevices[device.SessionId] = device
server.sessionTimestamps[device.SessionId] = time.Now()
server.mutex.Unlock()
}
func (server *Server) updateSessionTimestamp(sessionId string) {
server.mutex.Lock()
server.sessionTimestamps[sessionId] = time.Now()
server.mutex.Unlock()
}
func (server *Server) authHandler(w http.ResponseWriter, r *http.Request) {
configLoad()
logHTTPRequest(r)
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
return
}
var device Device
err := json.NewDecoder(r.Body).Decode(&device)
if err != nil {
http.Error(w, "Could not decode provided JSON.", http.StatusBadRequest)
log.Error("Could not decode provided JSON.")
return
}
if configCheckDevice(device.UUID) {
server.allowDevice(&device)
log.Println("Allowing saved device connection", device)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(device)
return
}
robotgo.SetActive(robotgo.GetHandPid(robotgo.GetPID()))
if GetBool("pairingEnabled") {
server.allowDevice(&device)
log.Println("Allowing new device connection", device)
configSaveDevice(device.Name, device.UUID)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(device)
} else {
http.Error(w, "Device request rejected.", http.StatusUnauthorized)
log.Error("Device request rejected.")
return
}
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ActionPad Server "+CURRENT_VERSION)
}
type PairingResponse struct {
Name string `json:"name"`
Code string `json:"code"`
}
func (server *Server) pairingHandler(w http.ResponseWriter, r *http.Request) {
configLoad()
if !GetBool("pairingEnabled") {
http.Error(w, "Device not authorized.", http.StatusForbidden)
return
}
response := PairingResponse{
Name: getHostname(),
Code: GetString("serverSecret"),
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func (server *Server) interfaceHandler(w http.ResponseWriter, r *http.Request) {
configLoad()
if !GetBool("pairingEnabled") {
http.Error(w, "Device not authorized.", http.StatusForbidden)
return
}
interfaceInfos, err := getInterfaceInfo()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
jsonData, err := json.Marshal(interfaceInfos)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
type StatusResponse struct {
Connected []string `json:"connected"`
Saved []string `json:"saved"`
}
func (server *Server) statusHandler(w http.ResponseWriter, r *http.Request) {
configLoad()
devices := GetStringMap("devices")
var deviceNames []string
for _, name := range devices {
deviceNames = append(deviceNames, name)
}
var connectedDeviceNames []string
uniqueConnectedNames := make(map[string]bool)
for _, device := range server.sessionDevices {
if _, exists := uniqueConnectedNames[device.Name]; !exists {
connectedDeviceNames = append(connectedDeviceNames, device.Name)
uniqueConnectedNames[device.Name] = true
}
}
sort.Strings(deviceNames)
sort.Strings(connectedDeviceNames)
response := StatusResponse{
Connected: connectedDeviceNames,
Saved: deviceNames,
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func infoHandler(w http.ResponseWriter, r *http.Request) {
pageContent := assembleQRPage(GetString("runningHost"), GetInt("runningPort"), GetString("serverSecret"))
t, err := template.New("QRPage").Parse(pageContent)
if err != nil {
http.Error(w, "Couldn't parse the template", 500)
return
}
err = t.Execute(w, nil)
if err != nil {
http.Error(w, "Couldn't render the page", 500)
}
}
func (server *Server) startInputHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
inputDispatcher := &InputDispatcher{}
var input InputRequest
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
http.Error(w, "Could not decode provided JSON.", http.StatusBadRequest)
log.Error("Could not decode provided JSON.")
return
}
if device != nil && device.UUID == uuid {
server.mutex.Lock()
server.sessionInputs[device.SessionId+"-"+input.UUID] = inputDispatcher
server.mutex.Unlock()
inputDispatcher.InputAction = input.InputAction
inputDispatcher.startExecute()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(input)
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) sustainInputHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
inputId := params["inputId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
server.mutex.Lock()
inputDispatcher, ok := server.sessionInputs[device.SessionId+"-"+inputId]
server.mutex.Unlock()
if !ok {
http.Error(w, "Invalid input ID.", http.StatusBadRequest)
log.Error("Invalid input ID.")
return
}
inputDispatcher.sustainExecute()
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "{\"success\":true}")
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) stopInputHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
inputId := params["inputId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
inputDispatcherId := device.SessionId + "-" + inputId
server.mutex.Lock()
inputDispatcher, ok := server.sessionInputs[inputDispatcherId]
server.mutex.Unlock()
if !ok {
http.Error(w, "Invalid input ID.", http.StatusBadRequest)
log.Error("Invalid input ID.")
return
}
inputDispatcher.stopExecute()
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "{\"success\":true}")
server.mutex.Lock()
delete(server.sessionInputs, inputDispatcherId)
server.mutex.Unlock()
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) browseFileHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
filename, err := browseFile()
if err != nil {
http.Error(w, "Did not choose file.", http.StatusInternalServerError)
return
}
result := Result{Data: filename}
log.Println(result)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) mousePosHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
var pos MousePos
pos.X, pos.Y = robotgo.GetMousePos()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(pos)
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) actionHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
var action Action
err := json.NewDecoder(r.Body).Decode(&action)
if err != nil {
http.Error(w, "Could not decode provided JSON.", http.StatusBadRequest)
log.Error("Could not decode provided JSON.")
return
}
err = action.dispatch()
if err != nil {
http.Error(w, "Invalid Action", http.StatusBadRequest)
log.Error("Invalid Action.")
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(action)
log.Println("Finished dispatch action response.")
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
log.Error("Device not authorized.")
}
}
func (server *Server) sessionStatusHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
server.updateSessionTimestamp(sessionId)
logHTTPRequest(r)
if device != nil && device.UUID == uuid {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(device)
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
}
}
func (server *Server) stopSessionHandler(w http.ResponseWriter, r *http.Request) {
if server.authorizeRequest(w, r.Header.Get("Authorization")) == false {
return
}
params := mux.Vars(r)
uuid := params["uuid"]
sessionId := params["sessionId"]
device := server.sessionDevices[sessionId]
if device != nil && device.UUID == uuid {
server.mutex.Lock()
delete(server.sessionDevices, sessionId)
delete(server.sessionTimestamps, sessionId)
delete(server.sessionNonces, sessionId)
server.mutex.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(device)
} else {
http.Error(w, "Device not authorized.", http.StatusUnauthorized)
}
}
func (server *Server) notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, "<h1>Error error errrr</h1>")
}
func (server *Server) run(port int) error {
if port == 0 {
port = 2960 // default port
}
if port <= 0 || port > 65535 {
return errors.New("Provided port is out of range. Server offline.")
}
log.Println("Attempting to run server port:", port)
router := mux.NewRouter()
// addr := strings.Join([]string{host, ":", strconv.Itoa(port)}, "")
serverAddr := ":" + strconv.Itoa(port)
ipOverride := GetString("ipOverride")
if len(ipOverride) > 0 {
serverAddr = ipOverride + serverAddr
}
server.httpServer = &http.Server{
Addr: serverAddr,
Handler: router,
WriteTimeout: 60 * time.Second,
ReadTimeout: 60 * time.Second,
}
server.mutex = &sync.Mutex{}
server.sessionDevices = make(map[string]*Device)
server.sessionInputs = make(map[string]*InputDispatcher)
server.sessionNonces = make(map[string]bool)
server.sessionTimestamps = make(map[string]time.Time)
server.port = port
// routes
router.HandleFunc("/", rootHandler).Methods("GET")
router.HandleFunc("/pairing", server.pairingHandler).Methods("GET")
router.HandleFunc("/interfaces", server.interfaceHandler).Methods("GET")
router.HandleFunc("/info", infoHandler).Methods("GET")
router.HandleFunc("/status", server.statusHandler).Methods("GET")
router.HandleFunc("/auth", server.authHandler).Methods("POST")
router.HandleFunc("/action/{uuid}/{sessionId}", server.actionHandler).Methods("POST")
router.HandleFunc("/mouse_pos/{uuid}/{sessionId}", server.mousePosHandler).Methods("GET")
router.HandleFunc("/browse/{uuid}/{sessionId}", server.browseFileHandler).Methods("GET")
router.HandleFunc("/input/start/{uuid}/{sessionId}", server.startInputHandler).Methods("POST")
router.HandleFunc("/input/sustain/{uuid}/{sessionId}/{inputId}", server.sustainInputHandler).Methods("POST")
router.HandleFunc("/input/stop/{uuid}/{sessionId}/{inputId}", server.stopInputHandler).Methods("POST")
router.HandleFunc("/session/{uuid}/{sessionId}", server.sessionStatusHandler).Methods("GET")
router.HandleFunc("/session/{uuid}/{sessionId}", server.stopSessionHandler).Methods("DELETE")
router.NotFoundHandler = router.NewRoute().HandlerFunc(server.notFoundHandler).GetHandler()
go func(server *Server) {
for range time.Tick(time.Second * 20) {
for sessionId, timestamp := range server.sessionTimestamps {
t := time.Now()
elapsed := t.Sub(timestamp)
log.Println("sessionId", sessionId, "elapsed", elapsed)
if elapsed > time.Second*60 {
server.mutex.Lock()
log.Println("Disconnecting device with SessionId:", sessionId)
delete(server.sessionDevices, sessionId)
delete(server.sessionTimestamps, sessionId)
delete(server.sessionNonces, sessionId)
server.mutex.Unlock()
}
}
}
}(server)
err := server.httpServer.ListenAndServe()
if err != nil {
log.Fatal("Server could not run with err", err)
return err
}
return nil // no errors, server running
}
func authenticate() {
}