-
Notifications
You must be signed in to change notification settings - Fork 45
/
DHT.java
1321 lines (1054 loc) · 36.2 KB
/
DHT.java
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
/*
* This file is part of mlDHT.
*
* mlDHT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* mlDHT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with mlDHT. If not, see <http://www.gnu.org/licenses/>.
*/
package lbms.plugins.mldht.kad;
import static the8472.bencode.Utils.prettyPrint;
import static the8472.utils.Functional.awaitAll;
import lbms.plugins.mldht.DHTConfiguration;
import lbms.plugins.mldht.kad.GenericStorage.StorageItem;
import lbms.plugins.mldht.kad.GenericStorage.UpdateResult;
import lbms.plugins.mldht.kad.Node.RoutingTableEntry;
import lbms.plugins.mldht.kad.messages.AbstractLookupRequest;
import lbms.plugins.mldht.kad.messages.AbstractLookupResponse;
import lbms.plugins.mldht.kad.messages.AnnounceRequest;
import lbms.plugins.mldht.kad.messages.AnnounceResponse;
import lbms.plugins.mldht.kad.messages.ErrorMessage;
import lbms.plugins.mldht.kad.messages.ErrorMessage.ErrorCode;
import lbms.plugins.mldht.kad.messages.FindNodeRequest;
import lbms.plugins.mldht.kad.messages.FindNodeResponse;
import lbms.plugins.mldht.kad.messages.GetPeersRequest;
import lbms.plugins.mldht.kad.messages.GetPeersResponse;
import lbms.plugins.mldht.kad.messages.GetRequest;
import lbms.plugins.mldht.kad.messages.GetResponse;
import lbms.plugins.mldht.kad.messages.MessageBase;
import lbms.plugins.mldht.kad.messages.PingRequest;
import lbms.plugins.mldht.kad.messages.PingResponse;
import lbms.plugins.mldht.kad.messages.PutRequest;
import lbms.plugins.mldht.kad.messages.PutResponse;
import lbms.plugins.mldht.kad.messages.SampleRequest;
import lbms.plugins.mldht.kad.messages.SampleResponse;
import lbms.plugins.mldht.kad.messages.UnknownTypeResponse;
import lbms.plugins.mldht.kad.tasks.AnnounceTask;
import lbms.plugins.mldht.kad.tasks.NodeLookup;
import lbms.plugins.mldht.kad.tasks.PeerLookupTask;
import lbms.plugins.mldht.kad.tasks.PingRefreshTask;
import lbms.plugins.mldht.kad.tasks.Task;
import lbms.plugins.mldht.kad.tasks.TaskListener;
import lbms.plugins.mldht.kad.tasks.TaskManager;
import lbms.plugins.mldht.kad.utils.AddressUtils;
import lbms.plugins.mldht.kad.utils.ByteWrapper;
import lbms.plugins.mldht.kad.utils.PopulationEstimator;
import lbms.plugins.mldht.utils.NIOConnectionManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ProtocolFamily;
import java.net.SocketException;
import java.net.StandardProtocolFamily;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* @author Damokles
*
*/
public class DHT implements DHTBase {
public static enum DHTtype {
IPV4_DHT("IPv4",20+4+2, 4+2, Inet4Address.class,20+8, 1450, StandardProtocolFamily.INET),
IPV6_DHT("IPv6",20+16+2, 16+2, Inet6Address.class,40+8, 1200, StandardProtocolFamily.INET6);
public final int HEADER_LENGTH;
public final int NODES_ENTRY_LENGTH;
public final int ADDRESS_ENTRY_LENGTH;
public final Class<? extends InetAddress> PREFERRED_ADDRESS_TYPE;
public final int MAX_PACKET_SIZE;
public final String shortName;
public final ProtocolFamily PROTO_FAMILY;
private DHTtype(String shortName, int nodeslength, int addresslength, Class<? extends InetAddress> addresstype, int header, int maxSize, ProtocolFamily family) {
this.shortName = shortName;
this.NODES_ENTRY_LENGTH = nodeslength;
this.PREFERRED_ADDRESS_TYPE = addresstype;
this.ADDRESS_ENTRY_LENGTH = addresslength;
this.HEADER_LENGTH = header;
this.MAX_PACKET_SIZE = maxSize;
this.PROTO_FAMILY = family;
}
public boolean canUseSocketAddress(InetSocketAddress addr) {
return PREFERRED_ADDRESS_TYPE.isInstance(addr.getAddress());
}
public boolean canUseAddress(InetAddress addr) {
return PREFERRED_ADDRESS_TYPE.isInstance(addr);
}
}
private static DHTLogger logger;
private static LogLevel logLevel = LogLevel.Info;
private volatile static ScheduledThreadPoolExecutor defaultScheduler;
private static ThreadGroup executorGroup;
static {
logger = new DHTLogger() {
public void log (String message, LogLevel l) {
System.out.println(message);
};
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTLogger#log(java.lang.Exception)
*/
public void log (Throwable e, LogLevel l) {
e.printStackTrace();
}
};
}
private boolean running;
enum BootstrapState {
NONE,
BOOTSTRAP,
FILL
}
AtomicReference<BootstrapState> bootstrapping = new AtomicReference<>(BootstrapState.NONE);
private long lastBootstrap;
DHTConfiguration config;
private Node node;
private RPCServerManager serverManager;
private GenericStorage storage;
private Database db;
private TaskManager tman;
IDMismatchDetector mismatchDetector;
NonReachableCache unreachableCache;
private Path table_file;
private boolean useRouterBootstrapping;
private List<DHTStatsListener> statsListeners;
private List<DHTStatusListener> statusListeners;
private List<DHTIndexingListener> indexingListeners;
private DHTStats stats;
private DHTStatus status;
private PopulationEstimator estimator;
private AnnounceNodeCache cache;
private NIOConnectionManager connectionManager;
RPCStats serverStats;
private final DHTtype type;
private List<ScheduledFuture<?>> scheduledActions = new ArrayList<>();
private List<DHT> siblingGroup = new ArrayList<>();
private ScheduledExecutorService scheduler;
public DHT(DHTtype type) {
this.type = type;
siblingGroup.add(this);
stats = new DHTStats();
status = DHTStatus.Stopped;
statsListeners = new ArrayList<>(2);
statusListeners = new ArrayList<>(2);
indexingListeners = new ArrayList<>();
estimator = new PopulationEstimator();
}
public ScheduledExecutorService getScheduler() {
return scheduler;
}
public void setScheduler(ScheduledExecutorService scheduler) {
this.scheduler = scheduler;
}
public void addSiblings(List<DHT> toAdd) {
toAdd.forEach(s -> {
if(!siblingGroup.contains(s))
siblingGroup.add(s);
});
}
public Optional<DHT> getSiblingByType(DHTtype type) {
return siblingGroup.stream().filter(sib -> sib.getType() == type).findAny();
}
public List<DHT> getSiblings() {
return Collections.unmodifiableList(siblingGroup);
}
public static interface IncomingMessageListener {
void received(DHT dht, MessageBase msg);
}
private List<IncomingMessageListener> incomingMessageListeners = new ArrayList<>();
/**
* Listeners must be threadsafe, non-blocking and exception-free and avoid modifying the passed messages or their contents.
* They are invoked from the message-processing threads, so any incorrect behavior may prevent the messages from being processed properly.
*
* registration itself is not thread-safe, thus listeners should be registered between creation of the DHT instance and invocation of its start() method.
*/
public void addIncomingMessageListener(IncomingMessageListener l) {
incomingMessageListeners.add(l);
}
void incomingMessage(MessageBase msg) {
incomingMessageListeners.forEach(e -> e.received(this, msg));
}
public void ping (PingRequest r) {
if (!isRunning()) {
return;
}
// ignore requests we get from ourself
if (node.isLocalId(r.getID())) {
return;
}
PingResponse rsp = new PingResponse(r.getMTID());
rsp.setDestination(r.getOrigin());
r.getServer().sendMessage(rsp);
node.recieved(r);
}
public void findNode(AbstractLookupRequest r) {
if (!isRunning()) {
return;
}
// ignore requests we get from ourself
if (node.isLocalId(r.getID())) {
return;
}
AbstractLookupResponse response;
if(r instanceof FindNodeRequest)
response = new FindNodeResponse(r.getMTID());
else
response = new UnknownTypeResponse(r.getMTID());
populateResponse(r.getTarget(), response, r.doesWant4() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0, r.doesWant6() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0);
response.setDestination(r.getOrigin());
r.getServer().sendMessage(response);
node.recieved(r);
}
void populateResponse(Key target, AbstractLookupResponse rsp, int v4, int v6) {
if(v4 > 0) {
getSiblingByType(DHTtype.IPV4_DHT).filter(DHT::isRunning).ifPresent(sib -> {
KClosestNodesSearch kns = new KClosestNodesSearch(target, v4, sib);
kns.fill(DHTtype.IPV4_DHT != type);
rsp.setNodes(kns.asNodeList());
});
}
if(v6 > 0) {
getSiblingByType(DHTtype.IPV6_DHT).filter(DHT::isRunning).ifPresent(sib -> {
KClosestNodesSearch kns = new KClosestNodesSearch(target, v6, sib);
kns.fill(DHTtype.IPV6_DHT != type);
rsp.setNodes(kns.asNodeList());
});
}
}
public void response (MessageBase r) {
if (!isRunning()) {
return;
}
node.recieved(r);
}
public void get(GetRequest req) {
if (!isRunning()) {
return;
}
GetResponse rsp = new GetResponse(req.getMTID());
populateResponse(req.getTarget(), rsp, req.doesWant4() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0, req.doesWant6() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0);
Key k = req.getTarget();
Optional.ofNullable(db.genToken(req.getID(), req.getOrigin().getAddress(), req.getOrigin().getPort(), k)).ifPresent(token -> {
rsp.setToken(token.arr);
});
storage.get(k).ifPresent(item -> {
if(req.getSeq() < 0 || item.sequenceNumber < 0 || req.getSeq() < item.sequenceNumber) {
rsp.setRawValue(ByteBuffer.wrap(item.value));
rsp.setKey(item.pubkey);
rsp.setSignature(item.signature);
if(item.sequenceNumber >= 0)
rsp.setSequenceNumber(item.sequenceNumber);
}
});
rsp.setDestination(req.getOrigin());
req.getServer().sendMessage(rsp);
node.recieved(req);
}
public void put(PutRequest req) {
Key k = req.deriveTargetKey();
if(!db.checkToken(new ByteWrapper(req.getToken()), req.getID(), req.getOrigin().getAddress(), req.getOrigin().getPort(), k)) {
sendError(req, ErrorCode.ProtocolError.code, "received invalid or expired token for PUT request");
return;
}
UpdateResult result = storage.putOrUpdate(k, new StorageItem(req), req.getExpectedSequenceNumber());
switch(result) {
case CAS_FAIL:
sendError(req, ErrorCode.CasFail.code, "CAS failure");
return;
case SIG_FAIL:
sendError(req, ErrorCode.InvalidSignature.code, "signature validation failed");
return;
case SEQ_FAIL:
sendError(req, ErrorCode.CasNotMonotonic.code, "sequence number less than current");
return;
case IMMUTABLE_SUBSTITUTION_FAIL:
sendError(req, ErrorCode.ProtocolError.code, "PUT request replacing mutable data with immutable is not supported");
return;
case SUCCESS:
PutResponse rsp = new PutResponse(req.getMTID());
rsp.setDestination(req.getOrigin());
req.getServer().sendMessage(rsp);
break;
}
node.recieved(req);
}
public void getPeers (GetPeersRequest r) {
if (!isRunning()) {
return;
}
// ignore requests we get from ourself
if (node.isLocalId(r.getID())) {
return;
}
BloomFilterBEP33 peerFilter = r.isScrape() ? db.createScrapeFilter(r.getInfoHash(), false) : null;
BloomFilterBEP33 seedFilter = r.isScrape() ? db.createScrapeFilter(r.getInfoHash(), true) : null;
boolean v6 = Inet6Address.class.isAssignableFrom(type.PREFERRED_ADDRESS_TYPE);
boolean heavyWeight = peerFilter != null;
int valuesTargetLength = v6 ? 35 : 50;
// scrape filter gobble up a lot of space, restrict list sizes
if(heavyWeight)
valuesTargetLength = v6 ? 15 : 30;
List<DBItem> dbl = db.sample(r.getInfoHash(), valuesTargetLength,type, r.isNoSeeds());
for(DHTIndexingListener listener : indexingListeners)
{
List<PeerAddressDBItem> toAdd = listener.incomingPeersRequest(r.getInfoHash(), r.getOrigin().getAddress(), r.getID());
if(dbl == null && !toAdd.isEmpty())
dbl = new ArrayList<>();
if(dbl != null && !toAdd.isEmpty())
dbl.addAll(toAdd);
}
// generate a token
ByteWrapper token = null;
if(db.insertForKeyAllowed(r.getInfoHash()))
token = db.genToken(r.getID(), r.getOrigin().getAddress(), r.getOrigin().getPort(), r.getInfoHash());
int want4 = r.doesWant4() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0;
int want6 = r.doesWant6() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0;
if(v6 && peerFilter != null)
want6 = Math.min(5, want6);
// only fulfill both wants if we have neither filters nor values to send
if(heavyWeight || dbl != null) {
if(v6)
want4 = 0;
else
want6 = 0;
}
GetPeersResponse resp = new GetPeersResponse(r.getMTID());
populateResponse(r.getTarget(), resp, want4, want6);
resp.setToken(token != null ? token.arr : null);
resp.setScrapePeers(peerFilter);
resp.setScrapeSeeds(seedFilter);
resp.setPeerItems(dbl);
resp.setDestination(r.getOrigin());
r.getServer().sendMessage(resp);
node.recieved(r);
}
public void announce (AnnounceRequest r) {
if (!isRunning()) {
return;
}
// ignore requests we get from ourself
if (node.isLocalId(r.getID())) {
return;
}
// first check if the token is OK
ByteWrapper token = new ByteWrapper(r.getToken());
if (!db.checkToken(token, r.getID(), r.getOrigin().getAddress(), r.getOrigin().getPort(), r.getInfoHash())) {
logDebug("DHT Received Announce Request with invalid token.");
sendError(r, ErrorCode.ProtocolError.code, "Invalid Token; tokens expire after "+DHTConstants.TOKEN_TIMEOUT+"ms; only valid for the IP/port to which it was issued; only valid for the infohash for which it was issued");
return;
}
logDebug("DHT Received Announce Request, adding peer to db: "
+ r.getOrigin().getAddress());
// everything OK, so store the value
PeerAddressDBItem item = PeerAddressDBItem.createFromAddress(r.getOrigin().getAddress(), r.getPort(), r.isSeed());
r.getVersion().ifPresent(item::setVersion);
if(!AddressUtils.isBogon(item))
db.store(r.getInfoHash(), item);
// send a proper response to indicate everything is OK
AnnounceResponse rsp = new AnnounceResponse(r.getMTID());
rsp.setDestination(r.getOrigin());
r.getServer().sendMessage(rsp);
node.recieved(r);
}
public void sample(SampleRequest r) {
if(!isRunning())
return;
SampleResponse rsp = new SampleResponse(r.getMTID());
rsp.setSamples(db.samples());
rsp.setDestination(r.getOrigin());
rsp.setNum(db.getStats().getKeyCount());
rsp.setInterval((int) TimeUnit.MILLISECONDS.toSeconds(DHTConstants.CHECK_FOR_EXPIRED_ENTRIES));
populateResponse(r.getTarget(), rsp, r.doesWant4() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0, r.doesWant6() ? DHTConstants.MAX_ENTRIES_PER_BUCKET : 0);
r.getServer().sendMessage(rsp);
node.recieved(r);
}
public void error (ErrorMessage r) {
StringBuilder b = new StringBuilder();
b.append("Error [").append( r.getCode() ).append("] from: " ).append(r.getOrigin());
b.append(" Message: \"").append(r.getMessage()).append("\"");
r.getVersion().ifPresent(v -> b.append(" version:").append(prettyPrint(v)));
DHT.logError(b.toString());
}
public void timeout (RPCCall r) {
if (isRunning()) {
node.onTimeout(r);
}
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#addDHTNode(java.lang.String, int)
*/
public void addDHTNode (String host, int hport) {
if (!isRunning()) {
return;
}
InetSocketAddress addr = new InetSocketAddress(host, hport);
if (!addr.isUnresolved() && !AddressUtils.isBogon(addr)) {
if(!type.PREFERRED_ADDRESS_TYPE.isInstance(addr.getAddress()) || node.getNumEntriesInRoutingTable() > DHTConstants.BOOTSTRAP_IF_LESS_THAN_X_PEERS)
return;
RPCServer srv = serverManager.getRandomActiveServer(true);
if(srv != null)
srv.ping(addr);
}
}
/**
* returns a non-enqueued task for further configuration. or zero if the request cannot be serviced.
* use the task-manager to actually start the task.
*/
public PeerLookupTask createPeerLookup (byte[] info_hash) {
if (!isRunning()) {
return null;
}
Key id = new Key(info_hash);
RPCServer srv = serverManager.getRandomActiveServer(false);
if(srv == null)
return null;
PeerLookupTask lookupTask = new PeerLookupTask(srv, node, id);
return lookupTask;
}
public AnnounceTask announce(PeerLookupTask lookup, boolean isSeed, int btPort) {
if (!isRunning()) {
return null;
}
// reuse the same server to make sure our tokens are still valid
AnnounceTask announce = new AnnounceTask(lookup.getRPC(), node, lookup.getInfoHash(), btPort, lookup.getAnnounceCanidates());
announce.setSeed(isSeed);
tman.addTask(announce);
return announce;
}
public GenericStorage getStorage() {
return storage;
}
public DHTConfiguration getConfig() {
return config;
}
public AnnounceNodeCache getCache() {
return cache;
}
public RPCServerManager getServerManager() {
return serverManager;
}
public NIOConnectionManager getConnectionManager() {
return connectionManager;
}
public PopulationEstimator getEstimator() {
return estimator;
}
public DHTtype getType() {
return type;
}
public NonReachableCache getUnreachableCache() {
return unreachableCache;
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#getStats()
*/
public DHTStats getStats () {
return stats;
}
/**
* @return the status
*/
public DHTStatus getStatus () {
return status;
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#isRunning()
*/
public boolean isRunning () {
return running;
}
private int getPort() {
int port = config.getListeningPort();
if(port < 1 || port > 65535)
port = 49001;
return port;
}
final RPCCallListener rpcListener = new RPCCallListener() {
public void stateTransition(RPCCall c, RPCState previous, RPCState current) {
if(current == RPCState.RESPONDED)
mismatchDetector.add(c);
if(current == RPCState.RESPONDED || current == RPCState.TIMEOUT)
unreachableCache.onCallFinished(c);
if(current == RPCState.RESPONDED || current == RPCState.TIMEOUT || current == RPCState.STALLED)
tman.dequeue(c.getRequest().getServer());
}
};
final Consumer<RPCServer> serverListener = (srv) -> {
node.registerServer(srv);
srv.onEnqueue((c) -> {
c.addListener(rpcListener);
});
};
void populate() {
serverStats = new RPCStats();
cache = new AnnounceNodeCache();
stats.setRpcStats(serverStats);
serverManager = new RPCServerManager(this);
mismatchDetector = new IDMismatchDetector(this);
node = new Node(this);
unreachableCache = new NonReachableCache();
serverManager.notifyOnServerAdded(serverListener);
db = new Database();
stats.setDbStats(db.getStats());
tman = new TaskManager(this);
running = true;
storage = new GenericStorage();
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#start(java.lang.String, int)
*/
public void start (DHTConfiguration config)
throws SocketException {
if (running) {
return;
}
if(this.scheduler == null)
this.scheduler = getDefaultScheduler();
this.config = config;
useRouterBootstrapping = !config.noRouterBootstrap();
if(!Files.isDirectory(config.getStoragePath()))
DHT.log("Warning: storage path " + config.getStoragePath() +" is not a directory. DHT will not be able to persist state" , LogLevel.Info);
table_file = config.getStoragePath().resolve(type.shortName+"-table.cache");
setStatus(DHTStatus.Stopped, DHTStatus.Initializing);
stats.resetStartedTimestamp();
logInfo("Starting DHT on port " + getPort());
// we need the IPs to filter bootstrap nodes out from the routing table. but don't block startup on DNS resolution
scheduler.execute(this::resolveBootstrapAddresses);
connectionManager = new NIOConnectionManager("mlDHT "+type.shortName+" NIO Selector");
populate();
node.initKey(config);
node.loadTable(table_file);
// these checks are fairly expensive on large servers (network interface enumeration)
// schedule them separately
scheduledActions.add(scheduler.scheduleWithFixedDelay(serverManager::doBindChecks, 10, 10, TimeUnit.SECONDS));
scheduledActions.add(scheduler.scheduleWithFixedDelay(() -> {
// maintenance that should run all the time, before the first queries
tman.dequeue();
if (running)
onStatsUpdate();
}, 5000, DHTConstants.DHT_UPDATE_INTERVAL, TimeUnit.MILLISECONDS));
// initialize as many RPC servers as we need
serverManager.refresh(System.currentTimeMillis());
started();
}
public void started () {
for(RoutingTableEntry bucket : node.table().list()) {
RPCServer srv = serverManager.getRandomServer();
if(srv == null)
break;
Task t = new PingRefreshTask(srv, node, bucket.getBucket(), true);
t.setInfo("Startup ping for " + bucket.prefix);
if(t.getTodoCount() > 0)
tman.addTask(t);
}
bootstrap();
/*
if(type == DHTtype.IPV6_DHT)
{
Task t = new KeyspaceCrawler(srv, node);
tman.addTask(t);
}*/
scheduledActions.add(scheduler.scheduleWithFixedDelay(() -> {
try {
update();
} catch (RuntimeException e) {
log(e, LogLevel.Fatal);
}
}, 5000, DHTConstants.DHT_UPDATE_INTERVAL, TimeUnit.MILLISECONDS));
scheduledActions.add(scheduler.scheduleWithFixedDelay(() -> {
try
{
long now = System.currentTimeMillis();
db.expire(now);
cache.cleanup(now);
storage.cleanup();
} catch (Exception e)
{
log(e, LogLevel.Fatal);
}
}, 1000, DHTConstants.CHECK_FOR_EXPIRED_ENTRIES, TimeUnit.MILLISECONDS));
scheduledActions.add(scheduler.scheduleWithFixedDelay(node::decayThrottle, 1, Node.throttleUpdateIntervalMinutes, TimeUnit.MINUTES));
// single ping to a random node per server to check socket liveness
scheduledActions.add(scheduler.scheduleWithFixedDelay(() -> {
for(RPCServer srv : serverManager.getAllServers()) {
if(srv.getNumActiveRPCCalls() > 0)
continue;
node.getRandomEntry().ifPresent((entry) -> {
PingRequest req = new PingRequest();
req.setDestination(entry.getAddress());
RPCCall call = new RPCCall(req);
call.builtFromEntry(entry);
call.setExpectedID(entry.getID());
srv.doCall(call);
});
}
;
}, 1, 10, TimeUnit.SECONDS));
// deep lookup to make ourselves known to random parts of the keyspace
scheduledActions.add(scheduler.scheduleWithFixedDelay(() -> {
try {
for(RPCServer srv : serverManager.getAllServers())
findNode(Key.createRandomKey(), false, false, srv, t -> t.setInfo("Random Refresh Lookup"));
} catch (RuntimeException e1) {
log(e1, LogLevel.Fatal);
}
try {
if(!node.isInSurvivalMode())
node.saveTable(table_file);
} catch (IOException e2) {
e2.printStackTrace();
}
}, DHTConstants.RANDOM_LOOKUP_INTERVAL, DHTConstants.RANDOM_LOOKUP_INTERVAL, TimeUnit.MILLISECONDS));
scheduledActions.add(scheduler.scheduleWithFixedDelay(mismatchDetector::purge, 2, 3, TimeUnit.MINUTES));
scheduledActions.add(scheduler.scheduleWithFixedDelay(unreachableCache::cleanStaleEntries, 2, 3, TimeUnit.MINUTES));
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#stop()
*/
public void stop () {
if (!running) {
return;
}
//scheduler.shutdown();
logInfo("Initated DHT shutdown");
for (Task t : tman.getActiveTasks()) {
t.kill();
}
for(ScheduledFuture<?> future : scheduledActions) {
future.cancel(false);
// none of the scheduled tasks should experience exceptions, log them if they did
try {
future.get();
} catch (ExecutionException e) {
DHT.log(e.getCause(), LogLevel.Fatal);
} catch (InterruptedException e) {
DHT.log(e, LogLevel.Fatal);
} catch (CancellationException e) {
// do nothing, we just cancelled it
}
}
// scheduler.getQueue().removeAll(scheduledActions);
scheduledActions.clear();
logInfo("stopping servers");
running = false;
serverManager.destroy();
try {
logInfo("persisting routing table on shutdown");
node.saveTable(table_file);
logInfo("table persisted");
} catch (IOException e) {
e.printStackTrace();
}
stopped();
tman = null;
db = null;
node = null;
cache = null;
serverManager = null;
setStatus(DHTStatus.Initializing, DHTStatus.Stopped);
setStatus(DHTStatus.Running, DHTStatus.Stopped);
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#getNode()
*/
public Node getNode () {
return node;
}
public IDMismatchDetector getMismatchDetector() {
return mismatchDetector;
}
public Database getDatabase() {
return db;
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#getTaskManager()
*/
public TaskManager getTaskManager () {
return tman;
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#stopped()
*/
public void stopped () {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see lbms.plugins.mldht.kad.DHTBase#update()
*/
public void update () {
long now = System.currentTimeMillis();
serverManager.refresh(now);
if (!isRunning()) {
return;
}
node.doBucketChecks(now);
if (node.getNumEntriesInRoutingTable() < DHTConstants.BOOTSTRAP_IF_LESS_THAN_X_PEERS || now - lastBootstrap > DHTConstants.SELF_LOOKUP_INTERVAL) {
//regualary search for our id to update routing table
bootstrap();
} else {
setStatus(DHTStatus.Initializing, DHTStatus.Running);
}
}
private Collection<InetSocketAddress> bootstrapAddresses = Collections.emptyList();
private void resolveBootstrapAddresses() {
List<InetSocketAddress> nodeAddresses = new ArrayList<>();
for(InetSocketAddress unres : DHTConstants.UNRESOLVED_BOOTSTRAP_NODES) {
try {
for(InetAddress addr : InetAddress.getAllByName(unres.getHostString())) {
if(type.canUseAddress(addr))
nodeAddresses.add(new InetSocketAddress(addr, unres.getPort()));
}
} catch (Exception e) {
DHT.log("DNS lookupg for " + unres.getHostString() + "failed: " + e.getMessage(), LogLevel.Info);
}
}
// don't overwrite old addresses if DNS fails
if(!nodeAddresses.isEmpty())
bootstrapAddresses = nodeAddresses;
}
Collection<InetSocketAddress> getBootStrapNodes() {
return bootstrapAddresses;
}
/**
* Initiates a Bootstrap.
*
* This function bootstraps with router.bittorrent.com if there are less
* than 10 Peers in the routing table. If there are more then a lookup on
* our own ID is initiated. If the either Task is finished than it will try
* to fill the Buckets.
*/
public synchronized void bootstrap () {
if (!isRunning() || System.currentTimeMillis() - lastBootstrap < DHTConstants.BOOTSTRAP_MIN_INTERVAL) {
return;
}
if(!bootstrapping.compareAndSet(BootstrapState.NONE, BootstrapState.FILL))
return;
if (useRouterBootstrapping && node.getNumEntriesInRoutingTable() < DHTConstants.USE_BT_ROUTER_IF_LESS_THAN_X_PEERS) {
routerBootstrap();
} else {
fillHomeBuckets(Collections.emptyList());
}
}