diff --git a/examples/security_configuration_files/allow_unauthenticated/governance.p7s b/examples/security_configuration_files/allow_unauthenticated/governance.p7s new file mode 100644 index 00000000..04398f41 --- /dev/null +++ b/examples/security_configuration_files/allow_unauthenticated/governance.p7s @@ -0,0 +1,70 @@ +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha-256"; boundary="----75D1A96B6AA64466953A0DDB3FA5D00F" + +This is an S/MIME signed message + +------75D1A96B6AA64466953A0DDB3FA5D00F +Content-Type: text/plain + + + + + + + + 0 + 232 + + + + true + true + NONE + NONE + NONE + + + Protected + false + false + true + true + NONE + NONE + + + + + + +------75D1A96B6AA64466953A0DDB3FA5D00F +Content-Type: application/x-pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIID0AYJKoZIhvcNAQcCoIIDwTCCA70CAQExDzANBglghkgBZQMEAgEFADALBgkq +hkiG9w0BBwGgggHjMIIB3zCCAYWgAwIBAgIUZ15lOVw1lFhBNlKlgdqzkhBHDsww +CgYIKoZIzj0EAwIwRDEdMBsGA1UECgwURXhhbXBsZSBPcmdhbml6YXRpb24xIzAh +BgNVBAMMGnBlcm1pc3Npb25zX2NhX2NvbW1vbl9uYW1lMCAXDTI0MDMwODA4Mjk1 +MVoYDzQ3NjIwMjAyMDgyOTUxWjBEMR0wGwYDVQQKDBRFeGFtcGxlIE9yZ2FuaXph +dGlvbjEjMCEGA1UEAwwacGVybWlzc2lvbnNfY2FfY29tbW9uX25hbWUwWTATBgcq +hkjOPQIBBggqhkjOPQMBBwNCAAQwHk/PoxLxEP27ez5jzmof7KDXkcm9APMamnHe +G1E4TbBNZr7FVn5MbsW+5HeklhPSAPC1FefXsOb4AcbO4T/xo1MwUTAdBgNVHQ4E +FgQU1771sTC5VjQST2vWBFVoc6XwiRUwHwYDVR0jBBgwFoAU1771sTC5VjQST2vW +BFVoc6XwiRUwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBIb4Ro +lJ6v4JYqORbipeqKCLV7TuNlayxv6962VSk3yQIhAIjkrqBU9QSO+EIP6bsK+jcc +47gvd+cnf3/zPWJbNt21MYIBsTCCAa0CAQEwXDBEMR0wGwYDVQQKDBRFeGFtcGxl +IE9yZ2FuaXphdGlvbjEjMCEGA1UEAwwacGVybWlzc2lvbnNfY2FfY29tbW9uX25h +bWUCFGdeZTlcNZRYQTZSpYHas5IQRw7MMA0GCWCGSAFlAwQCAQUAoIHkMBgGCSqG +SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTExOTE2MTM1 +N1owLwYJKoZIhvcNAQkEMSIEIKcsv7qawh0F4VROxUTRUG3Jqqgxh2QKCPMwiVNx +oHm4MHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFlAwQBFjAL +BglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0GCCqGSIb3 +DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMAoGCCqGSM49BAMCBEgwRgIh +AL/kUhUKvKt9N/Qy68MUZ7SY8omgGB2qUZbvjl8iSvO3AiEA7wp9+gsBT/MTAwl9 +HLTGBqtGt0dkuSptdeF/x6Au24A= + +------75D1A96B6AA64466953A0DDB3FA5D00F-- + diff --git a/examples/security_configuration_files/allow_unauthenticated/governance_unsigned.xml b/examples/security_configuration_files/allow_unauthenticated/governance_unsigned.xml new file mode 100644 index 00000000..82726d59 --- /dev/null +++ b/examples/security_configuration_files/allow_unauthenticated/governance_unsigned.xml @@ -0,0 +1,32 @@ + + + + + + + 0 + 232 + + + + true + true + NONE + NONE + NONE + + + Protected + false + false + true + true + NONE + NONE + + + + + diff --git a/examples/security_configuration_files/allow_unauthenticated/permissions.p7s b/examples/security_configuration_files/allow_unauthenticated/permissions.p7s new file mode 100644 index 00000000..e52b8a28 --- /dev/null +++ b/examples/security_configuration_files/allow_unauthenticated/permissions.p7s @@ -0,0 +1,70 @@ +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha-256"; boundary="----34E244A1FE97937C84CDDCE9F7AEF215" + +This is an S/MIME signed message + +------34E244A1FE97937C84CDDCE9F7AEF215 +Content-Type: text/plain + + + + + + CN=participant1_common_name,O=Example Organization + + 2023-01-01T00:00:00 + 9999-01-01T00:00:00 + + + + + 0 + 232 + + + + + Protected + + + + + Protected + + + + DENY + + + + +------34E244A1FE97937C84CDDCE9F7AEF215 +Content-Type: application/x-pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIDzgYJKoZIhvcNAQcCoIIDvzCCA7sCAQExDzANBglghkgBZQMEAgEFADALBgkq +hkiG9w0BBwGgggHjMIIB3zCCAYWgAwIBAgIUZ15lOVw1lFhBNlKlgdqzkhBHDsww +CgYIKoZIzj0EAwIwRDEdMBsGA1UECgwURXhhbXBsZSBPcmdhbml6YXRpb24xIzAh +BgNVBAMMGnBlcm1pc3Npb25zX2NhX2NvbW1vbl9uYW1lMCAXDTI0MDMwODA4Mjk1 +MVoYDzQ3NjIwMjAyMDgyOTUxWjBEMR0wGwYDVQQKDBRFeGFtcGxlIE9yZ2FuaXph +dGlvbjEjMCEGA1UEAwwacGVybWlzc2lvbnNfY2FfY29tbW9uX25hbWUwWTATBgcq +hkjOPQIBBggqhkjOPQMBBwNCAAQwHk/PoxLxEP27ez5jzmof7KDXkcm9APMamnHe +G1E4TbBNZr7FVn5MbsW+5HeklhPSAPC1FefXsOb4AcbO4T/xo1MwUTAdBgNVHQ4E +FgQU1771sTC5VjQST2vWBFVoc6XwiRUwHwYDVR0jBBgwFoAU1771sTC5VjQST2vW +BFVoc6XwiRUwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBIb4Ro +lJ6v4JYqORbipeqKCLV7TuNlayxv6962VSk3yQIhAIjkrqBU9QSO+EIP6bsK+jcc +47gvd+cnf3/zPWJbNt21MYIBrzCCAasCAQEwXDBEMR0wGwYDVQQKDBRFeGFtcGxl +IE9yZ2FuaXphdGlvbjEjMCEGA1UEAwwacGVybWlzc2lvbnNfY2FfY29tbW9uX25h +bWUCFGdeZTlcNZRYQTZSpYHas5IQRw7MMA0GCWCGSAFlAwQCAQUAoIHkMBgGCSqG +SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTExOTE2MTQw +NVowLwYJKoZIhvcNAQkEMSIEIPf5TNqUkRbDbKl5HZH1PQ7f8qfFkMSGunuJQ4hX +ptsQMHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFlAwQBFjAL +BglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0GCCqGSIb3 +DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMAoGCCqGSM49BAMCBEYwRAIg +B+OuedMrdud2bXnfz1RFufosa+rFyqIcQD4c+/kz8dQCIAgXGMwIhHFqOyDVrlIS +TPjW2FNoW9Rmebij8aI6WA0U + +------34E244A1FE97937C84CDDCE9F7AEF215-- + diff --git a/examples/security_configuration_files/allow_unauthenticated/permissions_unsigned.xml b/examples/security_configuration_files/allow_unauthenticated/permissions_unsigned.xml new file mode 100644 index 00000000..5e1bc25b --- /dev/null +++ b/examples/security_configuration_files/allow_unauthenticated/permissions_unsigned.xml @@ -0,0 +1,32 @@ + + + + + CN=participant1_common_name,O=Example Organization + + 2023-01-01T00:00:00 + 9999-01-01T00:00:00 + + + + + 0 + 232 + + + + + Protected + + + + + Protected + + + + DENY + + + diff --git a/examples/security_configuration_files/generate-test-certificates-and-signatures.sh b/examples/security_configuration_files/generate-test-certificates-and-signatures.sh index 0c271dae..d38cb137 100755 --- a/examples/security_configuration_files/generate-test-certificates-and-signatures.sh +++ b/examples/security_configuration_files/generate-test-certificates-and-signatures.sh @@ -9,6 +9,8 @@ openssl req -x509 -newkey param:ec_parameters.pem -keyout permissions_ca_private # Sign the configuration documents openssl smime -sign -in governance_unsigned.xml -text -out governance.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password openssl smime -sign -in permissions_unsigned.xml -text -out permissions.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password +openssl smime -sign -in allow_unauthenticated/governance_unsigned.xml -text -out allow_unauthenticated/governance.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password +openssl smime -sign -in allow_unauthenticated/permissions_unsigned.xml -text -out allow_unauthenticated/permissions.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password # Create the identity CA diff --git a/examples/security_configuration_files/sign-test-configurations.sh b/examples/security_configuration_files/sign-test-configurations.sh index d8cd33d8..d83f1785 100755 --- a/examples/security_configuration_files/sign-test-configurations.sh +++ b/examples/security_configuration_files/sign-test-configurations.sh @@ -2,4 +2,8 @@ # Sign test configurations openssl smime -sign -in governance_unsigned.xml -text -out governance.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password -openssl smime -sign -in permissions_unsigned.xml -text -out permissions.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password \ No newline at end of file +openssl smime -sign -in permissions_unsigned.xml -text -out permissions.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password + +# For tests of participants that cannot be authenticated +openssl smime -sign -in allow_unauthenticated/governance_unsigned.xml -text -out allow_unauthenticated/governance.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password +openssl smime -sign -in allow_unauthenticated/permissions_unsigned.xml -text -out allow_unauthenticated/permissions.p7s -signer permissions_ca.cert.pem -inkey permissions_ca_private_key.pem -passin file:password diff --git a/src/discovery/discovery.rs b/src/discovery/discovery.rs index b1f2fbf1..ef035617 100644 --- a/src/discovery/discovery.rs +++ b/src/discovery/discovery.rs @@ -1056,14 +1056,39 @@ impl Discovery { &mut self, participant_data: &SpdpDiscoveredParticipantData, ) { - let was_new = discovery_db_write(&self.discovery_db).update_participant(participant_data); let guid_prefix = participant_data.participant_guid.prefix; + // Readers and writers kept in the attic while this participant was not + // known, e.g. since it timed out + let (was_new, (readers, writers)) = { + let mut db = discovery_db_write(&self.discovery_db); + let was_new = db.update_participant(participant_data); + (was_new, db.take_endpoints_from_attic(guid_prefix)) + }; // Send notification to dp_event_loop. It will update local reader/writer // proxies as the SpdpDiscoveredParticipantData contains a bitmap of the // available built-in endpoints. self.send_discovery_notification(DiscoveryNotificationType::ParticipantUpdated { guid_prefix }); + // SEDP does not deliver them again, so they are processed as if it did + // now. With security, that checks them again: what Discovery accepted + // before the participant was lost does not count, since the participant + // may e.g. be unauthenticated now, or have other permissions. + for reader in readers { + debug!( + "Participant {guid_prefix:?} discovered, processing its reader {:?}", + reader.reader_proxy.remote_reader_guid + ); + self.process_subscription_sample(Sample::Value(reader), None); + } + for writer in writers { + debug!( + "Participant {guid_prefix:?} discovered, processing its writer {:?}", + writer.writer_proxy.remote_writer_guid + ); + self.process_publication_sample(Sample::Value(writer)); + } + if was_new { // Inform DDS Applications self.send_participant_status(DomainParticipantStatusEvent::ParticipantDiscovered { @@ -1197,52 +1222,67 @@ impl Discovery { }; for d in drds { - #[cfg(not(feature = "security"))] - let permission = NormalDiscoveryPermission::Allow; + self.process_subscription_sample(d, read_history); + } + } - #[cfg(feature = "security")] - let permission = if let Some(security) = self.security_opt.as_mut() { - // Security is enabled. Do a secure read - security.check_nonsecure_subscription_read(&d, &self.discovery_db) - } else { - // No security configured, always allowed - NormalDiscoveryPermission::Allow - }; + // A sample of DCPSSubscription: a remote reader is entered into the + // DiscoveryDB and announced to the local writers, or it is removed. + fn process_subscription_sample( + &mut self, + d: Sample, + read_history: Option, + ) { + #[cfg(not(feature = "security"))] + let permission = NormalDiscoveryPermission::Allow; - if permission == NormalDiscoveryPermission::Allow { - match d { - Sample::Value(d) => { - trace!("sedp_receive_subscription - {d:?}"); - let drd = discovery_db_write(&self.discovery_db).update_subscription(&d); - debug!( - "sedp_receive_subscription - send_discovery_notification ReaderUpdated {:?}", - drd + #[cfg(feature = "security")] + let permission = if let Some(security) = self.security_opt.as_mut() { + // Security is enabled. Do a secure read + security.check_nonsecure_subscription_read(&d, &self.discovery_db) + } else { + // No security configured, always allowed + NormalDiscoveryPermission::Allow + }; + + if permission == NormalDiscoveryPermission::Allow { + match d { + Sample::Value(d) => { + trace!("sedp_receive_subscription - {d:?}"); + let drd = discovery_db_write(&self.discovery_db).update_subscription(&d); + let Some(drd) = drd else { + // Its participant is not known. The reader is matched if the + // participant is discovered (again). + return; + }; + debug!( + "sedp_receive_subscription - send_discovery_notification ReaderUpdated {:?}", + drd + ); + self.send_discovery_notification(DiscoveryNotificationType::ReaderUpdated { + discovered_reader_data: drd, + }); + if read_history == Some(d.reader_proxy.remote_reader_guid.prefix) { + info!( + "Rediscovered reader {:?} topic={:?}", + d.reader_proxy.remote_reader_guid, + d.subscription_topic_data.topic_name() ); - self.send_discovery_notification(DiscoveryNotificationType::ReaderUpdated { - discovered_reader_data: drd, - }); - if read_history == Some(d.reader_proxy.remote_reader_guid.prefix) { - info!( - "Rediscovered reader {:?} topic={:?}", - d.reader_proxy.remote_reader_guid, - d.subscription_topic_data.topic_name() - ); - } - } - Sample::Dispose(reader_key) => { - info!("Dispose Reader {reader_key:?}"); - discovery_db_write(&self.discovery_db).remove_topic_reader(reader_key); - self.send_discovery_notification(DiscoveryNotificationType::ReaderLost { - reader_guid: reader_key, - }); - self.send_participant_status(DomainParticipantStatusEvent::ReaderLost { - guid: reader_key, - reason: LostReason::Disposed, - }); } } + Sample::Dispose(reader_key) => { + info!("Dispose Reader {reader_key:?}"); + discovery_db_write(&self.discovery_db).remove_topic_reader(reader_key); + self.send_discovery_notification(DiscoveryNotificationType::ReaderLost { + reader_guid: reader_key, + }); + self.send_participant_status(DomainParticipantStatusEvent::ReaderLost { + guid: reader_key, + reason: LostReason::Disposed, + }); + } } - } // loop + } } pub fn sedp_receive_publication(&mut self, read_history: Option) { @@ -1276,44 +1316,55 @@ impl Discovery { }; for d in dwds { - #[cfg(not(feature = "security"))] - let permission = NormalDiscoveryPermission::Allow; + self.process_publication_sample(d); + } + } - #[cfg(feature = "security")] - let permission = if let Some(security) = self.security_opt.as_mut() { - // Security is enabled. Do a secure read - security.check_nonsecure_publication_read(&d, &self.discovery_db) - } else { - // No security configured, always allowed - NormalDiscoveryPermission::Allow - }; + // A sample of DCPSPublication: a remote writer is entered into the + // DiscoveryDB and announced to the local readers, or it is removed. + fn process_publication_sample(&mut self, d: Sample) { + #[cfg(not(feature = "security"))] + let permission = NormalDiscoveryPermission::Allow; - if permission == NormalDiscoveryPermission::Allow { - match d { - Sample::Value(dwd) => { - trace!("sedp_receive_publication discovered {:?}", dwd); - let discovered_writer_data = - discovery_db_write(&self.discovery_db).update_publication(&dwd); - self.send_discovery_notification(DiscoveryNotificationType::WriterUpdated { - discovered_writer_data, - }); - debug!("Discovered Writer {:?}", dwd); - } - Sample::Dispose(writer_key) => { - discovery_db_write(&self.discovery_db).remove_topic_writer(writer_key); - self.send_discovery_notification(DiscoveryNotificationType::WriterLost { - writer_guid: writer_key, - }); - self.send_participant_status(DomainParticipantStatusEvent::WriterLost { - guid: writer_key, - reason: LostReason::Disposed, - }); + #[cfg(feature = "security")] + let permission = if let Some(security) = self.security_opt.as_mut() { + // Security is enabled. Do a secure read + security.check_nonsecure_publication_read(&d, &self.discovery_db) + } else { + // No security configured, always allowed + NormalDiscoveryPermission::Allow + }; - debug!("Disposed Writer {writer_key:?}"); - } + if permission == NormalDiscoveryPermission::Allow { + match d { + Sample::Value(dwd) => { + trace!("sedp_receive_publication discovered {:?}", dwd); + let discovered_writer_data = + discovery_db_write(&self.discovery_db).update_publication(&dwd); + let Some(discovered_writer_data) = discovered_writer_data else { + // Its participant is not known. The writer is matched if the + // participant is discovered (again). + return; + }; + self.send_discovery_notification(DiscoveryNotificationType::WriterUpdated { + discovered_writer_data, + }); + debug!("Discovered Writer {:?}", dwd); + } + Sample::Dispose(writer_key) => { + discovery_db_write(&self.discovery_db).remove_topic_writer(writer_key); + self.send_discovery_notification(DiscoveryNotificationType::WriterLost { + writer_guid: writer_key, + }); + self.send_participant_status(DomainParticipantStatusEvent::WriterLost { + guid: writer_key, + reason: LostReason::Disposed, + }); + + debug!("Disposed Writer {writer_key:?}"); } } - } // loop + } } // TODO: Try to remember why the read_history parameter below was introduced @@ -1684,9 +1735,11 @@ impl Discovery { // Currently we use only the DiscoveredReaderData field, no DataTag let drd_from_topic = sec_sub.discovered_reader_data; let drd = discovery_db_write(&self.discovery_db).update_subscription(&drd_from_topic); - self.send_discovery_notification(DiscoveryNotificationType::ReaderUpdated { - discovered_reader_data: drd, - }); + if let Some(drd) = drd { + self.send_discovery_notification(DiscoveryNotificationType::ReaderUpdated { + discovered_reader_data: drd, + }); + } } Sample::Dispose(reader_guid) => { info!("Secure Dispose Reader {reader_guid:?}"); @@ -1731,9 +1784,11 @@ impl Discovery { // Currently we use only the DiscoveredWriterData field, no DataTag let dwd_from_topic = se_pub.discovered_writer_data; let dwd = discovery_db_write(&self.discovery_db).update_publication(&dwd_from_topic); - self.send_discovery_notification(DiscoveryNotificationType::WriterUpdated { - discovered_writer_data: dwd, - }); + if let Some(dwd) = dwd { + self.send_discovery_notification(DiscoveryNotificationType::WriterUpdated { + discovered_writer_data: dwd, + }); + } } Sample::Dispose(writer_guid) => { info!("Secure Dispose Writer {writer_guid:?}"); @@ -2171,8 +2226,8 @@ mod tests { test::{ shape_type::ShapeType, test_data::{ - create_cdr_pl_rtps_data_message, spdp_participant_msg_mod, spdp_publication_msg, - spdp_subscription_msg, + create_cdr_pl_rtps_data_message, spdp_participant_data, spdp_participant_msg_mod, + spdp_publication_msg, spdp_subscription_msg, }, test_domain::test_domain_id, }, @@ -2611,6 +2666,14 @@ mod tests { let subscriptions_writer = GUID::new(other, EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_WRITER); let publications_writer = GUID::new(other, EntityId::SEDP_BUILTIN_PUBLICATIONS_WRITER); + // The observer knows the other participant. Endpoints of a participant it + // does not know are not matched (see + // sedp_reader_of_removed_participant_is_not_matched). + let mut other_data = spdp_participant_data().unwrap(); + other_data.participant_guid = GUID::new(other, EntityId::PARTICIPANT); + other_data.lease_duration = Some(Duration::from_secs(60)); + discovery_db_write(&observer.discovery_db()).update_participant(&other_data); + // A reader and a writer that the observer knows and matches before the // new participant appears. Their dispose is pending below. add_pending_sedp_sample( @@ -2773,4 +2836,777 @@ mod tests { "the disposed reader and writer were not reported lost" ); } + + // A reader that SEDP announces is matched only while its participant is + // known. + // + // The SEDP readers deliver a sample only once its WriterProxy has received + // it, i.e. while the participant was known. But Discovery may process the + // sample after the participant was disposed (or timed out), e.g. when the + // SPDP dispose is handled first. Matching it then creates a ReaderProxy that + // nothing removes again: the participant is no longer there to be disposed + // or to time out. The proxy never acknowledges, so a reliable local writer + // never completes wait_for_acknowledgments() and stays on + // HEARTBEAT_PERIOD_FAST for the life of the process, with a multicast + // HEARTBEAT that every live reader answers ten times a second. + // + // If the participant is discovered again, its reader is matched. + #[test] + fn sedp_reader_of_removed_participant_is_not_matched() { + use std::{collections::BTreeSet, net::Ipv4Addr}; + + use serde::{Deserialize, Serialize}; + + use crate::{ + dds::{qos::policy, statusevents::DataWriterStatus}, + discovery::sedp_messages::{ReaderProxy, SubscriptionBuiltinTopicData}, + rtps::Message, + structure::{guid::EntityKind, locator::Locator}, + Keyed, StatusEvented, TopicKind, + }; + + #[derive(Serialize, Deserialize, Clone, Debug)] + struct Item { + key: i32, + } + impl Keyed for Item { + type K = i32; + fn key(&self) -> i32 { + self.key + } + } + + const TOPIC: &str = "orphan_reader"; + const TYPE: &str = "Item"; + let domain_id = test_domain_id(44); + // The QoS of rt/ros_discovery_info + let qos = QosPolicyBuilder::new() + .reliability(policy::Reliability::Reliable { + max_blocking_time: crate::Duration::from_millis(100), + }) + .durability(policy::Durability::TransientLocal) + .history(policy::History::KeepLast { depth: 1 }) + .build(); + + let observer = DomainParticipant::new(domain_id).expect("participant creation"); + let observer_db = observer.discovery_db(); + let topic = observer + .create_topic( + TOPIC.to_string(), + TYPE.to_string(), + &qos, + TopicKind::WithKey, + ) + .unwrap(); + let publisher = observer.create_publisher(&qos).unwrap(); + let local_writer = publisher + .create_datawriter_cdr::(&topic, None) + .unwrap(); + local_writer.write(Item { key: 1 }, None).unwrap(); + + // A short-lived remote participant, which has a reliable reader on the + // topic. Nothing listens on its locators. + let remote = GuidPrefix::new(b"short_lived!"); + let remote_known = || { + discovery_db_read(&observer_db) + .find_participant_proxy(remote) + .is_some() + }; + let wait_until = |what: &str, condition: &dyn Fn() -> bool| { + let deadline = std::time::Instant::now() + StdDuration::from_secs(10); + while !condition() { + assert!(std::time::Instant::now() < deadline, "timed out: {what}"); + std::thread::sleep(StdDuration::from_millis(10)); + } + }; + let mut participant_data = spdp_participant_data().unwrap(); + participant_data.participant_guid = GUID::new(remote, EntityId::PARTICIPANT); + let nowhere = Locator::from(SocketAddr::new("127.0.0.1".parse().unwrap(), 9)); + participant_data.metatraffic_unicast_locators = vec![nowhere]; + participant_data.metatraffic_multicast_locators.clear(); + participant_data.default_unicast_locators = vec![nowhere]; + participant_data.default_multicast_locators.clear(); + // Its lease does not run out during the test: it has to leave by the + // dispose below. If it timed out before the dispose is processed, the + // dispose would later drop its reader from the attic. + participant_data.lease_duration = Some(Duration::from_secs(600)); + let spdp_writer = GUID::new(remote, EntityId::SPDP_BUILTIN_PARTICIPANT_WRITER); + let participant_dispose = DDSData::new_disposed_by_key( + ChangeKind::NotAliveDisposed, + SerializedPayload::new_from_bytes( + RepresentationIdentifier::PL_CDR_LE, + Participant_GUID(participant_data.participant_guid) + .to_pl_cdr_bytes(RepresentationIdentifier::PL_CDR_LE) + .unwrap(), + ), + ); + let remote_reader = GUID::new( + remote, + EntityId::new([0, 0, 1], EntityKind::READER_WITH_KEY_USER_DEFINED), + ); + let reader_data = DiscoveredReaderData { + reader_proxy: ReaderProxy::new(remote_reader, false, vec![], vec![]), + subscription_topic_data: SubscriptionBuiltinTopicData::new( + remote_reader, + None, + TOPIC.to_string(), + TYPE.to_string(), + &qos, + None, + ), + content_filter: None, + user_data: Vec::new(), + }; + + // The observer discovers the remote participant. A new participant's SPDP + // announcement wakes the observer's SPDP processing, which then takes the + // sample put into its SPDP reader here too. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + spdp_writer, + 1, + sedp_value(&participant_data), + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + wait_until("the remote participant is discovered", &remote_known); + + // The remote participant is disposed. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + spdp_writer, + 2, + participant_dispose, + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + wait_until("the remote participant is disposed", &|| !remote_known()); + + // The remote participant's reader, received while the participant was + // known, is only now processed by Discovery. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_SUBSCRIPTION, + GUID::new(remote, EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_WRITER), + 1, + sedp_value(&reader_data), + ); + + // HEARTBEATs of reliable user writers go to the user traffic multicast + // group. + let mut multicast = UDPListener::new_multicast( + "0.0.0.0", + user_traffic_multicast_port(domain_id), + Ipv4Addr::new(239, 255, 0, 1), + ) + .expect("multicast listener"); + + // A local reader on the topic. Its SEDP announcement comes back through + // the observer's SEDP subscriptions reader and wakes Discovery, which then + // processes the remote reader too. The local reader is matched with the + // local writer and acknowledges its sample. + let subscriber = observer.create_subscriber(&qos).unwrap(); + let local_reader = subscriber + .create_datareader_cdr::(&topic, None) + .unwrap(); + + let mut writer_status = Vec::new(); + let matched = |status: &mut Vec, reader: GUID, timeout: StdDuration| { + let deadline = std::time::Instant::now() + timeout; + loop { + status.extend(std::iter::from_fn(|| local_writer.try_recv_status())); + let is_matched = status.iter().any(|s| { + matches!(s, DataWriterStatus::PublicationMatched { reader: r, current, .. } + if *r == reader && current.count_change() == 1) + }); + if is_matched || std::time::Instant::now() >= deadline { + return is_matched; + } + std::thread::sleep(StdDuration::from_millis(20)); + } + }; + assert!( + matched( + &mut writer_status, + local_reader.guid(), + StdDuration::from_secs(10) + ), + "the local writer was not matched with the local reader" + ); + let remote_reader_matched = + matched(&mut writer_status, remote_reader, StdDuration::from_secs(1)); + let all_acked = local_writer + .wait_for_acknowledgments(StdDuration::from_secs(2)) + .unwrap(); + + // Count the local writer's HEARTBEATs for two seconds. A HEARTBEAT is sent + // once per interface, with the same count. + multicast.messages_bounded(usize::MAX); // drop what came before + let mut heartbeat_counts = BTreeSet::new(); + let window = StdDuration::from_secs(2); + let end = std::time::Instant::now() + window; + while std::time::Instant::now() < end { + for (datagram, _origin) in multicast.messages_bounded(usize::MAX) { + let Ok(message) = Message::read_from_buffer(&datagram) else { + continue; + }; + if message.header.guid_prefix != observer.guid_prefix() { + continue; + } + for submessage in message.submessages { + if let SubmessageBody::Writer(WriterSubmessage::Heartbeat(hb, _)) = submessage.body { + if hb.writer_id == local_writer.guid().entity_id { + heartbeat_counts.insert(hb.count); + } + } + } + } + std::thread::sleep(StdDuration::from_millis(10)); + } + let heartbeats_per_s = heartbeat_counts.len() as f64 / window.as_secs_f64(); + let outcome = format!( + "local writer matched with the reader of the disposed participant: {remote_reader_matched}, \ + all its samples acknowledged: {all_acked}, its HEARTBEATs/s after that: {heartbeats_per_s}" + ); + eprintln!("{outcome}"); + assert!( + !remote_reader_matched && all_acked && heartbeats_per_s < 2.0, + "{outcome}" + ); + + // The remote participant is discovered again: its reader is matched. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + spdp_writer, + 3, + sedp_value(&participant_data), + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + assert!( + matched( + &mut writer_status, + remote_reader, + StdDuration::from_secs(10) + ), + "the reader was not matched when its participant was discovered again" + ); + } + + // A participant that times out and is discovered again gets its readers and + // writers matched again. + // + // Its SEDP samples are not delivered a second time, because the SEDP + // DataReaders have read them already. So the DiscoveryDB keeps the + // endpoints of a participant that timed out, and Discovery has to announce + // them to the local endpoints when the participant returns. + #[test] + fn endpoints_of_a_timed_out_participant_are_matched_again_when_it_returns() { + use crate::{ + dds::statusevents::{DataReaderStatus, DataWriterStatus}, + discovery::sedp_messages::{ + PublicationBuiltinTopicData, ReaderProxy, SubscriptionBuiltinTopicData, WriterProxy, + }, + structure::{guid::EntityKind, locator::Locator}, + StatusEvented, TopicKind, + }; + + const TOPIC: &str = "returning"; + let domain_id = test_domain_id(45); + + let observer = DomainParticipant::new(domain_id).expect("participant creation"); + let observer_db = observer.discovery_db(); + let topic = observer + .create_topic( + TOPIC.to_string(), + "ShapeType".to_string(), + &QosPolicies::qos_none(), + TopicKind::WithKey, + ) + .unwrap(); + let publisher = observer.create_publisher(&QosPolicies::qos_none()).unwrap(); + let local_writer = publisher + .create_datawriter_cdr::(&topic, None) + .unwrap(); + let subscriber = observer + .create_subscriber(&QosPolicies::qos_none()) + .unwrap(); + let local_reader = subscriber + .create_datareader_cdr::(&topic, None) + .unwrap(); + + // The remote participant, with a reader and a writer on the topic. Nothing + // listens on its locators, and it sends nothing, so it times out. + let remote = GuidPrefix::new(b"comes_back!!"); + let remote_reader = GUID::new( + remote, + EntityId::new([0, 0, 1], EntityKind::READER_WITH_KEY_USER_DEFINED), + ); + let remote_writer = GUID::new( + remote, + EntityId::new([0, 0, 2], EntityKind::WRITER_WITH_KEY_USER_DEFINED), + ); + let mut participant_data = spdp_participant_data().unwrap(); + participant_data.participant_guid = GUID::new(remote, EntityId::PARTICIPANT); + let nowhere = Locator::from(SocketAddr::new("127.0.0.1".parse().unwrap(), 9)); + participant_data.metatraffic_unicast_locators = vec![nowhere]; + participant_data.metatraffic_multicast_locators.clear(); + participant_data.default_unicast_locators = vec![nowhere]; + participant_data.default_multicast_locators.clear(); + participant_data.lease_duration = Some(Duration::from_secs(1)); + let reader_data = DiscoveredReaderData { + reader_proxy: ReaderProxy::new(remote_reader, false, vec![], vec![]), + subscription_topic_data: SubscriptionBuiltinTopicData::new( + remote_reader, + None, + TOPIC.to_string(), + "ShapeType".to_string(), + &QosPolicies::qos_none(), + None, + ), + content_filter: None, + user_data: Vec::new(), + }; + let writer_data = DiscoveredWriterData { + last_updated: std::time::Instant::now(), + writer_proxy: WriterProxy::new(remote_writer, vec![], vec![]), + publication_topic_data: PublicationBuiltinTopicData::new( + remote_writer, + None, + TOPIC.to_string(), + "ShapeType".to_string(), + None, + ), + user_data: Vec::new(), + }; + + let remote_known = || { + discovery_db_read(&observer_db) + .find_participant_proxy(remote) + .is_some() + }; + // How many times the local writer was matched with (change 1) or unmatched + // from (change -1) the remote reader so far, and the local reader with the + // remote writer + let mut writer_status = Vec::new(); + let mut reader_status = Vec::new(); + let mut matches = |change: i32| { + writer_status.extend(std::iter::from_fn(|| local_writer.try_recv_status())); + reader_status.extend(std::iter::from_fn(|| local_reader.try_recv_status())); + let with_reader = writer_status + .iter() + .filter(|s| { + matches!(s, DataWriterStatus::PublicationMatched { reader, current, .. } + if *reader == remote_reader && current.count_change() == change) + }) + .count(); + let with_writer = reader_status + .iter() + .filter(|s| { + matches!(s, DataReaderStatus::SubscriptionMatched { writer, current, .. } + if *writer == remote_writer && current.count_change() == change) + }) + .count(); + (with_reader, with_writer) + }; + let wait_until = |what: &str, condition: &mut dyn FnMut() -> bool| { + let deadline = std::time::Instant::now() + StdDuration::from_secs(10); + while !condition() { + assert!(std::time::Instant::now() < deadline, "timed out: {what}"); + std::thread::sleep(StdDuration::from_millis(20)); + } + }; + + // The observer discovers the remote participant and its endpoints. A new + // participant's SPDP announcement wakes the observer's SPDP processing, + // which then takes the SPDP sample put into its reader here too, and with + // it the pending SEDP samples. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_SUBSCRIPTION, + GUID::new(remote, EntityId::SEDP_BUILTIN_SUBSCRIPTIONS_WRITER), + 1, + sedp_value(&reader_data), + ); + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PUBLICATION, + GUID::new(remote, EntityId::SEDP_BUILTIN_PUBLICATIONS_WRITER), + 1, + sedp_value(&writer_data), + ); + let spdp_writer = GUID::new(remote, EntityId::SPDP_BUILTIN_PARTICIPANT_WRITER); + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + spdp_writer, + 1, + sedp_value(&participant_data), + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + wait_until( + "the remote participant's endpoints are matched", + &mut || matches(1) == (1, 1), + ); + + // The remote participant times out. Its endpoints are unmatched. + wait_until( + "the remote participant's endpoints are unmatched at its timeout", + &mut || !remote_known() && matches(-1) == (1, 1), + ); + + // The remote participant is discovered again. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + spdp_writer, + 2, + sedp_value(&participant_data), + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + wait_until("the remote participant is discovered again", &mut || { + remote_known() + }); + let deadline = std::time::Instant::now() + StdDuration::from_secs(3); + while matches(1) != (2, 2) && std::time::Instant::now() < deadline { + std::thread::sleep(StdDuration::from_millis(20)); + } + assert_eq!( + matches(1), + (2, 2), + "matches of the local writer with the remote reader, and of the local reader with the \ + remote writer: they were not matched again when the participant returned" + ); + } + + // The topic of governance.p7s and permissions.p7s in + // examples/security_configuration_files/allow_unauthenticated/. It has read + // and write access control, and no discovery protection. + #[cfg(feature = "security")] + const PROTECTED_TOPIC: &str = "Protected"; + + // A participant with the built-in security plugins. Its governance document + // allows unauthenticated participants. + #[cfg(feature = "security")] + fn participant_with_security(domain_id: u16) -> DomainParticipant { + use crate::{DomainParticipantBuilder, DomainParticipantSecurityConfigFiles}; + + let config_files = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("examples/security_configuration_files"); + let mut security = + DomainParticipantSecurityConfigFiles::with_ros_default_names(&config_files, String::new()); + security.domain_governance_document = config_files.join("allow_unauthenticated/governance.p7s"); + security.participant_permissions_document = + config_files.join("allow_unauthenticated/permissions.p7s"); + DomainParticipantBuilder::new(domain_id) + .builtin_security(security) + .build() + .expect("participant creation") + } + + // With DDS Security, a participant that returns after a timeout is checked + // anew, and it may no longer be what it was. Here it was authenticated, and + // it returns as a participant that cannot be authenticated, which this + // governance document allows. The reader and the writer that it had on a + // topic with access control must not be matched again: Discovery would not + // accept them if SEDP announced them now (DDS Security 1.1, 8.8.7.1). + // + // This shows that endpoints from the attic get the check for new SEDP data + // at all. It does not show which rule of the check rejects them: the check + // looks up the security attributes of the topic with the permissions handle + // of the remote participant, an unauthenticated participant has none, and + // the check rejects the endpoint there, before it comes to the access + // control of the topic. + #[cfg(feature = "security")] + #[test] + fn endpoints_of_a_participant_that_returns_unauthenticated_are_checked_again() { + use crate::{ + dds::statusevents::{DataReaderStatus, DataWriterStatus}, + discovery::sedp_messages::{ + PublicationBuiltinTopicData, ReaderProxy, SubscriptionBuiltinTopicData, WriterProxy, + }, + structure::{guid::EntityKind, locator::Locator}, + StatusEvented, TopicKind, + }; + + const TOPIC: &str = PROTECTED_TOPIC; + let domain_id = test_domain_id(48); + + let observer = participant_with_security(domain_id); + let observer_db = observer.discovery_db(); + let topic = observer + .create_topic( + TOPIC.to_string(), + "ShapeType".to_string(), + &QosPolicies::qos_none(), + TopicKind::WithKey, + ) + .unwrap(); + let publisher = observer.create_publisher(&QosPolicies::qos_none()).unwrap(); + let local_writer = publisher + .create_datawriter_cdr::(&topic, None) + .unwrap(); + let subscriber = observer + .create_subscriber(&QosPolicies::qos_none()) + .unwrap(); + let local_reader = subscriber + .create_datareader_cdr::(&topic, None) + .unwrap(); + // Remote endpoints are matched only if they have the security attributes of + // the local ones. + let (writer_security, reader_security) = { + let db = discovery_db_read(&observer_db); + ( + db.get_local_topic_writer(local_writer.guid()) + .unwrap() + .publication_topic_data + .security_info() + .clone(), + db.get_local_topic_reader(local_reader.guid()) + .unwrap() + .subscription_topic_data + .security_info() + .clone(), + ) + }; + assert!(writer_security.is_some() && reader_security.is_some()); + + // The remote participant, with a reader and a writer on the topic. Its SPDP + // data has no identity token, so it cannot be authenticated. + let remote = GuidPrefix::new(b"unauthentic."); + let remote_reader = GUID::new( + remote, + EntityId::new([0, 0, 1], EntityKind::READER_WITH_KEY_USER_DEFINED), + ); + let remote_writer = GUID::new( + remote, + EntityId::new([0, 0, 2], EntityKind::WRITER_WITH_KEY_USER_DEFINED), + ); + let mut participant_data = spdp_participant_data().unwrap(); + assert!(participant_data.identity_token.is_none()); + participant_data.participant_guid = GUID::new(remote, EntityId::PARTICIPANT); + let nowhere = Locator::from(SocketAddr::new("127.0.0.1".parse().unwrap(), 9)); + participant_data.metatraffic_unicast_locators = vec![nowhere]; + participant_data.metatraffic_multicast_locators.clear(); + participant_data.default_unicast_locators = vec![nowhere]; + participant_data.default_multicast_locators.clear(); + let reader_data = DiscoveredReaderData { + reader_proxy: ReaderProxy::new(remote_reader, false, vec![], vec![]), + subscription_topic_data: SubscriptionBuiltinTopicData::new( + remote_reader, + None, + TOPIC.to_string(), + "ShapeType".to_string(), + &QosPolicies::qos_none(), + writer_security, + ), + content_filter: None, + user_data: Vec::new(), + }; + let writer_data = DiscoveredWriterData { + last_updated: std::time::Instant::now(), + writer_proxy: WriterProxy::new(remote_writer, vec![], vec![]), + publication_topic_data: PublicationBuiltinTopicData::new( + remote_writer, + None, + TOPIC.to_string(), + "ShapeType".to_string(), + reader_security, + ), + user_data: Vec::new(), + }; + + // The state after the remote participant was authenticated, Discovery + // accepted its reader and its writer, and it timed out. + { + let mut db = discovery_db_write(&observer_db); + db.update_participant(&participant_data); + assert!(db.update_subscription(&reader_data).is_some()); + assert!(db.update_publication(&writer_data).is_some()); + db.remove_participant(remote, false); // false = timed out + } + + // The remote participant is discovered again. A new participant's SPDP + // announcement wakes the observer's SPDP processing, which then takes the + // SPDP sample put into its reader here too. + add_pending_sedp_sample( + &observer, + builtin_topic_names::DCPS_PARTICIPANT, + GUID::new(remote, EntityId::SPDP_BUILTIN_PARTICIPANT_WRITER), + 1, + sedp_value(&participant_data), + ); + let _newcomer = DomainParticipant::new(domain_id).expect("participant creation"); + let deadline = std::time::Instant::now() + StdDuration::from_secs(10); + while discovery_db_read(&observer_db) + .find_participant_proxy(remote) + .is_none() + { + assert!( + std::time::Instant::now() < deadline, + "the remote participant was not discovered again" + ); + std::thread::sleep(StdDuration::from_millis(20)); + } + + // Its reader and its writer are not matched, and not entered either. + std::thread::sleep(StdDuration::from_secs(1)); + let matched_with_reader = std::iter::from_fn(|| local_writer.try_recv_status()).any(|s| { + matches!(s, DataWriterStatus::PublicationMatched { reader, .. } if reader == remote_reader) + }); + let matched_with_writer = std::iter::from_fn(|| local_reader.try_recv_status()).any(|s| { + matches!(s, DataReaderStatus::SubscriptionMatched { writer, .. } if writer == remote_writer) + }); + assert_eq!( + (matched_with_reader, matched_with_writer), + (false, false), + "the local writer was matched with the remote reader, or the local reader with the remote \ + writer, on a topic with access control, although their participant is unauthenticated now" + ); + let db = discovery_db_read(&observer_db); + assert_eq!( + ( + db.get_all_external_topic_readers() + .filter(|r| r.reader_proxy.remote_reader_guid.prefix == remote) + .count(), + db.get_all_external_topic_writers() + .filter(|w| w.writer_proxy.remote_writer_guid.prefix == remote) + .count() + ), + (0, 0), + "endpoints of the unauthenticated participant on a topic with access control were entered" + ); + } + + // A participant that returns after a timeout is authenticated again, and + // its readers and writers stay in the attic until its DCPSParticipantsSecure + // data is processed. They are then checked again and entered. But a reader + // or a writer that the participant deletes before that does not come back: + // its dispose is processed although it is not among the entered endpoints + // then. + #[cfg(feature = "security")] + #[test] + fn endpoint_disposed_while_its_participant_is_authenticated_again_does_not_return() { + use crate::{discovery::secure_discovery::AuthenticationStatus, TopicKind}; + + let domain_id = test_domain_id(49); + let qos = QosPolicies::qos_none(); + let wait_until = |what: &str, condition: &mut dyn FnMut() -> bool| { + let deadline = std::time::Instant::now() + StdDuration::from_secs(10); + while !condition() { + assert!(std::time::Instant::now() < deadline, "timed out: {what}"); + std::thread::sleep(StdDuration::from_millis(20)); + } + }; + let topic_of = |participant: &DomainParticipant| { + participant + .create_topic( + PROTECTED_TOPIC.to_string(), + "ShapeType".to_string(), + &qos, + TopicKind::WithKey, + ) + .unwrap() + }; + + // Two participants with the same identity and permissions, which + // authenticate each other. Both have a reader and a writer on the topic. + let observer = participant_with_security(domain_id); + let observer_db = observer.discovery_db(); + let observer_topic = topic_of(&observer); + let _local_reader = observer + .create_subscriber(&qos) + .unwrap() + .create_datareader_cdr::(&observer_topic, None) + .unwrap(); + let _local_writer = observer + .create_publisher(&qos) + .unwrap() + .create_datawriter_cdr::(&observer_topic, None) + .unwrap(); + let remote = participant_with_security(domain_id); + let remote_prefix = remote.guid().prefix; + let remote_topic = topic_of(&remote); + let remote_subscriber = remote.create_subscriber(&qos).unwrap(); + let remote_publisher = remote.create_publisher(&qos).unwrap(); + let remote_reader = remote_subscriber + .create_datareader_cdr::(&remote_topic, None) + .unwrap(); + let remote_writer = remote_publisher + .create_datawriter_cdr::(&remote_topic, None) + .unwrap(); + + // Has the observer entered this reader or writer of the remote participant? + let entered = |endpoint: GUID| { + let db = discovery_db_read(&observer_db); + let is_reader = db + .get_all_external_topic_readers() + .any(|r| r.reader_proxy.remote_reader_guid == endpoint); + let is_writer = db + .get_all_external_topic_writers() + .any(|w| w.writer_proxy.remote_writer_guid == endpoint); + is_reader || is_writer + }; + // Puts the observer into the state after the remote participant has timed + // out, has returned and has been authenticated again, before its + // DCPSParticipantsSecure data is processed: it is known and authenticated, + // and its endpoints are in the attic. + let lose_and_authenticate_again = || { + let mut db = discovery_db_write(&observer_db); + let participant_data = db.find_participant_proxy(remote_prefix).unwrap().clone(); + db.remove_participant(remote_prefix, false); // false = timed out + db.update_participant(&participant_data); + db.update_authentication_status(remote_prefix, AuthenticationStatus::Authenticated); + }; + // A new participant makes the remote participant announce itself at once, + // also on DCPSParticipantsSecure. With that, the observer processes the + // endpoints that the remote participant has in the attic. + let process_the_attic = || DomainParticipant::new(domain_id).expect("participant creation"); + + let (reader, writer) = (remote_reader.guid(), remote_writer.guid()); + wait_until( + "the remote participant is authenticated and its endpoints are entered", + &mut || entered(reader) && entered(writer), + ); + assert_eq!( + discovery_db_read(&observer_db).get_authentication_status(remote_prefix), + Some(AuthenticationStatus::Authenticated) + ); + + // The remote participant deletes its reader while it is in the attic. The + // observer gets the dispose before it processes the attic. + lose_and_authenticate_again(); + assert!(!entered(reader) && !entered(writer)); + drop(remote_reader); + std::thread::sleep(StdDuration::from_millis(500)); + let _newcomer = process_the_attic(); + wait_until( + "the writer of the participant that was authenticated again is entered again", + &mut || entered(writer), + ); + wait_until( + "the reader that the remote participant deleted is not entered again", + &mut || !entered(reader), + ); + + // The same with a writer that the remote participant deletes. + let remote_reader = remote_subscriber + .create_datareader_cdr::(&remote_topic, None) + .unwrap(); + let reader = remote_reader.guid(); + wait_until("the new reader is entered", &mut || entered(reader)); + lose_and_authenticate_again(); + assert!(!entered(reader) && !entered(writer)); + drop(remote_writer); + std::thread::sleep(StdDuration::from_millis(500)); + let _newcomer = process_the_attic(); + wait_until( + "the reader of the participant that was authenticated again is entered again", + &mut || entered(reader), + ); + wait_until( + "the writer that the remote participant deleted is not entered again", + &mut || !entered(writer), + ); + } } diff --git a/src/discovery/discovery_db.rs b/src/discovery/discovery_db.rs index 7069169c..69175cec 100644 --- a/src/discovery/discovery_db.rs +++ b/src/discovery/discovery_db.rs @@ -23,6 +23,7 @@ use crate::{ duration::Duration, entity::RTPSEntity, guid::{EntityId, GuidPrefix, GUID}, + locator::Locator, }, }; use super::{ @@ -64,9 +65,24 @@ pub(crate) struct DiscoveryDB { // remote readers and writers (via discovery) external_topic_readers: BTreeMap, external_topic_writers: BTreeMap, - - // These are "attic" storages for readers and writers whose participant - // was lost due to time-out. If we have a + // Which locator lists of those are not what the reader or writer announced, + // but the default locators of its participant. See update_subscription(). + // Only endpoints with such a list have an entry. + default_locators_used: BTreeMap, + + // The "attic": remote readers and writers whose participant is not in + // participant_proxies. Endpoints belong to a discovered participant (RTPS + // 2.5 8.5.4.1, 8.5.5), so these are not matched with local endpoints. + // - The endpoints of a participant that timed out are moved here. + // - An endpoint whose SEDP sample Discovery processes while its participant + // is not known is entered here, e.g. because the participant was disposed + // or timed out after the sample was received. + // They are kept because SEDP does not deliver them a second time. When the + // participant is discovered (again), Discovery takes them out with + // take_endpoints_from_attic() and processes them as new SEDP data. A dispose + // of the participant, or of the endpoint, drops them. + // The attic has the locators that the endpoints announced, without default + // locators of the participant: it may return with other ones. external_topic_readers_attic: BTreeMap, external_topic_writers_attic: BTreeMap, @@ -81,6 +97,14 @@ pub(crate) struct DiscoveryDB { participant_status_sender: StatusChannelSender, } +// Whether a remote reader or writer announced no unicast locators, or no +// multicast locators, so that it has the default ones of its participant +#[derive(Clone, Copy)] +struct DefaultLocatorsUsed { + unicast: bool, + multicast: bool, +} + // How did we discover this topic #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub(crate) enum DiscoveredVia { @@ -101,6 +125,14 @@ fn move_by_guid_prefix( } } +fn remove_by_guid_prefix(guid_prefix: GuidPrefix, from: &mut BTreeMap) -> Vec { + let to_remove: Vec = from.range(guid_prefix.range()).map(|(g, _)| *g).collect(); + to_remove + .into_iter() + .filter_map(|guid| from.remove(&guid)) + .collect() +} + pub(crate) fn discovery_db_read( discovery_db: &Arc>, ) -> RwLockReadGuard<'_, DiscoveryDB> { @@ -135,6 +167,7 @@ impl DiscoveryDB { local_topic_readers: BTreeMap::new(), external_topic_readers: BTreeMap::new(), external_topic_writers: BTreeMap::new(), + default_locators_used: BTreeMap::new(), external_topic_readers_attic: BTreeMap::new(), external_topic_writers_attic: BTreeMap::new(), topics: BTreeMap::new(), @@ -182,18 +215,9 @@ impl DiscoveryDB { } // This may be a rediscovery: Participant lease time timed out, but then - // came back, e.g. by network outage. We then restore readers/writers from - // attic to discovery DB. - move_by_guid_prefix( - guid.prefix, - &mut self.external_topic_readers_attic, - &mut self.external_topic_readers, - ); - move_by_guid_prefix( - guid.prefix, - &mut self.external_topic_writers_attic, - &mut self.external_topic_writers, - ); + // came back, e.g. by network outage. Its readers/writers are still in the + // attic. The caller gets them with take_endpoints_from_attic() and + // processes them as new SEDP data, so that they are matched again. } // In any case: @@ -235,6 +259,10 @@ impl DiscoveryDB { if active_disposal { self.remove_topic_reader_with_prefix(guid_prefix); self.remove_topic_writer_with_prefix(guid_prefix); + // The participant does not come back, so neither do the endpoints it has + // in the attic. + remove_by_guid_prefix(guid_prefix, &mut self.external_topic_readers_attic); + remove_by_guid_prefix(guid_prefix, &mut self.external_topic_writers_attic); } else { // move to attic move_by_guid_prefix( @@ -247,7 +275,32 @@ impl DiscoveryDB { &mut self.external_topic_writers, &mut self.external_topic_writers_attic, ); + // The default locators of this participant stay behind. If it returns, + // its endpoints get the ones it announces then. + for (guid, used) in self.default_locators_used.range(guid_prefix.range()) { + let locator_lists = match ( + self.external_topic_readers_attic.get_mut(guid), + self.external_topic_writers_attic.get_mut(guid), + ) { + (Some(reader), _) => ( + &mut reader.reader_proxy.unicast_locator_list, + &mut reader.reader_proxy.multicast_locator_list, + ), + (None, Some(writer)) => ( + &mut writer.writer_proxy.unicast_locator_list, + &mut writer.writer_proxy.multicast_locator_list, + ), + (None, None) => continue, + }; + if used.unicast { + locator_lists.0.clear(); + } + if used.multicast { + locator_lists.1.clear(); + } + } } + remove_by_guid_prefix(guid_prefix, &mut self.default_locators_used); } pub fn find_participant_proxy( @@ -273,6 +326,8 @@ impl DiscoveryDB { pub fn remove_topic_reader(&mut self, guid: GUID) { info!("remove_topic_reader {guid:?}"); self.external_topic_readers.remove(&guid); + self.default_locators_used.remove(&guid); + self.external_topic_readers_attic.remove(&guid); } #[cfg(feature = "security")] @@ -285,6 +340,25 @@ impl DiscoveryDB { self.external_topic_writers.get(guid) } + // A remote reader or writer that SEDP may dispose: one of those above, or + // one in the attic, which remove_topic_reader() and remove_topic_writer() + // drop too. + #[cfg(feature = "security")] + pub fn get_disposable_topic_reader(&self, guid: &GUID) -> Option<&DiscoveredReaderData> { + self + .external_topic_readers + .get(guid) + .or_else(|| self.external_topic_readers_attic.get(guid)) + } + + #[cfg(feature = "security")] + pub fn get_disposable_topic_writer(&self, guid: &GUID) -> Option<&DiscoveredWriterData> { + self + .external_topic_writers + .get(guid) + .or_else(|| self.external_topic_writers_attic.get(guid)) + } + fn remove_topic_writer_with_prefix(&mut self, guid_prefix: GuidPrefix) { // TODO: Implement this using .drain_filter() in BTreeMap once it lands in // stable. @@ -300,6 +374,8 @@ impl DiscoveryDB { pub fn remove_topic_writer(&mut self, guid: GUID) { self.external_topic_writers.remove(&guid); + self.default_locators_used.remove(&guid); + self.external_topic_writers_attic.remove(&guid); } // Delete participant proxies, if we have not heard of them within @@ -421,32 +497,41 @@ impl DiscoveryDB { // them from the remote participant. // // The topic is updated to the topics table. - pub fn update_subscription(&mut self, data: &DiscoveredReaderData) -> DiscoveredReaderData { + // + // If the remote participant is not known, the reader is kept in the attic + // until the participant is discovered, and None is returned: it must not be + // matched yet. See take_endpoints_from_attic(). + pub fn update_subscription( + &mut self, + data: &DiscoveredReaderData, + ) -> Option { let guid = data.reader_proxy.remote_reader_guid; // fill in the default locators from participant, in case DRD did not provide // any - let default_locator_lists = self - .find_participant_proxy(guid.prefix) - .map(|pp| { - debug!("Added participant locators to Reader {guid:?}"); - ( - pp.default_unicast_locators.clone(), - pp.default_multicast_locators.clone(), - ) - }) - .unwrap_or_else(|| { - if guid.prefix != GuidPrefix::UNKNOWN { - // This is normal, since we might not know about the participant yet. - debug!( - "No remote participant known for {:?}\nSearched with {:?} in {:?}", - data, - guid.prefix, - self.participant_proxies.keys() - ); - } - (Vec::default(), Vec::default()) - }); + let Some(default_locator_lists) = self.find_participant_proxy(guid.prefix).map(|pp| { + debug!("Added participant locators to Reader {guid:?}"); + ( + pp.default_unicast_locators.clone(), + pp.default_multicast_locators.clone(), + ) + }) else { + // The participant may not be known yet, or it may be gone already. A + // reader matched now would then never be removed again. + debug!( + "No remote participant known for Reader {guid:?}. Keeping it until the participant is \ + discovered." + ); + self.external_topic_readers_attic.insert(guid, data.clone()); + return None; + }; + // Newer data than any in the attic + self.external_topic_readers_attic.remove(&guid); + self.note_default_locators_used( + guid, + &data.reader_proxy.unicast_locator_list, + &data.reader_proxy.multicast_locator_list, + ); // Build enriched data with participant's default locators filled in, so that // later lookups via readers_on_topic() return usable locator information. @@ -474,36 +559,42 @@ impl DiscoveryDB { // reader update. If there is a DiscoveredVia::Topic record, use QosPolicies // from that record and modify by QoS given in the DRD. - enriched + Some(enriched) } // TODO: This is silly. Returns one of the parameters cloned, or None - pub fn update_publication(&mut self, data: &DiscoveredWriterData) -> DiscoveredWriterData { + // + // As update_subscription(), a writer of an unknown participant is kept in the + // attic until the participant is discovered, and None is returned. + pub fn update_publication( + &mut self, + data: &DiscoveredWriterData, + ) -> Option { let guid = data.writer_proxy.remote_writer_guid; // fill in the default locators from participant, in case DRD did not provide // any - let default_locator_lists = self - .find_participant_proxy(guid.prefix) - .map(|pp| { - debug!("Added participant locators to Writer {guid:?}"); - ( - pp.default_unicast_locators.clone(), - pp.default_multicast_locators.clone(), - ) - }) - .unwrap_or_else(|| { - if guid.prefix != GuidPrefix::UNKNOWN { - // This is normal, since we might not know about the participant yet. - debug!( - "No remote participant known for {:?}\nSearched with {:?} in {:?}", - data, - guid.prefix, - self.participant_proxies.keys() - ); - } - (Vec::default(), Vec::default()) - }); + let Some(default_locator_lists) = self.find_participant_proxy(guid.prefix).map(|pp| { + debug!("Added participant locators to Writer {guid:?}"); + ( + pp.default_unicast_locators.clone(), + pp.default_multicast_locators.clone(), + ) + }) else { + debug!( + "No remote participant known for Writer {guid:?}. Keeping it until the participant is \ + discovered." + ); + self.external_topic_writers_attic.insert(guid, data.clone()); + return None; + }; + // Newer data than any in the attic + self.external_topic_writers_attic.remove(&guid); + self.note_default_locators_used( + guid, + &data.writer_proxy.unicast_locator_list, + &data.writer_proxy.multicast_locator_list, + ); // Build enriched data with participant's default locators filled in, so that // later lookups via writers_on_topic() return usable locator information. @@ -527,7 +618,45 @@ impl DiscoveryDB { DiscoveredVia::Publication, ); - enriched + Some(enriched) + } + + // Remembers which locator lists of a remote reader or writer, as announced, + // are empty, so that the endpoint gets the default locators of its + // participant. + fn note_default_locators_used( + &mut self, + guid: GUID, + announced_unicast: &[Locator], + announced_multicast: &[Locator], + ) { + let used = DefaultLocatorsUsed { + unicast: announced_unicast.is_empty(), + multicast: announced_multicast.is_empty(), + }; + if used.unicast || used.multicast { + self.default_locators_used.insert(guid, used); + } else { + self.default_locators_used.remove(&guid); + } + } + + // Takes the readers and writers of this participant out of the attic. Call + // this once the participant is in the DB, and process them as SEDP data + // that arrives now: update_subscription() and update_publication() enter + // them and return them, so that they can be matched with local endpoints. + // With security, they have to be checked again before that. + pub fn take_endpoints_from_attic( + &mut self, + guid_prefix: GuidPrefix, + ) -> (Vec, Vec) { + if self.find_participant_proxy(guid_prefix).is_none() { + return (Vec::new(), Vec::new()); + } + ( + remove_by_guid_prefix(guid_prefix, &mut self.external_topic_readers_attic), + remove_by_guid_prefix(guid_prefix, &mut self.external_topic_writers_attic), + ) } // This is for local participant updating the topic table @@ -858,6 +987,334 @@ mod tests { }, }; + // SPDP data of a remote participant with this GUID prefix + fn participant_data(guid_prefix: GuidPrefix) -> SpdpDiscoveredParticipantData { + let mut data = spdp_participant_data().unwrap(); + data.participant_guid = GUID::new(guid_prefix, EntityId::PARTICIPANT); + data + } + + // An empty DiscoveryDB of some local participant + fn empty_db() -> DiscoveryDB { + let (discovery_db_event_sender, _discovery_db_event_receiver) = + std::sync::mpsc::sync_channel::<()>(4); + let (status_sender, _status_receiver) = sync_status_channel(16).unwrap(); + DiscoveryDB::new( + GUID::new_participant_guid(), + discovery_db_event_sender, + status_sender, + ) + } + + // SEDP data of a reader of the participant with this GUID prefix + fn reader_of(guid_prefix: GuidPrefix) -> DiscoveredReaderData { + let guid = GUID::new( + guid_prefix, + EntityId::new([0, 0, 1], EntityKind::READER_WITH_KEY_USER_DEFINED), + ); + DiscoveredReaderData { + reader_proxy: ReaderProxy::new(guid, false, vec![], vec![]), + subscription_topic_data: SubscriptionBuiltinTopicData::new( + guid, + None, + "topic".to_string(), + "type".to_string(), + &QosPolicies::qos_none(), + None, + ), + content_filter: None, + user_data: Vec::new(), + } + } + + // SEDP data of a writer of the participant with this GUID prefix + fn writer_of(guid_prefix: GuidPrefix) -> DiscoveredWriterData { + use crate::discovery::sedp_messages::PublicationBuiltinTopicData; + + let guid = GUID::new( + guid_prefix, + EntityId::new([0, 0, 2], EntityKind::WRITER_WITH_KEY_USER_DEFINED), + ); + DiscoveredWriterData { + last_updated: Instant::now(), + writer_proxy: WriterProxy::new(guid, vec![], vec![]), + publication_topic_data: PublicationBuiltinTopicData::new( + guid, + None, + "topic".to_string(), + "type".to_string(), + None, + ), + user_data: Vec::new(), + } + } + + // What Discovery does with the endpoints that a participant has in the + // attic when it is discovered: they are entered as new SEDP data. Returns the + // entered ones, which Discovery announces to the local endpoints. + fn enter_endpoints_from_attic( + db: &mut DiscoveryDB, + guid_prefix: GuidPrefix, + ) -> (Vec, Vec) { + let (readers, writers) = db.take_endpoints_from_attic(guid_prefix); + ( + readers + .iter() + .filter_map(|r| db.update_subscription(r)) + .collect(), + writers + .iter() + .filter_map(|w| db.update_publication(w)) + .collect(), + ) + } + + // Is the reader, or the writer, among the external ones of the DB? + fn reader_known(db: &DiscoveryDB, reader: &DiscoveredReaderData) -> bool { + db.get_all_external_topic_readers() + .any(|r| r.reader_proxy.remote_reader_guid == reader.reader_proxy.remote_reader_guid) + } + fn writer_known(db: &DiscoveryDB, writer: &DiscoveredWriterData) -> bool { + db.get_all_external_topic_writers() + .any(|w| w.writer_proxy.remote_writer_guid == writer.writer_proxy.remote_writer_guid) + } + + // An endpoint that SEDP announces while its participant is not known, i.e. + // before the participant's SPDP data or after the participant was removed, + // is not entered until the participant is discovered, and it is dropped with + // the participant. + #[test] + fn discdb_endpoints_wait_for_their_participant() { + let mut db = empty_db(); + let reader = |prefix: &[u8; 12]| reader_of(GuidPrefix::new(prefix)); + let writer = |prefix: &[u8; 12]| writer_of(GuidPrefix::new(prefix)); + + // SEDP before SPDP: the endpoints wait for their participant. + let (early_reader, early_writer) = (reader(b"early_partcp"), writer(b"early_partcp")); + let early = early_reader.reader_proxy.remote_reader_guid.prefix; + assert!(db.update_subscription(&early_reader).is_none()); + assert!(db.update_publication(&early_writer).is_none()); + assert!(!reader_known(&db, &early_reader) && !writer_known(&db, &early_writer)); + assert_eq!( + enter_endpoints_from_attic(&mut db, early), + (vec![], vec![]), + "endpoints were released while their participant is unknown" + ); + db.update_participant(&participant_data(early)); + let (readers, writers) = enter_endpoints_from_attic(&mut db, early); + assert_eq!(readers.len(), 1); + assert_eq!(writers.len(), 1); + assert!(reader_known(&db, &early_reader) && writer_known(&db, &early_writer)); + // The participant is known now, so updates are entered at once. + assert!(db.update_subscription(&early_reader).is_some()); + assert!(db.update_publication(&early_writer).is_some()); + + // SEDP after the participant was removed: the endpoints are not entered. + let (late_reader, late_writer) = (reader(b"late_partcpt"), writer(b"late_partcpt")); + let late = late_reader.reader_proxy.remote_reader_guid.prefix; + db.update_participant(&participant_data(late)); + db.remove_participant(late, true); + assert!(db.update_subscription(&late_reader).is_none()); + assert!(db.update_publication(&late_writer).is_none()); + assert!(!reader_known(&db, &late_reader) && !writer_known(&db, &late_writer)); + + // A participant removed while its endpoints wait takes them with it. + let (gone_reader, gone_writer) = (reader(b"gone_partcpt"), writer(b"gone_partcpt")); + let gone = gone_reader.reader_proxy.remote_reader_guid.prefix; + assert!(db.update_subscription(&gone_reader).is_none()); + assert!(db.update_publication(&gone_writer).is_none()); + db.remove_participant(gone, true); + db.update_participant(&participant_data(gone)); + assert_eq!(enter_endpoints_from_attic(&mut db, gone), (vec![], vec![])); + assert!(!reader_known(&db, &gone_reader) && !writer_known(&db, &gone_writer)); + + // An endpoint disposed over SEDP while it waits is dropped too. + let (disposed_reader, disposed_writer) = (reader(b"disp_partcpt"), writer(b"disp_partcpt")); + let disposed = disposed_reader.reader_proxy.remote_reader_guid.prefix; + assert!(db.update_subscription(&disposed_reader).is_none()); + assert!(db.update_publication(&disposed_writer).is_none()); + db.remove_topic_reader(disposed_reader.reader_proxy.remote_reader_guid); + db.remove_topic_writer(disposed_writer.writer_proxy.remote_writer_guid); + db.update_participant(&participant_data(disposed)); + assert_eq!( + enter_endpoints_from_attic(&mut db, disposed), + (vec![], vec![]) + ); + } + + // SEDP does not deliver the endpoints of a participant a second time, so + // the endpoints of a participant that timed out are kept. When the + // participant is discovered again, they are entered again and returned, so + // that they can be matched with local endpoints. + #[test] + fn discdb_endpoints_of_a_timed_out_participant_return_with_it() { + let mut db = empty_db(); + let prefix = GuidPrefix::new(b"timeout_part"); + let (reader, writer) = (reader_of(prefix), writer_of(prefix)); + db.update_participant(&participant_data(prefix)); + db.update_subscription(&reader); + db.update_publication(&writer); + assert!(reader_known(&db, &reader) && writer_known(&db, &writer)); + + db.remove_participant(prefix, false); // false = timed out + assert!(!reader_known(&db, &reader) && !writer_known(&db, &writer)); + + db.update_participant(&participant_data(prefix)); + let (readers, writers) = enter_endpoints_from_attic(&mut db, prefix); + assert_eq!( + readers + .iter() + .map(|r| r.reader_proxy.remote_reader_guid) + .collect::>(), + vec![reader.reader_proxy.remote_reader_guid], + "the reader of the returned participant was not handed out for matching" + ); + assert_eq!( + writers + .iter() + .map(|w| w.writer_proxy.remote_writer_guid) + .collect::>(), + vec![writer.writer_proxy.remote_writer_guid], + "the writer of the returned participant was not handed out for matching" + ); + assert!(reader_known(&db, &reader) && writer_known(&db, &writer)); + } + + // A reader or writer that announces no locators is reached at the default + // locators of its participant. A participant that returns after a timeout + // may announce new ones, e.g. because its address changed. Its endpoints + // are then reached there, and no longer at the old locators. + #[test] + fn discdb_endpoints_of_a_returning_participant_use_its_new_default_locators() { + use std::net::{Ipv4Addr, SocketAddr}; + + let locator = |host: u8, port: u16| { + Locator::from(SocketAddr::new(Ipv4Addr::new(192, 0, 2, host).into(), port)) + }; + let multicast = |group: u8| { + Locator::from(SocketAddr::new( + Ipv4Addr::new(239, 255, 0, group).into(), + 7401, + )) + }; + let participant_at = |prefix, host: u8, group: u8| { + let mut data = participant_data(prefix); + data.default_unicast_locators = vec![locator(host, 7411)]; + data.default_multicast_locators = vec![multicast(group)]; + data + }; + + let mut db = empty_db(); + let prefix = GuidPrefix::new(b"moving_partc"); + // The reader announces no locators. The writer announces a unicast locator + // of its own, and no multicast locators. + let reader = reader_of(prefix); + let mut writer = writer_of(prefix); + let writers_own = locator(77, 7477); + writer.writer_proxy.unicast_locator_list = vec![writers_own]; + + db.update_participant(&participant_at(prefix, 1, 1)); + let entered_reader = db.update_subscription(&reader).unwrap(); + let entered_writer = db.update_publication(&writer).unwrap(); + assert_eq!( + ( + &entered_reader.reader_proxy.unicast_locator_list, + &entered_reader.reader_proxy.multicast_locator_list, + &entered_writer.writer_proxy.unicast_locator_list, + &entered_writer.writer_proxy.multicast_locator_list, + ), + ( + &vec![locator(1, 7411)], + &vec![multicast(1)], + &vec![writers_own], + &vec![multicast(1)], + ) + ); + + db.remove_participant(prefix, false); // false = timed out + db.update_participant(&participant_at(prefix, 2, 2)); + let (readers, writers) = enter_endpoints_from_attic(&mut db, prefix); + + let reader_locators: Vec<_> = readers + .iter() + .chain(db.get_all_external_topic_readers()) + .map(|r| { + ( + r.reader_proxy.unicast_locator_list.clone(), + r.reader_proxy.multicast_locator_list.clone(), + ) + }) + .collect(); + assert_eq!( + reader_locators, + vec![(vec![locator(2, 7411)], vec![multicast(2)]); 2], + "the reader kept the default locators its participant had before it timed out" + ); + let writer_locators: Vec<_> = writers + .iter() + .chain(db.get_all_external_topic_writers()) + .map(|w| { + ( + w.writer_proxy.unicast_locator_list.clone(), + w.writer_proxy.multicast_locator_list.clone(), + ) + }) + .collect(); + assert_eq!( + writer_locators, + vec![(vec![writers_own], vec![multicast(2)]); 2], + "the writer lost its own unicast locator, or kept the default multicast locators its \ + participant had before it timed out" + ); + } + + // An endpoint that is disposed over SEDP while its participant is timed out + // does not return with the participant. + #[test] + fn discdb_endpoint_disposed_while_its_participant_is_timed_out_does_not_return() { + let mut db = empty_db(); + let prefix = GuidPrefix::new(b"timeout_part"); + let (reader, writer) = (reader_of(prefix), writer_of(prefix)); + db.update_participant(&participant_data(prefix)); + db.update_subscription(&reader); + db.update_publication(&writer); + assert!(reader_known(&db, &reader) && writer_known(&db, &writer)); + db.remove_participant(prefix, false); // false = timed out + + db.remove_topic_reader(reader.reader_proxy.remote_reader_guid); + db.remove_topic_writer(writer.writer_proxy.remote_writer_guid); + + db.update_participant(&participant_data(prefix)); + assert_eq!( + enter_endpoints_from_attic(&mut db, prefix), + (vec![], vec![]) + ); + assert!(!reader_known(&db, &reader) && !writer_known(&db, &writer)); + } + + // A participant that is disposed after it timed out takes its endpoints with + // it. + #[test] + fn discdb_dispose_of_a_timed_out_participant_drops_its_endpoints() { + let mut db = empty_db(); + let prefix = GuidPrefix::new(b"timeout_part"); + let (reader, writer) = (reader_of(prefix), writer_of(prefix)); + db.update_participant(&participant_data(prefix)); + db.update_subscription(&reader); + db.update_publication(&writer); + assert!(reader_known(&db, &reader) && writer_known(&db, &writer)); + db.remove_participant(prefix, false); // false = timed out + + db.remove_participant(prefix, true); // true = disposed + + db.update_participant(&participant_data(prefix)); + assert_eq!( + enter_endpoints_from_attic(&mut db, prefix), + (vec![], vec![]) + ); + assert!(!reader_known(&db, &reader) && !writer_known(&db, &writer)); + } + #[test] fn discdb_participant_operations() { let (discovery_db_event_sender, _discovery_db_event_receiver) = @@ -1011,7 +1468,8 @@ mod tests { assert_eq!(discovery_db.get_all_external_topic_readers().count(), 0); assert_eq!(discovery_db.get_all_external_topic_writers().count(), 0); - // Discover one external Reader via SEDP subscription data. + // Discover one external Reader via SEDP subscription data. Its participant + // has to be known first. let reader = reader_proxy_data().unwrap(); let reader_sub = subscription_builtin_topic_data().unwrap(); let dreader = DiscoveredReaderData { @@ -1020,6 +1478,9 @@ mod tests { content_filter: None, user_data: Vec::new(), }; + discovery_db.update_participant(&participant_data( + dreader.reader_proxy.remote_reader_guid.prefix, + )); discovery_db.update_subscription(&dreader); // Discover one external Writer via SEDP publication data. @@ -1040,6 +1501,7 @@ mod tests { .create_datawriter::>(&topic, None) .unwrap(); let writer_data = DiscoveredWriterData::new(&dw, &topic, &domain_participant, None); + discovery_db.update_participant(&participant_data(domain_participant.guid_prefix())); discovery_db.update_publication(&writer_data); // Both accessors return the discovered endpoints as a snapshot. diff --git a/src/discovery/secure_discovery.rs b/src/discovery/secure_discovery.rs index f9af3ef6..3de2085e 100644 --- a/src/discovery/secure_discovery.rs +++ b/src/discovery/secure_discovery.rs @@ -420,7 +420,9 @@ impl SecureDiscovery { reader_data.reader_proxy.remote_reader_guid.prefix, ), Sample::Dispose(reader_guid) => { - if let Some(reader) = discovery_db_read(discovery_db).get_topic_reader(reader_guid) { + if let Some(reader) = + discovery_db_read(discovery_db).get_disposable_topic_reader(reader_guid) + { // We do know a reader with this guid ( reader.subscription_topic_data.topic_name().clone(), @@ -592,7 +594,9 @@ impl SecureDiscovery { writer_data.writer_proxy.remote_writer_guid.prefix, ), Sample::Dispose(writer_guid) => { - if let Some(writer) = discovery_db_read(discovery_db).get_topic_writer(writer_guid) { + if let Some(writer) = + discovery_db_read(discovery_db).get_disposable_topic_writer(writer_guid) + { // We do know a writer with this guid ( writer.publication_topic_data.topic_name().clone(), @@ -978,7 +982,9 @@ impl SecureDiscovery { .prefix, ), Sample::Dispose(reader_guid) => { - if let Some(reader) = discovery_db_read(discovery_db).get_topic_reader(reader_guid) { + if let Some(reader) = + discovery_db_read(discovery_db).get_disposable_topic_reader(reader_guid) + { // We do know a reader with this guid ( reader.subscription_topic_data.topic_name().clone(), @@ -1101,7 +1107,9 @@ impl SecureDiscovery { .prefix, ), Sample::Dispose(writer_guid) => { - if let Some(writer) = discovery_db_read(discovery_db).get_topic_writer(writer_guid) { + if let Some(writer) = + discovery_db_read(discovery_db).get_disposable_topic_writer(writer_guid) + { // We do know a writer with this guid ( writer.publication_topic_data.topic_name().clone(), @@ -1360,7 +1368,14 @@ impl SecureDiscovery { // DP event loop. This will result in matching the builtin // ParticipantStatelessMessage endpoints, which are used for exchanging // authentication messages. - discovery_db_write(discovery_db).update_participant(participant_data); + { + let mut db = discovery_db_write(discovery_db); + db.update_participant(participant_data); + // If the participant returns after a timeout, the readers and writers it + // had stay in the attic of the DiscoveryDB for now. Once it is + // authenticated, Discovery::process_discovered_participant_data() + // processes them as new SEDP data, which checks them again. + } self.update_participant_authentication_status_and_notify_dp( remote_guid.prefix, AuthenticationStatus::Authenticating,