-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrv.go
2559 lines (2200 loc) · 73.2 KB
/
srv.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
package rpc25519
// srv.go: simple TCP server, with TLS encryption.
import (
"bufio"
"bytes"
"context"
"crypto/ed25519"
"crypto/tls"
"errors"
"fmt"
"go/token"
"io"
"log"
"net"
"net/http"
"os"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/glycerine/greenpack/msgp"
"github.com/glycerine/idem"
"github.com/glycerine/ipaddr"
"github.com/glycerine/rpc25519/selfcert"
"github.com/quic-go/quic-go"
)
var _ = os.MkdirAll
var _ = fmt.Printf
const notClient = false
const yesIsClient = true
//var serverAddress = "0.0.0.0:8443"
//var serverAddress = "192.168.254.151:8443"
var ErrContextCancelled = fmt.Errorf("rpc25519 error: context cancelled")
var ErrHaltRequested = fmt.Errorf("rpc25519 error: halt requested")
var ErrSendTimeout = fmt.Errorf("rpc25519 eroror: send timeout")
// boundCh should be buffered, at least 1, if it is not nil. If not nil, we
// will send the bound net.Addr back on it after we have started listening.
func (s *Server) runServerMain(
serverAddress string, tcp_only bool, certPath string, boundCh chan net.Addr) {
defer func() {
s.halt.Done.Close()
}()
log.SetFlags(log.LstdFlags | log.Lshortfile) // Add Lshortfile for short file names
s.tmStart = time.Now()
s.cfg.checkPreSharedKey("server")
//vv("server: s.cfg.encryptPSK = %v", s.cfg.encryptPSK)
dirCerts := GetCertsDir()
sslCA := fixSlash(dirCerts + "/ca.crt") // path to CA cert
keyName := "node"
if s.cfg.ServerKeyPairName != "" {
keyName = s.cfg.ServerKeyPairName
}
// since was redundant always,
// selfcert.LoadNodeTLSConfigProtected() below does not use.
// So commenting out:
// path to CA cert to verify client certs, can be same as sslCA
// sslClientCA := sslCA
sslCert := fixSlash(fmt.Sprintf(dirCerts+"/%v.crt", keyName)) // path to server cert
sslCertKey := fixSlash(fmt.Sprintf(dirCerts+"/%v.key", keyName)) // path to server key
if certPath != "" {
sslCA = fixSlash(fmt.Sprintf("%v/ca.crt", certPath)) // path to CA cert
//sslClientCA = sslCA
sslCert = fixSlash(fmt.Sprintf("%v/%v.crt", certPath, keyName)) // path to server cert
sslCertKey = fixSlash(fmt.Sprintf("%v/%v.key", certPath, keyName)) // path to server key
}
var err error
var config *tls.Config
if !tcp_only {
// handle pass-phrase protected certs/node.key
config, s.creds, err = selfcert.LoadNodeTLSConfigProtected(true, sslCA, sslCert, sslCertKey)
if err != nil {
panic(fmt.Sprintf("error on LoadServerTLSConfig(): '%v'", err))
}
}
// Not needed now that we have proper CA cert from gen.sh; or
// perhaps this is the default anyway(?)
// In any event, "localhost" is what we see during handshake; but
// maybe that is because localhost is what we put in the ca.cnf and openssl-san.cnf
// as the CN and DNS.1 names too(!)
//config.ServerName = "localhost" // this would be the name of the remote client.
// start of as http, the get CONNECT and hijack to TCP.
if tcp_only {
// actually just run TCP and not TLS, since we might not have cert authority (e.g. under test)
s.runTCP(serverAddress, boundCh)
return
}
if s.cfg.SkipVerifyKeys {
// turns off client cert checking, allowing any
// random person on the internet to connect... not a good idea!
config.ClientAuth = tls.NoClientCert
} else {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
if s.cfg.UseQUIC {
if s.cfg.TCPonly_no_TLS {
panic("cannot have both UseQUIC and TCPonly_no_TLS true")
}
s.runQUICServer(serverAddress, config, boundCh)
return
}
// Listen on the specified serverAddress
listener, err := tls.Listen("tcp", serverAddress, config)
if err != nil {
log.Fatalf("Failed to listen on %v: %v", serverAddress, err)
}
defer listener.Close()
addr := listener.Addr()
//vv("Server listening on %v://%v ... addr='%#v'/%T", addr.Network(), addr.String(), addr, addr) // net.TCPAddr
vv("Server listening on %v://%v", addr.Network(), addr.String())
switch a := addr.(type) {
case *net.TCPAddr:
// a.IP is a net.IP
if a.IP.IsUnspecified() {
externalIP, extNetIP := ipaddr.GetExternalIP2() // e.g. 100.x.x.x
vv("have unspecified IP, trying to report a specific external: '%v'", externalIP)
a.IP = extNetIP
}
default:
panic(fmt.Sprintf("arg! handle this type: %T", addr))
}
// net.ParseIP() to go from string -> net.IP if need be.
//scheme, ip, port, isUnspecified, isIPv6, err := ipaddr.ParseURLAddress(hostIP)
//panicOn(err)
//vv("server defaults to binding: scheme='%v', ip='%v', port=%v, isUnspecified='%v', isIPv6='%v'", scheme, ip, port, isUnspecified, isIPv6)
if boundCh != nil {
select {
case boundCh <- addr:
case <-time.After(100 * time.Millisecond):
}
}
s.mut.Lock() // avoid data race
addrs := addr.Network() + "://" + addr.String()
s.boundAddressString = addrs
AliasRegister(addrs, addrs+" (server: "+s.name+")")
s.lsn = listener // allow shutdown
s.mut.Unlock()
for {
select {
case <-s.halt.ReqStop.Chan:
return
default:
}
// Accept a new connection
conn, err := listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
// check for shutdown
select {
case <-s.halt.ReqStop.Chan:
return
default:
}
}
alwaysPrintf("Failed to accept connection: %v", err)
continue
}
//vv("Accepted connection from %v", conn.RemoteAddr())
// Handle the connection in a new goroutine
tlsConn := conn.(*tls.Conn)
go s.handleTLSConnection(tlsConn)
}
}
func (s *Server) runTCP(serverAddress string, boundCh chan net.Addr) {
// Listen on the specified serverAddress
listener, err := net.Listen("tcp", serverAddress)
if err != nil {
log.Fatalf("Failed to listen on %v: %v", serverAddress, err)
}
defer listener.Close()
addr := listener.Addr()
s.mut.Lock()
addrs := addr.Network() + "://" + addr.String()
s.boundAddressString = addrs
AliasRegister(addrs, addrs+" (tcp_server: "+s.name+")")
s.mut.Unlock()
//vv("Server listening on %v://%v", addr.Network(), addr.String())
if boundCh != nil {
select {
case boundCh <- addr:
case <-time.After(100 * time.Millisecond):
}
}
s.lsn = listener // allow shutdown
if s.cfg.HTTPConnectRequired {
mux := http.NewServeMux()
mux.Handle(DefaultRPCPath, s) // calls back to Server.ServeHTTP(),
httpsrv := &http.Server{Handler: mux}
httpsrv.Serve(listener) // calls Server.serveConn(conn) with each new connection.
return
}
acceptAgain:
for {
select {
case <-s.halt.ReqStop.Chan:
return
default:
}
// Accept a new connection
conn, err := listener.Accept()
if err != nil {
// If it is a shutdown request, the the s.halt.ReqStop.Chan will return for us.
if strings.Contains(err.Error(), "use of closed network connection") {
continue acceptAgain // fullRestart
}
alwaysPrintf("Failed to accept connection: %v", err)
continue acceptAgain
}
//vv("server accepted connection from %v", conn.RemoteAddr())
if false {
// another rpc system did this:
if tc, ok := conn.(*net.TCPConn); ok {
theTCPKeepAlivePeriod := time.Minute * 3
if theTCPKeepAlivePeriod > 0 {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(theTCPKeepAlivePeriod)
// For *only* 10 seconds, the OS will try to send
// data even after we close. The default is longer, wethinks.
tc.SetLinger(10)
}
}
}
s.serveConn(conn)
}
}
// can be called after HTTP CONNECT hijack too; see Server.ServeHTTP().
func (s *Server) serveConn(conn net.Conn) {
//vv("tcp only server: s.cfg.encryptPSK = %v", s.cfg.encryptPSK)
var randomSymmetricSessKey [32]byte
var cliEphemPub []byte
var srvEphemPub []byte
var cliStaticPub ed25519.PublicKey
if !s.cfg.TCPonly_no_TLS && s.cfg.encryptPSK {
var err error
switch {
case useVerifiedHandshake:
randomSymmetricSessKey, cliEphemPub, srvEphemPub, cliStaticPub, err =
symmetricServerVerifiedHandshake(conn, s.cfg.preSharedKey, s.creds)
case wantForwardSecrecy:
randomSymmetricSessKey, cliEphemPub, srvEphemPub, cliStaticPub, err =
symmetricServerHandshake(conn, s.cfg.preSharedKey, s.creds)
case mixRandomnessWithPSK:
randomSymmetricSessKey, err = simpleSymmetricServerHandshake(conn, s.cfg.preSharedKey, s.creds)
default:
randomSymmetricSessKey = s.cfg.preSharedKey
}
if err != nil {
alwaysPrintf("tcp/tls failed to athenticate: '%v'", err)
//continue acceptAgain
return
}
}
pair := s.newRWPair(conn)
pair.randomSymmetricSessKeyFromPreSharedKey = randomSymmetricSessKey
pair.cliEphemPub = cliEphemPub
pair.srvEphemPub = srvEphemPub
pair.cliStaticPub = cliStaticPub
go pair.runSendLoop(conn)
go pair.runReadLoop(conn)
}
func (s *Server) handleTLSConnection(conn *tls.Conn) {
//vv("top of handleTLSConnection()")
// Perform the handshake; it is lazy on first Read/Write, and
// we want to check the certifcates from the client; we
// won't get them until the handshake happens. From the docs:
//
// Handshake runs the client or server handshake protocol if it has not yet been run.
//
// Most uses of this package need not call Handshake explicitly:
// the first Conn.Read or Conn.Write will call it automatically.
//
// For control over canceling or setting a timeout on a handshake,
// use Conn.HandshakeContext or the Dialer's DialContext method instead.
// Create a context with a timeout for the handshake, since
// it can hang.
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
_ = ctx
defer cancel()
// ctx gives us a timeout. Otherwise, one must set a deadline
// on the conn to avoid an infinite hang during handshake.
if err := conn.HandshakeContext(ctx); err != nil {
alwaysPrintf("tlsConn.Handshake() failed: '%v'", err)
return
}
knownHostsPath := "known_client_keys"
connState := conn.ConnectionState()
raddr := conn.RemoteAddr()
remoteAddr := strings.TrimSpace(raddr.String())
if !s.cfg.SkipVerifyKeys {
// NB only ed25519 keys are permitted, any others will result
// in an immediate error
good, bad, wasNew, err := hostKeyVerifies(knownHostsPath, &connState, remoteAddr)
_ = wasNew
_ = bad
if err != nil && len(good) == 0 {
//fmt.Fprintf(os.Stderr, "key failed list:'%#v': '%v'\n", bad, err)
return
}
if err != nil {
//vv("hostKeyVerifies returned error '%v' for remote addr '%v'", err, remoteAddr)
return
}
const showAcceptedIdentities = false
if showAcceptedIdentities {
for i := range good {
alwaysPrintf("accepted identity for client: '%v' (was new: %v)\n", good[i], wasNew)
}
}
}
// end of handleTLSConnection()
s.serveConn(conn)
}
func (s *rwPair) runSendLoop(conn net.Conn) {
defer func() {
s.Server.deletePair(s)
s.halt.ReqStop.Close()
s.halt.Done.Close()
}()
sendLoopGoroNum := GoroNumber()
_ = sendLoopGoroNum
//vv("srv.go rwPair.runSendLoop(cli '%v' -> '%v' srv) sendLoopGoroNum = [%v] for pairID = '%v'", remote(conn), local(conn), sendLoopGoroNum, s.pairID)
symkey := s.cfg.preSharedKey
if s.cfg.encryptPSK {
s.mut.Lock()
symkey = s.randomSymmetricSessKeyFromPreSharedKey
s.mut.Unlock()
}
//vv("about to make a newBlabber for server send loop; s.Server.cfg = %p", s.Server.cfg)
w := newBlabber("server send loop", symkey, conn, s.Server.cfg.encryptPSK, maxMessage, true, s.Server.cfg, s, nil)
// implement ServerSendKeepAlive
var lastPing time.Time
var doPing bool
var pingEvery time.Duration
var pingWakeCh <-chan time.Time
var keepAliveWriteTimeout time.Duration // := s.cfg.WriteTimeout
if s.cfg.ServerSendKeepAlive > 0 {
doPing = true
pingEvery = s.cfg.ServerSendKeepAlive
lastPing = time.Now()
pingWakeCh = time.After(pingEvery)
// keep the ping attempts to a minimum to keep this loop lively.
if keepAliveWriteTimeout == 0 || keepAliveWriteTimeout > 10*time.Second {
keepAliveWriteTimeout = 2 * time.Second
}
}
for {
if doPing {
now := time.Now()
if time.Since(lastPing) > pingEvery {
err := w.sendMessage(conn, keepAliveMsg, &keepAliveWriteTimeout)
//vv("srv sent rpc25519 keep alive. err='%v'; keepAliveWriteTimeout='%v'", err, keepAliveWriteTimeout)
if err != nil {
alwaysPrintf("server had problem sending keep alive: '%v'", err)
}
lastPing = now
pingWakeCh = time.After(pingEvery)
} else {
pingWakeCh = time.After(lastPing.Add(pingEvery).Sub(now))
}
}
select {
case <-pingWakeCh:
// check and send above.
continue
case msg := <-s.SendCh:
//vv("srv %v (%v) sendLoop got from s.SendCh, sending msg.HDR = '%v'", s.Server.name, s.from, msg.HDR.String())
real, ok := s.Server.unNAT.Get(msg.HDR.To)
if ok && real != msg.HDR.To {
vv("unNAT replacing msg.HDR.To '%v' -> '%v'", msg.HDR.To, real)
msg.HDR.To = real
}
//err := w.sendMessage(conn, msg, &s.cfg.WriteTimeout)
err := w.sendMessage(conn, msg, nil)
if err != nil {
// notify any short-time-waiting server push user.
// This is super useful to let goq retry jobs quickly.
msg.LocalErr = err
if msg.DoneCh != nil {
msg.DoneCh.Close()
}
alwaysPrintf("sendMessage got err = '%v'; on trying to send Seqno=%v", err, msg.HDR.Seqno)
// just let user try again?
} else {
// tell caller there was no error.
if msg.DoneCh != nil {
msg.DoneCh.Close()
}
lastPing = time.Now() // no need for ping
}
case <-s.halt.ReqStop.Chan:
return
}
}
}
func (s *rwPair) runReadLoop(conn net.Conn) {
ctx, canc := context.WithCancel(context.Background())
defer func() {
//vv("rpc25519.Server: runReadLoop shutting down for local conn = '%v'", conn.LocalAddr())
canc()
s.halt.ReqStop.Close()
s.halt.Done.Close()
conn.Close() // just the one, let other clients continue.
}()
localAddr := local(conn)
remoteAddr := remote(conn)
symkey := s.cfg.preSharedKey
if s.cfg.encryptPSK {
s.mut.Lock()
symkey = s.randomSymmetricSessKeyFromPreSharedKey
s.mut.Unlock()
}
//vv("about to make a newBlabber for server read loop; s.Server.cfg = %p", s.Server.cfg)
w := newBlabber("server read loop", symkey, conn, s.Server.cfg.encryptPSK, maxMessage, true, s.Server.cfg, s, nil)
for {
select {
case <-s.halt.ReqStop.Chan:
//vv("s.halt.ReqStop.Chan requested!")
return
default:
}
// It does not work to use a timeout with readMessage.
// Under load, we will get
// partial reads which are then difficult to
// recover from, because we have not tracked
// how much of the rest of the incoming
// stream needs to be discarded!
// So: always read without a timeout. Update:
// we've eliminated the readTimeout parameter all together
// to disallow it.
req, err := w.readMessage(conn)
if err == io.EOF {
//vv("server sees io.EOF from receiveMessage")
// close of socket before read of full message.
// shutdown this connection or we'll just
// spin here at 500% cpu.
return
}
if err != nil {
//vv("srv read loop err = '%v'", err)
r := err.Error()
if strings.Contains(r, "remote error: tls: bad certificate") {
//vv("ignoring client connection with bad TLS cert.")
continue
}
if strings.Contains(r, "i/o timeout") || strings.Contains(r, "deadline exceeded") {
//if strings.Contains(r, "deadline exceeded") {
// just our readTimeout happening, so we can poll on shutting down, above.
continue
}
if strings.Contains(r, "use of closed network connection") {
return // shutting down
}
// "timeout: no recent network activity" should only
// be seen on disconnection of a client because we
// have a 10 second heartbeat going.
if strings.Contains(r, "timeout: no recent network activity") {
// We should never see this because of our app level keep-alives.
// If we do, then it means the client really went down.
//vv("quic server read loop exiting on '%v'", err)
return
}
if strings.Contains(r, "Application error 0x0 (remote)") {
// normal message from active client who knew they were
// closing down and politely let us know too. Otherwise
// we just have to time out.
return
}
alwaysPrintf("ugh. error from remote %v: %v", conn.RemoteAddr(), err)
return
}
//vv("srv read loop sees req = '%v'", req.String())
if req.HDR.From != "" {
s.Server.unNAT.Set(req.HDR.From, remoteAddr)
}
if req.HDR.To != "" {
s.Server.unNAT.Set(req.HDR.To, localAddr)
}
switch req.HDR.Typ {
case CallKeepAlive:
//vv("srv read loop got an rpc25519 keep alive.")
continue
case CallPeerStart, CallPeerStartCircuit, CallPeerStartCircuitTakeToID:
err := s.Server.PeerAPI.bootstrapCircuit(notClient, req, ctx, s.SendCh)
if err != nil {
// only error is on shutdown request received.
return
}
continue
}
if s.Server.notifies.handleReply_to_CallID_ToPeerID(notClient, ctx, req) {
//vv("server side (%v) notifies says we are done after "+
// "req = '%v'", s.from, req.HDR.String())
continue
} else {
//vv("server side (%v) notifies says we are NOT done after "+
// "req = '%v'", s.from, req.HDR.String())
}
if req.HDR.Typ == CallPeerTraffic ||
req.HDR.Typ == CallPeerError {
bad := fmt.Sprintf("srv readLoop: Peer traffic should never get here!"+
" req.HDR='%v'", req.HDR.String())
vv(bad)
panic(bad)
}
// Idea: send the job to the central work queue, so
// we service jobs fairly in FIFO order.
// Update: turns out this didn't really matter.
// So we got rid of the work queue.
job := &job{req: req, conn: conn, pair: s, w: w}
s.handleIncomingMessage(ctx, req, job)
}
}
func (pair *rwPair) handleIncomingMessage(ctx context.Context, req *Message, job *job) {
switch req.HDR.Typ {
// We destroy the FIFO of a stream if we don't
// queue up the stream messages here, exactly in
// the order we received them.
case CallUploadBegin, CallRequestBistreaming:
// early but sequential setup, we'll revist
// this again for CallUploadBegin to add ctx and
// cancel func. The important thing is that
// we queue up req in the stream channel now.
pair.Server.registerInFlightCallToCancel(req, nil, nil)
// fallthrough and processWork to handle the rest;
// we just needed to do this beforehand to make sure
// we got FIFO order of incoming Messages.
// Once we start a goroutine for processWork,
// FIFO order will be lost.
case CallUploadMore, CallUploadEnd:
pair.Server.handleUploadParts(req)
return
}
// Workers requesting jobs can keep calls open for
// minutes or hours or days; so we cannot just have
// just use this readLoop goroutine to process
// call sequentially; we cannot block here: this
// has to be in a new goroutine.
go pair.Server.processWork(job)
}
// Client and Server both use (their own copies) to keep code in sync.
type notifies struct {
// use mapIDtoChan instead of mutex in notifies, to avoid
// deadlocks with the cli readLoop and the peer pump both accessing,
// while the cli readLoop wants the pump to service the
// channel send it got from the notifies map in the first place;
// while the pump wants to unregister a shutdown peerID chan.
isCli bool
notifyOnReadCallIDMap *mapIDtoChan
notifyOnErrorCallIDMap *mapIDtoChan
notifyOnReadToPeerIDMap *mapIDtoChan
notifyOnErrorToPeerIDMap *mapIDtoChan
}
// for notifies to avoid long holds of a mutex, we use this instead.
// See also mutmap.go, a later generic version.
type mapIDtoChan struct {
mut sync.RWMutex
m map[string]chan *Message
}
func newMapIDtoChan() *mapIDtoChan {
return &mapIDtoChan{
m: make(map[string]chan *Message),
}
}
func (m *mapIDtoChan) get(id string) (ch chan *Message, ok bool) {
m.mut.RLock()
ch, ok = m.m[id]
m.mut.RUnlock()
return
}
func (m *mapIDtoChan) set(id string, ch chan *Message) {
m.mut.Lock()
m.m[id] = ch
m.mut.Unlock()
}
func (m *mapIDtoChan) del(id string) {
m.mut.Lock()
delete(m.m, id)
m.mut.Unlock()
}
func (m *mapIDtoChan) clear() {
m.mut.Lock()
clear(m.m)
m.mut.Unlock()
}
func newNotifies(isCli bool) *notifies {
return ¬ifies{
notifyOnReadCallIDMap: newMapIDtoChan(),
notifyOnErrorCallIDMap: newMapIDtoChan(),
notifyOnReadToPeerIDMap: newMapIDtoChan(),
notifyOnErrorToPeerIDMap: newMapIDtoChan(),
isCli: isCli,
}
}
// For Peer/Object systems, ToPeerID get priority over CallID
// to allow such systems to implement custom message
// types. An example is the Fragment/Peer/Circuit system.
func (c *notifies) handleReply_to_CallID_ToPeerID(isCli bool, ctx context.Context, msg *Message) (done bool) {
switch msg.HDR.Typ {
case CallError, CallPeerError:
// not CallPeerFromIsShutdown per pump handling it on ReadsIn
//alwaysPrintf("error type seen!: '%v'", msg.HDR.Typ.String())
// give ToPeerID priority
if msg.HDR.ToPeerID != "" {
wantsErrObj, ok := c.notifyOnErrorToPeerIDMap.get(msg.HDR.ToPeerID)
if ok {
select {
case wantsErrObj <- msg:
//vv("notified a channel! %p for CallID '%v'", wantsErr, msg.HDR.ToPeerID)
case <-ctx.Done():
// think we want backpressure and to make sure the peer goro keep up.
//default:
// panic(fmt.Sprintf("Should never happen b/c the "+
// "channels must be buffered!: could not send to "+
// "whoCh from notifyOnErrorToPeerIDMap; for ToPeerID = %v.",
// msg.HDR.ToPeerID))
}
return true // only send to ToPeerID, not CallID too.
}
}
wantsErr, ok := c.notifyOnErrorCallIDMap.get(msg.HDR.CallID)
if ok {
select {
case wantsErr <- msg:
//vv("notified a channel! %p for CallID '%v'", wantsErr, msg.HDR.CallID)
case <-ctx.Done():
//default:
// panic(fmt.Sprintf("Should never happen b/c the "+
// "channels must be buffered!: could not send to "+
// "whoCh from notifyOnErrorCallIDMap; for CallID = %v.",
// msg.HDR.CallID))
}
return true
}
} // end CallError
if msg.HDR.ToPeerID != "" {
wantsToPeerID, ok := c.notifyOnReadToPeerIDMap.get(msg.HDR.ToPeerID)
//vv("have ToPeerID msg = '%v'; ok='%v'", msg.HDR.String(), ok)
if ok {
select {
case wantsToPeerID <- msg:
//vv("sent msg to wantsToPeerID chan!")
case <-ctx.Done():
return
case <-ctx.Done():
}
return true // only send to ToPeerID, priority over CallID.
}
}
wantsCallID, ok := c.notifyOnReadCallIDMap.get(msg.HDR.CallID)
//vv("isCli=%v, c.notifyOnReadCallIDMap[callID='%v'] -> %p, ok=%v", c.isCli, msg.HDR.CallID, wantsCallID, ok)
if ok {
select {
case wantsCallID <- msg:
//vv("isCli = %v; notifies.handleReply notified registered channel for callID = '%v'", isCli, msg.HDR.CallID)
case <-ctx.Done():
}
return true
}
return false
}
type job struct {
req *Message
conn net.Conn
pair *rwPair
w *blabber
}
// PRE: only req.HDR.Typ in {CallUploadMore, CallUploadEnd}
// should be calling here.
func (s *Server) handleUploadParts(req *Message) {
callID := req.HDR.CallID
s.inflight.mut.Lock()
cc, ok := s.inflight.activeCalls[callID]
var part int64
_ = part
if ok {
// track progress
part = req.HDR.StreamPart
cc.lastStreamPart = part
}
s.inflight.mut.Unlock()
if !ok {
alwaysPrintf("Warning: dropping a StreamPart: '%s' because no handler "+
"registered/inflight. This is highly un-expected. "+
"However, it might mean the server func exited with "+
"an error but the client has not caught up with "+
"that yet. hdr='%v'", req.HDR.Typ, req.HDR.String())
return
}
// be aware that we are on the read-loop goroutine stack here.
// If we are stalled, we will stall all reads on the server.
// If we hang, the server becomes unresponsive.
//
// BUT! This is probably good, because we *want* back-pressure
// when under load. If the streamer cannot take any more
// messages, then we don't want to read any more off the wire either.
// Just wait until a slot opens up.
select {
case cc.streamCh <- req:
//vv("handleUploadParts: cc.StreamCh: sent req with part %v", part)
case <-s.halt.ReqStop.Chan:
return
// don't time out here! allow for back-pressure on
// the network read, which can be transmitted across
// TCP to slow the sending side down.
}
}
func (s *Server) processWork(job *job) {
var callme1 OneWayFunc
var callme2 TwoWayFunc
var callmeServerSendsDownloadFunc ServerSendsDownloadFunc
var callmeUploadReaderFunc UploadReaderFunc
var callmeBi BistreamFunc
foundCallback1 := false
foundCallback2 := false
foundServerSendsDownload := false
foundBistream := false
foundUploader := false
req := job.req
//vv("processWork got job: req.HDR='%v'", req.HDR.String())
if req.HDR.Typ == CallCancelPrevious {
s.cancelCallID(req.HDR.CallID)
return
}
//vv("processWork() sees req.HDR = %v", req.HDR.String())
conn := job.conn
pair := job.pair
w := job.w
req.HDR.Nc = conn
if req.HDR.Typ == CallNetRPC {
//vv("have IsNetRPC call: '%v'", req.HDR.ServiceName)
err := pair.callBridgeNetRpc(req, job)
if err != nil {
alwaysPrintf("callBridgeNetRpc errored out: '%v'", err)
}
return // continue
}
switch req.HDR.Typ {
case CallRPC:
back, ok := s.callme2map.Get(req.HDR.ServiceName)
if ok {
callme2 = back
foundCallback2 = true
} else {
s.respondToReqWithError(req, job, fmt.Sprintf("error! CallRPC begin received but no server side upcall registered for req.HDR.ServiceName='%v'; req.HDR.CallID='%v'", req.HDR.ServiceName, req.HDR.CallID))
return
}
case CallRequestBistreaming:
back, ok := s.callmeBistreamMap.Get(req.HDR.ServiceName)
if ok {
callmeBi = back
foundBistream = true
//vv("foundBistream true!")
} else {
s.respondToReqWithError(req, job, fmt.Sprintf("error! CallRequestBistreaming received but no server side upcall registered for req.HDR.ServiceName='%v'; req.HDR.CallID='%v'", req.HDR.ServiceName, req.HDR.CallID))
return
}
case CallRequestDownload:
back, ok := s.callmeServerSendsDownloadMap.Get(req.HDR.ServiceName)
if ok {
callmeServerSendsDownloadFunc = back
foundServerSendsDownload = true
} else {
s.respondToReqWithError(req, job, fmt.Sprintf("error! CallRequestDownload received but no server side upcall registered for req.HDR.ServiceName='%v'; req.HDR.CallID='%v'", req.HDR.ServiceName, req.HDR.CallID))
return
}
case CallUploadBegin:
uploader, ok := s.callmeUploadReaderMap.Get(req.HDR.ServiceName)
if !ok {
// nothing to do
// send back a CallError
s.respondToReqWithError(req, job, fmt.Sprintf("error! CallUploadBegin stream begin received but no registered stream upload reader available on the server. req.HDR.ServiceName='%v'; req.HDR.CallID='%v'", req.HDR.ServiceName, req.HDR.CallID))
return
}
foundUploader = true
callmeUploadReaderFunc = uploader
case CallUploadMore, CallUploadEnd:
panic("cannot see these here, must for FIFO of the stream be called from the readloop")
case CallOneWay:
back, ok := s.callme1map.Get(req.HDR.ServiceName)
if ok {
callme1 = back
foundCallback1 = true
} else {
s.respondToReqWithError(req, job, fmt.Sprintf("error! CallOneWay received but no server side callme1map upcall registered for ServiceName='%v'; from req.HDR='%v'", req.HDR.ServiceName, req.HDR.String()))
return
}
}
if !foundCallback1 &&
!foundCallback2 &&
!foundServerSendsDownload &&
!foundBistream &&
!foundUploader {
//vv("warning! no callbacks found for req = '%v'", req)
return
}
if foundCallback1 {
callme1(req)
return
}
// handle:
//
// foundCallback2
// foundServerSendsDownload
// foundBistream
// foundUploader
//vv("foundCallback2 true, req.HDR = '%v'", req.HDR)
//vv("req.Nc local = '%v', remote = '%v'", local(req.Nc), remote(req.Nc))
//vv("stream local = '%v', remote = '%v'", local(stream), remote(stream))
//vv("conn local = '%v', remote = '%v'", local(conn), remote(conn))
reply := s.getMessage()
// enforce these are the same.
replySeqno := req.HDR.Seqno
reqCallID := req.HDR.CallID
serviceName := req.HDR.ServiceName
// allow user to change Subject
reply.HDR.Subject = req.HDR.Subject
// allow cancellation of inflight calls.
ctx0 := context.Background()
var cancelFunc context.CancelFunc
var deadline time.Time
if !req.HDR.Deadline.IsZero() {
//vv("server side sees deadline set on request HDR: '%v'", req.HDR.Deadline)
deadline = req.HDR.Deadline
ctx0, cancelFunc = context.WithDeadline(ctx0, deadline)
} else {
//vv("server side sees NO deadline")
ctx0, cancelFunc = context.WithCancel(ctx0)
}
defer cancelFunc()
ctx := ContextWithHDR(ctx0, &req.HDR)
s.registerInFlightCallToCancel(req, cancelFunc, ctx)
defer s.noLongerInFlight(reqCallID)
req.HDR.Ctx = ctx
var err error
switch {
case foundCallback2:
err = callme2(req, reply)
//err = callme2(ctx, req, reply) // add ctx?
case foundServerSendsDownload:
help := s.newServerSendDownloadHelper(ctx, job)
err = callmeServerSendsDownloadFunc(s, ctx, req, help.sendDownloadPart, reply)
case foundBistream:
help := s.newServerSendDownloadHelper(ctx, job)
err = callmeBi(s, ctx, req, req.HDR.streamCh, help.sendDownloadPart, reply)
case foundUploader:
err = pair.beginReadStream(ctx, callmeUploadReaderFunc, req, reply)
}
if err != nil {
reply.JobErrs = err.Error()
}
// don't read from req now, just in case callme2 messed with it.
reply.HDR.Created = time.Now()
reply.HDR.Serial = issueSerial()