-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
server.go
1505 lines (1404 loc) · 37.3 KB
/
server.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 dht
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"net"
"runtime/pprof"
"slices"
"strings"
"text/tabwriter"
"time"
"github.com/anacrolix/generics"
"github.com/anacrolix/log"
"github.com/anacrolix/missinggo/v2"
"github.com/anacrolix/sync"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/iplist"
"github.com/anacrolix/torrent/logonce"
"github.com/anacrolix/torrent/metainfo"
"golang.org/x/time/rate"
"github.com/anacrolix/dht/v2/bep44"
"github.com/anacrolix/dht/v2/int160"
"github.com/anacrolix/dht/v2/krpc"
peer_store "github.com/anacrolix/dht/v2/peer-store"
"github.com/anacrolix/dht/v2/transactions"
"github.com/anacrolix/dht/v2/traversal"
"github.com/anacrolix/dht/v2/types"
)
// A Server defines parameters for a DHT node server that is able to send
// queries, and respond to the ones from the network. Each node has a globally
// unique identifier known as the "node ID." Node IDs are chosen at random
// from the same 160-bit space as BitTorrent infohashes and define the
// behaviour of the node. Zero valued Server does not have a valid ID and thus
// is unable to function properly. Use `NewServer(nil)` to initialize a
// default node.
type Server struct {
id int160.T
socket net.PacketConn
resendDelay func() time.Duration
mu sync.RWMutex
transactions transactions.Dispatcher[*transaction]
nextT uint64 // unique "t" field for outbound queries
table table
closed missinggo.Event
ipBlockList iplist.Ranger
tokenServer tokenServer // Manages tokens we issue to our queriers.
config ServerConfig
stats ServerStats
sendLimit *rate.Limiter
lastBootstrap time.Time
bootstrappingNow bool
store *bep44.Wrapper
}
func (s *Server) numGoodNodes() (num int) {
s.table.forNodes(func(n *node) bool {
if s.IsGood(n) {
num++
}
return true
})
return
}
func prettySince(t time.Time) string {
if t.IsZero() {
return "never"
}
d := time.Since(t)
d /= time.Second
d *= time.Second
return fmt.Sprintf("%s ago", d)
}
func (s *Server) WriteStatus(w io.Writer) {
fmt.Fprintf(w, "Listening on %s\n", s.Addr())
s.mu.Lock()
defer s.mu.Unlock()
fmt.Fprintf(w, "Nodes in table: %d good, %d total\n", s.numGoodNodes(), s.numNodes())
fmt.Fprintf(w, "Ongoing transactions: %d\n", s.transactions.NumActive())
fmt.Fprintf(w, "Server node ID: %x\n", s.id.Bytes())
buckets := &s.table.buckets
for i := range s.table.buckets {
b := &buckets[i]
if b.Len() == 0 && b.lastChanged.IsZero() {
continue
}
fmt.Fprintf(w,
"b# %v: %v nodes, last updated: %v\n",
i, b.Len(), prettySince(b.lastChanged))
if b.Len() > 0 {
tw := tabwriter.NewWriter(w, 0, 0, 1, ' ', 0)
fmt.Fprintf(tw, " node id\taddr\tlast query\tlast response\trecv\tdiscard\tflags\n")
// Bucket nodes ordered by distance from server ID.
nodes := slices.SortedFunc(b.NodeIter(), func(l *node, r *node) int {
return l.Id.Distance(s.id).Cmp(r.Id.Distance(s.id))
})
for _, n := range nodes {
var flags []string
if s.IsQuestionable(n) {
flags = append(flags, "q10e")
}
if s.nodeIsBad(n) {
flags = append(flags, "bad")
}
if s.IsGood(n) {
flags = append(flags, "good")
}
if n.IsSecure() {
flags = append(flags, "sec")
}
fmt.Fprintf(tw, " %x\t%s\t%s\t%s\t%d\t%v\t%v\n",
n.Id.Bytes(),
n.Addr,
prettySince(n.lastGotQuery),
prettySince(n.lastGotResponse),
n.numReceivesFrom,
n.failedLastQuestionablePing,
strings.Join(flags, ","),
)
}
tw.Flush()
}
}
fmt.Fprintln(w)
}
func (s *Server) numNodes() (num int) {
s.table.forNodes(func(n *node) bool {
num++
return true
})
return
}
// Stats returns statistics for the server.
func (s *Server) Stats() ServerStats {
s.mu.Lock()
defer s.mu.Unlock()
ss := s.stats
ss.GoodNodes = s.numGoodNodes()
ss.Nodes = s.numNodes()
ss.OutstandingTransactions = s.transactions.NumActive()
return ss
}
// Addr returns the listen address for the server. Packets arriving to this address
// are processed by the server (unless aliens are involved).
func (s *Server) Addr() net.Addr {
return s.socket.LocalAddr()
}
func NewDefaultServerConfig() *ServerConfig {
return &ServerConfig{
NoSecurity: true,
StartingNodes: func() ([]Addr, error) { return GlobalBootstrapAddrs("udp") },
DefaultWant: []krpc.Want{krpc.WantNodes, krpc.WantNodes6},
Store: bep44.NewMemory(),
Exp: 2 * time.Hour,
SendLimiter: DefaultSendLimiter,
}
}
// If the NodeId hasn't been specified, generate a suitable one. deterministic if c.Conn and
// c.PublicIP are non-nil.
func (c *ServerConfig) InitNodeId() (deterministic bool) {
if c.NodeId.IsZero() {
var secure bool
if c.Conn != nil && c.PublicIP != nil {
// Is this sufficient for a deterministic node ID?
c.NodeId = HashTuple(
[]byte(c.Conn.LocalAddr().Network()),
[]byte(c.Conn.LocalAddr().String()),
c.PublicIP,
)
// Since we have a public IP we can secure, and the choice must not be influenced by the
// NoSecure configuration option.
secure = true
deterministic = true
} else {
c.NodeId = RandomNodeID()
secure = !c.NoSecurity && c.PublicIP != nil
}
if secure {
SecureNodeId(&c.NodeId, c.PublicIP)
}
}
return
}
// NewServer initializes a new DHT node server.
func NewServer(c *ServerConfig) (s *Server, err error) {
if c == nil {
c = NewDefaultServerConfig()
}
if c.Conn == nil {
c.Conn, err = net.ListenPacket("udp", ":0")
if err != nil {
return
}
}
c.InitNodeId()
// If Logger is empty, emulate the old behaviour: Everything is logged to the default location,
// and there are no debug messages.
if c.Logger.IsZero() {
c.Logger = log.Default.FilterLevel(log.Info)
}
// Add log.Debug by default.
c.Logger = c.Logger.WithDefaultLevel(log.Debug)
if c.Store == nil {
c.Store = bep44.NewMemory()
}
if c.SendLimiter == nil {
c.SendLimiter = DefaultSendLimiter
}
s = &Server{
config: *c,
ipBlockList: c.IPBlocklist,
tokenServer: tokenServer{
maxIntervalDelta: 2,
interval: 5 * time.Minute,
secret: make([]byte, 20),
},
table: table{
k: 8,
},
store: bep44.NewWrapper(c.Store, c.Exp),
}
rand.Read(s.tokenServer.secret)
s.socket = c.Conn
s.id = int160.FromByteArray(c.NodeId)
s.table.rootID = s.id
s.resendDelay = s.config.QueryResendDelay
if s.resendDelay == nil {
s.resendDelay = defaultQueryResendDelay
}
go s.serveUntilClosed()
return
}
func (s *Server) serveUntilClosed() {
err := s.serve()
s.mu.Lock()
defer s.mu.Unlock()
if s.closed.IsSet() {
return
}
if err != nil {
panic(err)
}
}
// Returns a description of the Server.
func (s *Server) String() string {
return fmt.Sprintf("dht server on %s (node id %v)", s.socket.LocalAddr(), s.id)
}
// Packets to and from any address matching a range in the list are dropped.
func (s *Server) SetIPBlockList(list iplist.Ranger) {
s.mu.Lock()
defer s.mu.Unlock()
s.ipBlockList = list
}
func (s *Server) IPBlocklist() iplist.Ranger {
return s.ipBlockList
}
func (s *Server) processPacket(b []byte, addr Addr) {
// log.Printf("got packet %q", b)
if len(b) < 2 || b[0] != 'd' {
// KRPC messages are bencoded dicts.
readNotKRPCDict.Add(1)
return
}
var d krpc.Msg
err := bencode.Unmarshal(b, &d)
if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
// log.Printf("%s: received message packet with %d trailing bytes: %q", s, _err.NumUnusedBytes, b[len(b)-_err.NumUnusedBytes:])
expvars.Add("processed packets with trailing bytes", 1)
} else if err != nil {
readUnmarshalError.Add(1)
// log.Printf("%s: received bad krpc message from %s: %s: %+q", s, addr, err, b)
func() {
if se, ok := err.(*bencode.SyntaxError); ok {
// The message was truncated.
if int(se.Offset) == len(b) {
return
}
// Some messages seem to drop to nul chars abruptly.
if int(se.Offset) < len(b) && b[se.Offset] == 0 {
return
}
// The message isn't bencode from the first.
if se.Offset == 0 {
return
}
}
// if missinggo.CryHeard() {
log.Printf("%s: received bad krpc message from %s: %s: %+q", s, addr, err, b)
// }
}()
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed.IsSet() {
return
}
if d.Y == "q" {
expvars.Add("received queries", 1)
s.logger().Printf("received query %q from %v", d.Q, addr)
s.handleQuery(addr, d)
return
}
tk := transactionKey{
RemoteAddr: addr.String(),
T: d.T,
}
if !s.transactions.Have(tk) {
s.logger().Printf("received response for untracked transaction %q from %v", d.T, addr)
return
}
t := s.transactions.Pop(tk)
// s.logger().Printf("received response for transaction %q from %v", d.T, addr)
go t.handleResponse(d)
s.updateNode(addr, d.SenderID(), !d.ReadOnly, func(n *node) {
n.lastGotResponse = time.Now()
n.failedLastQuestionablePing = false
n.numReceivesFrom++
})
}
func (s *Server) serve() error {
var b [0x10000]byte
for {
n, addr, err := s.socket.ReadFrom(b[:])
if err != nil {
if ignoreReadFromError(err) {
continue
}
return err
}
expvars.Add("packets read", 1)
if n == len(b) {
logonce.Stderr.Printf("received dht packet exceeds buffer size")
continue
}
if missinggo.AddrPort(addr) == 0 {
readZeroPort.Add(1)
continue
}
blocked, err := func() (bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.closed.IsSet() {
return false, errors.New("server is closed")
}
return s.ipBlocked(missinggo.AddrIP(addr)), nil
}()
if err != nil {
return err
}
if blocked {
readBlocked.Add(1)
continue
}
s.processPacket(b[:n], NewAddr(addr))
}
}
func (s *Server) ipBlocked(ip net.IP) (blocked bool) {
if s.ipBlockList == nil {
return
}
_, blocked = s.ipBlockList.Lookup(ip)
return
}
// Adds directly to the node table.
func (s *Server) AddNode(ni krpc.NodeInfo) error {
id := int160.FromByteArray(ni.ID)
if id.IsZero() {
go s.Ping(ni.Addr.UDP())
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
return s.updateNode(NewAddr(ni.Addr.UDP()), (*krpc.ID)(&ni.ID), true, func(*node) {})
}
func wantsContain(ws []krpc.Want, w krpc.Want) bool {
for _, _w := range ws {
if _w == w {
return true
}
}
return false
}
func shouldReturnNodes(queryWants []krpc.Want, querySource net.IP) bool {
if len(queryWants) != 0 {
return wantsContain(queryWants, krpc.WantNodes)
}
// Is it possible to be over IPv6 with IPv4 endpoints?
return querySource.To4() != nil
}
func shouldReturnNodes6(queryWants []krpc.Want, querySource net.IP) bool {
if len(queryWants) != 0 {
return wantsContain(queryWants, krpc.WantNodes6)
}
return querySource.To4() == nil
}
func (s *Server) makeReturnNodes(target int160.T, filter func(krpc.NodeAddr) bool) []krpc.NodeInfo {
return s.closestGoodNodeInfos(8, target, filter)
}
var krpcErrMissingArguments = krpc.Error{
Code: krpc.ErrorCodeProtocolError,
Msg: "missing arguments dict",
}
// Filters peers per BEP 32 to return in the values field to a get_peers query.
func filterPeers(querySourceIp net.IP, queryWants []krpc.Want, allPeers []krpc.NodeAddr) (filtered []krpc.NodeAddr) {
// The logic here is common with nodes, see BEP 32.
retain4 := shouldReturnNodes(queryWants, querySourceIp)
retain6 := shouldReturnNodes6(queryWants, querySourceIp)
for _, peer := range allPeers {
if ip, ok := func(ip net.IP) (net.IP, bool) {
as4 := peer.IP.To4()
as16 := peer.IP.To16()
switch {
case retain4 && len(ip) == net.IPv4len:
return ip, true
case retain6 && len(ip) == net.IPv6len:
return ip, true
case retain4 && as4 != nil:
// Is it possible that we're converting to an IPv4 address when the transport in use
// is IPv6?
return as4, true
case retain6 && as16 != nil:
// Couldn't any IPv4 address be converted to IPv6, but isn't listening over IPv6?
return as16, true
default:
return nil, false
}
}(peer.IP); ok {
filtered = append(filtered, krpc.NodeAddr{IP: ip, Port: peer.Port})
}
}
return
}
func (s *Server) setReturnNodes(r *krpc.Return, queryMsg krpc.Msg, querySource Addr) *krpc.Error {
if queryMsg.A == nil {
return &krpcErrMissingArguments
}
target := int160.FromByteArray(queryMsg.A.InfoHash)
if shouldReturnNodes(queryMsg.A.Want, querySource.IP()) {
r.Nodes = s.makeReturnNodes(target, func(na krpc.NodeAddr) bool { return na.IP.To4() != nil })
}
if shouldReturnNodes6(queryMsg.A.Want, querySource.IP()) {
r.Nodes6 = s.makeReturnNodes(target, func(krpc.NodeAddr) bool { return true })
}
return nil
}
func (s *Server) handleQuery(source Addr, m krpc.Msg) {
go func() {
expvars.Add(fmt.Sprintf("received query %q", m.Q), 1)
if a := m.A; a != nil {
if a.NoSeed != 0 {
expvars.Add("received argument noseed", 1)
}
if a.Scrape != 0 {
expvars.Add("received argument scrape", 1)
}
}
}()
s.updateNode(source, m.SenderID(), !m.ReadOnly, func(n *node) {
n.lastGotQuery = time.Now()
n.numReceivesFrom++
})
if s.config.OnQuery != nil {
propagate := s.config.OnQuery(&m, source.Raw())
if !propagate {
return
}
}
// Don't respond.
if s.config.Passive {
return
}
// TODO: Should we disallow replying to ourself?
args := m.A
switch m.Q {
case "ping":
s.reply(source, m.T, krpc.Return{})
case "get_peers":
// Check for the naked m.A.Want deref below.
if m.A == nil {
s.sendError(source, m.T, krpcErrMissingArguments)
break
}
var r krpc.Return
if ps := s.config.PeerStore; ps != nil {
r.Values = filterPeers(source.IP(), m.A.Want, ps.GetPeers(peer_store.InfoHash(args.InfoHash)))
r.Token = func() *string {
t := s.createToken(source)
return &t
}()
}
if len(r.Values) == 0 {
if err := s.setReturnNodes(&r, m, source); err != nil {
s.sendError(source, m.T, *err)
break
}
}
s.reply(source, m.T, r)
case "find_node":
var r krpc.Return
if err := s.setReturnNodes(&r, m, source); err != nil {
s.sendError(source, m.T, *err)
break
}
s.reply(source, m.T, r)
case "announce_peer":
if !s.validToken(args.Token, source) {
expvars.Add("received announce_peer with invalid token", 1)
return
}
expvars.Add("received announce_peer with valid token", 1)
var port int
portOk := false
if args.Port != nil {
port = *args.Port
portOk = true
}
if args.ImpliedPort {
expvars.Add("received announce_peer with implied_port", 1)
port = source.Port()
portOk = true
}
if !portOk {
expvars.Add("received announce_peer with no derivable port", 1)
}
if h := s.config.OnAnnouncePeer; h != nil {
go h(metainfo.Hash(args.InfoHash), source.IP(), port, portOk)
}
if ps := s.config.PeerStore; ps != nil {
go ps.AddPeer(
peer_store.InfoHash(args.InfoHash),
krpc.NodeAddr{IP: source.IP(), Port: port},
)
}
s.reply(source, m.T, krpc.Return{})
case "put":
if !s.validToken(args.Token, source) {
expvars.Add("received put with invalid token", 1)
return
}
expvars.Add("received put with valid token", 1)
if args.Seq == nil {
s.sendError(source, m.T, krpc.Error{
Code: krpc.ErrorCodeProtocolError,
Msg: "expected seq argument",
})
return
}
i := &bep44.Item{
V: args.V,
K: args.K,
Salt: args.Salt,
Sig: args.Sig,
Cas: args.Cas,
Seq: *args.Seq,
}
if err := s.store.Put(i); err != nil {
kerr, ok := err.(krpc.Error)
if !ok {
s.sendError(source, m.T, krpc.ErrorMethodUnknown)
break
}
s.sendError(source, m.T, kerr)
break
}
s.reply(source, m.T, krpc.Return{
ID: s.ID(),
})
case "get":
var r krpc.Return
if err := s.setReturnNodes(&r, m, source); err != nil {
s.sendError(source, m.T, *err)
break
}
t := s.createToken(source)
r.Token = &t
item, err := s.store.Get(bep44.Target(args.Target))
if err == bep44.ErrItemNotFound {
s.reply(source, m.T, r)
break
}
if kerr, ok := err.(krpc.Error); ok {
s.sendError(source, m.T, kerr)
break
}
if err != nil {
s.sendError(source, m.T, krpc.Error{
Code: krpc.ErrorCodeGenericError,
Msg: err.Error(),
})
break
}
r.Seq = &item.Seq
if args.Seq != nil && item.Seq <= *args.Seq {
s.reply(source, m.T, r)
break
}
r.V = bencode.MustMarshal(item.V)
r.K = item.K
r.Sig = item.Sig
s.reply(source, m.T, r)
// case "sample_infohashes":
// // Nodes supporting this extension should always include the samples field in the response,
// // even when it is zero-length. This lets indexing nodes to distinguish nodes supporting this
// // extension from those that respond to unknown query types which contain a target field [2].
default:
// TODO: http://libtorrent.org/dht_extensions.html#forward-compatibility
s.sendError(source, m.T, krpc.ErrorMethodUnknown)
}
}
func (s *Server) sendError(addr Addr, t string, e krpc.Error) {
go func() {
m := krpc.Msg{
T: t,
Y: "e",
E: &e,
}
b, err := bencode.Marshal(m)
if err != nil {
panic(err)
}
s.logger().Printf("sending error to %q: %v", addr, e)
_, err = s.writeToNode(context.Background(), b, addr, false, true)
if err != nil {
s.logger().Printf("error replying to %q: %v", addr, err)
}
}()
}
func (s *Server) reply(addr Addr, t string, r krpc.Return) {
go func() {
r.ID = s.id.AsByteArray()
m := krpc.Msg{
T: t,
Y: "r",
R: &r,
IP: addr.KRPC(),
}
b := bencode.MustMarshal(m)
log.Fmsg("replying to %q", addr).Log(s.logger())
wrote, err := s.writeToNode(context.Background(), b, addr, s.config.WaitToReply, true)
if err != nil {
s.config.Logger.Printf("error replying to %s: %s", addr, err)
}
if wrote {
expvars.Add("replied to peer", 1)
}
}()
}
// Adds a node if appropriate.
func (s *Server) addNode(n *node) error {
if s.nodeIsBad(n) {
return errors.New("node is bad")
}
b := s.table.bucketForID(n.Id)
if b.Len() >= s.table.k {
if b.EachNode(func(bn *node) bool {
// Replace bad and untested nodes with a good one.
if s.nodeIsBad(bn) || (s.IsGood(n) && bn.lastGotResponse.IsZero()) {
s.table.dropNode(bn)
}
return b.Len() >= s.table.k
}) {
return errors.New("no room in bucket")
}
}
if err := s.table.addNode(n); err != nil {
panic(fmt.Sprintf("expected to add node: %s", err))
}
return nil
}
func (s *Server) NodeRespondedToPing(addr Addr, id int160.T) {
s.mu.Lock()
defer s.mu.Unlock()
if id == s.id {
return
}
b := s.table.bucketForID(id)
if b.GetNode(addr, id) == nil {
return
}
b.lastChanged = time.Now()
}
// Updates the node, adding it if appropriate.
func (s *Server) updateNode(addr Addr, id *krpc.ID, tryAdd bool, update func(*node)) error {
if id == nil {
return errors.New("id is nil")
}
int160Id := int160.FromByteArray(*id)
n := s.table.getNode(addr, int160Id)
missing := n == nil
if missing {
if !tryAdd {
return errors.New("node not present and add flag false")
}
if int160Id == s.id {
return errors.New("can't store own id in routing table")
}
n = &node{nodeKey: nodeKey{
Id: int160Id,
Addr: addr,
}}
}
update(n)
if !missing {
return nil
}
return s.addNode(n)
}
func (s *Server) nodeIsBad(n *node) bool {
return s.nodeErr(n) != nil
}
func (s *Server) nodeErr(n *node) error {
if n.Id == s.id {
return errors.New("is self")
}
if n.Id.IsZero() {
return errors.New("has zero id")
}
if !(s.config.NoSecurity || n.IsSecure()) {
return errors.New("not secure")
}
if n.failedLastQuestionablePing {
return errors.New("didn't respond to last questionable node ping")
}
return nil
}
func (s *Server) writeToNode(ctx context.Context, b []byte, node Addr, wait, rate bool) (wrote bool, err error) {
func() {
// This is a pain. It would be better if the blocklist returned an error if it was closed
// instead.
s.mu.RLock()
defer s.mu.RUnlock()
if s.closed.IsSet() {
err = errors.New("server is closed")
return
}
if list := s.ipBlockList; list != nil {
if r, ok := list.Lookup(node.IP()); ok {
err = fmt.Errorf("write to %v blocked by %v", node, r)
return
}
}
}()
if err != nil {
return
}
// s.config.Logger.WithValues(log.Debug).Printf("writing to %s: %q", node.String(), b)
if rate {
if wait {
err = s.config.SendLimiter.Wait(ctx)
if err != nil {
err = fmt.Errorf("waiting for rate-limit token: %w", err)
return false, err
}
} else {
if !s.config.SendLimiter.Allow() {
return false, errors.New("rate limit exceeded")
}
}
}
n, err := s.socket.WriteTo(b, node.Raw())
writes.Add(1)
if rate {
expvars.Add("rated writes", 1)
} else {
expvars.Add("unrated writes", 1)
}
if err != nil {
writeErrors.Add(1)
if rate {
// Give the token back. nfi if this will actually work.
s.config.SendLimiter.AllowN(time.Now(), -1)
}
err = fmt.Errorf("error writing %d bytes to %s: %s", len(b), node, err)
return
}
wrote = true
if n != len(b) {
err = io.ErrShortWrite
return
}
return
}
func (s *Server) nextTransactionID() string {
return transactions.DefaultIdIssuer.Issue()
}
func (s *Server) deleteTransaction(k transactionKey) {
if s.transactions.Have(k) {
s.transactions.Pop(k)
}
}
func (s *Server) addTransaction(k transactionKey, t *transaction) {
s.transactions.Add(k, t)
}
// ID returns the 20-byte server ID. This is the ID used to communicate with the
// DHT network.
func (s *Server) ID() [20]byte {
return s.id.AsByteArray()
}
func (s *Server) createToken(addr Addr) string {
return s.tokenServer.CreateToken(addr)
}
func (s *Server) validToken(token string, addr Addr) bool {
return s.tokenServer.ValidToken(token, addr)
}
type numWrites int
func (s *Server) makeQueryBytes(q string, a krpc.MsgArgs, t string) []byte {
a.ID = s.ID()
m := krpc.Msg{
T: t,
Y: "q",
Q: q,
A: &a,
}
// BEP 43. Outgoing queries from passive nodes should contain "ro":1 in the top level
// dictionary.
if s.config.Passive {
m.ReadOnly = true
}
b, err := bencode.Marshal(m)
if err != nil {
panic(err)
}
return b
}
type QueryResult struct {
Reply krpc.Msg
Writes numWrites
Err error
}
func (qr QueryResult) ToError() error {
if qr.Err != nil {
return qr.Err
}
e := qr.Reply.Error()
if e != nil {
return e
}
return nil
}
// Converts a Server QueryResult to a traversal.QueryResult.
func (me QueryResult) TraversalQueryResult(addr krpc.NodeAddr) (ret traversal.QueryResult) {
r := me.Reply.R
if r == nil {
return
}
ret.ResponseFrom = &krpc.NodeInfo{
Addr: addr,
ID: r.ID,
}
ret.Nodes = r.Nodes
ret.Nodes6 = r.Nodes6
if r.Token != nil {
ret.ClosestData = *r.Token
}
return
}
// Rate-limiting to be applied to writes for a given query. Queries occur inside transactions that
// will attempt to send several times. If the STM rate-limiting helpers are used, the first send is
// often already accounted for in the rate-limiting machinery before the query method that does the
// IO is invoked.
type QueryRateLimiting struct {
// Don't rate-limit the first send for a query.
NotFirst bool
// Don't rate-limit any sends for a query. Note that there's still built-in waits before retries.
NotAny bool
WaitOnRetries bool
NoWaitFirst bool
}
// The zero value for this uses reasonable/traditional defaults on Server methods.
type QueryInput struct {
MsgArgs krpc.MsgArgs
RateLimiting QueryRateLimiting
NumTries int
}
// Performs an arbitrary query. `q` is the query value, defined by the DHT BEP. `a` should contain
// the appropriate argument values, if any. `a.ID` is clobbered by the Server. Responses to queries
// made this way are not interpreted by the Server. More specific methods like FindNode and GetPeers
// may make use of the response internally before passing it back to the caller.
func (s *Server) Query(ctx context.Context, addr Addr, q string, input QueryInput) (ret QueryResult) {
if input.NumTries == 0 {
input.NumTries = defaultMaxQuerySends
}
defer func(started time.Time) {
s.logger().WithDefaultLevel(log.Debug).WithValues(q).Printf(
"Query(%v) returned after %v (err=%v, reply.Y=%v, reply.E=%v, writes=%v)",
q, time.Since(started), ret.Err, ret.Reply.Y, ret.Reply.E, ret.Writes)
}(time.Now())
replyChan := make(chan krpc.Msg, 1)
t := &transaction{
onResponse: func(m krpc.Msg) {
replyChan <- m
},
}
tk := transactionKey{
RemoteAddr: addr.String(),
}
s.mu.Lock()
tid := s.nextTransactionID()
s.stats.OutboundQueriesAttempted++
tk.T = tid
s.addTransaction(tk, t)
s.mu.Unlock()
// Receives a non-nil error from the sender, and closes when the sender completes.
sendErr := make(chan error, 1)
sendCtx, cancelSend := context.WithCancel(pprof.WithLabels(ctx, pprof.Labels("q", q)))
go func() {
err := s.transactionQuerySender(
sendCtx,
s.makeQueryBytes(q, input.MsgArgs, tid),
&ret.Writes,
addr,
input.RateLimiting,
input.NumTries)
if err != nil {
sendErr <- err
}
close(sendErr)
}()
expvars.Add(fmt.Sprintf("outbound %s queries", q), 1)
select {
case ret.Reply = <-replyChan:
case <-ctx.Done():
ret.Err = ctx.Err()
case ret.Err = <-sendErr:
}
// Make sure the query sender stops.
cancelSend()