summaryrefslogtreecommitdiffstats
path: root/src/core/hle/service/nwm
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/hle/service/nwm')
-rw-r--r--src/core/hle/service/nwm/nwm_uds.cpp402
-rw-r--r--src/core/hle/service/nwm/uds_beacon.cpp4
-rw-r--r--src/core/hle/service/nwm/uds_connection.cpp9
-rw-r--r--src/core/hle/service/nwm/uds_connection.h5
-rw-r--r--src/core/hle/service/nwm/uds_data.cpp103
-rw-r--r--src/core/hle/service/nwm/uds_data.h86
6 files changed, 501 insertions, 108 deletions
diff --git a/src/core/hle/service/nwm/nwm_uds.cpp b/src/core/hle/service/nwm/nwm_uds.cpp
index 893bbb1e7..0aa63cc1e 100644
--- a/src/core/hle/service/nwm/nwm_uds.cpp
+++ b/src/core/hle/service/nwm/nwm_uds.cpp
@@ -2,8 +2,10 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <algorithm>
#include <array>
#include <cstring>
+#include <list>
#include <mutex>
#include <unordered_map>
#include <vector>
@@ -13,6 +15,7 @@
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/event.h"
#include "core/hle/kernel/shared_memory.h"
+#include "core/hle/lock.h"
#include "core/hle/result.h"
#include "core/hle/service/nwm/nwm_uds.h"
#include "core/hle/service/nwm/uds_beacon.h"
@@ -37,9 +40,12 @@ static ConnectionStatus connection_status{};
/* Node information about the current network.
* The amount of elements in this vector is always the maximum number
* of nodes specified in the network configuration.
- * The first node is always the host, so this always contains at least 1 entry.
+ * The first node is always the host.
*/
-static NodeList node_info(1);
+static NodeList node_info;
+
+// Node information about our own system.
+static NodeInfo current_node;
// Mapping of bind node ids to their respective events.
static std::unordered_map<u32, Kernel::SharedPtr<Kernel::Event>> bind_node_events;
@@ -54,6 +60,10 @@ static NetworkInfo network_info;
// Event that will generate and send the 802.11 beacon frames.
static int beacon_broadcast_event;
+// Mutex to synchronize access to the connection status between the emulation thread and the
+// network thread.
+static std::mutex connection_status_mutex;
+
// Mutex to synchronize access to the list of received beacons between the emulation thread and the
// network thread.
static std::mutex beacon_mutex;
@@ -63,14 +73,26 @@ static std::mutex beacon_mutex;
constexpr size_t MaxBeaconFrames = 15;
// List of the last <MaxBeaconFrames> beacons received from the network.
-static std::deque<Network::WifiPacket> received_beacons;
+static std::list<Network::WifiPacket> received_beacons;
/**
* Returns a list of received 802.11 beacon frames from the specified sender since the last call.
*/
-std::deque<Network::WifiPacket> GetReceivedBeacons(const MacAddress& sender) {
+std::list<Network::WifiPacket> GetReceivedBeacons(const MacAddress& sender) {
std::lock_guard<std::mutex> lock(beacon_mutex);
- // TODO(Subv): Filter by sender.
+ if (sender != Network::BroadcastMac) {
+ std::list<Network::WifiPacket> filtered_list;
+ const auto beacon = std::find_if(received_beacons.begin(), received_beacons.end(),
+ [&sender](const Network::WifiPacket& packet) {
+ return packet.transmitter_address == sender;
+ });
+ if (beacon != received_beacons.end()) {
+ filtered_list.push_back(*beacon);
+ // TODO(B3N30): Check if the complete deque is cleared or just the fetched entries
+ received_beacons.erase(beacon);
+ }
+ return filtered_list;
+ }
return std::move(received_beacons);
}
@@ -79,10 +101,33 @@ void SendPacket(Network::WifiPacket& packet) {
// TODO(Subv): Implement.
}
+/*
+ * Returns an available index in the nodes array for the
+ * currently-hosted UDS network.
+ */
+static u16 GetNextAvailableNodeId() {
+ for (u16 index = 0; index < connection_status.max_nodes; ++index) {
+ if ((connection_status.node_bitmask & (1 << index)) == 0)
+ return index;
+ }
+
+ // Any connection attempts to an already full network should have been refused.
+ ASSERT_MSG(false, "No available connection slots in the network");
+}
+
// Inserts the received beacon frame in the beacon queue and removes any older beacons if the size
// limit is exceeded.
void HandleBeaconFrame(const Network::WifiPacket& packet) {
std::lock_guard<std::mutex> lock(beacon_mutex);
+ const auto unique_beacon =
+ std::find_if(received_beacons.begin(), received_beacons.end(),
+ [&packet](const Network::WifiPacket& new_packet) {
+ return new_packet.transmitter_address == packet.transmitter_address;
+ });
+ if (unique_beacon != received_beacons.end()) {
+ // We already have a beacon from the same mac in the deque, remove the old one;
+ received_beacons.erase(unique_beacon);
+ }
received_beacons.emplace_back(packet);
@@ -91,21 +136,110 @@ void HandleBeaconFrame(const Network::WifiPacket& packet) {
received_beacons.pop_front();
}
-/*
- * Returns an available index in the nodes array for the
- * currently-hosted UDS network.
- */
-static u16 GetNextAvailableNodeId() {
- ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost),
- "Can not accept clients if we're not hosting a network");
+void HandleAssociationResponseFrame(const Network::WifiPacket& packet) {
+ auto assoc_result = GetAssociationResult(packet.data);
- for (u16 index = 0; index < connection_status.max_nodes; ++index) {
- if ((connection_status.node_bitmask & (1 << index)) == 0)
- return index;
+ ASSERT_MSG(std::get<AssocStatus>(assoc_result) == AssocStatus::Successful,
+ "Could not join network");
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::Connecting));
}
- // Any connection attempts to an already full network should have been refused.
- ASSERT_MSG(false, "No available connection slots in the network");
+ // Send the EAPoL-Start packet to the server.
+ using Network::WifiPacket;
+ WifiPacket eapol_start;
+ eapol_start.channel = network_channel;
+ eapol_start.data = GenerateEAPoLStartFrame(std::get<u16>(assoc_result), current_node);
+ // TODO(B3N30): Encrypt the packet.
+ eapol_start.destination_address = packet.transmitter_address;
+ eapol_start.type = WifiPacket::PacketType::Data;
+
+ SendPacket(eapol_start);
+}
+
+static void HandleEAPoLPacket(const Network::WifiPacket& packet) {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+
+ if (GetEAPoLFrameType(packet.data) == EAPoLStartMagic) {
+ if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
+ LOG_DEBUG(Service_NWM, "Connection sequence aborted, because connection status is %u",
+ connection_status.status);
+ return;
+ }
+
+ auto node = DeserializeNodeInfoFromFrame(packet.data);
+
+ if (connection_status.max_nodes == connection_status.total_nodes) {
+ // Reject connection attempt
+ LOG_ERROR(Service_NWM, "Reached maximum nodes, but reject packet wasn't sent.");
+ // TODO(B3N30): Figure out what packet is sent here
+ return;
+ }
+
+ // Get an unused network node id
+ u16 node_id = GetNextAvailableNodeId();
+ node.network_node_id = node_id + 1;
+
+ connection_status.node_bitmask |= 1 << node_id;
+ connection_status.changed_nodes |= 1 << node_id;
+ connection_status.nodes[node_id] = node.network_node_id;
+ connection_status.total_nodes++;
+
+ u8 current_nodes = network_info.total_nodes;
+ node_info[current_nodes] = node;
+
+ network_info.total_nodes++;
+
+ // Send the EAPoL-Logoff packet.
+ using Network::WifiPacket;
+ WifiPacket eapol_logoff;
+ eapol_logoff.channel = network_channel;
+ eapol_logoff.data =
+ GenerateEAPoLLogoffFrame(packet.transmitter_address, node.network_node_id, node_info,
+ network_info.max_nodes, network_info.total_nodes);
+ // TODO(Subv): Encrypt the packet.
+ eapol_logoff.destination_address = packet.transmitter_address;
+ eapol_logoff.type = WifiPacket::PacketType::Data;
+
+ SendPacket(eapol_logoff);
+ // TODO(B3N30): Broadcast updated node list
+ // The 3ds does this presumably to support spectators.
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ connection_status_event->Signal();
+ } else {
+ if (connection_status.status != static_cast<u32>(NetworkStatus::NotConnected)) {
+ LOG_DEBUG(Service_NWM, "Connection sequence aborted, because connection status is %u",
+ connection_status.status);
+ return;
+ }
+ auto logoff = ParseEAPoLLogoffFrame(packet.data);
+
+ network_info.total_nodes = logoff.connected_nodes;
+ network_info.max_nodes = logoff.max_nodes;
+
+ connection_status.network_node_id = logoff.assigned_node_id;
+ connection_status.total_nodes = logoff.connected_nodes;
+ connection_status.max_nodes = logoff.max_nodes;
+
+ node_info.clear();
+ node_info.reserve(network_info.max_nodes);
+ for (size_t index = 0; index < logoff.connected_nodes; ++index) {
+ connection_status.node_bitmask |= 1 << index;
+ connection_status.changed_nodes |= 1 << index;
+ connection_status.nodes[index] = logoff.nodes[index].network_node_id;
+
+ node_info.emplace_back(DeserializeNodeInfo(logoff.nodes[index]));
+ }
+
+ // We're now connected, signal the application
+ connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsClient);
+ // Some games require ConnectToNetwork to block, for now it doesn't
+ // If blocking is implemented this lock needs to be changed,
+ // otherwise it might cause deadlocks
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ connection_status_event->Signal();
+ }
}
/*
@@ -113,35 +247,46 @@ static u16 GetNextAvailableNodeId() {
* authentication frame with SEQ1.
*/
void StartConnectionSequence(const MacAddress& server) {
- ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::NotConnected));
-
- // TODO(Subv): Handle timeout.
-
- // Send an authentication frame with SEQ1
using Network::WifiPacket;
WifiPacket auth_request;
- auth_request.channel = network_channel;
- auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ1);
- auth_request.destination_address = server;
- auth_request.type = WifiPacket::PacketType::Authentication;
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::NotConnected));
+
+ // TODO(Subv): Handle timeout.
+
+ // Send an authentication frame with SEQ1
+ auth_request.channel = network_channel;
+ auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ1);
+ auth_request.destination_address = server;
+ auth_request.type = WifiPacket::PacketType::Authentication;
+ }
SendPacket(auth_request);
}
/// Sends an Association Response frame to the specified mac address
void SendAssociationResponseFrame(const MacAddress& address) {
- ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost));
-
using Network::WifiPacket;
WifiPacket assoc_response;
- assoc_response.channel = network_channel;
- // TODO(Subv): This will cause multiple clients to end up with the same association id, but
- // we're not using that for anything.
- u16 association_id = 1;
- assoc_response.data = GenerateAssocResponseFrame(AssocStatus::Successful, association_id,
- network_info.network_id);
- assoc_response.destination_address = address;
- assoc_response.type = WifiPacket::PacketType::AssociationResponse;
+
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
+ LOG_ERROR(Service_NWM, "Connection sequence aborted, because connection status is %u",
+ connection_status.status);
+ return;
+ }
+
+ assoc_response.channel = network_channel;
+ // TODO(Subv): This will cause multiple clients to end up with the same association id, but
+ // we're not using that for anything.
+ u16 association_id = 1;
+ assoc_response.data = GenerateAssocResponseFrame(AssocStatus::Successful, association_id,
+ network_info.network_id);
+ assoc_response.destination_address = address;
+ assoc_response.type = WifiPacket::PacketType::AssociationResponse;
+ }
SendPacket(assoc_response);
}
@@ -155,22 +300,40 @@ void SendAssociationResponseFrame(const MacAddress& address) {
void HandleAuthenticationFrame(const Network::WifiPacket& packet) {
// Only the SEQ1 auth frame is handled here, the SEQ2 frame doesn't need any special behavior
if (GetAuthenticationSeqNumber(packet.data) == AuthenticationSeq::SEQ1) {
- ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost));
-
- // Respond with an authentication response frame with SEQ2
using Network::WifiPacket;
WifiPacket auth_request;
- auth_request.channel = network_channel;
- auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ2);
- auth_request.destination_address = packet.transmitter_address;
- auth_request.type = WifiPacket::PacketType::Authentication;
-
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
+ LOG_ERROR(Service_NWM,
+ "Connection sequence aborted, because connection status is %u",
+ connection_status.status);
+ return;
+ }
+
+ // Respond with an authentication response frame with SEQ2
+ auth_request.channel = network_channel;
+ auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ2);
+ auth_request.destination_address = packet.transmitter_address;
+ auth_request.type = WifiPacket::PacketType::Authentication;
+ }
SendPacket(auth_request);
SendAssociationResponseFrame(packet.transmitter_address);
}
}
+static void HandleDataFrame(const Network::WifiPacket& packet) {
+ switch (GetFrameEtherType(packet.data)) {
+ case EtherType::EAPoL:
+ HandleEAPoLPacket(packet);
+ break;
+ case EtherType::SecureData:
+ // TODO(B3N30): Handle SecureData packets
+ break;
+ }
+}
+
/// Callback to parse and handle a received wifi packet.
void OnWifiPacketReceived(const Network::WifiPacket& packet) {
switch (packet.type) {
@@ -180,6 +343,12 @@ void OnWifiPacketReceived(const Network::WifiPacket& packet) {
case Network::WifiPacket::PacketType::Authentication:
HandleAuthenticationFrame(packet);
break;
+ case Network::WifiPacket::PacketType::AssociationResponse:
+ HandleAssociationResponseFrame(packet);
+ break;
+ case Network::WifiPacket::PacketType::Data:
+ HandleDataFrame(packet);
+ break;
}
}
@@ -246,7 +415,7 @@ static void RecvBeaconBroadcastData(Interface* self) {
auto beacons = GetReceivedBeacons(mac_address);
BeaconDataReplyHeader data_reply_header{};
- data_reply_header.total_entries = beacons.size();
+ data_reply_header.total_entries = static_cast<u32>(beacons.size());
data_reply_header.max_output_size = out_buffer_size;
Memory::WriteBlock(current_buffer_pos, &data_reply_header, sizeof(BeaconDataReplyHeader));
@@ -256,8 +425,8 @@ static void RecvBeaconBroadcastData(Interface* self) {
for (const auto& beacon : beacons) {
BeaconEntryHeader entry{};
// TODO(Subv): Figure out what this size is used for.
- entry.unk_size = sizeof(BeaconEntryHeader) + beacon.data.size();
- entry.total_size = sizeof(BeaconEntryHeader) + beacon.data.size();
+ entry.unk_size = static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
+ entry.total_size = static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
entry.wifi_channel = beacon.channel;
entry.header_size = sizeof(BeaconEntryHeader);
entry.mac_address = beacon.transmitter_address;
@@ -268,9 +437,9 @@ static void RecvBeaconBroadcastData(Interface* self) {
current_buffer_pos += sizeof(BeaconEntryHeader);
Memory::WriteBlock(current_buffer_pos, beacon.data.data(), beacon.data.size());
- current_buffer_pos += beacon.data.size();
+ current_buffer_pos += static_cast<VAddr>(beacon.data.size());
- total_size += sizeof(BeaconEntryHeader) + beacon.data.size();
+ total_size += static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
}
// Update the total size in the structure and write it to the buffer again.
@@ -305,7 +474,7 @@ static void InitializeWithVersion(Interface* self) {
u32 sharedmem_size = rp.Pop<u32>();
// Update the node information with the data the game gave us.
- rp.PopRaw(node_info[0]);
+ rp.PopRaw(current_node);
u16 version = rp.Pop<u16>();
@@ -315,10 +484,14 @@ static void InitializeWithVersion(Interface* self) {
ASSERT_MSG(recv_buffer_memory->size == sharedmem_size, "Invalid shared memory size.");
- // Reset the connection status, it contains all zeros after initialization,
- // except for the actual status value.
- connection_status = {};
- connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+
+ // Reset the connection status, it contains all zeros after initialization,
+ // except for the actual status value.
+ connection_status = {};
+ connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
+ }
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS);
@@ -348,12 +521,16 @@ static void GetConnectionStatus(Interface* self) {
IPC::RequestBuilder rb = rp.MakeBuilder(13, 0);
rb.Push(RESULT_SUCCESS);
- rb.PushRaw(connection_status);
-
- // Reset the bitmask of changed nodes after each call to this
- // function to prevent falsely informing games of outstanding
- // changes in subsequent calls.
- connection_status.changed_nodes = 0;
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ rb.PushRaw(connection_status);
+
+ // Reset the bitmask of changed nodes after each call to this
+ // function to prevent falsely informing games of outstanding
+ // changes in subsequent calls.
+ // TODO(Subv): Find exactly where the NWM module resets this value.
+ connection_status.changed_nodes = 0;
+ }
LOG_DEBUG(Service_NWM, "called");
}
@@ -434,31 +611,36 @@ static void BeginHostingNetwork(Interface* self) {
// The real UDS module throws a fatal error if this assert fails.
ASSERT_MSG(network_info.max_nodes > 1, "Trying to host a network of only one member.");
- connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost);
-
- // Ensure the application data size is less than the maximum value.
- ASSERT_MSG(network_info.application_data_size <= ApplicationDataSize, "Data size is too big.");
-
- // Set up basic information for this network.
- network_info.oui_value = NintendoOUI;
- network_info.oui_type = static_cast<u8>(NintendoTagId::NetworkInfo);
-
- connection_status.max_nodes = network_info.max_nodes;
-
- // Resize the nodes list to hold max_nodes.
- node_info.resize(network_info.max_nodes);
-
- // There's currently only one node in the network (the host).
- connection_status.total_nodes = 1;
- network_info.total_nodes = 1;
- // The host is always the first node
- connection_status.network_node_id = 1;
- node_info[0].network_node_id = 1;
- connection_status.nodes[0] = connection_status.network_node_id;
- // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken.
- connection_status.node_bitmask |= 1;
- // Notify the application that the first node was set.
- connection_status.changed_nodes |= 1;
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost);
+
+ // Ensure the application data size is less than the maximum value.
+ ASSERT_MSG(network_info.application_data_size <= ApplicationDataSize,
+ "Data size is too big.");
+
+ // Set up basic information for this network.
+ network_info.oui_value = NintendoOUI;
+ network_info.oui_type = static_cast<u8>(NintendoTagId::NetworkInfo);
+
+ connection_status.max_nodes = network_info.max_nodes;
+
+ // Resize the nodes list to hold max_nodes.
+ node_info.resize(network_info.max_nodes);
+
+ // There's currently only one node in the network (the host).
+ connection_status.total_nodes = 1;
+ network_info.total_nodes = 1;
+ // The host is always the first node
+ connection_status.network_node_id = 1;
+ current_node.network_node_id = 1;
+ connection_status.nodes[0] = connection_status.network_node_id;
+ // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken.
+ connection_status.node_bitmask |= 1;
+ // Notify the application that the first node was set.
+ connection_status.changed_nodes |= 1;
+ node_info[0] = current_node;
+ }
// If the game has a preferred channel, use that instead.
if (network_info.channel != 0)
@@ -495,9 +677,13 @@ static void DestroyNetwork(Interface* self) {
// Unschedule the beacon broadcast event.
CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
- // TODO(Subv): Check if connection_status is indeed reset after this call.
- connection_status = {};
- connection_status.status = static_cast<u8>(NetworkStatus::NotConnected);
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+
+ // TODO(Subv): Check if connection_status is indeed reset after this call.
+ connection_status = {};
+ connection_status.status = static_cast<u8>(NetworkStatus::NotConnected);
+ }
connection_status_event->Signal();
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
@@ -540,17 +726,24 @@ static void SendTo(Interface* self) {
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
- if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) &&
- connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
- rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
- ErrorSummary::InvalidState, ErrorLevel::Status));
- return;
- }
+ u16 network_node_id;
- if (dest_node_id == connection_status.network_node_id) {
- rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS,
- ErrorSummary::WrongArgument, ErrorLevel::Status));
- return;
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) &&
+ connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
+ rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
+ ErrorSummary::InvalidState, ErrorLevel::Status));
+ return;
+ }
+
+ if (dest_node_id == connection_status.network_node_id) {
+ rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS,
+ ErrorSummary::WrongArgument, ErrorLevel::Status));
+ return;
+ }
+
+ network_node_id = connection_status.network_node_id;
}
// TODO(Subv): Do something with the flags.
@@ -567,8 +760,8 @@ static void SendTo(Interface* self) {
// TODO(Subv): Increment the sequence number after each sent packet.
u16 sequence_number = 0;
- std::vector<u8> data_payload = GenerateDataPayload(
- data, data_channel, dest_node_id, connection_status.network_node_id, sequence_number);
+ std::vector<u8> data_payload =
+ GenerateDataPayload(data, data_channel, dest_node_id, network_node_id, sequence_number);
// TODO(Subv): Retrieve the MAC address of the dest_node_id and our own to encrypt
// and encapsulate the payload.
@@ -595,6 +788,7 @@ static void GetChannel(Interface* self) {
IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 0, 0);
IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
bool is_connected = connection_status.status != static_cast<u32>(NetworkStatus::NotConnected);
u8 channel = is_connected ? network_channel : 0;
@@ -766,6 +960,7 @@ static void BeaconBroadcastCallback(u64 userdata, int cycles_late) {
* @param network_node_id Network Node Id of the connecting client.
*/
void OnClientConnected(u16 network_node_id) {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost),
"Can not accept clients if we're not hosting a network");
ASSERT_MSG(connection_status.total_nodes < connection_status.max_nodes,
@@ -827,8 +1022,11 @@ NWM_UDS::~NWM_UDS() {
connection_status_event = nullptr;
recv_buffer_memory = nullptr;
- connection_status = {};
- connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
+ {
+ std::lock_guard<std::mutex> lock(connection_status_mutex);
+ connection_status = {};
+ connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
+ }
CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
}
diff --git a/src/core/hle/service/nwm/uds_beacon.cpp b/src/core/hle/service/nwm/uds_beacon.cpp
index 552eaf65e..73a80d940 100644
--- a/src/core/hle/service/nwm/uds_beacon.cpp
+++ b/src/core/hle/service/nwm/uds_beacon.cpp
@@ -243,7 +243,7 @@ std::vector<u8> GenerateNintendoFirstEncryptedDataTag(const NetworkInfo& network
EncryptedDataTag tag{};
tag.header.tag_id = static_cast<u8>(TagId::VendorSpecific);
- tag.header.length = sizeof(tag) - sizeof(TagHeader) + payload_size;
+ tag.header.length = static_cast<u8>(sizeof(tag) - sizeof(TagHeader) + payload_size);
tag.oui_type = static_cast<u8>(NintendoTagId::EncryptedData0);
tag.oui = NintendoOUI;
@@ -279,7 +279,7 @@ std::vector<u8> GenerateNintendoSecondEncryptedDataTag(const NetworkInfo& networ
EncryptedDataTag tag{};
tag.header.tag_id = static_cast<u8>(TagId::VendorSpecific);
- tag.header.length = tag_length;
+ tag.header.length = static_cast<u8>(tag_length);
tag.oui_type = static_cast<u8>(NintendoTagId::EncryptedData1);
tag.oui = NintendoOUI;
diff --git a/src/core/hle/service/nwm/uds_connection.cpp b/src/core/hle/service/nwm/uds_connection.cpp
index c8a76ec2a..c74f51253 100644
--- a/src/core/hle/service/nwm/uds_connection.cpp
+++ b/src/core/hle/service/nwm/uds_connection.cpp
@@ -75,5 +75,14 @@ std::vector<u8> GenerateAssocResponseFrame(AssocStatus status, u16 association_i
return data;
}
+std::tuple<AssocStatus, u16> GetAssociationResult(const std::vector<u8>& body) {
+ AssociationResponseFrame frame;
+ memcpy(&frame, body.data(), sizeof(frame));
+
+ constexpr u16 AssociationIdMask = 0x3FFF;
+ return std::make_tuple(static_cast<AssocStatus>(frame.status_code),
+ frame.assoc_id & AssociationIdMask);
+}
+
} // namespace NWM
} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_connection.h b/src/core/hle/service/nwm/uds_connection.h
index 73f55a4fd..a664f8471 100644
--- a/src/core/hle/service/nwm/uds_connection.h
+++ b/src/core/hle/service/nwm/uds_connection.h
@@ -4,6 +4,7 @@
#pragma once
+#include <tuple>
#include <vector>
#include "common/common_types.h"
#include "common/swap.h"
@@ -47,5 +48,9 @@ AuthenticationSeq GetAuthenticationSeqNumber(const std::vector<u8>& body);
/// network id, starting at the frame body.
std::vector<u8> GenerateAssocResponseFrame(AssocStatus status, u16 association_id, u32 network_id);
+/// Returns a tuple of (association status, association id) from the body of an AssociationResponse
+/// frame.
+std::tuple<AssocStatus, u16> GetAssociationResult(const std::vector<u8>& body);
+
} // namespace NWM
} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_data.cpp b/src/core/hle/service/nwm/uds_data.cpp
index 8c6742dba..4b389710f 100644
--- a/src/core/hle/service/nwm/uds_data.cpp
+++ b/src/core/hle/service/nwm/uds_data.cpp
@@ -2,6 +2,7 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <algorithm>
#include <cstring>
#include <cryptopp/aes.h>
#include <cryptopp/ccm.h>
@@ -197,7 +198,7 @@ static std::vector<u8> DecryptDataFrame(const std::vector<u8>& encrypted_payload
df.ChannelMessageEnd(CryptoPP::DEFAULT_CHANNEL);
df.SetRetrievalChannel(CryptoPP::DEFAULT_CHANNEL);
- int size = df.MaxRetrievable();
+ size_t size = df.MaxRetrievable();
std::vector<u8> pdata(size);
df.Get(pdata.data(), size);
@@ -251,7 +252,7 @@ static std::vector<u8> EncryptDataFrame(const std::vector<u8>& payload,
df.SetRetrievalChannel(CryptoPP::DEFAULT_CHANNEL);
- int size = df.MaxRetrievable();
+ size_t size = df.MaxRetrievable();
std::vector<u8> cipher(size);
df.Get(cipher.data(), size);
@@ -266,13 +267,107 @@ static std::vector<u8> EncryptDataFrame(const std::vector<u8>& payload,
std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node,
u16 src_node, u16 sequence_number) {
std::vector<u8> buffer = GenerateLLCHeader(EtherType::SecureData);
- std::vector<u8> securedata_header =
- GenerateSecureDataHeader(data.size(), channel, dest_node, src_node, sequence_number);
+ std::vector<u8> securedata_header = GenerateSecureDataHeader(
+ static_cast<u16>(data.size()), channel, dest_node, src_node, sequence_number);
buffer.insert(buffer.end(), securedata_header.begin(), securedata_header.end());
buffer.insert(buffer.end(), data.begin(), data.end());
return buffer;
}
+std::vector<u8> GenerateEAPoLStartFrame(u16 association_id, const NodeInfo& node_info) {
+ EAPoLStartPacket eapol_start{};
+ eapol_start.association_id = association_id;
+ eapol_start.node.friend_code_seed = node_info.friend_code_seed;
+
+ std::copy(node_info.username.begin(), node_info.username.end(),
+ eapol_start.node.username.begin());
+
+ // Note: The network_node_id and unknown bytes seem to be uninitialized in the NWM module.
+ // TODO(B3N30): The last 8 bytes seem to have a fixed value of 07 88 15 00 04 e9 13 00 in
+ // EAPoL-Start packets from different 3DSs to the same host during a Super Smash Bros. 4 game.
+ // Find out what that means.
+
+ std::vector<u8> eapol_buffer(sizeof(EAPoLStartPacket));
+ std::memcpy(eapol_buffer.data(), &eapol_start, sizeof(eapol_start));
+
+ std::vector<u8> buffer = GenerateLLCHeader(EtherType::EAPoL);
+ buffer.insert(buffer.end(), eapol_buffer.begin(), eapol_buffer.end());
+ return buffer;
+}
+
+EtherType GetFrameEtherType(const std::vector<u8>& frame) {
+ LLCHeader header;
+ std::memcpy(&header, frame.data(), sizeof(header));
+
+ u16 ethertype = header.protocol;
+ return static_cast<EtherType>(ethertype);
+}
+
+u16 GetEAPoLFrameType(const std::vector<u8>& frame) {
+ // Ignore the LLC header
+ u16_be eapol_type;
+ std::memcpy(&eapol_type, frame.data() + sizeof(LLCHeader), sizeof(eapol_type));
+ return eapol_type;
+}
+
+NodeInfo DeserializeNodeInfoFromFrame(const std::vector<u8>& frame) {
+ EAPoLStartPacket eapol_start;
+
+ // Skip the LLC header
+ std::memcpy(&eapol_start, frame.data() + sizeof(LLCHeader), sizeof(eapol_start));
+
+ NodeInfo node{};
+ node.friend_code_seed = eapol_start.node.friend_code_seed;
+
+ std::copy(eapol_start.node.username.begin(), eapol_start.node.username.end(),
+ node.username.begin());
+
+ return node;
+}
+
+NodeInfo DeserializeNodeInfo(const EAPoLNodeInfo& node) {
+ NodeInfo node_info{};
+ node_info.friend_code_seed = node.friend_code_seed;
+ node_info.network_node_id = node.network_node_id;
+
+ std::copy(node.username.begin(), node.username.end(), node_info.username.begin());
+
+ return node_info;
+}
+
+std::vector<u8> GenerateEAPoLLogoffFrame(const MacAddress& mac_address, u16 network_node_id,
+ const NodeList& nodes, u8 max_nodes, u8 total_nodes) {
+ EAPoLLogoffPacket eapol_logoff{};
+ eapol_logoff.assigned_node_id = network_node_id;
+ eapol_logoff.connected_nodes = total_nodes;
+ eapol_logoff.max_nodes = max_nodes;
+
+ for (size_t index = 0; index < total_nodes; ++index) {
+ const auto& node_info = nodes[index];
+ auto& node = eapol_logoff.nodes[index];
+
+ node.friend_code_seed = node_info.friend_code_seed;
+ node.network_node_id = node_info.network_node_id;
+
+ std::copy(node_info.username.begin(), node_info.username.end(), node.username.begin());
+ }
+
+ std::vector<u8> eapol_buffer(sizeof(EAPoLLogoffPacket));
+ std::memcpy(eapol_buffer.data(), &eapol_logoff, sizeof(eapol_logoff));
+
+ std::vector<u8> buffer = GenerateLLCHeader(EtherType::EAPoL);
+ buffer.insert(buffer.end(), eapol_buffer.begin(), eapol_buffer.end());
+ return buffer;
+}
+
+EAPoLLogoffPacket ParseEAPoLLogoffFrame(const std::vector<u8>& frame) {
+ EAPoLLogoffPacket eapol_logoff;
+
+ // Skip the LLC header
+ std::memcpy(&eapol_logoff, frame.data() + sizeof(LLCHeader), sizeof(eapol_logoff));
+ return eapol_logoff;
+}
+
} // namespace NWM
} // namespace Service
diff --git a/src/core/hle/service/nwm/uds_data.h b/src/core/hle/service/nwm/uds_data.h
index a23520a41..76bccb1bf 100644
--- a/src/core/hle/service/nwm/uds_data.h
+++ b/src/core/hle/service/nwm/uds_data.h
@@ -8,6 +8,7 @@
#include <vector>
#include "common/common_types.h"
#include "common/swap.h"
+#include "core/hle/service/nwm/uds_beacon.h"
#include "core/hle/service/service.h"
namespace Service {
@@ -67,6 +68,49 @@ struct DataFrameCryptoCTR {
static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wrong size");
+struct EAPoLNodeInfo {
+ u64_be friend_code_seed;
+ std::array<u16_be, 10> username;
+ INSERT_PADDING_BYTES(4);
+ u16_be network_node_id;
+ INSERT_PADDING_BYTES(6);
+};
+
+static_assert(sizeof(EAPoLNodeInfo) == 0x28, "EAPoLNodeInfo has the wrong size");
+
+constexpr u16 EAPoLStartMagic = 0x201;
+
+/*
+ * Nintendo EAPoLStartPacket, is used to initaliaze a connection between client and host
+ */
+struct EAPoLStartPacket {
+ u16_be magic = EAPoLStartMagic;
+ u16_be association_id;
+ // This value is hardcoded to 1 in the NWM module.
+ u16_be unknown = 1;
+ INSERT_PADDING_BYTES(2);
+ EAPoLNodeInfo node;
+};
+
+static_assert(sizeof(EAPoLStartPacket) == 0x30, "EAPoLStartPacket has the wrong size");
+
+constexpr u16 EAPoLLogoffMagic = 0x202;
+
+struct EAPoLLogoffPacket {
+ u16_be magic = EAPoLLogoffMagic;
+ INSERT_PADDING_BYTES(2);
+ u16_be assigned_node_id;
+ MacAddress client_mac_address;
+ INSERT_PADDING_BYTES(6);
+ u8 connected_nodes;
+ u8 max_nodes;
+ INSERT_PADDING_BYTES(4);
+
+ std::array<EAPoLNodeInfo, UDSMaxNodes> nodes;
+};
+
+static_assert(sizeof(EAPoLLogoffPacket) == 0x298, "EAPoLLogoffPacket has the wrong size");
+
/**
* Generates an unencrypted 802.11 data payload.
* @returns The generated frame payload.
@@ -74,5 +118,47 @@ static_assert(sizeof(DataFrameCryptoCTR) == 16, "DataFrameCryptoCTR has the wron
std::vector<u8> GenerateDataPayload(const std::vector<u8>& data, u8 channel, u16 dest_node,
u16 src_node, u16 sequence_number);
+/*
+ * Generates an unencrypted 802.11 data frame body with the EAPoL-Start format for UDS
+ * communication.
+ * @returns The generated frame body.
+ */
+std::vector<u8> GenerateEAPoLStartFrame(u16 association_id, const NodeInfo& node_info);
+
+/*
+ * Returns the EtherType of the specified 802.11 frame.
+ */
+EtherType GetFrameEtherType(const std::vector<u8>& frame);
+
+/*
+ * Returns the EAPoL type (Start / Logoff) of the specified 802.11 frame.
+ * Note: The frame *must* be an EAPoL frame.
+ */
+u16 GetEAPoLFrameType(const std::vector<u8>& frame);
+
+/*
+ * Returns a deserialized NodeInfo structure from the information inside an EAPoL-Start packet
+ * encapsulated in an 802.11 data frame.
+ */
+NodeInfo DeserializeNodeInfoFromFrame(const std::vector<u8>& frame);
+
+/*
+ * Returns a NodeInfo constructed from the data in the specified EAPoLNodeInfo.
+ */
+NodeInfo DeserializeNodeInfo(const EAPoLNodeInfo& node);
+
+/*
+ * Generates an unencrypted 802.11 data frame body with the EAPoL-Logoff format for UDS
+ * communication.
+ * @returns The generated frame body.
+ */
+std::vector<u8> GenerateEAPoLLogoffFrame(const MacAddress& mac_address, u16 network_node_id,
+ const NodeList& nodes, u8 max_nodes, u8 total_nodes);
+
+/*
+ * Returns a EAPoLLogoffPacket representing the specified 802.11-encapsulated data frame.
+ */
+EAPoLLogoffPacket ParseEAPoLLogoffFrame(const std::vector<u8>& frame);
+
} // namespace NWM
} // namespace Service