netstack3_device/arp.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! The Address Resolution Protocol (ARP).
use alloc::fmt::Debug;
use core::time::Duration;
use log::{debug, trace, warn};
use net_types::ip::{Ipv4, Ipv4Addr};
use net_types::{SpecifiedAddr, UnicastAddr, Witness as _};
use netstack3_base::{
CoreTimerContext, Counter, CounterContext, DeviceIdContext, EventContext, FrameDestination,
InstantBindingsTypes, LinkDevice, SendFrameContext, SendFrameError, TimerContext,
TracingContext, WeakDeviceIdentifier,
};
use netstack3_ip::nud::{
self, ConfirmationFlags, DynamicNeighborUpdateSource, LinkResolutionContext, NudBindingsTypes,
NudConfigContext, NudContext, NudHandler, NudSenderContext, NudState, NudTimerId,
NudUserConfig,
};
use packet::{BufferMut, InnerPacketBuilder, Serializer};
use packet_formats::arp::{ArpOp, ArpPacket, ArpPacketBuilder, HType};
use packet_formats::utils::NonZeroDuration;
use ref_cast::RefCast;
/// A link device whose addressing scheme is supported by ARP.
///
/// `ArpDevice` is implemented for all `L: LinkDevice where L::Address: HType`.
pub trait ArpDevice: LinkDevice<Address: HType> {}
impl<L: LinkDevice<Address: HType>> ArpDevice for L {}
/// The identifier for timer events in the ARP layer.
pub(crate) type ArpTimerId<L, D> = NudTimerId<Ipv4, L, D>;
/// The metadata associated with an ARP frame.
#[cfg_attr(test, derive(Debug, PartialEq, Clone))]
pub struct ArpFrameMetadata<D: ArpDevice, DeviceId> {
/// The ID of the ARP device.
pub(super) device_id: DeviceId,
/// The destination hardware address.
pub(super) dst_addr: D::Address,
}
/// Counters for the ARP layer.
#[derive(Default)]
pub struct ArpCounters {
/// Count of ARP packets received from the link layer.
pub rx_packets: Counter,
/// Count of received ARP packets that were dropped due to being unparsable.
pub rx_malformed_packets: Counter,
/// Count of ARP request packets received.
pub rx_requests: Counter,
/// Count of ARP response packets received.
pub rx_responses: Counter,
/// Count of non-gratuitous ARP packets received and dropped because the
/// destination address is non-local.
pub rx_dropped_non_local_target: Counter,
/// Count of ARP request packets sent.
pub tx_requests: Counter,
/// Count of ARP request packets not sent because the source address was
/// unknown or unassigned.
pub tx_requests_dropped_no_local_addr: Counter,
/// Count of ARP response packets sent.
pub tx_responses: Counter,
}
/// An execution context for the ARP protocol that allows sending IP packets to
/// specific neighbors.
pub trait ArpSenderContext<D: ArpDevice, BC: ArpBindingsContext<D, Self::DeviceId>>:
ArpConfigContext + DeviceIdContext<D>
{
/// Send an IP packet to the neighbor with address `dst_link_address`.
fn send_ip_packet_to_neighbor_link_addr<S>(
&mut self,
bindings_ctx: &mut BC,
dst_link_address: D::Address,
body: S,
) -> Result<(), SendFrameError<S>>
where
S: Serializer,
S::Buffer: BufferMut;
}
// NOTE(joshlf): The `ArpDevice` parameter may seem unnecessary. We only ever
// use the associated `HType` type, so why not just take that directly? By the
// same token, why have it as a parameter on `ArpState`, `ArpTimerId`, and
// `ArpFrameMetadata`? The answer is that, if we did, there would be no way to
// distinguish between different link device protocols that all happened to use
// the same hardware addressing scheme.
//
// Consider that the way that we implement context traits is via blanket impls.
// Even though each module's code _feels_ isolated from the rest of the system,
// in reality, all context impls end up on the same context type. In particular,
// all impls are of the form `impl<C: SomeContextTrait> SomeOtherContextTrait
// for C`. The `C` is the same throughout the whole stack.
//
// Thus, for two different link device protocols with the same `HType` and
// `PType`, if we used an `HType` parameter rather than an `ArpDevice`
// parameter, the `ArpContext` impls would conflict (in fact, the
// `StateContext`, `TimerContext`, and `FrameContext` impls would all conflict
// for similar reasons).
/// The execution context for the ARP protocol provided by bindings.
pub trait ArpBindingsContext<D: ArpDevice, DeviceId>:
TimerContext
+ TracingContext
+ LinkResolutionContext<D>
+ EventContext<nud::Event<D::Address, DeviceId, Ipv4, <Self as InstantBindingsTypes>::Instant>>
{
}
impl<
DeviceId,
D: ArpDevice,
BC: TimerContext
+ TracingContext
+ LinkResolutionContext<D>
+ EventContext<
nud::Event<D::Address, DeviceId, Ipv4, <Self as InstantBindingsTypes>::Instant>,
>,
> ArpBindingsContext<D, DeviceId> for BC
{
}
/// An execution context for the ARP protocol.
pub trait ArpContext<D: ArpDevice, BC: ArpBindingsContext<D, Self::DeviceId>>:
DeviceIdContext<D>
+ SendFrameContext<BC, ArpFrameMetadata<D, Self::DeviceId>>
+ CounterContext<ArpCounters>
{
/// The inner configuration context.
type ConfigCtx<'a>: ArpConfigContext;
/// The inner sender context.
type ArpSenderCtx<'a>: ArpSenderContext<D, BC, DeviceId = Self::DeviceId>;
/// Calls the function with a mutable reference to ARP state and the
/// core sender context.
fn with_arp_state_mut_and_sender_ctx<
O,
F: FnOnce(&mut ArpState<D, BC>, &mut Self::ArpSenderCtx<'_>) -> O,
>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O;
/// Get a protocol address of this interface.
///
/// If `device_id` does not have any addresses associated with it, return
/// `None`.
fn get_protocol_addr(
&mut self,
bindings_ctx: &mut BC,
device_id: &Self::DeviceId,
) -> Option<Ipv4Addr>;
/// Get the hardware address of this interface.
fn get_hardware_addr(
&mut self,
bindings_ctx: &mut BC,
device_id: &Self::DeviceId,
) -> UnicastAddr<D::Address>;
/// Calls the function with a mutable reference to ARP state and the ARP
/// configuration context.
fn with_arp_state_mut<O, F: FnOnce(&mut ArpState<D, BC>, &mut Self::ConfigCtx<'_>) -> O>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O;
/// Calls the function with an immutable reference to ARP state.
fn with_arp_state<O, F: FnOnce(&ArpState<D, BC>) -> O>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O;
}
/// An execution context for the ARP protocol that allows accessing
/// configuration parameters.
pub trait ArpConfigContext {
/// The retransmit timeout for ARP frames.
///
/// Provided implementation always return the default RFC period.
fn retransmit_timeout(&mut self) -> NonZeroDuration {
NonZeroDuration::new(DEFAULT_ARP_REQUEST_PERIOD).unwrap()
}
/// Calls the callback with an immutable reference to NUD configurations.
fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O;
}
/// Provides a [`NudContext`] IPv4 implementation for a core context that
/// implements [`ArpContext`].
#[derive(RefCast)]
#[repr(transparent)]
pub struct ArpNudCtx<CC>(CC);
impl<D, CC> DeviceIdContext<D> for ArpNudCtx<CC>
where
D: ArpDevice,
CC: DeviceIdContext<D>,
{
type DeviceId = CC::DeviceId;
type WeakDeviceId = CC::WeakDeviceId;
}
impl<D, CC, BC> NudContext<Ipv4, D, BC> for ArpNudCtx<CC>
where
D: ArpDevice,
BC: ArpBindingsContext<D, CC::DeviceId>,
CC: ArpContext<D, BC>,
{
type ConfigCtx<'a> = ArpNudCtx<CC::ConfigCtx<'a>>;
type SenderCtx<'a> = ArpNudCtx<CC::ArpSenderCtx<'a>>;
fn with_nud_state_mut_and_sender_ctx<
O,
F: FnOnce(&mut NudState<Ipv4, D, BC>, &mut Self::SenderCtx<'_>) -> O,
>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O {
let Self(core_ctx) = self;
core_ctx.with_arp_state_mut_and_sender_ctx(device_id, |ArpState { nud }, core_ctx| {
cb(nud, ArpNudCtx::ref_cast_mut(core_ctx))
})
}
fn with_nud_state_mut<
O,
F: FnOnce(&mut NudState<Ipv4, D, BC>, &mut Self::ConfigCtx<'_>) -> O,
>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O {
let Self(core_ctx) = self;
core_ctx.with_arp_state_mut(device_id, |ArpState { nud }, core_ctx| {
cb(nud, ArpNudCtx::ref_cast_mut(core_ctx))
})
}
fn with_nud_state<O, F: FnOnce(&NudState<Ipv4, D, BC>) -> O>(
&mut self,
device_id: &Self::DeviceId,
cb: F,
) -> O {
let Self(core_ctx) = self;
core_ctx.with_arp_state(device_id, |ArpState { nud }| cb(nud))
}
fn send_neighbor_solicitation(
&mut self,
bindings_ctx: &mut BC,
device_id: &Self::DeviceId,
lookup_addr: SpecifiedAddr<<Ipv4 as net_types::ip::Ip>::Addr>,
remote_link_addr: Option<<D as LinkDevice>::Address>,
) {
let Self(core_ctx) = self;
send_arp_request(core_ctx, bindings_ctx, device_id, lookup_addr.get(), remote_link_addr)
}
}
impl<CC: ArpConfigContext> NudConfigContext<Ipv4> for ArpNudCtx<CC> {
fn retransmit_timeout(&mut self) -> NonZeroDuration {
let Self(core_ctx) = self;
core_ctx.retransmit_timeout()
}
fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O {
let Self(core_ctx) = self;
core_ctx.with_nud_user_config(cb)
}
}
impl<D: ArpDevice, BC: ArpBindingsContext<D, CC::DeviceId>, CC: ArpSenderContext<D, BC>>
NudSenderContext<Ipv4, D, BC> for ArpNudCtx<CC>
{
fn send_ip_packet_to_neighbor_link_addr<S>(
&mut self,
bindings_ctx: &mut BC,
dst_mac: D::Address,
body: S,
) -> Result<(), SendFrameError<S>>
where
S: Serializer,
S::Buffer: BufferMut,
{
let Self(core_ctx) = self;
core_ctx.send_ip_packet_to_neighbor_link_addr(bindings_ctx, dst_mac, body)
}
}
pub(crate) trait ArpPacketHandler<D: ArpDevice, BC>: DeviceIdContext<D> {
fn handle_packet<B: BufferMut + Debug>(
&mut self,
bindings_ctx: &mut BC,
device_id: Self::DeviceId,
frame_dst: FrameDestination,
buffer: B,
);
}
impl<
D: ArpDevice,
BC: ArpBindingsContext<D, CC::DeviceId>,
CC: ArpContext<D, BC>
+ SendFrameContext<BC, ArpFrameMetadata<D, Self::DeviceId>>
+ NudHandler<Ipv4, D, BC>
+ CounterContext<ArpCounters>,
> ArpPacketHandler<D, BC> for CC
{
/// Handles an inbound ARP packet.
fn handle_packet<B: BufferMut + Debug>(
&mut self,
bindings_ctx: &mut BC,
device_id: Self::DeviceId,
frame_dst: FrameDestination,
buffer: B,
) {
handle_packet(self, bindings_ctx, device_id, frame_dst, buffer)
}
}
fn handle_packet<
D: ArpDevice,
BC: ArpBindingsContext<D, CC::DeviceId>,
B: BufferMut + Debug,
CC: ArpContext<D, BC>
+ SendFrameContext<BC, ArpFrameMetadata<D, CC::DeviceId>>
+ NudHandler<Ipv4, D, BC>
+ CounterContext<ArpCounters>,
>(
core_ctx: &mut CC,
bindings_ctx: &mut BC,
device_id: CC::DeviceId,
frame_dst: FrameDestination,
mut buffer: B,
) {
core_ctx.increment(|counters| &counters.rx_packets);
// TODO(wesleyac) Add support for probe.
let packet = match buffer.parse::<ArpPacket<_, D::Address, Ipv4Addr>>() {
Ok(packet) => packet,
Err(err) => {
// If parse failed, it's because either the packet was malformed, or
// it was for an unexpected hardware or network protocol. In either
// case, we just drop the packet and move on. RFC 826's "Packet
// Reception" section says of packet processing algorithm, "Negative
// conditionals indicate an end of processing and a discarding of
// the packet."
debug!("discarding malformed ARP packet: {}", err);
core_ctx.increment(|counters| &counters.rx_malformed_packets);
return;
}
};
enum ValidArpOp {
Request,
Response,
}
let op = match packet.operation() {
ArpOp::Request => {
core_ctx.increment(|counters| &counters.rx_requests);
ValidArpOp::Request
}
ArpOp::Response => {
core_ctx.increment(|counters| &counters.rx_responses);
ValidArpOp::Response
}
ArpOp::Other(o) => {
core_ctx.increment(|counters| &counters.rx_malformed_packets);
debug!("dropping arp packet with op = {:?}", o);
return;
}
};
enum PacketKind {
Gratuitous,
AddressedToMe,
}
// The following logic is equivalent to the "Packet Reception" section of
// RFC 826.
//
// We statically know that the hardware type and protocol type are correct,
// so we do not need to have additional code to check that. The remainder of
// the algorithm is:
//
// Merge_flag := false
// If the pair <protocol type, sender protocol address> is
// already in my translation table, update the sender
// hardware address field of the entry with the new
// information in the packet and set Merge_flag to true.
// ?Am I the target protocol address?
// Yes:
// If Merge_flag is false, add the triplet <protocol type,
// sender protocol address, sender hardware address> to
// the translation table.
// ?Is the opcode ares_op$REQUEST? (NOW look at the opcode!!)
// Yes:
// Swap hardware and protocol fields, putting the local
// hardware and protocol addresses in the sender fields.
// Set the ar$op field to ares_op$REPLY
// Send the packet to the (new) target hardware address on
// the same hardware on which the request was received.
//
// This can be summed up as follows:
//
// +----------+---------------+---------------+-----------------------------+
// | opcode | Am I the TPA? | SPA in table? | action |
// +----------+---------------+---------------+-----------------------------+
// | REQUEST | yes | yes | Update table, Send response |
// | REQUEST | yes | no | Update table, Send response |
// | REQUEST | no | yes | Update table |
// | REQUEST | no | no | NOP |
// | RESPONSE | yes | yes | Update table |
// | RESPONSE | yes | no | Update table |
// | RESPONSE | no | yes | Update table |
// | RESPONSE | no | no | NOP |
// +----------+---------------+---------------+-----------------------------+
let sender_addr = packet.sender_protocol_address();
let target_addr = packet.target_protocol_address();
let (source, kind) = match (
sender_addr == target_addr,
Some(target_addr) == core_ctx.get_protocol_addr(bindings_ctx, &device_id),
) {
(true, false) => {
// Treat all GARP messages as neighbor probes as GARPs are not
// responses for previously sent requests, even if the packet
// operation is a response OP code.
//
// Per RFC 5944 section 4.6,
//
// A Gratuitous ARP [45] is an ARP packet sent by a node in order
// to spontaneously cause other nodes to update an entry in their
// ARP cache. A gratuitous ARP MAY use either an ARP Request or an
// ARP Reply packet. In either case, the ARP Sender Protocol
// Address and ARP Target Protocol Address are both set to the IP
// address of the cache entry to be updated, and the ARP Sender
// Hardware Address is set to the link-layer address to which this
// cache entry should be updated. When using an ARP Reply packet,
// the Target Hardware Address is also set to the link-layer
// address to which this cache entry should be updated (this field
// is not used in an ARP Request packet).
//
// In either case, for a gratuitous ARP, the ARP packet MUST be
// transmitted as a local broadcast packet on the local link. As
// specified in [16], any node receiving any ARP packet (Request
// or Reply) MUST update its local ARP cache with the Sender
// Protocol and Hardware Addresses in the ARP packet, if the
// receiving node has an entry for that IP address already in its
// ARP cache. This requirement in the ARP protocol applies even
// for ARP Request packets, and for ARP Reply packets that do not
// match any ARP Request transmitted by the receiving node [16].
(DynamicNeighborUpdateSource::Probe, PacketKind::Gratuitous)
}
(false, true) => {
// Consider ARP replies as solicited if they were unicast directly to us, and
// unsolicited otherwise.
let solicited = match frame_dst {
FrameDestination::Individual { local } => local,
FrameDestination::Broadcast | FrameDestination::Multicast => false,
};
let source = match op {
ValidArpOp::Request => DynamicNeighborUpdateSource::Probe,
ValidArpOp::Response => {
DynamicNeighborUpdateSource::Confirmation(ConfirmationFlags {
solicited_flag: solicited,
// ARP does not have the concept of an override flag in a neighbor
// confirmation; if the link address that's received does not match the one
// in the neighbor cache, the entry should always go to STALE.
override_flag: false,
})
}
};
(source, PacketKind::AddressedToMe)
}
(false, false) => {
core_ctx.increment(|counters| &counters.rx_dropped_non_local_target);
trace!(
"non-gratuitous ARP packet not targetting us; sender = {}, target={}",
sender_addr,
target_addr
);
return;
}
(true, true) => {
warn!(
"got gratuitous ARP packet with our address {target_addr} on device {device_id:?}, \
dropping...",
);
return;
}
};
let sender_hw_addr = packet.sender_hardware_address();
if let Some(addr) = SpecifiedAddr::new(sender_addr) {
NudHandler::<Ipv4, D, _>::handle_neighbor_update(
core_ctx,
bindings_ctx,
&device_id,
addr,
sender_hw_addr,
source,
)
};
match kind {
PacketKind::Gratuitous => return,
PacketKind::AddressedToMe => match source {
DynamicNeighborUpdateSource::Probe => {
let self_hw_addr = core_ctx.get_hardware_addr(bindings_ctx, &device_id);
core_ctx.increment(|counters| &counters.tx_responses);
debug!("sending ARP response for {target_addr} to {sender_addr}");
SendFrameContext::send_frame(
core_ctx,
bindings_ctx,
ArpFrameMetadata { device_id, dst_addr: sender_hw_addr },
ArpPacketBuilder::new(
ArpOp::Response,
self_hw_addr.get(),
target_addr,
sender_hw_addr,
sender_addr,
)
.into_serializer_with(buffer),
)
.unwrap_or_else(|serializer| {
warn!(
"failed to send ARP response for {target_addr} to {sender_addr}: \
{serializer:?}"
)
});
}
DynamicNeighborUpdateSource::Confirmation(_flags) => {}
},
}
}
// Use the same default retransmit timeout that is defined for NDP in
// [RFC 4861 section 10], to align behavior between IPv4 and IPv6 and simplify
// testing.
//
// TODO(https://fxbug.dev/42075782): allow this default to be overridden.
//
// [RFC 4861 section 10]: https://tools.ietf.org/html/rfc4861#section-10
const DEFAULT_ARP_REQUEST_PERIOD: Duration = nud::RETRANS_TIMER_DEFAULT.get();
fn send_arp_request<
D: ArpDevice,
BC: ArpBindingsContext<D, CC::DeviceId>,
CC: ArpContext<D, BC> + CounterContext<ArpCounters>,
>(
core_ctx: &mut CC,
bindings_ctx: &mut BC,
device_id: &CC::DeviceId,
lookup_addr: Ipv4Addr,
remote_link_addr: Option<D::Address>,
) {
if let Some(sender_protocol_addr) = core_ctx.get_protocol_addr(bindings_ctx, device_id) {
let self_hw_addr = core_ctx.get_hardware_addr(bindings_ctx, device_id);
let dst_addr = remote_link_addr.unwrap_or(D::Address::BROADCAST);
core_ctx.increment(|counters| &counters.tx_requests);
debug!("sending ARP request for {lookup_addr} to {dst_addr:?}");
SendFrameContext::send_frame(
core_ctx,
bindings_ctx,
ArpFrameMetadata { device_id: device_id.clone(), dst_addr },
ArpPacketBuilder::new(
ArpOp::Request,
self_hw_addr.get(),
sender_protocol_addr,
// This is meaningless, since RFC 826 does not specify the
// behaviour. However, `dst_addr` is sensible, as this is the
// actual address we are sending the packet to.
dst_addr,
lookup_addr,
)
.into_serializer(),
)
.unwrap_or_else(|serializer| {
warn!("failed to send ARP request for {lookup_addr} to {dst_addr:?}: {serializer:?}")
});
} else {
// RFC 826 does not specify what to do if we don't have a local address,
// but there is no reasonable way to send an ARP request without one (as
// the receiver will cache our local address on receiving the packet.
// So, if this is the case, we do not send an ARP request.
// TODO(wesleyac): Should we cache these, and send packets once we have
// an address?
core_ctx.increment(|counters| &counters.tx_requests_dropped_no_local_addr);
debug!("Not sending ARP request, since we don't know our local protocol address");
}
}
/// The state associated with an instance of the Address Resolution Protocol
/// (ARP).
///
/// Each device will contain an `ArpState` object for each of the network
/// protocols that it supports.
pub struct ArpState<D: ArpDevice, BT: NudBindingsTypes<D>> {
pub(crate) nud: NudState<Ipv4, D, BT>,
}
impl<D: ArpDevice, BC: NudBindingsTypes<D> + TimerContext> ArpState<D, BC> {
/// Creates a new `ArpState` for `device_id`.
pub fn new<
DeviceId: WeakDeviceIdentifier,
CC: CoreTimerContext<ArpTimerId<D, DeviceId>, BC>,
>(
bindings_ctx: &mut BC,
device_id: DeviceId,
) -> Self {
ArpState { nud: NudState::new::<_, CC>(bindings_ctx, device_id) }
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use alloc::vec::Vec;
use core::iter;
use net_types::ethernet::Mac;
use netstack3_base::socket::SocketIpAddr;
use netstack3_base::testutil::{
assert_empty, FakeBindingsCtx, FakeCoreCtx, FakeDeviceId, FakeInstant, FakeLinkDeviceId,
FakeNetworkSpec, FakeTimerId, FakeWeakDeviceId, WithFakeFrameContext,
};
use netstack3_base::{CtxPair, InstantContext as _, IntoCoreTimerCtx, TimerHandler};
use netstack3_ip::nud::testutil::{
assert_dynamic_neighbor_state, assert_dynamic_neighbor_with_addr, assert_neighbor_unknown,
};
use netstack3_ip::nud::{
DelegateNudContext, DynamicNeighborState, NudCounters, NudIcmpContext, Reachable, Stale,
UseDelegateNudContext,
};
use packet::{Buf, ParseBuffer};
use packet_formats::arp::{peek_arp_types, ArpHardwareType, ArpNetworkType};
use packet_formats::ipv4::Ipv4FragmentType;
use test_case::test_case;
use super::*;
use crate::internal::ethernet::EthernetLinkDevice;
const TEST_LOCAL_IPV4: Ipv4Addr = Ipv4Addr::new([1, 2, 3, 4]);
const TEST_REMOTE_IPV4: Ipv4Addr = Ipv4Addr::new([5, 6, 7, 8]);
const TEST_ANOTHER_REMOTE_IPV4: Ipv4Addr = Ipv4Addr::new([9, 10, 11, 12]);
const TEST_LOCAL_MAC: Mac = Mac::new([0, 1, 2, 3, 4, 5]);
const TEST_REMOTE_MAC: Mac = Mac::new([6, 7, 8, 9, 10, 11]);
const TEST_INVALID_MAC: Mac = Mac::new([0, 0, 0, 0, 0, 0]);
/// A fake `ArpContext` that stores frames, address resolution events, and
/// address resolution failure events.
struct FakeArpCtx {
proto_addr: Option<Ipv4Addr>,
hw_addr: UnicastAddr<Mac>,
arp_state: ArpState<EthernetLinkDevice, FakeBindingsCtxImpl>,
inner: FakeArpInnerCtx,
config: FakeArpConfigCtx,
counters: ArpCounters,
nud_counters: NudCounters<Ipv4>,
}
/// A fake `ArpSenderContext` that sends IP packets.
struct FakeArpInnerCtx;
/// A fake `ArpConfigContext`.
struct FakeArpConfigCtx;
impl FakeArpCtx {
fn new(bindings_ctx: &mut FakeBindingsCtxImpl) -> FakeArpCtx {
FakeArpCtx {
proto_addr: Some(TEST_LOCAL_IPV4),
hw_addr: UnicastAddr::new(TEST_LOCAL_MAC).unwrap(),
arp_state: ArpState::new::<_, IntoCoreTimerCtx>(
bindings_ctx,
FakeWeakDeviceId(FakeLinkDeviceId),
),
inner: FakeArpInnerCtx,
config: FakeArpConfigCtx,
counters: Default::default(),
nud_counters: Default::default(),
}
}
}
type FakeBindingsCtxImpl = FakeBindingsCtx<
ArpTimerId<EthernetLinkDevice, FakeWeakDeviceId<FakeLinkDeviceId>>,
nud::Event<Mac, FakeLinkDeviceId, Ipv4, FakeInstant>,
(),
(),
>;
type FakeCoreCtxImpl = FakeCoreCtx<
FakeArpCtx,
ArpFrameMetadata<EthernetLinkDevice, FakeLinkDeviceId>,
FakeDeviceId,
>;
fn new_context() -> CtxPair<FakeCoreCtxImpl, FakeBindingsCtxImpl> {
CtxPair::with_default_bindings_ctx(|bindings_ctx| {
FakeCoreCtxImpl::with_state(FakeArpCtx::new(bindings_ctx))
})
}
enum ArpNetworkSpec {}
impl FakeNetworkSpec for ArpNetworkSpec {
type Context = CtxPair<FakeCoreCtxImpl, FakeBindingsCtxImpl>;
type TimerId = ArpTimerId<EthernetLinkDevice, FakeWeakDeviceId<FakeLinkDeviceId>>;
type SendMeta = ArpFrameMetadata<EthernetLinkDevice, FakeLinkDeviceId>;
type RecvMeta = ArpFrameMetadata<EthernetLinkDevice, FakeLinkDeviceId>;
fn handle_frame(
ctx: &mut Self::Context,
ArpFrameMetadata { device_id, .. }: Self::RecvMeta,
data: Buf<Vec<u8>>,
) {
let CtxPair { core_ctx, bindings_ctx } = ctx;
handle_packet(
core_ctx,
bindings_ctx,
device_id,
FrameDestination::Individual { local: true },
data,
)
}
fn handle_timer(ctx: &mut Self::Context, dispatch: Self::TimerId, timer: FakeTimerId) {
let CtxPair { core_ctx, bindings_ctx } = ctx;
TimerHandler::handle_timer(core_ctx, bindings_ctx, dispatch, timer)
}
fn process_queues(_ctx: &mut Self::Context) -> bool {
false
}
fn fake_frames(ctx: &mut Self::Context) -> &mut impl WithFakeFrameContext<Self::SendMeta> {
&mut ctx.core_ctx
}
}
impl DeviceIdContext<EthernetLinkDevice> for FakeCoreCtxImpl {
type DeviceId = FakeLinkDeviceId;
type WeakDeviceId = FakeWeakDeviceId<FakeLinkDeviceId>;
}
impl DeviceIdContext<EthernetLinkDevice> for FakeArpInnerCtx {
type DeviceId = FakeLinkDeviceId;
type WeakDeviceId = FakeWeakDeviceId<FakeLinkDeviceId>;
}
impl ArpContext<EthernetLinkDevice, FakeBindingsCtxImpl> for FakeCoreCtxImpl {
type ConfigCtx<'a> = FakeArpConfigCtx;
type ArpSenderCtx<'a> = FakeArpInnerCtx;
fn with_arp_state_mut_and_sender_ctx<
O,
F: FnOnce(
&mut ArpState<EthernetLinkDevice, FakeBindingsCtxImpl>,
&mut Self::ArpSenderCtx<'_>,
) -> O,
>(
&mut self,
FakeLinkDeviceId: &FakeLinkDeviceId,
cb: F,
) -> O {
let FakeArpCtx { arp_state, inner, .. } = &mut self.state;
cb(arp_state, inner)
}
fn with_arp_state<O, F: FnOnce(&ArpState<EthernetLinkDevice, FakeBindingsCtxImpl>) -> O>(
&mut self,
FakeLinkDeviceId: &FakeLinkDeviceId,
cb: F,
) -> O {
cb(&self.state.arp_state)
}
fn get_protocol_addr(
&mut self,
_bindings_ctx: &mut FakeBindingsCtxImpl,
_device_id: &FakeLinkDeviceId,
) -> Option<Ipv4Addr> {
self.state.proto_addr
}
fn get_hardware_addr(
&mut self,
_bindings_ctx: &mut FakeBindingsCtxImpl,
_device_id: &FakeLinkDeviceId,
) -> UnicastAddr<Mac> {
self.state.hw_addr
}
fn with_arp_state_mut<
O,
F: FnOnce(
&mut ArpState<EthernetLinkDevice, FakeBindingsCtxImpl>,
&mut Self::ConfigCtx<'_>,
) -> O,
>(
&mut self,
FakeLinkDeviceId: &FakeLinkDeviceId,
cb: F,
) -> O {
let FakeArpCtx { arp_state, config, .. } = &mut self.state;
cb(arp_state, config)
}
}
impl UseDelegateNudContext for FakeArpCtx {}
impl DelegateNudContext<Ipv4> for FakeArpCtx {
type Delegate<T> = ArpNudCtx<T>;
}
impl NudIcmpContext<Ipv4, EthernetLinkDevice, FakeBindingsCtxImpl> for FakeCoreCtxImpl {
fn send_icmp_dest_unreachable(
&mut self,
_bindings_ctx: &mut FakeBindingsCtxImpl,
_frame: Buf<Vec<u8>>,
_device_id: Option<&Self::DeviceId>,
_original_src: SocketIpAddr<Ipv4Addr>,
_original_dst: SocketIpAddr<Ipv4Addr>,
_metadata: (usize, Ipv4FragmentType),
) {
panic!("send_icmp_dest_unreachable should not be called");
}
}
impl ArpConfigContext for FakeArpConfigCtx {
fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O {
cb(&NudUserConfig::default())
}
}
impl ArpConfigContext for FakeArpInnerCtx {
fn with_nud_user_config<O, F: FnOnce(&NudUserConfig) -> O>(&mut self, cb: F) -> O {
cb(&NudUserConfig::default())
}
}
impl ArpSenderContext<EthernetLinkDevice, FakeBindingsCtxImpl> for FakeArpInnerCtx {
fn send_ip_packet_to_neighbor_link_addr<S>(
&mut self,
_bindings_ctx: &mut FakeBindingsCtxImpl,
_dst_link_address: Mac,
_body: S,
) -> Result<(), SendFrameError<S>> {
Ok(())
}
}
impl CounterContext<ArpCounters> for FakeArpCtx {
fn with_counters<O, F: FnOnce(&ArpCounters) -> O>(&self, cb: F) -> O {
cb(&self.counters)
}
}
impl CounterContext<NudCounters<Ipv4>> for FakeArpCtx {
fn with_counters<O, F: FnOnce(&NudCounters<Ipv4>) -> O>(&self, cb: F) -> O {
cb(&self.nud_counters)
}
}
fn send_arp_packet(
core_ctx: &mut FakeCoreCtxImpl,
bindings_ctx: &mut FakeBindingsCtxImpl,
op: ArpOp,
sender_ipv4: Ipv4Addr,
target_ipv4: Ipv4Addr,
sender_mac: Mac,
target_mac: Mac,
frame_dst: FrameDestination,
) {
let buf = ArpPacketBuilder::new(op, sender_mac, sender_ipv4, target_mac, target_ipv4)
.into_serializer()
.serialize_vec_outer()
.unwrap();
let (hw, proto) = peek_arp_types(buf.as_ref()).unwrap();
assert_eq!(hw, ArpHardwareType::Ethernet);
assert_eq!(proto, ArpNetworkType::Ipv4);
handle_packet::<_, _, _, _>(core_ctx, bindings_ctx, FakeLinkDeviceId, frame_dst, buf);
}
// Validate that buf is an ARP packet with the specific op, local_ipv4,
// remote_ipv4, local_mac and remote_mac.
fn validate_arp_packet(
mut buf: &[u8],
op: ArpOp,
local_ipv4: Ipv4Addr,
remote_ipv4: Ipv4Addr,
local_mac: Mac,
remote_mac: Mac,
) {
let packet = buf.parse::<ArpPacket<_, Mac, Ipv4Addr>>().unwrap();
assert_eq!(packet.sender_hardware_address(), local_mac);
assert_eq!(packet.target_hardware_address(), remote_mac);
assert_eq!(packet.sender_protocol_address(), local_ipv4);
assert_eq!(packet.target_protocol_address(), remote_ipv4);
assert_eq!(packet.operation(), op);
}
// Validate that we've sent `total_frames` frames in total, and that the
// most recent one was sent to `dst` with the given ARP packet contents.
fn validate_last_arp_packet(
core_ctx: &FakeCoreCtxImpl,
total_frames: usize,
dst: Mac,
op: ArpOp,
local_ipv4: Ipv4Addr,
remote_ipv4: Ipv4Addr,
local_mac: Mac,
remote_mac: Mac,
) {
assert_eq!(core_ctx.frames().len(), total_frames);
let (meta, frame) = &core_ctx.frames()[total_frames - 1];
assert_eq!(meta.dst_addr, dst);
validate_arp_packet(frame, op, local_ipv4, remote_ipv4, local_mac, remote_mac);
}
#[test]
fn test_receive_gratuitous_arp_request() {
// Test that, when we receive a gratuitous ARP request, we cache the
// sender's address information, and we do not send a response.
let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
send_arp_packet(
&mut core_ctx,
&mut bindings_ctx,
ArpOp::Request,
TEST_REMOTE_IPV4,
TEST_REMOTE_IPV4,
TEST_REMOTE_MAC,
TEST_INVALID_MAC,
FrameDestination::Individual { local: false },
);
// We should have cached the sender's address information.
assert_dynamic_neighbor_with_addr(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
TEST_REMOTE_MAC,
);
// Gratuitous ARPs should not prompt a response.
assert_empty(core_ctx.frames().iter());
}
#[test]
fn test_receive_gratuitous_arp_response() {
// Test that, when we receive a gratuitous ARP response, we cache the
// sender's address information, and we do not send a response.
let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
send_arp_packet(
&mut core_ctx,
&mut bindings_ctx,
ArpOp::Response,
TEST_REMOTE_IPV4,
TEST_REMOTE_IPV4,
TEST_REMOTE_MAC,
TEST_REMOTE_MAC,
FrameDestination::Individual { local: false },
);
// We should have cached the sender's address information.
assert_dynamic_neighbor_with_addr(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
TEST_REMOTE_MAC,
);
// Gratuitous ARPs should not send a response.
assert_empty(core_ctx.frames().iter());
}
#[test]
fn test_receive_gratuitous_arp_response_existing_request() {
// Test that, if we have an outstanding request retry timer and receive
// a gratuitous ARP for the same host, we cancel the timer and notify
// the device layer.
let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
// Trigger link resolution.
assert_neighbor_unknown(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
);
assert_eq!(
NudHandler::send_ip_packet_to_neighbor(
&mut core_ctx,
&mut bindings_ctx,
&FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
Buf::new([1], ..),
),
Ok(())
);
send_arp_packet(
&mut core_ctx,
&mut bindings_ctx,
ArpOp::Response,
TEST_REMOTE_IPV4,
TEST_REMOTE_IPV4,
TEST_REMOTE_MAC,
TEST_REMOTE_MAC,
FrameDestination::Individual { local: false },
);
// The response should now be in our cache.
assert_dynamic_neighbor_with_addr(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
TEST_REMOTE_MAC,
);
// Gratuitous ARPs should not send a response (the 1 frame is for the
// original request).
assert_eq!(core_ctx.frames().len(), 1);
}
#[test]
fn test_handle_arp_request() {
// Test that, when we receive an ARP request, we cache the sender's
// address information and send an ARP response.
let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
send_arp_packet(
&mut core_ctx,
&mut bindings_ctx,
ArpOp::Request,
TEST_REMOTE_IPV4,
TEST_LOCAL_IPV4,
TEST_REMOTE_MAC,
TEST_LOCAL_MAC,
FrameDestination::Individual { local: true },
);
// Make sure we cached the sender's address information.
assert_dynamic_neighbor_with_addr(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
TEST_REMOTE_MAC,
);
// We should have sent an ARP response.
validate_last_arp_packet(
&core_ctx,
1,
TEST_REMOTE_MAC,
ArpOp::Response,
TEST_LOCAL_IPV4,
TEST_REMOTE_IPV4,
TEST_LOCAL_MAC,
TEST_REMOTE_MAC,
);
}
struct ArpHostConfig<'a> {
name: &'a str,
proto_addr: Ipv4Addr,
hw_addr: Mac,
}
#[test_case(ArpHostConfig {
name: "remote",
proto_addr: TEST_REMOTE_IPV4,
hw_addr: TEST_REMOTE_MAC
},
vec![]
)]
#[test_case(ArpHostConfig {
name: "requested_remote",
proto_addr: TEST_REMOTE_IPV4,
hw_addr: TEST_REMOTE_MAC
},
vec![
ArpHostConfig {
name: "non_requested_remote",
proto_addr: TEST_ANOTHER_REMOTE_IPV4,
hw_addr: TEST_REMOTE_MAC
}
]
)]
fn test_address_resolution(
requested_remote_cfg: ArpHostConfig<'_>,
other_remote_cfgs: Vec<ArpHostConfig<'_>>,
) {
// Test a basic ARP resolution scenario.
// We expect the following steps:
// 1. When a lookup is performed and results in a cache miss, we send an
// ARP request and set a request retry timer.
// 2. When the requested remote receives the request, it populates its cache with
// the local's information, and sends an ARP reply.
// 3. Any non-requested remotes will neither populate their caches nor send ARP replies.
// 4. When the reply is received, the timer is canceled, the table is
// updated, a new entry expiration timer is installed, and the device
// layer is notified of the resolution.
const LOCAL_HOST_CFG: ArpHostConfig<'_> =
ArpHostConfig { name: "local", proto_addr: TEST_LOCAL_IPV4, hw_addr: TEST_LOCAL_MAC };
let host_iter = other_remote_cfgs
.iter()
.chain(iter::once(&requested_remote_cfg))
.chain(iter::once(&LOCAL_HOST_CFG));
let mut network = ArpNetworkSpec::new_network(
{
host_iter.clone().map(|cfg| {
let ArpHostConfig { name, proto_addr, hw_addr } = cfg;
let mut ctx = new_context();
let CtxPair { core_ctx, bindings_ctx: _ } = &mut ctx;
core_ctx.state.hw_addr = UnicastAddr::new(*hw_addr).unwrap();
core_ctx.state.proto_addr = Some(*proto_addr);
(*name, ctx)
})
},
|ctx: &str, meta: ArpFrameMetadata<_, _>| {
host_iter
.clone()
.filter_map(|cfg| {
let ArpHostConfig { name, proto_addr: _, hw_addr: _ } = cfg;
if !ctx.eq(*name) {
Some((*name, meta.clone(), None))
} else {
None
}
})
.collect::<Vec<_>>()
},
);
let ArpHostConfig {
name: local_name,
proto_addr: local_proto_addr,
hw_addr: local_hw_addr,
} = LOCAL_HOST_CFG;
let ArpHostConfig {
name: requested_remote_name,
proto_addr: requested_remote_proto_addr,
hw_addr: requested_remote_hw_addr,
} = requested_remote_cfg;
// Trigger link resolution.
network.with_context(local_name, |CtxPair { core_ctx, bindings_ctx }| {
assert_neighbor_unknown(
core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(requested_remote_proto_addr).unwrap(),
);
assert_eq!(
NudHandler::send_ip_packet_to_neighbor(
core_ctx,
bindings_ctx,
&FakeLinkDeviceId,
SpecifiedAddr::new(requested_remote_proto_addr).unwrap(),
Buf::new([1], ..),
),
Ok(())
);
// We should have sent an ARP request.
validate_last_arp_packet(
core_ctx,
1,
Mac::BROADCAST,
ArpOp::Request,
local_proto_addr,
requested_remote_proto_addr,
local_hw_addr,
Mac::BROADCAST,
);
});
// Step once to deliver the ARP request to the remotes.
let res = network.step();
assert_eq!(res.timers_fired, 0);
// Our faked broadcast network should deliver frames to every host other
// than the sender itself. These should include all non-participating remotes
// and either the local or the participating remote, depending on who is
// sending the packet.
let expected_frames_sent_bcast = other_remote_cfgs.len() + 1;
assert_eq!(res.frames_sent, expected_frames_sent_bcast);
// The requested remote should have populated its ARP cache with the local's
// information.
network.with_context(requested_remote_name, |CtxPair { core_ctx, bindings_ctx: _ }| {
assert_dynamic_neighbor_with_addr(
core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(local_proto_addr).unwrap(),
LOCAL_HOST_CFG.hw_addr,
);
// The requested remote should have sent an ARP response.
validate_last_arp_packet(
core_ctx,
1,
local_hw_addr,
ArpOp::Response,
requested_remote_proto_addr,
local_proto_addr,
requested_remote_hw_addr,
local_hw_addr,
);
});
// Step once to deliver the ARP response to the local.
let res = network.step();
assert_eq!(res.timers_fired, 0);
assert_eq!(res.frames_sent, expected_frames_sent_bcast);
// The local should have populated its cache with the remote's
// information.
network.with_context(local_name, |CtxPair { core_ctx, bindings_ctx: _ }| {
assert_dynamic_neighbor_with_addr(
core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(requested_remote_proto_addr).unwrap(),
requested_remote_hw_addr,
);
});
other_remote_cfgs.iter().for_each(
|ArpHostConfig { name: unrequested_remote_name, proto_addr: _, hw_addr: _ }| {
// The non-requested_remote should not have populated its ARP cache.
network.with_context(
*unrequested_remote_name,
|CtxPair { core_ctx, bindings_ctx: _ }| {
// The non-requested_remote should not have sent an ARP response.
assert_empty(core_ctx.frames().iter());
assert_neighbor_unknown(
core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(local_proto_addr).unwrap(),
);
},
)
},
);
}
#[test_case(FrameDestination::Individual { local: true }, true; "unicast to us is solicited")]
#[test_case(
FrameDestination::Individual { local: false },
false;
"unicast to other addr is unsolicited"
)]
#[test_case(FrameDestination::Multicast, false; "multicast reply is unsolicited")]
#[test_case(FrameDestination::Broadcast, false; "broadcast reply is unsolicited")]
fn only_unicast_reply_treated_as_solicited(
frame_dst: FrameDestination,
expect_solicited: bool,
) {
let CtxPair { mut core_ctx, mut bindings_ctx } = new_context();
// Trigger link resolution.
assert_neighbor_unknown(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
);
assert_eq!(
NudHandler::send_ip_packet_to_neighbor(
&mut core_ctx,
&mut bindings_ctx,
&FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
Buf::new([1], ..),
),
Ok(())
);
// Now send a confirmation with the specified frame destination.
send_arp_packet(
&mut core_ctx,
&mut bindings_ctx,
ArpOp::Response,
TEST_REMOTE_IPV4,
TEST_LOCAL_IPV4,
TEST_REMOTE_MAC,
TEST_LOCAL_MAC,
frame_dst,
);
// If the confirmation was interpreted as solicited, the entry should be
// marked as REACHABLE; otherwise, it should have transitioned to STALE.
let expected_state = if expect_solicited {
DynamicNeighborState::Reachable(Reachable {
link_address: TEST_REMOTE_MAC,
last_confirmed_at: bindings_ctx.now(),
})
} else {
DynamicNeighborState::Stale(Stale { link_address: TEST_REMOTE_MAC })
};
assert_dynamic_neighbor_state(
&mut core_ctx,
FakeLinkDeviceId,
SpecifiedAddr::new(TEST_REMOTE_IPV4).unwrap(),
expected_state,
);
}
}