nwm_uds.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. // Copyright 2017 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <cstring>
  7. #include <list>
  8. #include <mutex>
  9. #include <unordered_map>
  10. #include <vector>
  11. #include "common/common_types.h"
  12. #include "common/logging/log.h"
  13. #include "core/core_timing.h"
  14. #include "core/hle/ipc_helpers.h"
  15. #include "core/hle/kernel/event.h"
  16. #include "core/hle/kernel/shared_memory.h"
  17. #include "core/hle/lock.h"
  18. #include "core/hle/result.h"
  19. #include "core/hle/service/nwm/nwm_uds.h"
  20. #include "core/hle/service/nwm/uds_beacon.h"
  21. #include "core/hle/service/nwm/uds_connection.h"
  22. #include "core/hle/service/nwm/uds_data.h"
  23. #include "core/memory.h"
  24. #include "network/network.h"
  25. namespace Service {
  26. namespace NWM {
  27. // Event that is signaled every time the connection status changes.
  28. static Kernel::SharedPtr<Kernel::Event> connection_status_event;
  29. // Shared memory provided by the application to store the receive buffer.
  30. // This is not currently used.
  31. static Kernel::SharedPtr<Kernel::SharedMemory> recv_buffer_memory;
  32. // Connection status of this 3DS.
  33. static ConnectionStatus connection_status{};
  34. /* Node information about the current network.
  35. * The amount of elements in this vector is always the maximum number
  36. * of nodes specified in the network configuration.
  37. * The first node is always the host.
  38. */
  39. static NodeList node_info;
  40. // Node information about our own system.
  41. static NodeInfo current_node;
  42. // Mapping of bind node ids to their respective events.
  43. static std::unordered_map<u32, Kernel::SharedPtr<Kernel::Event>> bind_node_events;
  44. // The WiFi network channel that the network is currently on.
  45. // Since we're not actually interacting with physical radio waves, this is just a dummy value.
  46. static u8 network_channel = DefaultNetworkChannel;
  47. // Information about the network that we're currently connected to.
  48. static NetworkInfo network_info;
  49. // Event that will generate and send the 802.11 beacon frames.
  50. static int beacon_broadcast_event;
  51. // Mutex to synchronize access to the connection status between the emulation thread and the
  52. // network thread.
  53. static std::mutex connection_status_mutex;
  54. // Mutex to synchronize access to the list of received beacons between the emulation thread and the
  55. // network thread.
  56. static std::mutex beacon_mutex;
  57. // Number of beacons to store before we start dropping the old ones.
  58. // TODO(Subv): Find a more accurate value for this limit.
  59. constexpr size_t MaxBeaconFrames = 15;
  60. // List of the last <MaxBeaconFrames> beacons received from the network.
  61. static std::list<Network::WifiPacket> received_beacons;
  62. /**
  63. * Returns a list of received 802.11 beacon frames from the specified sender since the last call.
  64. */
  65. std::list<Network::WifiPacket> GetReceivedBeacons(const MacAddress& sender) {
  66. std::lock_guard<std::mutex> lock(beacon_mutex);
  67. if (sender != Network::BroadcastMac) {
  68. std::list<Network::WifiPacket> filtered_list;
  69. const auto beacon = std::find_if(received_beacons.begin(), received_beacons.end(),
  70. [&sender](const Network::WifiPacket& packet) {
  71. return packet.transmitter_address == sender;
  72. });
  73. if (beacon != received_beacons.end()) {
  74. filtered_list.push_back(*beacon);
  75. // TODO(B3N30): Check if the complete deque is cleared or just the fetched entries
  76. received_beacons.erase(beacon);
  77. }
  78. return filtered_list;
  79. }
  80. return std::move(received_beacons);
  81. }
  82. /// Sends a WifiPacket to the room we're currently connected to.
  83. void SendPacket(Network::WifiPacket& packet) {
  84. // TODO(Subv): Implement.
  85. }
  86. /*
  87. * Returns an available index in the nodes array for the
  88. * currently-hosted UDS network.
  89. */
  90. static u16 GetNextAvailableNodeId() {
  91. for (u16 index = 0; index < connection_status.max_nodes; ++index) {
  92. if ((connection_status.node_bitmask & (1 << index)) == 0)
  93. return index;
  94. }
  95. // Any connection attempts to an already full network should have been refused.
  96. ASSERT_MSG(false, "No available connection slots in the network");
  97. }
  98. // Inserts the received beacon frame in the beacon queue and removes any older beacons if the size
  99. // limit is exceeded.
  100. void HandleBeaconFrame(const Network::WifiPacket& packet) {
  101. std::lock_guard<std::mutex> lock(beacon_mutex);
  102. const auto unique_beacon =
  103. std::find_if(received_beacons.begin(), received_beacons.end(),
  104. [&packet](const Network::WifiPacket& new_packet) {
  105. return new_packet.transmitter_address == packet.transmitter_address;
  106. });
  107. if (unique_beacon != received_beacons.end()) {
  108. // We already have a beacon from the same mac in the deque, remove the old one;
  109. received_beacons.erase(unique_beacon);
  110. }
  111. received_beacons.emplace_back(packet);
  112. // Discard old beacons if the buffer is full.
  113. if (received_beacons.size() > MaxBeaconFrames)
  114. received_beacons.pop_front();
  115. }
  116. void HandleAssociationResponseFrame(const Network::WifiPacket& packet) {
  117. auto assoc_result = GetAssociationResult(packet.data);
  118. ASSERT_MSG(std::get<AssocStatus>(assoc_result) == AssocStatus::Successful,
  119. "Could not join network");
  120. {
  121. std::lock_guard<std::mutex> lock(connection_status_mutex);
  122. ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::Connecting));
  123. }
  124. // Send the EAPoL-Start packet to the server.
  125. using Network::WifiPacket;
  126. WifiPacket eapol_start;
  127. eapol_start.channel = network_channel;
  128. eapol_start.data = GenerateEAPoLStartFrame(std::get<u16>(assoc_result), current_node);
  129. // TODO(B3N30): Encrypt the packet.
  130. eapol_start.destination_address = packet.transmitter_address;
  131. eapol_start.type = WifiPacket::PacketType::Data;
  132. SendPacket(eapol_start);
  133. }
  134. static void HandleEAPoLPacket(const Network::WifiPacket& packet) {
  135. std::lock_guard<std::mutex> lock(connection_status_mutex);
  136. if (GetEAPoLFrameType(packet.data) == EAPoLStartMagic) {
  137. if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
  138. LOG_DEBUG(Service_NWM, "Connection sequence aborted, because connection status is %u",
  139. connection_status.status);
  140. return;
  141. }
  142. auto node = DeserializeNodeInfoFromFrame(packet.data);
  143. if (connection_status.max_nodes == connection_status.total_nodes) {
  144. // Reject connection attempt
  145. LOG_ERROR(Service_NWM, "Reached maximum nodes, but reject packet wasn't sent.");
  146. // TODO(B3N30): Figure out what packet is sent here
  147. return;
  148. }
  149. // Get an unused network node id
  150. u16 node_id = GetNextAvailableNodeId();
  151. node.network_node_id = node_id + 1;
  152. connection_status.node_bitmask |= 1 << node_id;
  153. connection_status.changed_nodes |= 1 << node_id;
  154. connection_status.nodes[node_id] = node.network_node_id;
  155. connection_status.total_nodes++;
  156. u8 current_nodes = network_info.total_nodes;
  157. node_info[current_nodes] = node;
  158. network_info.total_nodes++;
  159. // Send the EAPoL-Logoff packet.
  160. using Network::WifiPacket;
  161. WifiPacket eapol_logoff;
  162. eapol_logoff.channel = network_channel;
  163. eapol_logoff.data =
  164. GenerateEAPoLLogoffFrame(packet.transmitter_address, node.network_node_id, node_info,
  165. network_info.max_nodes, network_info.total_nodes);
  166. // TODO(Subv): Encrypt the packet.
  167. eapol_logoff.destination_address = packet.transmitter_address;
  168. eapol_logoff.type = WifiPacket::PacketType::Data;
  169. SendPacket(eapol_logoff);
  170. // TODO(B3N30): Broadcast updated node list
  171. // The 3ds does this presumably to support spectators.
  172. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  173. connection_status_event->Signal();
  174. } else {
  175. if (connection_status.status != static_cast<u32>(NetworkStatus::NotConnected)) {
  176. LOG_DEBUG(Service_NWM, "Connection sequence aborted, because connection status is %u",
  177. connection_status.status);
  178. return;
  179. }
  180. auto logoff = ParseEAPoLLogoffFrame(packet.data);
  181. network_info.total_nodes = logoff.connected_nodes;
  182. network_info.max_nodes = logoff.max_nodes;
  183. connection_status.network_node_id = logoff.assigned_node_id;
  184. connection_status.total_nodes = logoff.connected_nodes;
  185. connection_status.max_nodes = logoff.max_nodes;
  186. node_info.clear();
  187. node_info.reserve(network_info.max_nodes);
  188. for (size_t index = 0; index < logoff.connected_nodes; ++index) {
  189. connection_status.node_bitmask |= 1 << index;
  190. connection_status.changed_nodes |= 1 << index;
  191. connection_status.nodes[index] = logoff.nodes[index].network_node_id;
  192. node_info.emplace_back(DeserializeNodeInfo(logoff.nodes[index]));
  193. }
  194. // We're now connected, signal the application
  195. connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsClient);
  196. // Some games require ConnectToNetwork to block, for now it doesn't
  197. // If blocking is implemented this lock needs to be changed,
  198. // otherwise it might cause deadlocks
  199. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  200. connection_status_event->Signal();
  201. }
  202. }
  203. /*
  204. * Start a connection sequence with an UDS server. The sequence starts by sending an 802.11
  205. * authentication frame with SEQ1.
  206. */
  207. void StartConnectionSequence(const MacAddress& server) {
  208. using Network::WifiPacket;
  209. WifiPacket auth_request;
  210. {
  211. std::lock_guard<std::mutex> lock(connection_status_mutex);
  212. ASSERT(connection_status.status == static_cast<u32>(NetworkStatus::NotConnected));
  213. // TODO(Subv): Handle timeout.
  214. // Send an authentication frame with SEQ1
  215. auth_request.channel = network_channel;
  216. auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ1);
  217. auth_request.destination_address = server;
  218. auth_request.type = WifiPacket::PacketType::Authentication;
  219. }
  220. SendPacket(auth_request);
  221. }
  222. /// Sends an Association Response frame to the specified mac address
  223. void SendAssociationResponseFrame(const MacAddress& address) {
  224. using Network::WifiPacket;
  225. WifiPacket assoc_response;
  226. {
  227. std::lock_guard<std::mutex> lock(connection_status_mutex);
  228. if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
  229. LOG_ERROR(Service_NWM, "Connection sequence aborted, because connection status is %u",
  230. connection_status.status);
  231. return;
  232. }
  233. assoc_response.channel = network_channel;
  234. // TODO(Subv): This will cause multiple clients to end up with the same association id, but
  235. // we're not using that for anything.
  236. u16 association_id = 1;
  237. assoc_response.data = GenerateAssocResponseFrame(AssocStatus::Successful, association_id,
  238. network_info.network_id);
  239. assoc_response.destination_address = address;
  240. assoc_response.type = WifiPacket::PacketType::AssociationResponse;
  241. }
  242. SendPacket(assoc_response);
  243. }
  244. /*
  245. * Handles the authentication request frame and sends the authentication response and association
  246. * response frames. Once an Authentication frame with SEQ1 is received by the server, it responds
  247. * with an Authentication frame containing SEQ2, and immediately sends an Association response frame
  248. * containing the details of the access point and the assigned association id for the new client.
  249. */
  250. void HandleAuthenticationFrame(const Network::WifiPacket& packet) {
  251. // Only the SEQ1 auth frame is handled here, the SEQ2 frame doesn't need any special behavior
  252. if (GetAuthenticationSeqNumber(packet.data) == AuthenticationSeq::SEQ1) {
  253. using Network::WifiPacket;
  254. WifiPacket auth_request;
  255. {
  256. std::lock_guard<std::mutex> lock(connection_status_mutex);
  257. if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
  258. LOG_ERROR(Service_NWM,
  259. "Connection sequence aborted, because connection status is %u",
  260. connection_status.status);
  261. return;
  262. }
  263. // Respond with an authentication response frame with SEQ2
  264. auth_request.channel = network_channel;
  265. auth_request.data = GenerateAuthenticationFrame(AuthenticationSeq::SEQ2);
  266. auth_request.destination_address = packet.transmitter_address;
  267. auth_request.type = WifiPacket::PacketType::Authentication;
  268. }
  269. SendPacket(auth_request);
  270. SendAssociationResponseFrame(packet.transmitter_address);
  271. }
  272. }
  273. static void HandleDataFrame(const Network::WifiPacket& packet) {
  274. switch (GetFrameEtherType(packet.data)) {
  275. case EtherType::EAPoL:
  276. HandleEAPoLPacket(packet);
  277. break;
  278. case EtherType::SecureData:
  279. // TODO(B3N30): Handle SecureData packets
  280. break;
  281. }
  282. }
  283. /// Callback to parse and handle a received wifi packet.
  284. void OnWifiPacketReceived(const Network::WifiPacket& packet) {
  285. switch (packet.type) {
  286. case Network::WifiPacket::PacketType::Beacon:
  287. HandleBeaconFrame(packet);
  288. break;
  289. case Network::WifiPacket::PacketType::Authentication:
  290. HandleAuthenticationFrame(packet);
  291. break;
  292. case Network::WifiPacket::PacketType::AssociationResponse:
  293. HandleAssociationResponseFrame(packet);
  294. break;
  295. case Network::WifiPacket::PacketType::Data:
  296. HandleDataFrame(packet);
  297. break;
  298. }
  299. }
  300. /**
  301. * NWM_UDS::Shutdown service function
  302. * Inputs:
  303. * 1 : None
  304. * Outputs:
  305. * 0 : Return header
  306. * 1 : Result of function, 0 on success, otherwise error code
  307. */
  308. static void Shutdown(Interface* self) {
  309. u32* cmd_buff = Kernel::GetCommandBuffer();
  310. // TODO(purpasmart): Verify return header on HW
  311. cmd_buff[1] = RESULT_SUCCESS.raw;
  312. LOG_WARNING(Service_NWM, "(STUBBED) called");
  313. }
  314. /**
  315. * NWM_UDS::RecvBeaconBroadcastData service function
  316. * Returns the raw beacon data for nearby networks that match the supplied WlanCommId.
  317. * Inputs:
  318. * 1 : Output buffer max size
  319. * 2-3 : Unknown
  320. * 4-5 : Host MAC address.
  321. * 6-14 : Unused
  322. * 15 : WLan Comm Id
  323. * 16 : Id
  324. * 17 : Value 0
  325. * 18 : Input handle
  326. * 19 : (Size<<4) | 12
  327. * 20 : Output buffer ptr
  328. * Outputs:
  329. * 0 : Return header
  330. * 1 : Result of function, 0 on success, otherwise error code
  331. */
  332. static void RecvBeaconBroadcastData(Interface* self) {
  333. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x0F, 16, 4);
  334. u32 out_buffer_size = rp.Pop<u32>();
  335. u32 unk1 = rp.Pop<u32>();
  336. u32 unk2 = rp.Pop<u32>();
  337. MacAddress mac_address;
  338. rp.PopRaw(mac_address);
  339. rp.Skip(9, false);
  340. u32 wlan_comm_id = rp.Pop<u32>();
  341. u32 id = rp.Pop<u32>();
  342. Kernel::Handle input_handle = rp.PopHandle();
  343. size_t desc_size;
  344. const VAddr out_buffer_ptr = rp.PopMappedBuffer(&desc_size);
  345. ASSERT(desc_size == out_buffer_size);
  346. VAddr current_buffer_pos = out_buffer_ptr;
  347. u32 total_size = sizeof(BeaconDataReplyHeader);
  348. // Retrieve all beacon frames that were received from the desired mac address.
  349. auto beacons = GetReceivedBeacons(mac_address);
  350. BeaconDataReplyHeader data_reply_header{};
  351. data_reply_header.total_entries = static_cast<u32>(beacons.size());
  352. data_reply_header.max_output_size = out_buffer_size;
  353. Memory::WriteBlock(current_buffer_pos, &data_reply_header, sizeof(BeaconDataReplyHeader));
  354. current_buffer_pos += sizeof(BeaconDataReplyHeader);
  355. // Write each of the received beacons into the buffer
  356. for (const auto& beacon : beacons) {
  357. BeaconEntryHeader entry{};
  358. // TODO(Subv): Figure out what this size is used for.
  359. entry.unk_size = static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
  360. entry.total_size = static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
  361. entry.wifi_channel = beacon.channel;
  362. entry.header_size = sizeof(BeaconEntryHeader);
  363. entry.mac_address = beacon.transmitter_address;
  364. ASSERT(current_buffer_pos < out_buffer_ptr + out_buffer_size);
  365. Memory::WriteBlock(current_buffer_pos, &entry, sizeof(BeaconEntryHeader));
  366. current_buffer_pos += sizeof(BeaconEntryHeader);
  367. Memory::WriteBlock(current_buffer_pos, beacon.data.data(), beacon.data.size());
  368. current_buffer_pos += static_cast<VAddr>(beacon.data.size());
  369. total_size += static_cast<u32>(sizeof(BeaconEntryHeader) + beacon.data.size());
  370. }
  371. // Update the total size in the structure and write it to the buffer again.
  372. data_reply_header.total_size = total_size;
  373. Memory::WriteBlock(out_buffer_ptr, &data_reply_header, sizeof(BeaconDataReplyHeader));
  374. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  375. rb.Push(RESULT_SUCCESS);
  376. LOG_DEBUG(Service_NWM, "called out_buffer_size=0x%08X, wlan_comm_id=0x%08X, id=0x%08X,"
  377. "input_handle=0x%08X, out_buffer_ptr=0x%08X, unk1=0x%08X, unk2=0x%08X",
  378. out_buffer_size, wlan_comm_id, id, input_handle, out_buffer_ptr, unk1, unk2);
  379. }
  380. /**
  381. * NWM_UDS::Initialize service function
  382. * Inputs:
  383. * 1 : Shared memory size
  384. * 2-11 : Input NodeInfo Structure
  385. * 12 : 2-byte Version
  386. * 13 : Value 0
  387. * 14 : Shared memory handle
  388. * Outputs:
  389. * 0 : Return header
  390. * 1 : Result of function, 0 on success, otherwise error code
  391. * 2 : Value 0
  392. * 3 : Output event handle
  393. */
  394. static void InitializeWithVersion(Interface* self) {
  395. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1B, 12, 2);
  396. u32 sharedmem_size = rp.Pop<u32>();
  397. // Update the node information with the data the game gave us.
  398. rp.PopRaw(current_node);
  399. u16 version = rp.Pop<u16>();
  400. Kernel::Handle sharedmem_handle = rp.PopHandle();
  401. recv_buffer_memory = Kernel::g_handle_table.Get<Kernel::SharedMemory>(sharedmem_handle);
  402. ASSERT_MSG(recv_buffer_memory->size == sharedmem_size, "Invalid shared memory size.");
  403. {
  404. std::lock_guard<std::mutex> lock(connection_status_mutex);
  405. // Reset the connection status, it contains all zeros after initialization,
  406. // except for the actual status value.
  407. connection_status = {};
  408. connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
  409. }
  410. IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
  411. rb.Push(RESULT_SUCCESS);
  412. rb.PushCopyHandles(Kernel::g_handle_table.Create(connection_status_event).Unwrap());
  413. // TODO(Subv): Connect the OnWifiPacketReceived function to the wifi packet received callback of
  414. // the room we're currently in.
  415. LOG_DEBUG(Service_NWM, "called sharedmem_size=0x%08X, version=0x%08X, sharedmem_handle=0x%08X",
  416. sharedmem_size, version, sharedmem_handle);
  417. }
  418. /**
  419. * NWM_UDS::GetConnectionStatus service function.
  420. * Returns the connection status structure for the currently open network connection.
  421. * This structure contains information about the connection,
  422. * like the number of connected nodes, etc.
  423. * Inputs:
  424. * 0 : Command header.
  425. * Outputs:
  426. * 0 : Return header
  427. * 1 : Result of function, 0 on success, otherwise error code
  428. * 2-13 : Channel of the current WiFi network connection.
  429. */
  430. static void GetConnectionStatus(Interface* self) {
  431. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xB, 0, 0);
  432. IPC::RequestBuilder rb = rp.MakeBuilder(13, 0);
  433. rb.Push(RESULT_SUCCESS);
  434. {
  435. std::lock_guard<std::mutex> lock(connection_status_mutex);
  436. rb.PushRaw(connection_status);
  437. // Reset the bitmask of changed nodes after each call to this
  438. // function to prevent falsely informing games of outstanding
  439. // changes in subsequent calls.
  440. // TODO(Subv): Find exactly where the NWM module resets this value.
  441. connection_status.changed_nodes = 0;
  442. }
  443. LOG_DEBUG(Service_NWM, "called");
  444. }
  445. /**
  446. * NWM_UDS::Bind service function.
  447. * Binds a BindNodeId to a data channel and retrieves a data event.
  448. * Inputs:
  449. * 1 : BindNodeId
  450. * 2 : Receive buffer size.
  451. * 3 : u8 Data channel to bind to.
  452. * 4 : Network node id.
  453. * Outputs:
  454. * 0 : Return header
  455. * 1 : Result of function, 0 on success, otherwise error code
  456. * 2 : Copy handle descriptor.
  457. * 3 : Data available event handle.
  458. */
  459. static void Bind(Interface* self) {
  460. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x12, 4, 0);
  461. u32 bind_node_id = rp.Pop<u32>();
  462. u32 recv_buffer_size = rp.Pop<u32>();
  463. u8 data_channel = rp.Pop<u8>();
  464. u16 network_node_id = rp.Pop<u16>();
  465. // TODO(Subv): Store the data channel and verify it when receiving data frames.
  466. LOG_DEBUG(Service_NWM, "called");
  467. if (data_channel == 0) {
  468. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  469. rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
  470. ErrorSummary::WrongArgument, ErrorLevel::Usage));
  471. return;
  472. }
  473. // Create a new event for this bind node.
  474. // TODO(Subv): Signal this event when new data is received on this data channel.
  475. auto event = Kernel::Event::Create(Kernel::ResetType::OneShot,
  476. "NWM::BindNodeEvent" + std::to_string(bind_node_id));
  477. bind_node_events[bind_node_id] = event;
  478. IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
  479. rb.Push(RESULT_SUCCESS);
  480. rb.PushCopyHandles(Kernel::g_handle_table.Create(event).Unwrap());
  481. }
  482. /**
  483. * NWM_UDS::BeginHostingNetwork service function.
  484. * Creates a network and starts broadcasting its presence.
  485. * Inputs:
  486. * 1 : Passphrase buffer size.
  487. * 3 : VAddr of the NetworkInfo structure.
  488. * 5 : VAddr of the passphrase.
  489. * Outputs:
  490. * 0 : Return header
  491. * 1 : Result of function, 0 on success, otherwise error code
  492. */
  493. static void BeginHostingNetwork(Interface* self) {
  494. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1D, 1, 4);
  495. const u32 passphrase_size = rp.Pop<u32>();
  496. size_t desc_size;
  497. const VAddr network_info_address = rp.PopStaticBuffer(&desc_size, false);
  498. ASSERT(desc_size == sizeof(NetworkInfo));
  499. const VAddr passphrase_address = rp.PopStaticBuffer(&desc_size, false);
  500. ASSERT(desc_size == passphrase_size);
  501. // TODO(Subv): Store the passphrase and verify it when attempting a connection.
  502. LOG_DEBUG(Service_NWM, "called");
  503. Memory::ReadBlock(network_info_address, &network_info, sizeof(NetworkInfo));
  504. // The real UDS module throws a fatal error if this assert fails.
  505. ASSERT_MSG(network_info.max_nodes > 1, "Trying to host a network of only one member.");
  506. {
  507. std::lock_guard<std::mutex> lock(connection_status_mutex);
  508. connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost);
  509. // Ensure the application data size is less than the maximum value.
  510. ASSERT_MSG(network_info.application_data_size <= ApplicationDataSize,
  511. "Data size is too big.");
  512. // Set up basic information for this network.
  513. network_info.oui_value = NintendoOUI;
  514. network_info.oui_type = static_cast<u8>(NintendoTagId::NetworkInfo);
  515. connection_status.max_nodes = network_info.max_nodes;
  516. // Resize the nodes list to hold max_nodes.
  517. node_info.resize(network_info.max_nodes);
  518. // There's currently only one node in the network (the host).
  519. connection_status.total_nodes = 1;
  520. network_info.total_nodes = 1;
  521. // The host is always the first node
  522. connection_status.network_node_id = 1;
  523. current_node.network_node_id = 1;
  524. connection_status.nodes[0] = connection_status.network_node_id;
  525. // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken.
  526. connection_status.node_bitmask |= 1;
  527. // Notify the application that the first node was set.
  528. connection_status.changed_nodes |= 1;
  529. node_info[0] = current_node;
  530. }
  531. // If the game has a preferred channel, use that instead.
  532. if (network_info.channel != 0)
  533. network_channel = network_info.channel;
  534. connection_status_event->Signal();
  535. // Start broadcasting the network, send a beacon frame every 102.4ms.
  536. CoreTiming::ScheduleEvent(msToCycles(DefaultBeaconInterval * MillisecondsPerTU),
  537. beacon_broadcast_event, 0);
  538. LOG_WARNING(Service_NWM,
  539. "An UDS network has been created, but broadcasting it is unimplemented.");
  540. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  541. rb.Push(RESULT_SUCCESS);
  542. }
  543. /**
  544. * NWM_UDS::DestroyNetwork service function.
  545. * Closes the network that we're currently hosting.
  546. * Inputs:
  547. * 0 : Command header.
  548. * Outputs:
  549. * 0 : Return header
  550. * 1 : Result of function, 0 on success, otherwise error code
  551. */
  552. static void DestroyNetwork(Interface* self) {
  553. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x08, 0, 0);
  554. // TODO(Subv): Find out what happens if this is called while
  555. // no network is being hosted.
  556. // Unschedule the beacon broadcast event.
  557. CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
  558. {
  559. std::lock_guard<std::mutex> lock(connection_status_mutex);
  560. // TODO(Subv): Check if connection_status is indeed reset after this call.
  561. connection_status = {};
  562. connection_status.status = static_cast<u8>(NetworkStatus::NotConnected);
  563. }
  564. connection_status_event->Signal();
  565. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  566. rb.Push(RESULT_SUCCESS);
  567. LOG_WARNING(Service_NWM, "called");
  568. }
  569. /**
  570. * NWM_UDS::SendTo service function.
  571. * Sends a data frame to the UDS network we're connected to.
  572. * Inputs:
  573. * 0 : Command header.
  574. * 1 : Unknown.
  575. * 2 : u16 Destination network node id.
  576. * 3 : u8 Data channel.
  577. * 4 : Buffer size >> 2
  578. * 5 : Data size
  579. * 6 : Flags
  580. * 7 : Input buffer descriptor
  581. * 8 : Input buffer address
  582. * Outputs:
  583. * 0 : Return header
  584. * 1 : Result of function, 0 on success, otherwise error code
  585. */
  586. static void SendTo(Interface* self) {
  587. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x17, 6, 2);
  588. rp.Skip(1, false);
  589. u16 dest_node_id = rp.Pop<u16>();
  590. u8 data_channel = rp.Pop<u8>();
  591. rp.Skip(1, false);
  592. u32 data_size = rp.Pop<u32>();
  593. u32 flags = rp.Pop<u32>();
  594. size_t desc_size;
  595. const VAddr input_address = rp.PopStaticBuffer(&desc_size, false);
  596. ASSERT(desc_size == data_size);
  597. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  598. u16 network_node_id;
  599. {
  600. std::lock_guard<std::mutex> lock(connection_status_mutex);
  601. if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsClient) &&
  602. connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) {
  603. rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS,
  604. ErrorSummary::InvalidState, ErrorLevel::Status));
  605. return;
  606. }
  607. if (dest_node_id == connection_status.network_node_id) {
  608. rb.Push(ResultCode(ErrorDescription::NotFound, ErrorModule::UDS,
  609. ErrorSummary::WrongArgument, ErrorLevel::Status));
  610. return;
  611. }
  612. network_node_id = connection_status.network_node_id;
  613. }
  614. // TODO(Subv): Do something with the flags.
  615. constexpr size_t MaxSize = 0x5C6;
  616. if (data_size > MaxSize) {
  617. rb.Push(ResultCode(ErrorDescription::TooLarge, ErrorModule::UDS,
  618. ErrorSummary::WrongArgument, ErrorLevel::Usage));
  619. return;
  620. }
  621. std::vector<u8> data(data_size);
  622. Memory::ReadBlock(input_address, data.data(), data.size());
  623. // TODO(Subv): Increment the sequence number after each sent packet.
  624. u16 sequence_number = 0;
  625. std::vector<u8> data_payload =
  626. GenerateDataPayload(data, data_channel, dest_node_id, network_node_id, sequence_number);
  627. // TODO(Subv): Retrieve the MAC address of the dest_node_id and our own to encrypt
  628. // and encapsulate the payload.
  629. // TODO(Subv): Send the frame.
  630. rb.Push(RESULT_SUCCESS);
  631. LOG_WARNING(Service_NWM, "(STUB) called dest_node_id=%u size=%u flags=%u channel=%u",
  632. static_cast<u32>(dest_node_id), data_size, flags, static_cast<u32>(data_channel));
  633. }
  634. /**
  635. * NWM_UDS::GetChannel service function.
  636. * Returns the WiFi channel in which the network we're connected to is transmitting.
  637. * Inputs:
  638. * 0 : Command header.
  639. * Outputs:
  640. * 0 : Return header
  641. * 1 : Result of function, 0 on success, otherwise error code
  642. * 2 : Channel of the current WiFi network connection.
  643. */
  644. static void GetChannel(Interface* self) {
  645. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 0, 0);
  646. IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
  647. std::lock_guard<std::mutex> lock(connection_status_mutex);
  648. bool is_connected = connection_status.status != static_cast<u32>(NetworkStatus::NotConnected);
  649. u8 channel = is_connected ? network_channel : 0;
  650. rb.Push(RESULT_SUCCESS);
  651. rb.Push(channel);
  652. LOG_DEBUG(Service_NWM, "called");
  653. }
  654. /**
  655. * NWM_UDS::SetApplicationData service function.
  656. * Updates the application data that is being broadcast in the beacon frames
  657. * for the network that we're hosting.
  658. * Inputs:
  659. * 1 : Data size.
  660. * 3 : VAddr of the data.
  661. * Outputs:
  662. * 0 : Return header
  663. * 1 : Result of function, 0 on success, otherwise error code
  664. * 2 : Channel of the current WiFi network connection.
  665. */
  666. static void SetApplicationData(Interface* self) {
  667. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 1, 2);
  668. u32 size = rp.Pop<u32>();
  669. size_t desc_size;
  670. const VAddr address = rp.PopStaticBuffer(&desc_size, false);
  671. ASSERT(desc_size == size);
  672. LOG_DEBUG(Service_NWM, "called");
  673. IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
  674. if (size > ApplicationDataSize) {
  675. rb.Push(ResultCode(ErrorDescription::TooLarge, ErrorModule::UDS,
  676. ErrorSummary::WrongArgument, ErrorLevel::Usage));
  677. return;
  678. }
  679. network_info.application_data_size = size;
  680. Memory::ReadBlock(address, network_info.application_data.data(), size);
  681. rb.Push(RESULT_SUCCESS);
  682. }
  683. /**
  684. * NWM_UDS::DecryptBeaconData service function.
  685. * Decrypts the encrypted data tags contained in the 802.11 beacons.
  686. * Inputs:
  687. * 1 : Input network struct buffer descriptor.
  688. * 2 : Input network struct buffer ptr.
  689. * 3 : Input tag0 encrypted buffer descriptor.
  690. * 4 : Input tag0 encrypted buffer ptr.
  691. * 5 : Input tag1 encrypted buffer descriptor.
  692. * 6 : Input tag1 encrypted buffer ptr.
  693. * 64 : Output buffer descriptor.
  694. * 65 : Output buffer ptr.
  695. * Outputs:
  696. * 0 : Return header
  697. * 1 : Result of function, 0 on success, otherwise error code
  698. */
  699. static void DecryptBeaconData(Interface* self) {
  700. IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1F, 0, 6);
  701. size_t desc_size;
  702. const VAddr network_struct_addr = rp.PopStaticBuffer(&desc_size);
  703. ASSERT(desc_size == sizeof(NetworkInfo));
  704. size_t data0_size;
  705. const VAddr encrypted_data0_addr = rp.PopStaticBuffer(&data0_size);
  706. size_t data1_size;
  707. const VAddr encrypted_data1_addr = rp.PopStaticBuffer(&data1_size);
  708. size_t output_buffer_size;
  709. const VAddr output_buffer_addr = rp.PeekStaticBuffer(0, &output_buffer_size);
  710. // This size is hardcoded in the 3DS UDS code.
  711. ASSERT(output_buffer_size == sizeof(NodeInfo) * UDSMaxNodes);
  712. LOG_WARNING(Service_NWM, "called in0=%08X in1=%08X out=%08X", encrypted_data0_addr,
  713. encrypted_data1_addr, output_buffer_addr);
  714. NetworkInfo net_info;
  715. Memory::ReadBlock(network_struct_addr, &net_info, sizeof(net_info));
  716. // Read the encrypted data.
  717. // The first 4 bytes should be the OUI and the OUI Type of the tags.
  718. std::array<u8, 3> oui;
  719. Memory::ReadBlock(encrypted_data0_addr, oui.data(), oui.size());
  720. ASSERT_MSG(oui == NintendoOUI, "Unexpected OUI");
  721. Memory::ReadBlock(encrypted_data1_addr, oui.data(), oui.size());
  722. ASSERT_MSG(oui == NintendoOUI, "Unexpected OUI");
  723. ASSERT_MSG(Memory::Read8(encrypted_data0_addr + 3) ==
  724. static_cast<u8>(NintendoTagId::EncryptedData0),
  725. "Unexpected tag id");
  726. ASSERT_MSG(Memory::Read8(encrypted_data1_addr + 3) ==
  727. static_cast<u8>(NintendoTagId::EncryptedData1),
  728. "Unexpected tag id");
  729. std::vector<u8> beacon_data(data0_size + data1_size);
  730. Memory::ReadBlock(encrypted_data0_addr + 4, beacon_data.data(), data0_size);
  731. Memory::ReadBlock(encrypted_data1_addr + 4, beacon_data.data() + data0_size, data1_size);
  732. // Decrypt the data
  733. DecryptBeaconData(net_info, beacon_data);
  734. // The beacon data header contains the MD5 hash of the data.
  735. BeaconData beacon_header;
  736. std::memcpy(&beacon_header, beacon_data.data(), sizeof(beacon_header));
  737. // TODO(Subv): Verify the MD5 hash of the data and return 0xE1211005 if invalid.
  738. u8 num_nodes = net_info.max_nodes;
  739. std::vector<NodeInfo> nodes;
  740. for (int i = 0; i < num_nodes; ++i) {
  741. BeaconNodeInfo info;
  742. std::memcpy(&info, beacon_data.data() + sizeof(beacon_header) + i * sizeof(info),
  743. sizeof(info));
  744. // Deserialize the node information.
  745. NodeInfo node{};
  746. node.friend_code_seed = info.friend_code_seed;
  747. node.network_node_id = info.network_node_id;
  748. for (int i = 0; i < info.username.size(); ++i)
  749. node.username[i] = info.username[i];
  750. nodes.push_back(node);
  751. }
  752. Memory::ZeroBlock(output_buffer_addr, sizeof(NodeInfo) * UDSMaxNodes);
  753. Memory::WriteBlock(output_buffer_addr, nodes.data(), sizeof(NodeInfo) * nodes.size());
  754. IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
  755. rb.PushStaticBuffer(output_buffer_addr, output_buffer_size, 0);
  756. rb.Push(RESULT_SUCCESS);
  757. }
  758. // Sends a 802.11 beacon frame with information about the current network.
  759. static void BeaconBroadcastCallback(u64 userdata, int cycles_late) {
  760. // Don't do anything if we're not actually hosting a network
  761. if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost))
  762. return;
  763. std::vector<u8> frame = GenerateBeaconFrame(network_info, node_info);
  764. using Network::WifiPacket;
  765. WifiPacket packet;
  766. packet.type = WifiPacket::PacketType::Beacon;
  767. packet.data = std::move(frame);
  768. packet.destination_address = Network::BroadcastMac;
  769. packet.channel = network_channel;
  770. SendPacket(packet);
  771. // Start broadcasting the network, send a beacon frame every 102.4ms.
  772. CoreTiming::ScheduleEvent(msToCycles(DefaultBeaconInterval * MillisecondsPerTU) - cycles_late,
  773. beacon_broadcast_event, 0);
  774. }
  775. /*
  776. * Called when a client connects to an UDS network we're hosting,
  777. * updates the connection status and signals the update event.
  778. * @param network_node_id Network Node Id of the connecting client.
  779. */
  780. void OnClientConnected(u16 network_node_id) {
  781. std::lock_guard<std::mutex> lock(connection_status_mutex);
  782. ASSERT_MSG(connection_status.status == static_cast<u32>(NetworkStatus::ConnectedAsHost),
  783. "Can not accept clients if we're not hosting a network");
  784. ASSERT_MSG(connection_status.total_nodes < connection_status.max_nodes,
  785. "Can not accept connections on a full network");
  786. u32 node_id = GetNextAvailableNodeId();
  787. connection_status.node_bitmask |= 1 << node_id;
  788. connection_status.changed_nodes |= 1 << node_id;
  789. connection_status.nodes[node_id] = network_node_id;
  790. connection_status.total_nodes++;
  791. connection_status_event->Signal();
  792. }
  793. const Interface::FunctionInfo FunctionTable[] = {
  794. {0x000102C2, nullptr, "Initialize (deprecated)"},
  795. {0x00020000, nullptr, "Scrap"},
  796. {0x00030000, Shutdown, "Shutdown"},
  797. {0x00040402, nullptr, "CreateNetwork (deprecated)"},
  798. {0x00050040, nullptr, "EjectClient"},
  799. {0x00060000, nullptr, "EjectSpectator"},
  800. {0x00070080, nullptr, "UpdateNetworkAttribute"},
  801. {0x00080000, DestroyNetwork, "DestroyNetwork"},
  802. {0x00090442, nullptr, "ConnectNetwork (deprecated)"},
  803. {0x000A0000, nullptr, "DisconnectNetwork"},
  804. {0x000B0000, GetConnectionStatus, "GetConnectionStatus"},
  805. {0x000D0040, nullptr, "GetNodeInformation"},
  806. {0x000E0006, nullptr, "DecryptBeaconData (deprecated)"},
  807. {0x000F0404, RecvBeaconBroadcastData, "RecvBeaconBroadcastData"},
  808. {0x00100042, SetApplicationData, "SetApplicationData"},
  809. {0x00110040, nullptr, "GetApplicationData"},
  810. {0x00120100, Bind, "Bind"},
  811. {0x00130040, nullptr, "Unbind"},
  812. {0x001400C0, nullptr, "PullPacket"},
  813. {0x00150080, nullptr, "SetMaxSendDelay"},
  814. {0x00170182, SendTo, "SendTo"},
  815. {0x001A0000, GetChannel, "GetChannel"},
  816. {0x001B0302, InitializeWithVersion, "InitializeWithVersion"},
  817. {0x001D0044, BeginHostingNetwork, "BeginHostingNetwork"},
  818. {0x001E0084, nullptr, "ConnectToNetwork"},
  819. {0x001F0006, DecryptBeaconData, "DecryptBeaconData"},
  820. {0x00200040, nullptr, "Flush"},
  821. {0x00210080, nullptr, "SetProbeResponseParam"},
  822. {0x00220402, nullptr, "ScanOnConnection"},
  823. };
  824. NWM_UDS::NWM_UDS() {
  825. connection_status_event =
  826. Kernel::Event::Create(Kernel::ResetType::OneShot, "NWM::connection_status_event");
  827. Register(FunctionTable);
  828. beacon_broadcast_event =
  829. CoreTiming::RegisterEvent("UDS::BeaconBroadcastCallback", BeaconBroadcastCallback);
  830. }
  831. NWM_UDS::~NWM_UDS() {
  832. network_info = {};
  833. bind_node_events.clear();
  834. connection_status_event = nullptr;
  835. recv_buffer_memory = nullptr;
  836. {
  837. std::lock_guard<std::mutex> lock(connection_status_mutex);
  838. connection_status = {};
  839. connection_status.status = static_cast<u32>(NetworkStatus::NotConnected);
  840. }
  841. CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);
  842. }
  843. } // namespace NWM
  844. } // namespace Service