-
Notifications
You must be signed in to change notification settings - Fork 31
/
wsClient.go
1777 lines (1632 loc) · 61.2 KB
/
wsClient.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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// WebCall Copyright 2023 timur.mobi. All rights reserved.
//
// Method serve() is the Websocket handler for http-to-ws upgrade.
// Method handleClientMessage() is the Websocket signaling handler.
// KeepAliveMgr takes care of keeping ws-clients connected.
package main
import (
"bytes"
"time"
"strings"
"fmt"
"strconv"
"errors"
"encoding/json"
"net/http"
"sync/atomic"
"sync"
"github.com/lesismal/nbio/nbhttp/websocket"
)
const (
pingPeriod = 60
// we send a ping to the client when we didn't hear from it for pingPeriod secs
// when we send a ping, we set the time for our next ping in pingPeriod secs after that
// whenever we receive something from the client (data or a ping or a pong)
// we reset the time for our next ping to be sent in pingPeriod secs after that moment
// when pingPeriod expires, it means that we didn't hear from the client for pingPeriod secs
// so we send our ping
// and we set SetReadDeadline bc we expect to receive a pong in response within max 30s
// if there is still no response from the client by then, we consider the client to be dead
// in other words: we cap the connection if we don't hear from a client for pingPeriod + 30 secs
// browser clients do not send pings, so it is only the server sending pings
// new: android clients do not send pings anymore (for powermgmt reasons)
// now outdated:
// android clients send pings to the server every 60 secs and we respond with pongs
// since the pingPeriod of android clients is shorter than that of this server,
// this server will in practice not send any pings to android clients
// say an android client sends a ping, the server sends a pong and shortly after the client reboots
// the server will wait for 90s without receiving anything from this client
// after 90s the server will send a ping to check the client
// after another 20s the server declares the client dead - 100s after the clients last ping
)
var keepAliveMgr *KeepAliveMgr
var ErrWriteNotConnected = errors.New("Write not connected")
type WsClient struct {
hub *Hub
wsConn *websocket.Conn
mastodonID string
mastodonSendTootOnCall bool
askCallerBeforeNotify bool
isOnline atomic.Bool // connected to signaling server
isConnectedToPeer atomic.Bool // before pickup
isMediaConnectedToPeer atomic.Bool // after pickup
pickupSent atomic.Bool
calleeInitReceived atomic.Bool
callerOfferForwarded atomic.Bool
reached14s atomic.Bool
calleeAnswerReceived chan struct{}
RemoteAddr string // with port
RemoteAddrNoPort string // no port
userAgent string // ws UA
calleeID string
globalCalleeID string // unique calleeID for multiCallees as key for hubMap[]
connType string
callerID string
callerName string
callerHost string
textMode string
dialID string
clientVersion string
callerTextMsg string
pingSent uint64
pongReceived uint64
pongSent uint64
pingReceived uint64
authenticationShown bool // whether to show "pion auth for client (%v) SUCCESS"
isCallee bool
autologin bool
}
func serveWs(w http.ResponseWriter, r *http.Request) {
serve(w, r, false)
}
func serveWss(w http.ResponseWriter, r *http.Request) {
serve(w, r, true)
}
func serve(w http.ResponseWriter, r *http.Request, tls bool) {
if logWantedFor("wsverbose") {
fmt.Printf("wsClient url=%s tls=%v\n", r.URL.String(), tls)
}
if keepAliveMgr==nil {
keepAliveMgr = NewKeepAliveMgr()
go keepAliveMgr.Run()
}
remoteAddr := r.RemoteAddr
realIpFromRevProxy := r.Header.Get("X-Real-Ip")
if realIpFromRevProxy!="" {
remoteAddr = realIpFromRevProxy
}
remoteAddrNoPort := remoteAddr
idxPort := strings.Index(remoteAddrNoPort,":")
if idxPort>=0 {
remoteAddrNoPort = remoteAddrNoPort[:idxPort]
}
var wsClientID64 uint64 = 0
var wsClientData wsClientDataType
url_arg_array, ok := r.URL.Query()["wsid"]
if !ok || len(url_arg_array[0]) <= 0{
return
}
wsClientIDstr := strings.ToLower(url_arg_array[0])
wsClientID64, _ = strconv.ParseUint(wsClientIDstr, 10, 64)
if wsClientID64<=0 {
// not valid
fmt.Printf("# wsClient invalid wsClientIDstr=%s %s url=%s\n",
wsClientIDstr, remoteAddr, r.URL.String())
return
}
//fmt.Printf("wsClient wsClientIDstr=%s wsClientID64=%d\n",wsClientIDstr,wsClientID64)
wsClientMutex.Lock()
wsClientData,ok = wsClientMap[wsClientID64]
if ok {
// ensure wsClientMap[wsClientID64] will not be removed
wsClientData.removeFlag = false
wsClientMap[wsClientID64] = wsClientData
}
wsClientMutex.Unlock()
if !ok {
// this callee has just exited, no need to log
//fmt.Printf("wsClient ws=%d does not exist %s url=%s\n",
// wsClientID64, remoteAddr, r.URL.String())
return
}
callerID := ""
url_arg_array, ok = r.URL.Query()["callerId"]
if ok && len(url_arg_array[0]) > 0 {
callerID = strings.ToLower(url_arg_array[0])
}
callerHost := ""
url_arg_array, ok = r.URL.Query()["callerHost"]
if ok && len(url_arg_array[0]) > 0 {
callerHost = strings.ToLower(url_arg_array[0])
}
// callerIdLong = callerId @ callerHost
callerIdLong := callerID
if callerHost!="" && !strings.HasPrefix(callerHost,hostname) {
if(strings.Index(callerIdLong,"@")>=0) {
callerIdLong += "@"+callerHost
} else {
callerIdLong += "@@"+callerHost
}
//fmt.Printf("wsClient (%s) callerID=%s Long=%s callerHost=%s hostname=%s\n",
// wsClientData.calleeID, callerID, callerIdLong, callerHost, hostname)
}
callerName := ""
url_arg_array, ok = r.URL.Query()["callerName"]
if ok && len(url_arg_array[0]) >= 1 {
callerName = url_arg_array[0]
}
if callerName=="" {
url_arg_array, ok = r.URL.Query()["name"]
if ok && len(url_arg_array[0]) >= 1 {
callerName = url_arg_array[0]
}
}
// if callerName is empty, but callerIdLong and wsClientData.calleeID are set
// we try to get callerName from the callee's contacts (but only if callerName is not 'unknown')
if callerName=="" && callerIdLong!="" && wsClientData.calleeID!="" {
if !strings.HasPrefix(wsClientData.calleeID,"answie") &&
!strings.HasPrefix(wsClientData.calleeID,"talkback") {
// callerName is empty, but we got callerID and calleeID
// try to fetch callerName by searching for callerID in contacts of calleeID
//fmt.Printf("wsClient try to get callerName for callerID=%s via calleeID=%s\n",
// callerID, wsClientData.calleeID)
var idNameMap map[string]string // callerID -> compoundName
err := kvContacts.Get(dbContactsBucket,wsClientData.calleeID,&idNameMap)
if err!=nil {
fmt.Printf("# wsClient db get calleeID=%s (ignore) err=%v\n", wsClientData.calleeID, err)
} else {
compoundName := idNameMap[callerIdLong]
tokenSlice := strings.Split(compoundName, "|")
for idx, tok := range tokenSlice {
switch idx {
case 0: if tok!="unknown" { callerName = tok }
//case 1: = tok
//case 2: = tok
}
}
if callerName!="" {
if logWantedFor("contacts") {
fmt.Printf("wsClient got callerName=%s for callerID=%s from contacts of calleeID=%s\n",
callerName, callerIdLong, wsClientData.calleeID)
}
}
}
}
}
clientVersion := ""
url_arg_array, ok = r.URL.Query()["ver"]
if ok && len(url_arg_array[0]) > 0 {
clientVersion = url_arg_array[0]
}
auto := ""
url_arg_array, ok = r.URL.Query()["auto"]
if ok && len(url_arg_array[0]) > 0 {
auto = url_arg_array[0]
}
textMode := ""
url_arg_array, ok = r.URL.Query()["text"]
if ok && len(url_arg_array[0]) > 0 {
textMode = strings.ToLower(url_arg_array[0])
}
upgrader := websocket.NewUpgrader()
//upgrader.EnableCompression = true // TODO
upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Printf("# Upgrade err=%v\n", err)
return
}
wsConn := conn.(*websocket.Conn)
//wsConn.EnableWriteCompression(true) // TODO
// the only time browser clients can be expected to send anything, is after we sent a ping
// this is why we set NO read deadline here; we do it when we send a ping
wsConn.SetReadDeadline(time.Time{})
client := &WsClient{wsConn:wsConn}
client.calleeID = wsClientData.calleeID // this is the main-calleeID
client.dialID = wsClientData.dialID
client.globalCalleeID = wsClientData.globalID
dialID := wsClientData.dialID
//fmt.Printf("wsClient calleeID=%s dialID=%s\n", client.calleeID, dialID)
if dialID != "" && dialID != client.calleeID {
// original dialID was mapped to client.calleeID
mappingMutex.RLock()
mappingData,ok := mapping[dialID]
mappingMutex.RUnlock()
if ok {
// dialID is mapped (caller is using a temporary (mapped) calleeID)
// if a name was assigned for dialID, we attach it to callerName
assignedName := mappingData.Assign
if assignedName!="" && assignedName!="none" {
if callerName=="" {
callerName = "("+assignedName+")"
} else if strings.Index(callerName,"(")<0 {
callerName += " ("+assignedName+")"
}
if callerName!="" {
fmt.Printf("wsClient callerName=%s for dialID=%s mappedID=%s(=%s)\n",
callerName, dialID, mappingData.CalleeId, wsClientData.calleeID)
}
}
}
}
//fmt.Printf("serve (%s) callerID=%s callerName=%s auto=%s ver=%s\n",
// wsClientData.calleeID, callerIdLong, callerName, auto, clientVersion)
client.clientVersion = wsClientData.clientVersion
if clientVersion!="" {
client.clientVersion = clientVersion
}
if auto=="true" {
client.autologin = true
}
client.callerID = callerIdLong
client.callerName = callerName
client.callerHost = callerHost
client.textMode = textMode
if tls {
client.connType = "serveWss"
} else {
client.connType = "serveWs"
}
/*
keepAliveMgr.Add(wsConn)
// set the time for sending the next ping
keepAliveMgr.SetPingDeadline(wsConn, pingPeriod, client) // now + pingPeriod secs
*/
client.isOnline.Store(true)
client.RemoteAddr = remoteAddr
client.RemoteAddrNoPort = remoteAddrNoPort
client.userAgent = r.UserAgent()
client.authenticationShown = false // being used to make sure 'TURN auth SUCCESS' is only shown 1x per client
hub := wsClientData.hub // set by /login wsClientMap[wsClientID] = wsClientDataType{...}
client.hub = hub
upgrader.OnMessage(func(wsConn *websocket.Conn, messageType websocket.MessageType, data []byte) {
// clear read deadline; don't expect data from this cli for now; set it again when we send the next ping
wsConn.SetReadDeadline(time.Time{})
if(client.isCallee) {
// push forward the time for sending the next ping
// (whenever client sends anything, we postpone sending our next ping by pingPeriod secs)
keepAliveMgr.SetPingDeadline(wsConn, pingPeriod, client) // now + pingPeriod secs
}
switch messageType {
case websocket.TextMessage:
//fmt.Println("TextMessage:", messageType, string(data), len(data))
n := len(data)
if n>0 {
//if logWantedFor("wsreceive") {
// max := n; if max>20 { max = 20 }
// fmt.Printf("%s (%s) received n=%d isCallee=%v (%s)\n",
// client.connType, client.calleeID, n, client.isCallee, data[:max])
//}
client.handleClientMessage(data, wsConn)
}
case websocket.BinaryMessage:
fmt.Printf("# %s binary dataLen=%d\n", client.connType, len(data))
}
})
upgrader.SetPongHandler(func(wsConn *websocket.Conn, s string) {
// we received a pong from the client
if logWantedFor("gotpong") {
fmt.Printf("gotPong (%s) %s\n",client.calleeID, wsConn.RemoteAddr().String())
}
// clear read deadline; don't expect data from this cli for now; set it again when we send the next ping
wsConn.SetReadDeadline(time.Time{})
if(client.isCallee) {
// push forward the time for sending the next ping: now + pingPeriod secs
keepAliveMgr.SetPingDeadline(wsConn, pingPeriod, client) // now + pingPeriod secs
}
client.pongReceived++
})
upgrader.SetPingHandler(func(wsConn *websocket.Conn, s string) {
// received a ping from the client (this only happens in rare cases; usually we send pings to client)
if logWantedFor("gotping") {
fmt.Printf("gotPing (%s)\n",client.calleeID)
}
client.pingReceived++
// clear read deadline; don't expect data from this cli for now; set it again when we send the next ping
wsConn.SetReadDeadline(time.Time{})
// send the pong
err := wsConn.WriteMessage(websocket.PongMessage, nil)
if err != nil {
fmt.Printf("# sendPong (%s) %s err=%v\n",client.calleeID, client.wsConn.RemoteAddr().String(), err)
if(client.isCallee) {
// callee is gone
client.hub.closeCallee("sendPong: "+err.Error())
return
}
// caller is gone (this can only happen for as long as the server has not disconnected the caller,
// so it is likely a manual (early/pre-14s) disconnect by the caller)
// TODO so we might want to call closePeerCon() instead
client.hub.closeCaller("sendPong: "+err.Error())
return
}
if(client.isCallee) {
// set the time for sending the next ping: now + pingPeriod secs
keepAliveMgr.SetPingDeadline(wsConn, pingPeriod, client) // now + pingPeriod secs
}
atomic.AddInt64(&pongSentCounter, 1)
client.pongSent++
})
wsConn.OnClose(func(c *websocket.Conn, err error) {
client.isOnline.Store(false) // prevent Close() from trying to close this already closed connection
if client.isCallee {
// callee has closed ws-con to server
keepAliveMgr.Delete(c)
// clear read deadline; we don't expect data from this cli
c.SetReadDeadline(time.Time{})
if logWantedFor("wsclose") {
if err!=nil {
fmt.Printf("%s (%s) OnClose callee err=%v %s v=%s\n",
client.connType, client.calleeID, err, client.RemoteAddr, client.clientVersion)
} else {
fmt.Printf("%s (%s) OnClose callee noerr %s v=%s\n",
client.connType, client.calleeID, client.RemoteAddr, client.clientVersion)
}
}
// stop watchdog timer
if client.hub!=nil {
client.hub.HubMutex.RLock()
if client.hub.CallerClient!=nil && client.hub.CallerClient.calleeAnswerReceived!=nil {
client.hub.CallerClient.calleeAnswerReceived <- struct{}{}
}
client.hub.HubMutex.RUnlock()
if err!=nil {
client.hub.closeCallee("OnClose callee: "+ err.Error())
} else {
client.hub.closeCallee("OnClose callee: noerr")
}
}
} else {
// caller has closed ws-con to server
if logWantedFor("wsclose") {
if err!=nil {
fmt.Printf("%s (%s) OnClose caller err=%v %s v=%s\n",
client.connType, client.calleeID, err, client.RemoteAddr, client.clientVersion)
} else {
fmt.Printf("%s (%s) OnClose caller noerr %s v=%s\n",
client.connType, client.calleeID, client.RemoteAddr, client.clientVersion)
}
}
if client.hub!=nil {
client.hub.HubMutex.RLock()
if client.hub.CallerClient!=nil {
client.hub.CallerClient.calleeAnswerReceived <- struct{}{}
}
client.hub.HubMutex.RUnlock()
if !client.reached14s.Load() {
// a caller disconnect before reached14s is definitely a manual discon by the caller
// -> force closePeerCon
if err!=nil {
client.hub.closePeerCon("OnCloseCaller "+err.Error())
} else {
client.hub.closePeerCon("OnCloseCaller noerr")
}
} else {
// a caller disconnect after reached14s is a regular discon of the caller by the server
// (see: disconCallerOnPeerConnected)
// -> let peerCon alive, just close the caller
// NOTE we treat err=read timeout like noerr (testing)
if err!=nil && strings.Index(err.Error(),"read timeout")<0 {
client.hub.closeCaller("OnCloseCaller "+err.Error())
} else {
client.hub.closeCaller("OnCloseCaller noerr")
}
}
}
}
})
hub.HubMutex.Lock()
if hub.CalleeClient==nil {
// callee client (1st client)
if logWantedFor("wsclient") {
fmt.Printf("%s (%s) callee conn ws=%d %s\n", client.connType,
client.calleeID, wsClientID64, client.RemoteAddr)
}
client.isCallee = true
client.calleeInitReceived.Store(false)
client.mastodonID = wsClientData.dbUser.MastodonID
client.mastodonSendTootOnCall = wsClientData.dbUser.MastodonSendTootOnCall
client.askCallerBeforeNotify = wsClientData.dbUser.AskCallerBeforeNotify
hub.IsCalleeHidden = wsClientData.dbUser.Int2&1!=0
hub.IsUnHiddenForCallerAddr = ""
hub.WsClientID = wsClientID64
hub.CalleeClient = client // only hub.closeCallee() sets CalleeClient = nil
hub.CallerClient = nil
hub.ServiceStartTime = time.Now().Unix()
if !strings.HasPrefix(client.calleeID,"random") {
// get values related to talk- and service-time for this callee from the db
// so that 1s-ticker can calculate the live remaining time
hub.ServiceStartTime = wsClientData.dbEntry.StartTime // race?
//hub.ConnectedToPeerSecs = int64(wsClientData.dbUser.ConnectedToPeerSecs)
}
hub.CallDurationSecs = 0
hub.HubMutex.Unlock()
keepAliveMgr.Add(wsConn)
// set the time for sending the next ping
keepAliveMgr.SetPingDeadline(wsConn, pingPeriod, client) // now + pingPeriod secs
return
}
if hub.CallerClient==nil {
// caller client (2nd client)
if logWantedFor("attach") {
fmt.Printf("%s (%s) caller conn dialID=%s ws=%d (%s) %s\n", client.connType, client.calleeID,
client.dialID, wsClientID64, callerIdLong, client.RemoteAddr)
}
client.isCallee = false
client.callerOfferForwarded.Store(false)
client.reached14s.Store(false)
hub.CallDurationSecs = 0
hub.CallerClient = client
hub.CallerIpNoPort = client.RemoteAddrNoPort
hub.CallerID = callerIdLong
hub.lastCallerContactTime = time.Now().Unix()
hub.HubMutex.Unlock()
// connection watchdog now has two timeouts
// 1. from when caller connects (now) to when callee sends calleeAnswer (max 60s)
// 2. from when callee sends calleeAnswer to when p2p-connect should occur (max 14s)
go func() {
// NOTE: client is same as hub.CallerClient
client.calleeAnswerReceived = make(chan struct{}, 8)
secs := 60
timer := time.NewTimer(time.Duration(secs) * time.Second)
if logWantedFor("wsclose") {
fmt.Printf("%s (%s) %ds timer start ws=%d\n",
client.connType, client.calleeID, secs, wsClientID64)
}
select {
case <-timer.C:
// no calleeAnswer in response to callerOffer within 60s
// we want to send cancel to both clients,
// then disconnect the caller, reset the callee, and do peerConHasEnded
if logWantedFor("wsclose") {
fmt.Printf("%s (%s) %ds timer: time is up ws=%d\n",
client.connType, client.calleeID, secs, wsClientID64)
}
hub.HubMutex.RLock()
if hub.CallerClient!=nil {
// disconnect caller's ws-connection (client is caller)
client.Write([]byte("cancel|disconnect")) // ignore any errors
}
if hub.CalleeClient!=nil {
// callee is here, disconnect caller's ws-connection
err = hub.CalleeClient.Write([]byte("cancel|c"))
if err != nil {
// callee is gone
fmt.Printf("# %s (%s) %ds timer: time is up, cancel msg to callee failed %v\n",
hub.CalleeClient.connType, hub.CalleeClient.calleeID, secs, err)
hub.HubMutex.RUnlock()
hub.closeCallee("disconCallerAfter60s: cancel to callee: "+err.Error())
return
}
}
hub.HubMutex.RUnlock()
// closePeerCon() will close the caller
hub.closePeerCon("disconCallAfter60s")
return
case <-client.calleeAnswerReceived:
// event coming from cmd=="calleeAnswer"
// this is also used to signal "caller gone", but with CallerClient.isOnline=false
if logWantedFor("wsclose") {
fmt.Printf("%s (%s) %ds timer: calleeAnswerReceived ws=%d\n",
client.connType, client.calleeID, secs, wsClientID64)
}
timer.Stop()
// fall through, start 14s timer
}
delaySecs := 14
// incoming caller will get removed if there is no peerConnect after 14s
// (it can take up to 14 seconds in some cases for a devices to get fully out of deep sleep)
myCallerContactTime := hub.lastCallerContactTime
//fmt.Printf("%s (%s) caller conn 14s delay start\n", client.connType, client.calleeID)
time.Sleep(time.Duration(delaySecs) * time.Second)
//fmt.Printf("%s (%s) caller conn 14s delay end\n", client.connType, client.calleeID)
hub.HubMutex.RLock()
if hub.CalleeClient==nil {
//fmt.Printf("%s (%s) no peercon check: callee gone (hub.CalleeClient==nil)\n",
// client.connType, client.calleeID)
hub.HubMutex.RUnlock()
return
}
if hub.CallerClient==nil {
//fmt.Printf("%s (%s) no peercon check: caller gone (hub.CallerClient==nil)\n",
// client.connType, client.calleeID)
hub.HubMutex.RUnlock()
return
}
if !hub.CallerClient.isOnline.Load() {
// this helps us to NOT throw a false NO PEERCON when the caller hanged up early
// we don't ws-disconnect the caller on peercon, so we can detect a hangup shortly after
//fmt.Printf("%s (%s) no peercon check: !CallerClient.isOnline\n",
// client.connType, client.calleeID)
hub.HubMutex.RUnlock()
return
}
if !hub.CallerClient.callerOfferForwarded.Load() {
// caller has not sent a calleroffer yet -> it has hanged up early
//fmt.Printf("%s (%s) no peercon check: !CallerClient.callerOfferForwarded\n",
// client.connType, client.calleeID)
hub.HubMutex.RUnlock()
return
}
client.reached14s.Store(true)
// if isConnectedToPeer and disconCallerOnPeerConnected -> force discon caller (but not peercon) now!
// caller onClose will from now on not anymore disconnect peercon on caller gone
if hub.CalleeClient.isConnectedToPeer.Load() {
// peercon steht; no peercon meldung nicht nötig; force caller ws-disconnect
// we know this is the caller, shall it be ws-disconnected?
readConfigLock.RLock()
myDisconCallerOnPeerConnected := disconCallerOnPeerConnected
readConfigLock.RUnlock()
if myDisconCallerOnPeerConnected {
// force-disconnect the caller WITHOUT disconnecting peerCon
hub.HubMutex.RUnlock()
if logWantedFor("wsclose") {
fmt.Printf("%s (%s) reached14s -> force disconnect caller\n",
client.connType, client.calleeID)
}
hub.closeCaller("disconCallerAfter14s") // this will clear .CallerClient
return
}
if logWantedFor("wsclose") {
fmt.Printf("%s (%s) reached14s -> do not force disconnect caller\n",
client.connType, client.calleeID)
}
hub.HubMutex.RUnlock()
return
}
if hub!=nil && myCallerContactTime != hub.lastCallerContactTime {
// this callee is engaged with a new caller session already (myCallerContactTime is outdated)
// TODO must investigate this
hub.HubMutex.RUnlock()
fmt.Printf("%s (%s) reached14s and no peerCon, but outdated %d != %d\n",
client.connType, client.calleeID, myCallerContactTime, hub.lastCallerContactTime)
return
}
// NO PEERCON: calleroffer received, but after 14s still no peer-connect: this is a webrtc issue
// let's assume both sides are still ws-connected. let's send a status msg to both
fmt.Printf("%s (%s) reached14s NO PEERCON📵 %ds %s <- %s (%s) %v ua=%s\n",
client.connType, client.calleeID, delaySecs, hub.CalleeClient.RemoteAddr,
client.RemoteAddr, client.callerID, client.isOnline.Load(), client.userAgent)
// NOTE: msg MUST NOT contain apostroph (') characters
msg := "Unable to establish a direct P2P connection. "+
"This might be a WebRTC related issue with your browser/WebView. "+
"Or with the browser/WebView on the other side. "+
"It could also be a firewall issue. "+
"On Android, run <a href=\"/webcall/android/#webview\">WebRTC-Check</a> "+
"to test your System WebView."
err := client.Write([]byte("status|"+msg))
if err != nil {
// caller is gone
fmt.Printf("%s (%s) failed to send NO PEERCON msg to caller %s err=%v\n",
client.connType, client.calleeID, remoteAddr, err)
// ignore err bc below we disconnect the caller anyway
}
if strings.HasPrefix(hub.CalleeClient.calleeID,"answie") ||
strings.HasPrefix(hub.CalleeClient.calleeID,"talkback") {
// if callee is answie or talkback, the problem must be with the caller side
// don't send msg to callee
} else {
// this is a real callee-user
err = hub.CalleeClient.Write([]byte("status|"+msg))
if err != nil {
// callee is gone
fmt.Printf("%s (%s) failed to send NO PEERCON msg to callee %s err=%v\n",
client.connType, client.calleeID, hub.CalleeClient.RemoteAddr, err)
hub.HubMutex.RUnlock()
hub.closeCallee("failed to send NO PEERCON msg to callee: "+err.Error())
return
}
}
hub.HubMutex.RUnlock()
// let callee alive but close caller + clear CallerIpInHubMap
hub.closePeerCon("NO PEERCON")
}()
return
}
hub.HubMutex.Unlock()
// can be ignored
//fmt.Printf("# %s (%s/%s) CallerClient already set [%s] %s ws=%d\n",
// client.connType, client.calleeID, client.globalCalleeID, hub.CallerClient.RemoteAddr,
// client.RemoteAddr, wsClientID64)
}
func (c *WsClient) handleClientMessage(message []byte, cliWsConn *websocket.Conn) {
// check message integrity: cmd's can not be longer than 32 chars
checkLen := 32
if len(message) < checkLen {
checkLen = len(message)
}
idxPipe := bytes.Index(message[:checkLen], []byte("|"))
if idxPipe<0 {
// invalid -> ignore
//fmt.Printf("# serveWs receive no pipe char found; abort; checkLen=%d (%s)\n",
// checkLen,string(message[:checkLen]))
return
}
tok := strings.Split(string(message),"|")
if len(tok)!=2 {
// invalid -> ignore
fmt.Printf("# serveWs receive len(tok)=%d is !=2; abort; checkLen=%d idxPipe=%d (%s)\n",
len(tok), checkLen, idxPipe, string(message[:checkLen]))
return
}
//fmt.Printf("_ %s (%s) receive isCallee=%v %s %s\n",
// c.connType, c.calleeID, c.isCallee, c.RemoteAddr, cliWsConn.RemoteAddr().String())
cmd := tok[0]
payload := tok[1]
if cmd=="init" {
// note: c == c.hub.CalleeClient
if !c.isCallee {
// only the callee can send "init|"
fmt.Printf("# %s (%s) deny init is not Callee %s\n", c.connType, c.calleeID, c.RemoteAddr)
return
}
if c.hub==nil {
fmt.Printf("# %s (%s) deny init c.hub==nil %s\n", c.connType, c.calleeID, c.RemoteAddr)
return
}
if !c.calleeInitReceived.Load() {
// on first init only
//fmt.Printf("%s (%s) init %s\n", c.connType, c.calleeID, c.RemoteAddr)
c.hub.HubMutex.Lock()
c.hub.CallerClient = nil
c.hub.HubMutex.Unlock()
c.calleeInitReceived.Store(true)
c.hub.CalleeLogin.Store(true)
c.pickupSent.Store(false)
// closeCallee() will call setDeadline(0) and processTimeValues() if this is false; then set it true
c.callerTextMsg = ""
if logWantedFor("attach") {
loginCount := 0
calleeLoginMutex.RLock()
calleeLoginSlice,ok := calleeLoginMap[c.calleeID]
calleeLoginMutex.RUnlock()
if ok {
loginCount = len(calleeLoginSlice)
}
fmt.Printf("%s (%s) init %d ws=%d %s v=%s\n",
c.connType, c.calleeID, loginCount, c.hub.WsClientID, c.RemoteAddr, c.clientVersion)
}
// TODO clear blockMap[c.calleeID] ?
//blockMapMutex.Lock()
//delete(blockMap,c.calleeID)
//blockMapMutex.Unlock()
}
// deliver the webcall codetag version string to callee
err := c.Write([]byte("sessionId|"+codetag))
if err != nil {
fmt.Printf("# %s (%s) init send sessionId %s <- to callee err=%v\n",
c.connType, c.calleeID, c.RemoteAddr, err)
c.hub.closeCallee("init, send sessionId to callee: "+err.Error())
return
}
if !strings.HasPrefix(c.calleeID,"answie") && !strings.HasPrefix(c.calleeID,"talkback") {
// send "newer client available"
if clientUpdateBelowVersion!="" && !c.autologin {
if c.clientVersion < clientUpdateBelowVersion {
//fmt.Printf("%s (%s) init v=%s\n",c.connType,c.calleeID,c.clientVersion)
// NOTE: msg MUST NOT contain apostroph (') characters
msg := "Please upgrade WebCall client to "+
"<a href=\"/webcall/update/\">v"+clientUpdateBelowVersion+" or higher</a>"
if logWantedFor("attach") {
fmt.Printf("%s (%s) init %s %s send status %s\n",
c.connType, c.calleeID, c.RemoteAddr, c.clientVersion, msg)
}
err = c.Write([]byte("status|"+msg))
if err != nil {
fmt.Printf("# %s (%s) init send status (%s) %s <- to callee err=%v\n",
c.connType, c.calleeID, c.RemoteAddr, err)
//c.hub.doUnregister(c, "init, send status to callee: "+err.Error())
//return
}
}
}
// send list of waitingCaller to callee client
var waitingCallerSlice []CallerInfo
// err can be ignored
kvCalls.Get(dbWaitingCaller,c.calleeID,&waitingCallerSlice)
// before we send waitingCallerSlice
// we remove all entries that are older than 10min
countOutdated:=0
for idx := range waitingCallerSlice {
//fmt.Printf("%s (idx=%d of %d)\n", c.connType,idx,len(waitingCallerSlice))
if idx >= len(waitingCallerSlice) {
break
}
if time.Now().Unix() - waitingCallerSlice[idx].CallTime > 10*60 {
// remove outdated caller from waitingCallerSlice
waitingCallerSlice = append(waitingCallerSlice[:idx],
waitingCallerSlice[idx+1:]...)
countOutdated++
}
}
var err error
if countOutdated>0 {
fmt.Printf("%s (%s) init deleted %d outdated from waitingCallerSlice\n",
c.connType, c.calleeID, countOutdated)
err = kvCalls.Put(dbWaitingCaller, c.calleeID, waitingCallerSlice, true) // skipConfirm
if err!=nil {
fmt.Printf("# %s (%s) init failed to store dbWaitingCaller\n",c.connType,c.calleeID)
}
}
// send list of missedCalls to callee client
var missedCallsSlice []CallerInfo
// err can be ignored
kvCalls.Get(dbMissedCalls,c.calleeID,&missedCallsSlice)
// TODO must check if .DialID is still a valid ID for this callee
// if a DialID is outdated, replace it with the calleeID - or with ""
if len(waitingCallerSlice)>0 || len(missedCallsSlice)>0 {
if logWantedFor("waitingCaller") {
fmt.Printf("%s (%s) init waitingCaller=%d missedCalls=%d\n",c.connType,c.calleeID,
len(waitingCallerSlice),len(missedCallsSlice))
}
// -> httpServer c.Write()
waitingCallerToCallee(c.calleeID, waitingCallerSlice, missedCallsSlice, c)
}
}
return
}
if cmd=="dummy" {
fmt.Printf("%s (%s) dummy %s ip=%s ua=%s\n",
c.connType, c.calleeID, payload, c.RemoteAddr, c.userAgent)
err := c.Write([]byte(payload))
if err != nil {
fmt.Printf("# %s (%s) send dummy reply (isCallee=%v) error\n",
c.connType, c.isCallee, c.calleeID)
c.hub.closeCallee("send dummy: "+err.Error())
}
return
}
if cmd=="msg" {
// sent by caller on hangup without mediaconnect
logTxtMsg := "(hidden)" // don't log actual cleanMsg
if c.hub==nil {
// don't log actual cleanMsg
fmt.Printf("# %s (%s) msg='%s' c.hub==nil callee=%v ip=%s ua=%s\n",
c.connType, c.calleeID, logTxtMsg, c.isCallee, c.RemoteAddr, c.userAgent)
return
}
c.hub.HubMutex.Lock()
if c.hub.CalleeClient==nil {
// don't log actual cleanMsg
c.hub.HubMutex.Unlock()
fmt.Printf("# %s (%s) msg='%s' c.hub.CalleeClient==nil callee=%v ip=%s ua=%s\n",
c.connType, c.calleeID, logTxtMsg, c.isCallee, c.RemoteAddr, c.userAgent)
return
}
cleanMsg := strings.Replace(payload, "\n", " ", -1)
cleanMsg = strings.Replace(cleanMsg, "\r", " ", -1)
cleanMsg = strings.TrimSpace(cleanMsg)
if cleanMsg == c.hub.CalleeClient.callerTextMsg {
// same text msg was already processed / forwarded
c.hub.HubMutex.Unlock()
return
}
fmt.Printf("%s (%s) msg='%s' callee=%v ip=%s ua=%s\n",
c.connType, c.calleeID, logTxtMsg, c.isCallee, c.RemoteAddr, c.userAgent)
c.hub.CalleeClient.callerTextMsg = cleanMsg;
c.hub.HubMutex.Unlock()
return // do NOT let msg fall thru; so it will NOT be fw to other side
}
if cmd=="missedcall" {
// sent by caller on hangup without mediaconnect
fmt.Printf("%s (%s) missedcall='%s' callee=%v ip=%s ua=%s\n",
c.connType, c.calleeID, payload, c.isCallee, c.RemoteAddr, c.userAgent)
//c.hub.CalleeClient.callerTextMsg = payload;
missedCall(payload, c.RemoteAddr, "cmd=missedcall")
return
}
if cmd=="callerOffer" {
// caller starting a call - payload is JSON.stringify(localDescription)
// note: c == c.hub.CallerClient
if c.callerOfferForwarded.Load() {
// prevent double callerOffer
//fmt.Printf("# %s (%s) CALL from %s was already forwarded\n",
// c.connType, c.calleeID, c.RemoteAddr)
return
}
//fmt.Printf("%s (%s) callerOffer... %s\n", c.connType, c.calleeID, c.RemoteAddr)
c.hub.HubMutex.RLock()
if c.hub.CalleeClient==nil {
fmt.Printf("# %s (%s) CALL🔔 from (%s) %s but hub.CalleeClient==nil\n",
c.connType, c.calleeID, c.callerID, c.RemoteAddr)
c.hub.HubMutex.RUnlock()
return
}
// prevent this callee from receiving a call, when already in a call
if c.hub.ConnectedCallerIp!="" {
// ConnectedCallerIp is set below by StoreCallerIpInHubMap()
fmt.Printf("# %s (%s) CALL🔔 but hub.ConnectedCallerIp not empty (%s) <- (%s) %s\n",
c.connType, c.calleeID, c.hub.ConnectedCallerIp, c.callerID, c.RemoteAddr)
// add missed call if dbUser.StoreMissedCalls is set
userKey := c.calleeID + "_" + strconv.FormatInt(int64(c.hub.registrationStartTime),10)
var dbUser DbUser
err := kvMain.Get(dbUserBucket, userKey, &dbUser)
if err!=nil {
fmt.Printf("# %s (%s) failed to get dbUser\n",c.connType,c.calleeID)
} else if dbUser.StoreMissedCalls {
addMissedCall(c.calleeID, CallerInfo{c.RemoteAddr, c.callerName,
time.Now().Unix(), c.callerID, c.callerTextMsg }, "callee busy")
}
c.hub.HubMutex.RUnlock()
return
}
fmt.Printf("%s (%s) CALL🔔 %s <- %s (%s) T=%s v=%s ua=%s\n",
c.connType, c.calleeID, c.hub.CalleeClient.RemoteAddr,
c.RemoteAddr, c.callerID, c.textMode, c.clientVersion, c.userAgent)
// forward the callerOffer message to the callee client
err := c.hub.CalleeClient.Write(message)
if err != nil {
// callee is gone
fmt.Printf("! %s (%s) CALL CalleeClient.Write(calleroffer) fail %v\n",
c.connType, c.calleeID, err)
c.hub.HubMutex.RUnlock()
c.hub.closeCallee("send callerOffer to callee: "+err.Error())
return
}
c.callerOfferForwarded.Store(true)
c.hub.CalleeClient.Write([]byte("textmode|"+c.textMode))
// send callerInfo to callee (see callee.js if(cmd=="callerInfo"))
if c.callerID!="" || c.callerName!="" {
// this data is used to display caller-info in the callee-client
// NOTE: c.callerID and c.callerHost must not contain colons
sendCmd := "callerInfo|"+c.callerID+"\t"+c.callerName
// if txtMsg exists, attach it to callerInfo as 3rd token
if c.hub.CalleeClient.callerTextMsg!="" {
sendCmd += "\t"+c.hub.CalleeClient.callerTextMsg
}
//fmt.Printf("%s (%s) CALL sendCmd=%s\n", c.connType, c.calleeID, sendCmd)
err = c.hub.CalleeClient.Write([]byte(sendCmd))
if err != nil {
// callee is gone
fmt.Printf("! %s (%s) CALL CalleeClient.Write(callerInfo) fail %v\n",
c.connType, c.calleeID, err)
c.hub.HubMutex.RUnlock()
c.hub.closeCallee("send callerInfo to callee: "+err.Error())
return
}
}
// send calleeInfo (with dbUser.Name) to caller (see caller.js if(cmd=="calleeInfo"))
if c.dialID == "" {
// c.calleeID was not mapped from dialID (caller has called callee's main-ID)
// send calleeInfo (with dbUser.Name) back to caller
//fmt.Printf("%s (%s) CALL dialID not set (caller called callee's main ID)\n", c.connType, c.calleeID)
// read dbUser for dbUser.Name
userKey := c.hub.CalleeClient.calleeID +"_"+strconv.FormatInt(int64(c.hub.registrationStartTime),10)
var dbUser DbUser
err := kvMain.Get(dbUserBucket, userKey, &dbUser)
if err!=nil {
fmt.Printf("# %s (%s) fail get dbUser.Name\n", c.connType, c.hub.CalleeClient.calleeID)
} else {
if dbUser.Name!="" {
sendCmd := "calleeInfo|"+c.hub.CalleeClient.calleeID+"\t"+dbUser.Name
err = c.Write([]byte(sendCmd))
if err != nil {
// caller is gone
fmt.Printf("! %s (%s) fail sending calleeInfo to caller %v\n",
c.connType, c.hub.CalleeClient.calleeID, err)
c.hub.HubMutex.RUnlock()
c.hub.closePeerCon("send calleeInfo to caller: "+err.Error())
return
}
}