Debian Codegraph @

src/response/network.rs

raw
1 //! RDAP IP Network.
2 use std::collections::HashSet;
3
4 use crate::prelude::ContentExtensions;
5
6 use {
7 crate::prelude::{Common, Extension, ObjectCommon},
8 std::str::FromStr,
9 };
10
11 use {
12 cidr::IpInet,
13 serde::{Deserialize, Serialize},
14 };
15
16 use super::{
17 CommonFields, Entity, Event, ExtensionId, GetSelfLink, Notice, Numberish, ObjectCommonFields,
18 Port43, RdapResponseError, Remark, SelfLink, Stringish, ToChild, ToResponse, to_opt_vec,
19 types::Link,
20 };
21
22 /// Cidr0 structure from the Cidr0 extension.
23 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
24 pub struct Cidr0Cidr {
25 #[serde(skip_serializing_if = "Option::is_none")]
26 #[serde(flatten)]
27 pub prefix: Option<Cidr0CidrPrefix>,
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub length: Option<Numberish<u8>>,
30 }
31
32 #[buildstructor::buildstructor]
33 impl Cidr0Cidr {
34 /// Builds a CIDR0.
35 #[builder(visibility = "pub")]
36 #[allow(clippy::needless_lifetimes)]
37 fn new<'a>(
38 network_type: &'a str,
39 prefix: String,
40 length: u8,
41 ) -> Result<Self, RdapResponseError> {
42 let prefix = match network_type {
43 "v4" | "V4" => Ok(Cidr0CidrPrefix::V4Prefix(prefix)),
44 "v6" | "V6" => Ok(Cidr0CidrPrefix::V6Prefix(prefix)),
45 _ => Err(RdapResponseError::InvalidNetworkType),
46 }?;
47 Ok(Self {
48 length: Some(Numberish::<u8>::from(length)),
49 prefix: Some(prefix),
50 })
51 }
52
53 /// Builds an Ipv4 CIDR0.
54 #[builder(entry = "v4", visibility = "pub")]
55 fn new_v4(prefix: String, length: u8) -> Self {
56 Self {
57 length: Some(Numberish::<u8>::from(length)),
58 prefix: Some(Cidr0CidrPrefix::V4Prefix(prefix)),
59 }
60 }
61
62 /// Builds an Ipv6 CIDR0.
63 #[builder(entry = "v6", visibility = "pub")]
64 fn new_v6(prefix: String, length: u8) -> Self {
65 Self {
66 length: Some(Numberish::<u8>::from(length)),
67 prefix: Some(Cidr0CidrPrefix::V6Prefix(prefix)),
68 }
69 }
70
71 // Get prefix as enum.
72 pub fn cidr0cidr_prefix(&self) -> Option<&Cidr0CidrPrefix> {
73 self.prefix.as_ref()
74 }
75
76 // Get the prefix.
77 pub fn prefix(&self) -> Option<String> {
78 self.prefix.clone().map(|p| match p {
79 Cidr0CidrPrefix::V4Prefix(prefix) => prefix.clone(),
80 Cidr0CidrPrefix::V6Prefix(prefix) => prefix.clone(),
81 })
82 }
83
84 // Get the length.
85 pub fn length(&self) -> Option<u8> {
86 self.length.as_ref().and_then(|n| n.as_u8())
87 }
88 }
89
90 impl std::fmt::Display for Cidr0Cidr {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 let length_s = if let Some(length) = &self.length {
93 length.to_string()
94 } else {
95 "not_given".to_string()
96 };
97 write!(
98 f,
99 "{}/{}",
100 self.prefix().unwrap_or("not_given".to_string()),
101 length_s
102 )
103 }
104 }
105
106 /// Represents the prefix choices
107 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
108 pub enum Cidr0CidrPrefix {
109 #[serde(rename = "v4prefix")]
110 V4Prefix(String),
111 #[serde(rename = "v6prefix")]
112 V6Prefix(String),
113 }
114
115 /// Represents an RDAP [IP network](https://rdap.rcode3.com/protocol/object_classes.html#ip-network) response.
116 ///
117 /// Use of the builder is recommended to create this structure.
118 /// The builder will create the appropriate CIDR0 structures and
119 /// is easier than specifying start and end IP addresses.
120 ///
121 /// ```rust
122 /// use icann_rdap_common::prelude::*;
123 ///
124 /// let net = Network::response_obj()
125 /// .cidr("10.0.0.0/24")
126 /// .handle("NET-10-0-0-0")
127 /// .status("active")
128 /// .build().unwrap();
129 /// ```
130 ///
131 /// This will create the following RDAP structure.
132 ///
133 /// ```norust
134 /// {
135 /// "rdapConformance": [
136 /// "cidr0",
137 /// "rdap_level_0"
138 /// ],
139 /// "objectClassName": "ip network",
140 /// "handle": "NET-10-0-0-0",
141 /// "status": [
142 /// "active"
143 /// ],
144 /// "startAddress": "10.0.0.0",
145 /// "endAddress": "10.0.0.255",
146 /// "ipVersion": "v4",
147 /// "cidr0_cidrs": [
148 /// {
149 /// "v4prefix": "10.0.0.0",
150 /// "length": 24
151 /// }
152 /// ]
153 /// }
154 /// ```
155 /// Use the getter functions to access the information in the network.
156 /// See [CommonFields] and [ObjectCommonFields] for common getter functions.
157 /// ```rust
158 /// # use icann_rdap_common::prelude::*;
159 /// # let net = Network::builder()
160 /// # .cidr("10.0.0.0/24")
161 /// # .build().unwrap();
162 /// let handle = net.handle();
163 /// let start_address = net.start_address();
164 /// let end_address = net.end_address();
165 /// let parent_handle = net.parent_handle();
166 /// ```
167 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
168 pub struct Network {
169 #[serde(flatten)]
170 pub common: Common,
171
172 #[serde(flatten)]
173 pub object_common: ObjectCommon,
174
175 #[serde(rename = "startAddress")]
176 #[serde(skip_serializing_if = "Option::is_none")]
177 pub start_address: Option<String>,
178
179 #[serde(rename = "endAddress")]
180 #[serde(skip_serializing_if = "Option::is_none")]
181 pub end_address: Option<String>,
182
183 #[serde(rename = "ipVersion")]
184 #[serde(skip_serializing_if = "Option::is_none")]
185 pub ip_version: Option<Stringish>,
186
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub name: Option<Stringish>,
189
190 #[serde(rename = "type")]
191 #[serde(skip_serializing_if = "Option::is_none")]
192 pub network_type: Option<Stringish>,
193
194 #[serde(rename = "parentHandle")]
195 #[serde(skip_serializing_if = "Option::is_none")]
196 pub parent_handle: Option<Stringish>,
197
198 #[serde(skip_serializing_if = "Option::is_none")]
199 pub country: Option<Stringish>,
200
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub cidr0_cidrs: Option<Vec<Cidr0Cidr>>,
203 }
204
205 #[buildstructor::buildstructor]
206 impl Network {
207 /// Builds a basic IP network object for use with embedding in other objects.
208 ///
209 /// ```rust
210 /// use icann_rdap_common::prelude::*;
211 ///
212 /// let net = Network::builder()
213 /// .cidr("10.0.0.0/24") //required for this builder
214 /// .handle("NET-10-0-0-0")
215 /// .status("active")
216 /// .build().unwrap();
217 /// ```
218 #[builder(visibility = "pub")]
219 fn new(
220 cidr: String,
221 handle: Option<String>,
222 country: Option<String>,
223 name: Option<String>,
224 network_type: Option<String>,
225 parent_handle: Option<String>,
226 remarks: Vec<Remark>,
227 links: Vec<Link>,
228 events: Vec<Event>,
229 statuses: Vec<String>,
230 port_43: Option<Port43>,
231 entities: Vec<Entity>,
232 redacted: Option<Vec<crate::response::redacted::Redacted>>,
233 ) -> Result<Self, RdapResponseError> {
234 let cidr = IpInet::from_str(&cidr)?;
235 Ok(Self {
236 common: Common::builder().build(),
237 object_common: ObjectCommon::ip_network()
238 .and_handle(handle.map(|s| s.into()) as Option<Stringish>)
239 .and_remarks(to_opt_vec(remarks))
240 .and_links(to_opt_vec(links))
241 .and_events(to_opt_vec(events))
242 .status(statuses)
243 .and_port_43(port_43)
244 .and_entities(to_opt_vec(entities))
245 .and_redacted(redacted)
246 .build(),
247 start_address: Some(cidr.first_address().to_string()),
248 end_address: Some(cidr.last_address().to_string()),
249 ip_version: Some(
250 match cidr {
251 IpInet::V4(_) => "v4",
252 IpInet::V6(_) => "v6",
253 }
254 .to_string()
255 .into(),
256 ),
257 name: name.map(|s| s.into()),
258 network_type: network_type.map(|s| s.into()),
259 parent_handle: parent_handle.map(|s| s.into()),
260 country: country.map(|s| s.into()),
261 cidr0_cidrs: match cidr {
262 IpInet::V4(cidr) => Some(vec![
263 Cidr0Cidr::v4()
264 .length(cidr.network_length())
265 .prefix(cidr.first_address().to_string())
266 .build(),
267 ]),
268 IpInet::V6(cidr) => Some(vec![
269 Cidr0Cidr::v6()
270 .length(cidr.network_length())
271 .prefix(cidr.first_address().to_string())
272 .build(),
273 ]),
274 },
275 })
276 }
277
278 /// Builds an IP network object for a response.
279 ///
280 /// ```rust
281 /// use icann_rdap_common::prelude::*;
282 ///
283 /// let net = Network::response_obj()
284 /// .cidr("10.0.0.0/24") //required for this builder
285 /// .handle("NET-10-0-0-0")
286 /// .status("active")
287 /// .extension(ExtensionId::NroRdapProfile0.as_ref())
288 /// .notice(Notice::builder().title("test").build())
289 /// .build().unwrap();
290 /// ```
291 #[builder(entry = "response_obj", visibility = "pub")]
292 fn new_response_obj(
293 cidr: String,
294 handle: Option<String>,
295 country: Option<String>,
296 name: Option<String>,
297 network_type: Option<String>,
298 parent_handle: Option<String>,
299 remarks: Vec<Remark>,
300 links: Vec<Link>,
301 events: Vec<Event>,
302 statuses: Vec<String>,
303 port_43: Option<Port43>,
304 entities: Vec<Entity>,
305 notices: Vec<Notice>,
306 mut extensions: Vec<Extension>,
307 redacted: Option<Vec<crate::response::redacted::Redacted>>,
308 ) -> Result<Self, RdapResponseError> {
309 let mut net_exts = vec![ExtensionId::Cidr0.to_extension()];
310 net_exts.append(&mut extensions);
311 let common = Common::level0()
312 .extensions(net_exts)
313 .and_notices(to_opt_vec(notices))
314 .build();
315 let mut net = Network::builder()
316 .cidr(cidr)
317 .and_handle(handle)
318 .and_country(country)
319 .and_name(name)
320 .and_network_type(network_type)
321 .and_parent_handle(parent_handle)
322 .remarks(remarks)
323 .links(links)
324 .events(events)
325 .statuses(statuses)
326 .and_port_43(port_43)
327 .entities(entities)
328 .and_redacted(redacted)
329 .build()?;
330 net.common = common;
331 Ok(net)
332 }
333
334 #[builder(entry = "illegal", visibility = "pub(crate)")]
335 #[allow(dead_code)]
336 fn new_illegal(
337 start_address: Option<String>,
338 end_address: Option<String>,
339 ip_version: Option<Stringish>,
340 cidr0_cidrs: Option<Vec<Cidr0Cidr>>,
341 country: Option<String>,
342 name: Option<String>,
343 network_type: Option<String>,
344 parent_handle: Option<String>,
345 notices: Vec<Notice>,
346 ) -> Self {
347 Self {
348 common: Common::level0()
349 .extension(ExtensionId::Cidr0.to_extension())
350 .and_notices(to_opt_vec(notices))
351 .build(),
352 object_common: ObjectCommon::ip_network().build(),
353 start_address,
354 end_address,
355 ip_version,
356 name: name.map(|s| s.into()),
357 network_type: network_type.map(|s| s.into()),
358 parent_handle: parent_handle.map(|s| s.into()),
359 country: country.map(|s| s.into()),
360 cidr0_cidrs,
361 }
362 }
363
364 /// Returns the start address of the network.
365 pub fn start_address(&self) -> Option<&str> {
366 self.start_address.as_deref()
367 }
368
369 /// Returns the end address of the network.
370 pub fn end_address(&self) -> Option<&str> {
371 self.end_address.as_deref()
372 }
373
374 /// Returns the IP version of the network.
375 pub fn ip_version(&self) -> Option<&str> {
376 self.ip_version.as_deref()
377 }
378
379 /// Returns the name of the network.
380 pub fn name(&self) -> Option<&str> {
381 self.name.as_deref()
382 }
383
384 /// Returns the type of the network.
385 pub fn network_type(&self) -> Option<&str> {
386 self.network_type.as_deref()
387 }
388
389 /// Returns the parent handle of the network.
390 pub fn parent_handle(&self) -> Option<&str> {
391 self.parent_handle.as_deref()
392 }
393
394 /// Returns the country of the network.
395 pub fn country(&self) -> Option<&str> {
396 self.country.as_deref()
397 }
398
399 /// Returns the CIDR0 CIDRs of the network.
400 pub fn cidr0_cidrs(&self) -> &[Cidr0Cidr] {
401 self.cidr0_cidrs.as_deref().unwrap_or_default()
402 }
403 }
404
405 impl ToResponse for Network {
406 fn to_response(self) -> super::RdapResponse {
407 super::RdapResponse::Network(Box::new(self))
408 }
409 }
410
411 impl GetSelfLink for Network {
412 fn self_link(&self) -> Option<&Link> {
413 self.object_common.self_link()
414 }
415 }
416
417 impl SelfLink for Network {
418 fn with_self_link(mut self, link: Link) -> Self {
419 self.object_common = self.object_common.with_self_link(link);
420 self
421 }
422 }
423
424 impl ToChild for Network {
425 fn to_child(mut self) -> Self {
426 self.common = Common {
427 rdap_conformance: None,
428 notices: None,
429 };
430 self
431 }
432 }
433
434 impl CommonFields for Network {
435 fn common(&self) -> &Common {
436 &self.common
437 }
438 }
439
440 impl ObjectCommonFields for Network {
441 fn object_common(&self) -> &ObjectCommon {
442 &self.object_common
443 }
444 }
445
446 impl ContentExtensions for Network {
447 fn content_extensions(&self) -> std::collections::HashSet<super::ExtensionId> {
448 let mut exts = HashSet::new();
449 exts.extend(self.common().content_extensions());
450 exts.extend(self.object_common().content_extensions());
451 if self.cidr0_cidrs.is_some() {
452 exts.insert(super::ExtensionId::Cidr0);
453 }
454 exts
455 }
456 }
457
458 #[cfg(test)]
459 mod tests {
460 use crate::{
461 prelude::{Cidr0Cidr, Cidr0CidrPrefix, Common, ObjectCommon},
462 response::network::Network,
463 };
464
465 #[test]
466 fn test_cidr0_v4_round_trip() {
467 // GIVEN network with cidr0
468 let expected = r#"{"objectClassName":"ip network","cidr0_cidrs":[{"v4prefix":"10.0.0.0","length":8}]}"#;
469
470 // WHEN deserialize
471 let net = serde_json::from_str::<Network>(expected).expect("deserialize network");
472
473 // WHEN serialize
474 let actual = serde_json::to_string(&net).expect("serialize network");
475
476 // THEN expected and actual match
477 assert_eq!(expected, &actual);
478 }
479
480 #[test]
481 fn test_cidr0_v4_deserialize() {
482 // GIVEN network with cidr0
483 let expected = r#"{"objectClassName":"ip network","cidr0_cidrs":[{"v4prefix":"10.0.0.0","length":8}]}"#;
484
485 // WHEN deserialize
486 let actual = serde_json::from_str::<Network>(expected).expect("deserialize network");
487
488 // THEN prefix and length are as expected
489 let cidr0 = actual.cidr0_cidrs().first().expect("cidr0 present");
490 assert_eq!(&cidr0.prefix().expect("prefix"), "10.0.0.0");
491 assert_eq!(cidr0.length().expect("length"), 8);
492 }
493
494 #[test]
495 fn test_cidr0_v6_round_trip() {
496 // GIVEN network with cidr0
497 let expected = r#"{"objectClassName":"ip network","cidr0_cidrs":[{"v6prefix":"2620:1EC::","length":36}]}"#;
498
499 // WHEN deserialize
500 let net = serde_json::from_str::<Network>(expected).expect("deserialize network");
501
502 // WHEN serialize
503 let actual = serde_json::to_string(&net).expect("serialize network");
504
505 // THEN expected and actual match
506 assert_eq!(expected, &actual);
507 }
508
509 #[test]
510 fn test_cidr0_v6_deserialize() {
511 // GIVEN network with cidr0
512 let expected = r#"{"objectClassName":"ip network","cidr0_cidrs":[{"v6prefix":"2620:1EC::","length":36}]}"#;
513
514 // WHEN deserialize
515 let actual = serde_json::from_str::<Network>(expected).expect("deserialize network");
516
517 // THEN prefix and length are as expected
518 let cidr0 = actual.cidr0_cidrs().first().expect("cidr0 present");
519 assert_eq!(&cidr0.prefix().expect("prefix"), "2620:1EC::");
520 assert_eq!(cidr0.length().expect("length"), 36);
521 }
522
523 #[test]
524 fn test_cidr0_v4_serialize() {
525 // GIVEN network with cidr0
526 let net = Network {
527 common: Common {
528 rdap_conformance: None,
529 notices: None,
530 },
531 object_common: ObjectCommon {
532 object_class_name: "ip network".to_string(),
533 handle: None,
534 remarks: None,
535 links: None,
536 events: None,
537 status: None,
538 port_43: None,
539 entities: None,
540 redacted: None,
541 },
542 start_address: None,
543 end_address: None,
544 ip_version: None,
545 name: None,
546 network_type: None,
547 parent_handle: None,
548 country: None,
549 cidr0_cidrs: Some(vec![Cidr0Cidr {
550 prefix: Some(Cidr0CidrPrefix::V4Prefix("10.0.0.0".to_string())),
551 length: Some(8.into()),
552 }]),
553 };
554
555 // WHEN serialize
556 let actual = serde_json::to_string(&net).expect("network serialize");
557
558 // THEN expected = actual
559 let expected = r#"{"objectClassName":"ip network","cidr0_cidrs":[{"v4prefix":"10.0.0.0","length":8}]}"#;
560 assert_eq!(&actual, expected);
561 }
562
563 #[test]
564 fn test_big_network_deserialization() {
565 // GIVEN a big network
566 let expected = r#"
567 {
568 "objectClassName" : "ip network",
569 "handle" : "XXXX-RIR",
570 "startAddress" : "2001:db8::",
571 "endAddress" : "2001:db8:0:ffff:ffff:ffff:ffff:ffff",
572 "ipVersion" : "v6",
573 "name": "NET-RTR-1",
574 "type" : "DIRECT ALLOCATION",
575 "country" : "AU",
576 "parentHandle" : "YYYY-RIR",
577 "status" : [ "active" ],
578 "remarks" :
579 [
580 {
581 "description" :
582 [
583 "She sells sea shells down by the sea shore.",
584 "Originally written by Terry Sullivan."
585 ]
586 }
587 ],
588 "links" :
589 [
590 {
591 "value" : "https://example.net/ip/2001:db8::/48",
592 "rel" : "self",
593 "href" : "https://example.net/ip/2001:db8::/48",
594 "type" : "application/rdap+json"
595 },
596 {
597 "value" : "https://example.net/ip/2001:db8::/48",
598 "rel" : "up",
599 "href" : "https://example.net/ip/2001:db8::/32",
600 "type" : "application/rdap+json"
601 }
602 ],
603 "events" :
604 [
605 {
606 "eventAction" : "registration",
607 "eventDate" : "1990-12-31T23:59:59Z"
608 },
609 {
610 "eventAction" : "last changed",
611 "eventDate" : "1991-12-31T23:59:59Z"
612 }
613 ],
614 "entities" :
615 [
616 {
617 "objectClassName" : "entity",
618 "handle" : "XXXX",
619 "vcardArray":[
620 "vcard",
621 [
622 ["version", {}, "text", "4.0"],
623 ["fn", {}, "text", "Joe User"],
624 ["kind", {}, "text", "individual"],
625 ["lang", {
626 "pref":"1"
627 }, "language-tag", "fr"],
628 ["lang", {
629 "pref":"2"
630 }, "language-tag", "en"],
631 ["org", {
632 "type":"work"
633 }, "text", "Example"],
634 ["title", {}, "text", "Research Scientist"],
635 ["role", {}, "text", "Project Lead"],
636 ["adr",
637 { "type":"work" },
638 "text",
639 [
640 "",
641 "Suite 1234",
642 "4321 Rue Somewhere",
643 "Quebec",
644 "QC",
645 "G1V 2M2",
646 "Canada"
647 ]
648 ],
649 ["tel",
650 { "type":["work", "voice"], "pref":"1" },
651 "uri", "tel:+1-555-555-1234;ext=102"
652 ],
653 ["email",
654 { "type":"work" },
655 "text", "[email protected]"
656 ]
657 ]
658 ],
659 "roles" : [ "registrant" ],
660 "remarks" :
661 [
662 {
663 "description" :
664 [
665 "She sells sea shells down by the sea shore.",
666 "Originally written by Terry Sullivan."
667 ]
668 }
669 ],
670 "links" :
671 [
672 {
673 "value" : "https://example.net/entity/xxxx",
674 "rel" : "self",
675 "href" : "https://example.net/entity/xxxx",
676 "type" : "application/rdap+json"
677 }
678 ],
679 "events" :
680 [
681 {
682 "eventAction" : "registration",
683 "eventDate" : "1990-12-31T23:59:59Z"
684
685 },
686 {
687 "eventAction" : "last changed",
688 "eventDate" : "1991-12-31T23:59:59Z"
689 }
690 ]
691 }
692 ]
693 }
694 "#;
695
696 // WHEN
697 let actual = serde_json::from_str::<Network>(expected);
698
699 // THEN
700 let actual = actual.unwrap();
701 assert_eq!(actual.object_common.object_class_name, "ip network");
702 assert!(actual.object_common.handle.is_some());
703 assert!(actual.start_address.is_some());
704 assert!(actual.end_address.is_some());
705 assert!(actual.ip_version.is_some());
706 assert!(actual.name.is_some());
707 assert!(actual.network_type.is_some());
708 assert!(actual.parent_handle.is_some());
709 assert!(actual.object_common.status.is_some());
710 assert!(actual.country.is_some());
711 assert!(actual.object_common.remarks.is_some());
712 assert!(actual.object_common.links.is_some());
713 assert!(actual.object_common.events.is_some());
714 assert!(actual.object_common.entities.is_some());
715 }
716 }