This repository has been archived by the owner on Jun 25, 2021. It is now read-only.
/
node.rs
3951 lines (3689 loc) · 145 KB
/
node.rs
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
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use super::common::{Base, Bootstrapped, USER_MSG_CACHE_EXPIRY_DURATION_SECS};
use ack_manager::{Ack, AckManager};
use action::Action;
use cache::Cache;
use config_handler;
use crust::{ConnectionInfoResult, CrustError, CrustUser};
use cumulative_own_section_merge::CumulativeOwnSectionMerge;
use error::{BootstrapResponseError, InterfaceError, RoutingError};
use event::Event;
#[cfg(feature = "use-mock-crust")]
use fake_clock::FakeClock as Instant;
use id::{FullId, PublicId};
use itertools::Itertools;
use log::Level;
use lru_time_cache::LruCache;
use maidsafe_utilities::serialisation;
use messages::{
DirectMessage, HopMessage, Message, MessageContent, RoutingMessage, SectionList, SignedMessage,
UserMessage, UserMessageCache, DEFAULT_PRIORITY, MAX_PARTS, MAX_PART_LEN,
};
use outbox::{EventBox, EventBuf};
use peer_manager::{
ConnectionInfoPreparedResult, Peer, PeerManager, PeerState, ReconnectingPeer,
RoutingConnection, SectionMap,
};
use rand::{self, Rng};
use rate_limiter::RateLimiter;
use resource_prover::{ResourceProver, RESOURCE_PROOF_DURATION_SECS};
use routing_message_filter::{FilteringResult, RoutingMessageFilter};
use routing_table::Error as RoutingTableError;
use routing_table::{
Authority, OwnMergeState, Prefix, RemovalDetails, RoutingTable, VersionedPrefix, Xorable,
};
use rust_sodium::crypto::{box_, sign};
use section_list_cache::SectionListCache;
use sha3::Digest256;
use signature_accumulator::SignatureAccumulator;
use state_machine::Transition;
use stats::Stats;
#[cfg(feature = "use-mock-crust")]
use std::collections::BTreeMap;
use std::collections::{BTreeSet, VecDeque};
use std::fmt::{Debug, Formatter};
use std::net::IpAddr;
use std::time::Duration;
#[cfg(not(feature = "use-mock-crust"))]
use std::time::Instant;
use std::{cmp, fmt, iter, mem};
use timer::Timer;
use tunnels::Tunnels;
use types::{MessageId, RoutingActionSender};
use utils::{self, DisplayDuration};
use xor_name::XorName;
use {
CrustEvent, PrivConnectionInfo, PubConnectionInfo, Service, QUORUM_DENOMINATOR,
QUORUM_NUMERATOR,
};
/// Time (in seconds) after which a `Tick` event is sent.
const TICK_TIMEOUT_SECS: u64 = 60;
/// The number of required leading zero bits for the resource proof
const RESOURCE_PROOF_DIFFICULTY: u8 = 0;
/// The total size of the resource proof data.
const RESOURCE_PROOF_TARGET_SIZE: usize = 250 * 1024 * 1024;
/// Initial delay between a routing table change and sending a `SectionUpdate`, in seconds.
const SU_MIN_TIMEOUT_SECS: u64 = 30;
/// Maximal delay between two subsequent `SectionUpdate`s, in seconds.
const SU_MAX_TIMEOUT_SECS: u64 = 300;
/// Interval between displaying info about current candidate, in seconds.
const CANDIDATE_STATUS_INTERVAL_SECS: u64 = 60;
/// Duration for which `OwnSectionMerge` messages are kept in the cache, in seconds.
const MERGE_TIMEOUT_SECS: u64 = 300;
/// Duration for which all clients on a given IP will be blocked from joining this node, in seconds.
const CLIENT_BAN_SECS: u64 = 2 * 60 * 60;
/// Duration for which clients' IDs we disconnected from are retained, in seconds.
const DROPPED_CLIENT_TIMEOUT_SECS: u64 = 2 * 60 * 60;
pub struct Node {
ack_mgr: AckManager,
cacheable_user_msg_cache: UserMessageCache,
crust_service: Service,
/// ID from before relocating.
old_full_id: FullId,
full_id: FullId,
is_first_node: bool,
is_approved: bool,
/// The queue of routing messages addressed to us. These do not themselves need forwarding,
/// although they may wrap a message which needs forwarding.
msg_queue: VecDeque<RoutingMessage>,
peer_mgr: PeerManager,
response_cache: Box<Cache>,
routing_msg_filter: RoutingMessageFilter,
sig_accumulator: SignatureAccumulator,
section_list_sigs: SectionListCache,
stats: Stats,
tick_timer_token: u64,
timer: Timer,
tunnels: Tunnels,
user_msg_cache: UserMessageCache,
/// Value which can be set in mock-crust tests to be used as the calculated name for the next
/// relocation request received by this node.
next_relocation_dst: Option<XorName>,
/// Interval used for relocation in mock crust tests.
next_relocation_interval: Option<(XorName, XorName)>,
/// The current duration between `RoutingTableRequest`s we send. Doubles with every message.
su_timeout: Duration,
/// The timer token for sending the next `RoutingTableRequest`.
su_timer_token: Option<u64>,
/// `RoutingMessage`s affecting the routing table that arrived before `NodeApproval`.
routing_msg_backlog: Vec<RoutingMessage>,
/// Cache of `OwnSectionMerge` messages we have received, by sender section prefix.
merge_cache: LruCache<Prefix<XorName>, SectionMap>,
/// Union of our merged section, deduced from multiple `OwnSectionMerge`.
our_merged_section: CumulativeOwnSectionMerge,
/// The timer token for sending a `CandidateApproval` message.
candidate_timer_token: Option<u64>,
/// The timer token for displaying the current candidate status.
candidate_status_token: Option<u64>,
resource_prover: ResourceProver,
joining_prefix: Prefix<XorName>,
/// Limits the rate at which clients can pass messages through this node when it acts as their
/// proxy.
clients_rate_limiter: RateLimiter,
/// IPs of clients which have been temporarily blocked from bootstrapping off this node.
banned_client_ips: LruCache<IpAddr, ()>,
/// Recently-disconnected clients. Clients are added to this when we disconnect from them so we
/// have a way to know to not handle subsequent hop messages from them (i.e. those which were
/// already enqueued in the channel or added before Crust handled the disconnect request). If a
/// client then re-connects, its ID is removed from here when we add it to the `PeerManager`.
dropped_clients: LruCache<PublicId, ()>,
/// Proxy client traffic handled
proxy_load_amount: u64,
/// Whether resource proof is disabled.
disable_resource_proof: bool,
}
impl Node {
pub fn first(
action_sender: RoutingActionSender,
cache: Box<Cache>,
crust_service: Service,
full_id: FullId,
min_section_size: usize,
timer: Timer,
) -> Option<Self> {
// old_id is useless for first node
let old_id = FullId::new();
let mut node = Self::new(
action_sender,
cache,
crust_service,
true,
old_id,
full_id,
min_section_size,
Stats::new(),
timer,
0,
);
if let Err(error) = node.crust_service.start_listening_tcp() {
error!("{:?} Failed to start listening: {:?}", node, error);
None
} else {
debug!("{:?} State changed to node.", node);
info!("{:?} Started a new network as a seed node.", node);
Some(node)
}
}
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
pub fn from_bootstrapping(
our_section: (Prefix<XorName>, BTreeSet<PublicId>),
action_sender: RoutingActionSender,
cache: Box<Cache>,
crust_service: Service,
old_full_id: FullId,
new_full_id: FullId,
min_section_size: usize,
proxy_pub_id: PublicId,
stats: Stats,
timer: Timer,
) -> Self {
let mut node = Self::new(
action_sender,
cache,
crust_service,
false,
old_full_id,
new_full_id,
min_section_size,
stats,
timer,
our_section.1.len(),
);
node.joining_prefix = our_section.0;
node.peer_mgr.insert_peer(Peer::new(
proxy_pub_id,
PeerState::Proxy,
false,
ReconnectingPeer::False,
));
node.join(our_section.1, &proxy_pub_id);
node
}
#[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
fn new(
action_sender: RoutingActionSender,
cache: Box<Cache>,
crust_service: Service,
first_node: bool,
old_full_id: FullId,
new_full_id: FullId,
min_section_size: usize,
stats: Stats,
timer: Timer,
challenger_count: usize,
) -> Self {
let dev_config = config_handler::get_config().dev.unwrap_or_default();
let public_id = *new_full_id.public_id();
let tick_period = Duration::from_secs(TICK_TIMEOUT_SECS);
let tick_timer_token = timer.schedule(tick_period);
let user_msg_cache_duration = Duration::from_secs(USER_MSG_CACHE_EXPIRY_DURATION_SECS);
Node {
ack_mgr: AckManager::new(),
cacheable_user_msg_cache: UserMessageCache::with_expiry_duration(
user_msg_cache_duration,
),
crust_service,
old_full_id,
full_id: new_full_id,
is_first_node: first_node,
is_approved: first_node,
msg_queue: VecDeque::new(),
peer_mgr: PeerManager::new(
min_section_size,
public_id,
dev_config.disable_client_rate_limiter,
),
response_cache: cache,
routing_msg_filter: RoutingMessageFilter::new(),
sig_accumulator: Default::default(),
section_list_sigs: SectionListCache::new(),
stats,
tick_timer_token,
timer: timer.clone(),
tunnels: Default::default(),
user_msg_cache: UserMessageCache::with_expiry_duration(user_msg_cache_duration),
next_relocation_dst: None,
next_relocation_interval: None,
su_timeout: Duration::from_secs(SU_MIN_TIMEOUT_SECS),
su_timer_token: None,
routing_msg_backlog: vec![],
merge_cache: LruCache::with_expiry_duration(Duration::from_secs(MERGE_TIMEOUT_SECS)),
our_merged_section: Default::default(),
candidate_timer_token: None,
candidate_status_token: None,
resource_prover: ResourceProver::new(action_sender, timer, challenger_count),
joining_prefix: Default::default(),
clients_rate_limiter: RateLimiter::new(dev_config.disable_client_rate_limiter),
banned_client_ips: LruCache::with_expiry_duration(Duration::from_secs(CLIENT_BAN_SECS)),
dropped_clients: LruCache::with_expiry_duration(Duration::from_secs(
DROPPED_CLIENT_TIMEOUT_SECS,
)),
proxy_load_amount: 0,
disable_resource_proof: dev_config.disable_resource_proof,
}
}
/// Called immediately after bootstrapping. Sends `ConnectionInfoRequest`s to all members of
/// `our_section` to then start the candidate approval process.
fn join(&mut self, our_section: BTreeSet<PublicId>, proxy_public_id: &PublicId) {
self.resource_prover.start(self.disable_resource_proof);
trace!("{:?} Relocation completed.", self);
info!(
"{:?} Received relocation section. Establishing connections to {} peers.",
self,
our_section.len()
);
let src = Authority::Client {
client_id: *self.full_id.public_id(),
proxy_node_name: *proxy_public_id.name(),
};
// There will be no events raised as a result of these calls, so safe to just use a
// throwaway `EventBox` here.
let mut outbox = EventBuf::new();
for pub_id in &our_section {
debug!(
"{:?} Sending connection info to {:?} on Relocation response.",
self, pub_id
);
let dst = Authority::ManagedNode(*pub_id.name());
if let Err(error) = self.send_connection_info_request(
*pub_id,
src,
dst,
&mut outbox,
ReconnectingPeer::False,
) {
debug!(
"{:?} - Failed to send connection info to {:?}: {:?}",
self, pub_id, error
);
}
}
}
fn update_stats(&mut self) {
let old_client_num = self.stats.cur_client_num;
self.stats.cur_client_num = self.peer_mgr.client_num();
if self.stats.cur_client_num != old_client_num {
if self.stats.cur_client_num > old_client_num {
self.stats.cumulative_client_num += self.stats.cur_client_num - old_client_num;
}
if self.is_approved {
info!(target: "routing_stats", "{:?} - Connected clients: {}, cumulative: {}",
self,
self.stats.cur_client_num,
self.stats.cumulative_client_num);
}
}
if self.stats.tunnel_connections != self.tunnels.tunnel_count()
|| self.stats.tunnel_client_pairs != self.tunnels.client_count()
{
self.stats.tunnel_connections = self.tunnels.tunnel_count();
self.stats.tunnel_client_pairs = self.tunnels.client_count();
if self.is_approved {
info!(target: "routing_stats",
"{:?} - Indirect connections: {}, tunnelling for: {}",
self,
self.stats.tunnel_connections,
self.stats.tunnel_client_pairs);
}
}
if self.stats.cur_routing_table_size != self.routing_table().len() {
self.stats.cur_routing_table_size = self.routing_table().len();
if self.is_approved {
self.print_rt_size();
}
}
}
fn print_rt_size(&self) {
const TABLE_LVL: Level = Level::Info;
if log_enabled!(TABLE_LVL) {
let status_str = format!(
"{:?} - Routing Table size: {:3}",
self, self.stats.cur_routing_table_size
);
let network_estimate = match self.routing_table().network_size_estimate() {
(n, true) => format!("Exact network size: {}", n),
(n, false) => format!("Estimated network size: {}", n),
};
let sep_len = cmp::max(status_str.len(), network_estimate.len());
let sep_str = iter::repeat('-').take(sep_len).collect::<String>();
log!(target: "routing_stats", TABLE_LVL, " -{}- ", sep_str);
log!(target: "routing_stats", TABLE_LVL, "| {:<1$} |", status_str, sep_len);
log!(target: "routing_stats", TABLE_LVL, "| {:<1$} |", network_estimate, sep_len);
log!(target: "routing_stats", TABLE_LVL, " -{}- ", sep_str);
}
}
pub fn handle_action(&mut self, action: Action, outbox: &mut EventBox) -> Transition {
match action {
Action::ClientSendRequest { result_tx, .. } => {
let _ = result_tx.send(Err(InterfaceError::InvalidState));
}
Action::NodeSendMessage {
src,
dst,
content,
priority,
result_tx,
} => {
let result = match self.send_user_message(src, dst, content, priority) {
Err(RoutingError::Interface(err)) => Err(err),
Err(_) | Ok(()) => Ok(()),
};
let _ = result_tx.send(result);
}
Action::Id { result_tx } => {
let _ = result_tx.send(*self.id());
}
Action::Timeout(token) => {
if let Transition::Terminate = self.handle_timeout(token, outbox) {
return Transition::Terminate;
}
}
Action::ResourceProofResult(pub_id, messages) => {
let msg = self
.resource_prover
.handle_action_res_proof(pub_id, messages);
self.send_direct_message(pub_id, msg);
}
Action::Terminate => {
return Transition::Terminate;
}
}
self.handle_routing_messages(outbox);
self.update_stats();
Transition::Stay
}
pub fn handle_crust_event(
&mut self,
crust_event: CrustEvent<PublicId>,
outbox: &mut EventBox,
) -> Transition {
match crust_event {
CrustEvent::BootstrapAccept(pub_id, peer_kind) => {
self.handle_bootstrap_accept(pub_id, peer_kind)
}
CrustEvent::BootstrapConnect(pub_id, _) => {
self.handle_bootstrap_connect(pub_id, outbox)
}
CrustEvent::ConnectSuccess(pub_id) => self.handle_connect_success(pub_id, outbox),
CrustEvent::ConnectFailure(pub_id) => self.handle_connect_failure(pub_id),
CrustEvent::LostPeer(pub_id) => {
if let Transition::Terminate = self.handle_lost_peer(pub_id, outbox) {
return Transition::Terminate;
}
}
CrustEvent::NewMessage(pub_id, _peer_kind, bytes) => {
match self.handle_new_message(pub_id, bytes, outbox) {
Err(RoutingError::FilterCheckFailed) | Ok(_) => (),
Err(err) => debug!("{:?} - {:?}", self, err),
}
}
CrustEvent::ConnectionInfoPrepared(ConnectionInfoResult {
result_token,
result,
}) => self.handle_connection_info_prepared(result_token, result),
CrustEvent::ListenerStarted(port) => {
trace!("{:?} Listener started on port {}.", self, port);
// If first node, allow other peers to bootstrap via us
// else wait until NodeApproval.
if self.is_first_node {
if let Err(err) = self.crust_service.set_accept_bootstrap(true) {
warn!(
"{:?} Unable to accept bootstrap connections. {:?}",
self, err
);
}
self.crust_service.set_service_discovery_listen(true);
}
return Transition::Stay;
}
CrustEvent::ListenerFailed => {
error!("{:?} Failed to start listening.", self);
outbox.send_event(Event::Terminate);
return Transition::Terminate;
}
CrustEvent::WriteMsgSizeProhibitive(pub_id, msg) => {
error!(
"{:?} Failed to send {}-byte message to {:?}. Message too large.",
self,
msg.len(),
pub_id
);
}
_ => {
debug!("{:?} - Unhandled crust event: {:?}", self, crust_event);
}
}
self.handle_routing_messages(outbox);
self.update_stats();
Transition::Stay
}
/// Routing table of this node.
pub fn routing_table(&self) -> &RoutingTable<XorName> {
self.peer_mgr.routing_table()
}
fn handle_routing_messages(&mut self, outbox: &mut EventBox) {
while let Some(routing_msg) = self.msg_queue.pop_front() {
if self.in_authority(&routing_msg.dst) {
if let Err(err) = self.dispatch_routing_message(routing_msg, outbox) {
debug!("{:?} Routing message dispatch failed: {:?}", self, err);
}
}
}
}
fn handle_bootstrap_accept(&mut self, pub_id: PublicId, peer_kind: CrustUser) {
trace!(
"{:?} Received BootstrapAccept from {:?} as {:?}.",
self,
pub_id,
peer_kind
);
let ip = if let Ok(ip) = self.crust_service.get_peer_ip_addr(&pub_id) {
ip
} else {
debug!(
"{:?} Can't get IP address of bootstrapper {:?}.",
self, pub_id
);
self.disconnect_peer(&pub_id, None);
if peer_kind == CrustUser::Client {
let _ = self.dropped_clients.insert(pub_id, ());
}
return;
};
if peer_kind == CrustUser::Client && self.banned_client_ips.contains_key(&ip) {
warn!(
"{:?} Client {:?} is trying to bootstrap on banned IP {}.",
self, pub_id, ip
);
self.ban_and_disconnect_peer(&pub_id);
return;
}
self.peer_mgr.insert_peer(Peer::new(
pub_id,
PeerState::Bootstrapper { peer_kind, ip },
false,
ReconnectingPeer::False,
));
}
fn handle_bootstrap_connect(&mut self, pub_id: PublicId, outbox: &mut EventBox) {
// A mature node doesn't need a bootstrap connection
self.disconnect_peer(&pub_id, Some(outbox))
}
fn handle_connect_success(&mut self, pub_id: PublicId, outbox: &mut EventBox) {
// Remove tunnel connection if we have one for this peer already
if let Some(tunnel_id) = self.tunnels.remove_tunnel_for(&pub_id) {
debug!("{:?} Removing unwanted tunnel for {:?}", self, pub_id);
let message = DirectMessage::TunnelDisconnect(pub_id);
self.send_direct_message(tunnel_id, message);
} else if self.peer_mgr.is_routing_peer(&pub_id) {
warn!(
"{:?} Received ConnectSuccess from {:?}, but node is already in routing \
state in peer_map.",
self, pub_id
);
return;
}
self.peer_mgr.connected_to(&pub_id);
debug!("{:?} Received ConnectSuccess from {}.", self, pub_id);
self.process_connection(pub_id, outbox);
}
fn handle_connect_failure(&mut self, pub_id: PublicId) {
if let Some(&PeerState::CrustConnecting) = self.peer_mgr.get_peer(&pub_id).map(Peer::state)
{
debug!("{:?} Failed to connect to peer {:?}.", self, pub_id);
if self.tunnels.tunnel_for(&pub_id).is_none() {
let valid = self
.peer_mgr
.get_peer(&pub_id)
.map_or(false, |peer| peer.valid());
self.find_tunnel_for_peer(&pub_id, valid);
} else {
debug!("{:?} already has tunnel to peer {}.", self, pub_id);
}
}
}
fn find_tunnel_for_peer(&mut self, pub_id: &PublicId, valid: bool) {
for dst_pub_id in self.peer_mgr.set_searching_for_tunnel(*pub_id, valid) {
trace!(
"{:?} Asking {} to serve as a tunnel for {:?}.",
self,
dst_pub_id,
pub_id
);
let tunnel_request = DirectMessage::TunnelRequest(*pub_id);
self.send_direct_message(dst_pub_id, tunnel_request);
}
}
fn handle_new_message(
&mut self,
pub_id: PublicId,
bytes: Vec<u8>,
outbox: &mut EventBox,
) -> Result<(), RoutingError> {
match serialisation::deserialise(&bytes) {
Ok(Message::Hop(hop_msg)) => self.handle_hop_message(hop_msg, pub_id),
Ok(Message::Direct(direct_msg)) => {
self.handle_direct_message(direct_msg, pub_id, outbox)
}
Ok(Message::TunnelDirect { content, src, dst }) => {
if dst == *self.full_id.public_id() {
if self.tunnels.tunnel_for(&src) == Some(&pub_id) {
self.handle_direct_message(content, src, outbox)
} else {
debug!(
"{:?} Message recd via unregistered tunnel node {} from src {:?}",
self, pub_id, src
);
Err(RoutingError::InvalidDestination)
}
} else if self.tunnels.has_clients(src, dst) {
self.send_or_drop(&dst, bytes, content.priority());
Ok(())
} else if !self.peer_mgr.can_tunnel_for(&src, &dst) {
debug!(
"{:?} Can no longer accept as a tunnel node for {:?} - {:?}",
self, src, dst
);
self.send_direct_message(src, DirectMessage::TunnelClosed(dst));
Err(RoutingError::InvalidDestination)
} else {
debug!(
"{:?} Invalid TunnelDirect message received via {}: {:?} -> {:?} \
{:?}",
self, pub_id, src, dst, content
);
Err(RoutingError::InvalidDestination)
}
}
Ok(Message::TunnelHop { content, src, dst }) => {
if dst == *self.full_id.public_id() {
self.handle_hop_message(content, src)
} else if self.tunnels.has_clients(src, dst) {
self.send_or_drop(&dst, bytes, content.content.priority());
Ok(())
} else {
debug!(
"{:?} Invalid TunnelHop message received via {}: {:?} -> {:?} {:?}",
self, pub_id, src, dst, content
);
Err(RoutingError::InvalidDestination)
}
}
Err(error) => Err(RoutingError::SerialisationError(error)),
}
}
// Deconstruct a `DirectMessage` and handle or forward as appropriate.
fn handle_direct_message(
&mut self,
direct_message: DirectMessage,
pub_id: PublicId,
outbox: &mut EventBox,
) -> Result<(), RoutingError> {
use messages::DirectMessage::*;
if let Err(error) = self.check_direct_message_sender(&direct_message, &pub_id) {
match error {
RoutingError::ClientConnectionNotFound => (),
_ => self.ban_and_disconnect_peer(&pub_id),
}
return Err(error);
}
match direct_message {
MessageSignature(digest, sig) => self.handle_message_signature(digest, sig, pub_id)?,
SectionListSignature(section_list, sig) => {
self.handle_section_list_signature(pub_id, section_list, sig)?
}
BootstrapRequest(signature) => {
if let Err(error) = self.handle_bootstrap_request(pub_id, signature, outbox) {
warn!(
"{:?} Invalid BootstrapRequest received ({:?}), dropping {}.",
self, error, pub_id
);
self.ban_and_disconnect_peer(&pub_id);
}
}
CandidateInfo {
ref old_public_id,
ref new_public_id,
ref signature_using_old,
ref signature_using_new,
ref new_client_auth,
} => {
if *new_public_id != pub_id {
error!(
"{:?} CandidateInfo(new_public_id: {}) does not match crust id {}.",
self, new_public_id, pub_id
);
self.disconnect_peer(&pub_id, Some(outbox));
return Err(RoutingError::InvalidSource);
}
self.handle_candidate_info(
old_public_id,
&pub_id,
signature_using_old,
signature_using_new,
new_client_auth,
outbox,
);
}
TunnelRequest(dst_id) => self.handle_tunnel_request(pub_id, dst_id, outbox),
TunnelSuccess(dst_id) => self.handle_tunnel_success(pub_id, dst_id, outbox),
TunnelSelect(dst_id) => self.handle_tunnel_select(pub_id, dst_id),
TunnelClosed(dst_id) => self.handle_tunnel_closed(pub_id, dst_id, outbox),
TunnelDisconnect(dst_id) => self.handle_tunnel_disconnect(pub_id, dst_id),
ResourceProof {
seed,
target_size,
difficulty,
} => {
let log_ident = format!("{:?}", self);
self.resource_prover.handle_request(
pub_id,
seed,
target_size,
difficulty,
log_ident,
);
}
ResourceProofResponseReceipt => {
if let Some(msg) = self.resource_prover.handle_receipt(pub_id) {
self.send_direct_message(pub_id, msg);
}
}
ResourceProofResponse {
part_index,
part_count,
proof,
leading_zero_bytes,
} => {
self.handle_resource_proof_response(
pub_id,
part_index,
part_count,
proof,
leading_zero_bytes,
);
}
msg @ BootstrapResponse(_) | msg @ ProxyRateLimitExceeded { .. } => {
debug!("{:?} Unhandled direct message: {:?}", self, msg);
}
}
Ok(())
}
/// Returns `Ok` if the peer's state indicates it's allowed to send the given message type.
fn check_direct_message_sender(
&self,
direct_message: &DirectMessage,
pub_id: &PublicId,
) -> Result<(), RoutingError> {
match self.peer_mgr.get_peer(pub_id).map(Peer::state) {
Some(&PeerState::Bootstrapper { .. }) => {
if let DirectMessage::BootstrapRequest(_) = *direct_message {
return Ok(());
}
}
Some(&PeerState::Client { .. }) => (),
None => return Err(RoutingError::ClientConnectionNotFound),
_ => return Ok(()),
}
debug!(
"{:?} Illegitimate direct message {:?} from {:?}.",
self, direct_message, pub_id
);
Err(RoutingError::InvalidStateForOperation)
}
/// Handles a signature of a `SignedMessage`, and if we have enough to verify the signed
/// message, handles it.
fn handle_message_signature(
&mut self,
digest: Digest256,
sig: sign::Signature,
pub_id: PublicId,
) -> Result<(), RoutingError> {
if !self.peer_mgr.is_routing_peer(&pub_id) {
debug!(
"{:?} Received message signature from unknown peer {}",
self, pub_id
);
return Err(RoutingError::UnknownConnection(pub_id));
}
let min_section_size = self.min_section_size();
if let Some((signed_msg, route)) =
self.sig_accumulator
.add_signature(min_section_size, digest, sig, pub_id)
{
let hop = *self.name(); // we accumulated the message, so now we act as the last hop
self.handle_signed_message(signed_msg, route, hop, &BTreeSet::new())?;
}
Ok(())
}
fn get_section(&self, prefix: &Prefix<XorName>) -> Result<BTreeSet<XorName>, RoutingError> {
let section = self
.routing_table()
.get_section(&prefix.lower_bound())
.ok_or(RoutingError::InvalidSource)?
.iter()
.cloned()
.collect();
Ok(section)
}
fn get_section_list(&self, prefix: &Prefix<XorName>) -> Result<SectionList, RoutingError> {
Ok(SectionList::new(
*prefix,
self.peer_mgr.get_pub_ids(&self.get_section(prefix)?),
))
}
/// Sends a signature for the list of members of all sections that we haven't signed yet.
fn send_section_list_signatures(&mut self) {
for prefix in self.routing_table().prefixes() {
self.send_section_list_signature(prefix, None);
}
}
/// Sends a signature for the list of members of a section with prefix `prefix` to our whole
/// section if `dst` is `None`, or to the given node if it is `Some(name)`
fn send_section_list_signature(&mut self, prefix: Prefix<XorName>, dst: Option<XorName>) {
if cfg!(not(feature = "use-mock-crust")) {
return;
}
let section = match self.get_section_list(&prefix) {
Ok(section) => section,
Err(err) => {
debug!(
"{:?} Error getting section list for {:?}: {:?}",
self, prefix, err
);
return;
}
};
let sig = if let Some(&sig) =
self.section_list_sigs
.get_signature_for(&prefix, self.full_id.public_id(), §ion)
{
sig
} else {
let serialised = match serialisation::serialise(§ion) {
Ok(serialised) => serialised,
Err(err) => {
warn!(
"{:?} Error serialising section list for {:?}: {:?}",
self, prefix, err
);
return;
}
};
let sig = sign::sign_detached(&serialised, self.full_id.signing_private_key());
let section_len = self.routing_table().our_section().len();
let our_id = *self.full_id.public_id();
self.section_list_sigs
.add_signature(prefix, our_id, section.clone(), sig, section_len);
sig
};
// this defines whom we are sending signature to: our section if dst is None, or given
// name if it's Some
let peers = if let Some(dst) = dst {
self.peer_mgr
.get_pub_id(&dst)
.into_iter()
.cloned()
.collect_vec()
} else {
self.routing_table()
.our_section()
.into_iter()
.filter(|&x| *x != *self.name()) // we don't want to send to ourselves
.filter_map(|x| self.peer_mgr.get_pub_id(x))
.cloned()
.collect_vec()
};
for pub_id in peers {
let msg = DirectMessage::SectionListSignature(section.clone(), sig);
self.send_direct_message(pub_id, msg);
}
}
fn handle_section_list_signature(
&mut self,
pub_id: PublicId,
section_list: SectionList,
sig: sign::Signature,
) -> Result<(), RoutingError> {
if !self.peer_mgr.is_routing_peer(&pub_id) {
return Err(RoutingError::InvalidSource);
}
let serialised = serialisation::serialise(§ion_list)?;
if sign::verify_detached(&sig, &serialised, pub_id.signing_public_key()) {
let section_len = self.routing_table().our_section().len();
self.section_list_sigs.add_signature(
section_list.prefix,
pub_id,
section_list,
sig,
section_len,
);
Ok(())
} else {
Err(RoutingError::FailedSignature)
}
}
fn handle_hop_message(
&mut self,
hop_msg: HopMessage,
pub_id: PublicId,
) -> Result<(), RoutingError> {
hop_msg.verify(pub_id.signing_public_key())?;
let mut client_ip = None;
let mut hop_name_result = match self.peer_mgr.get_peer(&pub_id).map(Peer::state) {
Some(&PeerState::Bootstrapper { .. }) => {
warn!(
"{:?} Hop message received from bootstrapper {:?}, disconnecting.",
self, pub_id
);
Err(RoutingError::InvalidStateForOperation)
}
Some(&PeerState::Client { ip, .. }) => {
client_ip = Some(ip);
Ok(*self.name())
}
Some(&PeerState::JoiningNode) => Ok(*self.name()),
Some(&PeerState::Candidate(_))
| Some(&PeerState::Proxy)
| Some(&PeerState::Routing(_)) => Ok(*pub_id.name()),
Some(&PeerState::ConnectionInfoPreparing { .. })
| Some(&PeerState::ConnectionInfoReady(_))
| Some(&PeerState::CrustConnecting)
| Some(&PeerState::SearchingForTunnel)
| Some(&PeerState::Connected(_))
| None => {
if self.dropped_clients.contains_key(&pub_id) {
debug!(
"{:?} Ignoring {:?} from recently-disconnected client {:?}.",
self, hop_msg, pub_id
);
return Ok(());
} else {
Ok(*self.name())
// FIXME - confirm we can return with an error here by running soak tests
// debug!("{:?} Invalid sender {} of {:?}", self, pub_id, hop_msg);
// return Err(RoutingError::InvalidSource);
}
}
};
if let Some(ip) = client_ip {
match self.check_valid_client_message(&ip, hop_msg.content.routing_message()) {
Ok(added_bytes) => {
self.proxy_load_amount += added_bytes;
self.peer_mgr.add_client_traffic(&pub_id, added_bytes);
}
Err(e) => hop_name_result = Err(e),
}
}
match hop_name_result {
Ok(hop_name) => {
let HopMessage {
content,
route,
sent_to,
..
} = hop_msg;
self.handle_signed_message(content, route, hop_name, &sent_to)
}
Err(RoutingError::ExceedsRateLimit(hash)) => {
trace!(
"{:?} Temporarily can't proxy messages from client {:?} (rate-limit hit).",
self,
pub_id
);
self.send_direct_message(
pub_id,
DirectMessage::ProxyRateLimitExceeded {
ack: Ack::compute(hop_msg.content.routing_message())?,
},
);
Err(RoutingError::ExceedsRateLimit(hash))
}
Err(error) => {
self.ban_and_disconnect_peer(&pub_id);
Err(error)
}
}
}