-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
2429 lines (2108 loc) · 71.7 KB
/
cli.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
// cli.go: simple TCP client, with TLS encryption.
import (
"bufio"
"bytes"
"context"
"crypto/ed25519"
"crypto/hmac"
cryrand "crypto/rand"
"crypto/sha256"
"crypto/tls"
"errors"
"fmt"
"golang.org/x/crypto/hkdf"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/glycerine/greenpack/msgp"
"github.com/glycerine/idem"
"github.com/glycerine/ipaddr"
"github.com/glycerine/loquet"
"github.com/glycerine/rpc25519/selfcert"
"github.com/quic-go/quic-go"
)
var _ = cryrand.Read
const DefaultUseCompression = true
const DefaultUseCompressAlgo = "s2" // see magic7.go
type localRemoteAddr interface {
RemoteAddr() net.Addr
LocalAddr() net.Addr
}
type uConnLR interface {
uConn
localRemoteAddr
}
var _ quic.Connection
var sep = string(os.PathSeparator)
// eg. serverAddr = "localhost:8443"
// serverAddr = "192.168.254.151:8443"
func (c *Client) runClientMain(serverAddr string, tcp_only bool, certPath string) {
defer func() {
c.halt.ReqStop.Close()
c.halt.Done.Close()
c.mut.Lock()
doClean := c.seenNetRPCCalls
c.mut.Unlock()
if doClean {
c.netRpcShutdownCleanup(ErrShutdown())
}
}()
dirCerts := GetCertsDir()
c.cfg.checkPreSharedKey("client")
sslCA := fixSlash(dirCerts + "/ca.crt") // path to CA cert
keyName := "client"
if c.cfg.ClientKeyPairName != "" {
keyName = c.cfg.ClientKeyPairName
}
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
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 config *tls.Config
var creds *selfcert.Creds
if !tcp_only {
// handle pass-phrase protected certs/client.key
var err2 error
config, creds, err2 = selfcert.LoadNodeTLSConfigProtected(false, sslCA, sslCert, sslCertKey)
//config, err2 := loadClientTLSConfig(embedded, sslCA, sslCert, sslCertKey)
if err2 != nil {
c.err = fmt.Errorf("error on LoadClientTLSConfig()'%v'", err2)
panic(c.err)
}
c.creds = creds
}
// since TCP may verify creds now too, only run TCP client *after* loading creds.
if tcp_only {
c.runClientTCP(serverAddr)
return
}
// without this ServerName assignment, we used to get (before gen.sh put in SANs using openssl-san.cnf)
// 2019/01/04 09:36:18 failed to call: x509: cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs
//
// update:
// ServerName set to "localhost" is still needed in order to run the server on a different TCP host.
// otherwise we get:
// 2024/10/04 21:27:50 Failed to connect to server: tls: failed to verify certificate: x509: certificate is valid for 127.0.0.1, not 192.168.254.151
//
// docs:
// "ServerName is the value of the Server Name Indication extension sent by
// the client. It's available both on the server and on the client side."
// See also: https://en.wikipedia.org/wiki/Server_Name_Indication
// and https://www.ietf.org/archive/id/draft-ietf-tls-esni-18.html for ECH
//
// Basically this lets the client say which cert they want to talk to,
// oblivious to whatever IP that the host is on, or the domain name of that
// IP alone.
config.ServerName = "localhost"
if c.cfg.SkipVerifyKeys {
config.InsecureSkipVerify = true // true would be insecure
}
if c.cfg.UseQUIC {
if c.cfg.TCPonly_no_TLS {
panic("cannot have both UseQUIC and TCPonly_no_TLS true")
}
localHostPort := c.cfg.ClientHostPort
if localHostPort == "" {
localHost, err := ipaddr.LocalAddrMatching(serverAddr)
panicOn(err)
//vv("localHost = '%v', matched to quicServerAddr = '%v'", localHost, serverAddr)
localHostPort = localHost + ":0" // client can pick any port
}
c.runQUIC(localHostPort, serverAddr, config)
return
}
// Dial the server, with a timeout
ctx := context.Background()
if c.cfg.ConnectTimeout > 0 {
// Create a context with a timeout
ctx2, cancel := context.WithTimeout(ctx, c.cfg.ConnectTimeout)
defer cancel() // Ensure cancel is called to release resources
ctx = ctx2
}
// Use tls.Dialer to dial with the context
d := &tls.Dialer{
NetDialer: &net.Dialer{},
Config: config,
}
// Dial the server, with a timeout.
nconn, err := d.DialContext(ctx, "tcp", serverAddr)
if err != nil {
c.err = err
c.connected <- fmt.Errorf("error: client local: '%v' failed to "+
"connect to server: '%v'", c.cfg.ClientHostPort, err)
alwaysPrintf("error: client from '%v' failed to connect to server: %v", c.cfg.ClientHostPort, err)
return
}
c.isTLS = true
// do this before signaling on c.connected, else tests will race and panic
// not having a connection
c.conn = nconn
conn := nconn.(*tls.Conn) // docs say this is for sure.
defer conn.Close() // in runClientMain() here.
c.setLocalAddr(conn)
// only signal ready once SetLocalAddr() is done, else submitter can crash.
c.connected <- nil
//alwaysPrintf("connected to server %s", serverAddr)
// possible to check host keys for TOFU like SSH does,
// but be aware that if they have the contents of
// certs/node.key that has the server key,
// they can use that to impersonate the server and MITM the connection.
// So protect both node.key and client.key from
// distribution.
knownHostsPath := "known_server_keys"
// return error on host-key change.
connState := conn.ConnectionState()
raddr := conn.RemoteAddr()
remoteAddr := strings.TrimSpace(raddr.String())
if !c.cfg.SkipVerifyKeys {
good, bad, wasNew, err := hostKeyVerifies(knownHostsPath, &connState, remoteAddr)
_ = good
_ = wasNew
_ = bad
if err != nil {
fmt.Fprintf(os.Stderr, "hostKeyVerifies has failed: key failed list:'%#v': '%v'\n", bad, err)
return
}
//for i := range good {
// vv("accepted identity for server: '%v' (was new: %v)\n", good[i], wasNew)
//}
}
err = c.setupPSK(conn)
if err != nil {
alwaysPrintf("setupPSK error: '%v'", err)
return
}
cpair := &cliPairState{}
go c.runSendLoop(conn, cpair)
c.runReadLoop(conn, cpair)
}
func (c *Client) runClientTCP(serverAddr string) {
// Dial the server
conn, err := net.Dial("tcp", serverAddr)
if err != nil {
c.err = err
c.connected <- err
alwaysPrintf("Failed to connect to server: %v", err)
return
}
c.setLocalAddr(conn)
c.isTLS = false
c.conn = conn
c.connected <- nil
defer conn.Close() // in runClientTCP() here.
//alwaysPrintf("connected to server %s", serverAddr)
if c.cfg.HTTPConnectRequired {
io.WriteString(conn, "CONNECT "+DefaultRPCPath+" HTTP/1.0\n\n")
// Require successful HTTP response
// before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
if err != nil || resp.Status != connectedToGoRPC {
alwaysPrintf("unexpected HTTP response: '%v'; err = '%v'", resp.Status, err)
return // does the conn.Close() above in the defer.
}
//vv("resp.Status = '%v'", resp.Status)
}
err = c.setupPSK(conn)
if err != nil {
alwaysPrintf("setupPSK error: '%v'", err)
return
}
cpair := &cliPairState{} // track the last compression used, so we can echo it.
go c.runSendLoop(conn, cpair)
c.runReadLoop(conn, cpair)
}
type cliPairState struct {
lastReadMagic7 atomic.Int64
}
func (c *Client) runReadLoop(conn net.Conn, cpair *cliPairState) {
var err error
ctx, canc := context.WithCancel(context.Background())
defer func() {
//vv("client runReadLoop exiting, last err = '%v'", err)
canc()
c.halt.ReqStop.Close()
c.halt.Done.Close()
}()
symkey := c.cfg.preSharedKey
if c.cfg.encryptPSK {
c.mut.Lock()
symkey = c.randomSymmetricSessKeyFromPreSharedKey
c.mut.Unlock()
}
cliLocalAddr := c.LocalAddr()
_ = cliLocalAddr
//vv("about to make a newBlabber for client read loop; c.cfg = %p ", c.cfg)
w := newBlabber("client read loop", symkey, conn, c.cfg.encryptPSK, maxMessage, false, c.cfg, nil, cpair)
readTimeout := time.Millisecond * 100
_ = readTimeout
var msg *Message
for {
// poll for: shutting down?
select {
case <-c.halt.ReqStop.Chan:
return
default:
}
// Receive a message
// Does not work to use a timeout: 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. In fact
// we've eliminated the parameter.
msg, err = w.readMessage(conn)
if err != nil {
if msg != nil {
panic("should not have a message if error back!")
}
r := err.Error()
// under TCP: its normal to see 'read tcp y.y.y.y:59705->x.x.x.x:9999: i/o timeout'
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
}
//vv("err = '%v'", err)
if strings.Contains(r, "timeout: no recent network activity") {
// we will hard spin the CPU to 100% (after disconnect)
// if we don't exit on this.
//vv("cli read loop exiting on '%v'", err)
return
}
// quic server specific
if strings.Contains(r, "Application error 0x0 (remote)") {
//vv("normal quic shutdown.")
return
}
if strings.Contains(r, "server shutdown") {
//vv("client sees quic server shutdown")
return
}
if strings.Contains(r, "use of closed network connection") {
return
}
if strings.Contains(r, "connection reset by peer") {
return
}
if strings.Contains(r, "Application error 0x0 (local)") {
return
}
if r == "EOF" && msg == nil {
//vv("cli readLoop sees EOF, exiting.")
return
}
if err == io.EOF && msg == nil {
return
}
//vvv("ignore err = '%v'; msg = '%v'", err, msg)
}
if msg == nil {
continue
}
if msg.HDR.Typ == CallKeepAlive {
//vv("client got an rpc25519 keep alive.")
// nothing more to do, the keepalive just keeps the
// middle boxes on the internet from dropping
// our network connection.
continue
}
msg.HDR.LocalRecvTm = time.Now()
seqno := msg.HDR.Seqno
//vv("client %v (cliLocalAddr='%v') received message with seqno=%v, msg.HDR='%v'", c.name, cliLocalAddr, seqno, msg.HDR.String())
// special case to bootstrap up a peer by remote
// request, since no other way to register stuff
// on the client, and this is a pretty unique call
// anyway. This is like the Client acting like
// a server and starting up a peer service.
switch msg.HDR.Typ {
case CallPeerStart, CallPeerStartCircuit, CallPeerStartCircuitTakeToID:
err := c.PeerAPI.bootstrapCircuit(yesIsClient, msg, ctx, c.oneWayCh)
if err != nil {
// only error is on shutdown request received.
return
}
continue
}
if c.notifies.handleReply_to_CallID_ToPeerID(true, ctx, msg) {
//vv("client side (%v) notifies says we are done after msg = '%v'", cliLocalAddr, msg.HDR.String())
continue
} else {
//vv("client side (%v) notifies says we are NOT done after msg = '%v'", cliLocalAddr, msg.HDR.String())
}
if msg.HDR.Typ == CallPeerTraffic ||
msg.HDR.Typ == CallPeerError {
bad := fmt.Sprintf("cli readLoop: Peer traffic should never get here! msg.HDR='%v'", msg.HDR.String())
alwaysPrintf(bad)
panic(bad)
}
// protect map access. Be sure to Unlock if you "continue" below.
c.mut.Lock()
whoCh, waiting := c.notifyOnce[seqno]
//vv("notifyOnce waiting = %v for seqno %v", waiting, seqno)
if waiting {
delete(c.notifyOnce, seqno)
whoCh.CloseWith(msg)
} else {
//vv("notifyOnce: nobody was waiting for seqno = %v", seqno)
//vv("len c.notifyOnRead = %v", len(c.notifyOnRead))
// assume the round-trip "calls" should be consumed,
// and not repeated here to client listeners who want events???
// trying to match what other RPC systems do.
for _, ch := range c.notifyOnRead {
select {
case ch <- msg:
//vv("client: %v: yay. sent on notifyOnRead channel: %p", c.name, ch)
default:
//vv("could not send to notifyOnRead channel!")
}
}
}
c.mut.Unlock()
}
}
func (c *Client) runSendLoop(conn net.Conn, cpair *cliPairState) {
defer func() {
//vv("client runSendLoop shutting down")
c.halt.ReqStop.Close()
c.halt.Done.Close()
}()
symkey := c.cfg.preSharedKey
if c.cfg.encryptPSK {
c.mut.Lock()
symkey = c.randomSymmetricSessKeyFromPreSharedKey
c.mut.Unlock()
}
//vv("about to make a newBlabber for client send loop; c.cfg = %p ", c.cfg)
w := newBlabber("client send loop", symkey, conn, c.cfg.encryptPSK, maxMessage, false, c.cfg, nil, cpair)
// PRE: Message.DoneCh must be buffered at least 1, so
// our logic below does not have to deal with ever blocking.
// implement ClientSendKeepAlive
var lastPing time.Time
var doPing bool
var pingEvery time.Duration
var pingWakeCh <-chan time.Time
var keepAliveWriteTimeout time.Duration // := c.cfg.WriteTimeout
if c.cfg.ClientSendKeepAlive > 0 {
//vv("client side pings are on")
doPing = true
pingEvery = c.cfg.ClientSendKeepAlive
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("cli sent rpc25519 keep alive. err='%v'; keepAliveWriteTimeout='%v'", err, keepAliveWriteTimeout)
if err != nil {
alwaysPrintf("client had problem sending keep alive: '%v'", err)
}
lastPing = now
pingWakeCh = time.After(pingEvery)
} else {
// Pre go1.23 this would have leaked timer memory, but not now.
// https://pkg.go.dev/time#After says
// Before Go 1.23, this documentation warned that the
// underlying Timer would not be recovered by the garbage
// collector until the timer fired, and that if efficiency
// was a concern, code should use NewTimer instead and call
// Timer.Stop if the timer is no longer needed. As of Go 1.23,
// the garbage collector can recover unreferenced,
// unstopped timers. There is no reason to prefer NewTimer
// when After will do.
// If using < go1.23, see
// https://medium.com/@oboturov/golang-time-after-is-not-garbage-collected-4cbc94740082
// for a memory leak story.
pingWakeCh = time.After(lastPing.Add(pingEvery).Sub(now))
}
}
select {
case <-pingWakeCh:
// check and send above.
continue
case <-c.halt.ReqStop.Chan:
return
case msg := <-c.oneWayCh:
// one-way now use seqno too, but may already be set.
if msg.HDR.Seqno == 0 {
seqno := c.nextSeqno()
msg.HDR.Seqno = seqno
}
//vv("cli name:'%v' has had a one-way requested: '%v'", c.name, msg)
if msg.HDR.Nc == nil {
// use default conn
msg.HDR.Nc = conn
}
// Send the message
//if err := w.sendMessage(conn, msg, &c.cfg.WriteTimeout); err != nil {
if err := w.sendMessage(conn, msg, nil); err != nil {
alwaysPrintf("Failed to send message: %v\n", err)
msg.LocalErr = err
if strings.Contains(err.Error(),
"use of closed network connection") {
return
}
} else {
//vv("cli %v has sent a 1-way message: %v'", c.name, msg)
lastPing = time.Now() // no need for ping
}
if msg.HDR.Typ == CallCancelPrevious {
if msg.LocalErr == nil {
msg.LocalErr = ErrCancelReqSent
}
}
// convey the error or lack thereof.
if msg.DoneCh != nil {
msg.DoneCh.Close()
}
case msg := <-c.roundTripCh:
seqno := c.nextSeqno()
msg.HDR.Seqno = seqno
//vv("cli %v has had a round trip requested: GetOneRead is registering for seqno=%v: '%v'; part '%v'", c.name, seqno, msg, msg.HDR.StreamPart)
c.GetOneRead(seqno, msg.DoneCh)
//if err := w.sendMessage(conn, msg, &c.cfg.WriteTimeout); err != nil {
if err := w.sendMessage(conn, msg, nil); err != nil {
//vv("Failed to send message: %v", err)
msg.LocalErr = err
c.UngetOneRead(seqno, msg.DoneCh)
if msg.DoneCh != nil {
msg.DoneCh.Close()
}
continue
} else {
//vv("7777777 (client %v) Sent message: (seqno=%v): CallID= %v", c.name, msg.HDR.Seqno, msg.HDR.CallID)
lastPing = time.Now() // no need for ping
}
}
}
}
// interface for goq
// TwoWayFunc is the user's own function that they
// register with the server for remote procedure calls.
//
// The user's Func may not want to return anything.
// In that case they should register a OneWayFunc instead.
//
// req.JobSerz []byte contains the job payload.
//
// Implementers of TwoWayFunc should assign their
// return []byte to reply.JobSerz. reply.Jobserz can also
// be left nil, of course.
//
// Any errors can be returned on reply.JobErrs; this is optional.
// Note that JobErrs is a string value rather than an error.
//
// The system will overwrite the reply.HDR.{To,From} fields when sending the
// reply, so the user should not bother setting those.
// The one exception to this rule is the reply.HDR.Subject string, which
// can be set by the user to return user-defined information.
// The reply will still be matched to the request on the HDR.Seqno, so
// a change of HDR.Subject will not change which goroutine
// receives the reply.
type TwoWayFunc func(req *Message, reply *Message) error
// OneWayFunc is the simpler sibling to the above.
// A OneWayFunc will not return anything to the sender.
//
// As above req.JobSerz [] byte contains the job payload.
type OneWayFunc func(req *Message)
// ServerSendsDownloadFunc is used to send a stream to the
// client on the streamToClientChan.
// Use Server.RegisterServerSendsDownloadFunc() to register it.
type ServerSendsDownloadFunc func(
srv *Server,
ctx context.Context,
req *Message,
sendDownloadPartToClient func(ctx context.Context, msg *Message, last bool) error,
lastReply *Message,
) (err error)
// BistreamFunc aims to allow the user to implement server
// operations with full generality; it provies for
// uploads and downloads to the originating client,
// and for communication with other clients.
// Use Server.RegisterBistreamFunc() to register your BistreamFunc
// under a name. The BistreamFunc and its siblings
// the ServerSendsDownloadFunc and the UploadReaderFunc
// are only available for the Message based API; not in
// the net/rpc API.
//
// On the client side, the Client.RequestBistreaming() call
// is used to create a Bistreamer that will call the
// BistreamFunc by its registered name (the name
// that Server.RegisterBistreamFunc() was called with).
//
// In a BistreamFunc on the server, the full
// generality of interleaving upload and download
// handling is available. The initial Message in req
// will also be the first Message in the req.HDR.UploadsCh
// which receives all upload messages from the client.
//
// To note, it may be more convenient for the user
// to use an UploadReaderFunc or
// ServerSendsDownloadFunc if the full generality
// of the BistreamFunc is not needed. For simplicity, the
// Server.RegisterServerSendsDownloadFunc() is used
// to register your ServerSendsDownloadFunc.
// Server.RegisterUploadReaderFunc() is used to
// register you UploadReaderFunc. Note in particular
// that the UploadReaderFunc is not persistent
// but rather receives a callback per Message
// received from the Client.Uploader. This may
// simplify the implementation of your server-side
// upload function. Note that persistent state between messages
// is still available by registering a method on
// your struct; see the ServerSideUploadFunc struct in
// example.go for example.
//
// BistreamFunc, in contrast, are not a callback-per-message, but rather
// persist and would typically only exit if ctx.Done()
// is received, or if it wishes to finish the operation (say on an
// error, or by noting that a CallUploadEnd type Message has
// been received) so as to save goroutine resources
// on the server. The BistreamFunc is started on the server
// when the CallRequestBistreaming Message.HDR.Typ
// is received with the ServiceName matching the registered
// name. Each live instance of the BistreamFunc is identified
// by the req.HDR.CallID set by the originating client. All
// download messages sent will have this same CallID
// on them (for the client to match).
//
// When the BistreamFunc finishes (returns), a
// final message will of type CallRPCReply will be
// sent back to the client. This is the lastReply
// *Message provided in the BistreamFunc. The
// BistreamFunc should fill in this lastReply
// with any final JobSerz payload it wishes to
// send; this is optional. On the client side, the
// Client.RequestBistreaming() is used to start
// bi-streaming. It returns a Bistreamer. This Bistreamer
// has a ReadCh that will receive this final message
// (as well as all other download messages). See the
// cli_test.go Test065_bidirectional_download_and_upload
// for example use.
//
// A BistreamFunc is run on its own goroutine. It can
// start new goroutines, if it wishes, but
// this is not required. An additional (new) goroutine
// may be useful to reduce the latency of message
// handling while simultaneously reading from
// req.HDR.UploadsCh for uploads and writing to
// downloads with sendDownloadPartToClient(),
// as both of these are blocking, synchronous, operations.
// If you do so, be sure to handle goroutine cancellation and
// cleanup if the ctx provided is cancelled.
//
// The sendDownloadPartToClient()
// helper function is used to write download
// Messages. It properly assigns the HDR.StreamPart
// sequence numbers and HDR.Typ as one of
// CallDownloadBegin, CallDownloadMore, and
// CallDownloadEnd). The BistreamFunc should
// call sendDownloadPartToClient() with last=true
// to signal the end of the download, in
// which case HDR.Typ CallDownloadEnd will
// be set on the sent Message.
//
// To provide back-pressure by default,
// the sendDownloadPartToClient() call is
// synchronous and will return only when
// the message is sent. If you wish to continue
// to process uploads while sending a download
// part, your BistreamFunc can call the
// provided sendDownloadPartToClient()
// in a goroutine that you start for this
// purpose. The sendDownloadPartToClient() call
// is goroutine safe, as it uses its own internal
// sync.Mutex to ensure only one send is in
// progress at a time.
//
// A BistreamFunc by default communicates download
// messages to its originating client. However
// other clients can also be sent messages.
// The Server.SendOneWayMessage() and
// Server.SendMessage() operations on the
// Server can be used for this purpose.
//
// Visit the example.go implementation of
// ServeBistreamState.ServeBistream() to see
// it in action.
type BistreamFunc func(
srv *Server,
ctx context.Context,
req *Message,
uploadsFromClientCh <-chan *Message,
sendDownloadPartToClient func(ctx context.Context, msg *Message, last bool) error,
lastReply *Message,
) (err error)
// A UploadReaderFunc receives messages from a Client's upload.
// It corresponds to the client-side Uploader, created
// by Client.UploadBegin().
//
// For a quick example, see the ReceiveFileInParts()
// implementation in the example.go file. It is a method on the
// ServerSideUploadFunc struct that holds state
// between the callbacks to ReceiveFileInParts().
//
// A UploadReaderFunc is like a OneWayFunc, but it
// generally should also be a method or closure to capture
// the state it needs, as it will receive multiple req *Message
// up-calls from the same client Stream. It should return a
// non-nil error to tell the client to stop sending.
// A nil return means we are fine and want to continue
// to receive more Messages from the same Stream.
// The req.HDR.CallID can be used to identify distinct Streams,
// and the req.HDR.StreamPart will convey their order
// which will start at 0 and count up.
//
// The lastReply argument will be nil until
// the Client calls Stream.More() with
// the last argument set to true. The user/client is
// telling the UploadReaderFunc not to expect any further
// messages. The UploadReaderFunc can then fill in the
// lastReply message with any finishing detail, and
// it will be sent back to the client.
//
// Note that even when lastReply is not nil,
// req may still have the tail content of
// the stream, and so generally req should be processed
// before considering if this is the last message and a final
// lastReply should also be filled out.
//
// For cleanup/avoiding memory leaks:
// If deadCallID is not the empty string, then the
// connection for this CallID has died and we should
// cleanup its resources. ctx, req, and lastReply
// will all be nil in this case.
type UploadReaderFunc func(ctx context.Context, req *Message, lastReply *Message, deadCallID string) error
// Config is the same struct type for both NewClient
// and NewServer setup.
//
// Config says who to contact (for a client), or
// where to listen (for a server and/or client); and sets how
// strong a security posture we adopt.
//
// Copying a Config is fine, but it should be a simple
// shallow copy to preserve the shared *sharedTransport struct.
// See/use the Config.Clone() method if in doubt.
//
// nitty gritty details/dev note: the `shared` pointer here is the
// basis of port (and file handle) reuse where a single
// process can maintain a server and multiple clients
// in a "star" pattern. This only works with QUIC of course,
// and is one of the main reasons to use QUIC.
//
// The shared pointer is reference counted and the underlying
// net.UDPConn is only closed when the last instance
// in use is Close()-ed.
type Config struct {
// ServerAddr host:port where the server should listen.
ServerAddr string
// optional. Can be used to suggest that the
// client use a specific host:port. NB: For QUIC, by default, the client and
// server will share the same port if they are in the same process.
// In that case this setting will definitely be ignored.
ClientHostPort string
// Who the client should contact
ClientDialToHostPort string
// TCP false means TLS-1.3 secured. true here means do TCP only; with no encryption.
TCPonly_no_TLS bool
// UseQUIC cannot be true if TCPonly_no_TLS is true.
UseQUIC bool
// NoSharePortQUIC defaults false so sharing is allowed.
// If true, then we do not share same UDP port between a QUIC
// client and server (in the same process). Used
// for testing client shutdown paths too.
NoSharePortQUIC bool
// path to certs/ like certificate
// directory on the live filesystem.
// defaults to GetCertsDir(); see config.go.
CertPath string
// SkipVerifyKeys true allows any incoming
// key to be signed by
// any CA; it does not have to be ours. Obviously
// this discards almost all access control; it
// should rarely be used unless communication
// with the any random agent/hacker/public person
// is desired.
SkipVerifyKeys bool
// This is not a Config option, but creating
// the known key file on the client/server is
// typically the last security measure in hardening.
//
// If known_client_keys exists on the server,
// then we will read from it.
// Likewise, if known_server_keys exists on
// the client, then we will read from it.
//
// If the known keys file is read-only: Read-only
// means we are in lockdown mode and no unknown
// client certs will be accepted, even if they
// have been properly signed by our CA.
//
// If the known keys file is writable then we are
// Trust On First Use mode, and new remote parties
// are recorded in the file if their certs are valid (signed
// by us/our CA).
//
// Note if the known_client_keys is read-only, it
// had better not be empty or nobody will be
// able to contact us. The server will notice
// this and crash since why bother being up.
ClientKeyPairName string // default "client" means use certs/client.crt and certs/client.key
ServerKeyPairName string // default "node" means use certs/node.crt and certs/node.key
// PreSharedKeyPath locates an optional pre-shared
// key. It must be 32 bytes (or more). Ideally
// it should be generated from crypto/rand.
// The `selfy -gensym outpath` command will
// do this, writing 32 cryptographically random
// bytes to output.
PreSharedKeyPath string
preSharedKey [32]byte
encryptPSK bool
// This is a timeout for dialing the initial socket connection.
// The default of 0 mean wait forever.
ConnectTimeout time.Duration
//
ServerSendKeepAlive time.Duration
ClientSendKeepAlive time.Duration
// CompressAlgo choices are in magic7.go;
// The current choices are "" (default compression, "s2" at the moment),
// or: "s2" (Klaus Post's faster SnappyV2, good for incompressibles);
// "lz4", (a very fast compressor; see https://lz4.org/);
// "zstd:01" (fastest setting for Zstandard, very little compression);
// "zstd:03", (the Zstandard 'default' level; slower but more compression);
// "zstd:07", (even more compression, even slower);
// "zstd:11", (slowest version of Zstandard, the most compression).
//
// Note! empty string means we use DefaultUseCompressAlgo
// (at the top of cli.go), which is currently "s2".
// To turn off compression, you must use the
// CompressionOff setting.
CompressAlgo string
CompressionOff bool
// Intially speak HTTP and only
// accept CONNECT requests that
// we turn into our protocol.
// Only works with TCPonly_no_TLS true also,
// at the moment. Also adds on another
// round trip.
HTTPConnectRequired bool
localAddress string
// for port sharing between a server and 1 or more clients over QUIC
shared *sharedTransport
// these starting directories
// noted on {Client/Server}.Start and referenced
// thereafter; to allow tests
// to change starting directories.
// Since these are set before starting goroutines,
// and then immutable, they should not need mutex protection.
cliStartingDir string
srvStartingDir string
// where the server stores its data. Server.DataDir() to view.
srvDataDir string
}
// ClientStartingDir returns the directory the Client was started in.
func (c *Client) ClientStartingDir() string {
return c.cfg.cliStartingDir
}
// ServerStartingDir returns the directory the Server was started in.
func (s *Server) ServerStartingDir() string {
return s.cfg.srvStartingDir
}
func (s *Server) DataDir() string {
return s.cfg.srvDataDir
}
// Clone returns a copy of cfg. This is a shallow copy to
// enable shared transport between a QUIC client and a QUIC
// server on the same port.
func (cfg *Config) Clone() *Config {
clone := *cfg
return &clone
}
func (cfg *Config) checkPreSharedKey(name string) {
if cfg.PreSharedKeyPath != "" && fileExists(cfg.PreSharedKeyPath) {
by, err := ioutil.ReadFile(cfg.PreSharedKeyPath)
panicOn(err)
if len(by) < 32 {
panic(fmt.Sprintf("cfg.PreSharedKeyPath '%v' did not have 32 bytes of data in it.", cfg.PreSharedKeyPath))
}
// We might have gotten a file of hex string text instead of binary.
// Or, we might have gotten some other user-defined stuff. Either
// way still use all of it, but run through an HKDF for safety first.
salt := make([]byte, 32)
salt[0] = 43 // make it apparent, not a great salt.
hkdf := hkdf.New(sha256.New, by, salt, nil)
var finalKey [32]byte
_, err = io.ReadFull(hkdf, finalKey[:])
panicOn(err)
by = finalKey[:]
copy(cfg.preSharedKey[:], by)
cfg.encryptPSK = true
//alwaysPrintf("activated pre-shared-key on '%v' from cfg.PreSharedKeyPath='%v'", name, cfg.PreSharedKeyPath)
}
}
type sharedTransport struct {
mut sync.Mutex
quicTransport *quic.Transport
shareCount int
isClosed bool
}
// NewConfig should be used to create Config
// for use in NewClient or NewServer setup.
func NewConfig() *Config {
return &Config{
shared: &sharedTransport{},
}
}
// A Client starts requests, and (might) wait for responses.
type Client struct {
cfg *Config
mut sync.Mutex
// these are client only. server keeps track
// per connection in their rwPair.
// These ephemeral keys are from the ephemeral ECDH handshake
// to estblish randomSymmetricSessKeyFromPreSharedKey.
randomSymmetricSessKeyFromPreSharedKey [32]byte
cliEphemPub []byte
srvEphemPub []byte
srvStaticPub ed25519.PublicKey