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
|
using LibHac.Ns;
using Ryujinx.Common;
using Ryujinx.Common.Configuration.Multiplayer;
using Ryujinx.Common.Logging;
using Ryujinx.Common.Memory;
using Ryujinx.Common.Utilities;
using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.Ipc;
using Ryujinx.HLE.HOS.Kernel.Threading;
using Ryujinx.HLE.HOS.Services.Ldn.Types;
using Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator.RyuLdn;
using Ryujinx.Horizon.Common;
using Ryujinx.Memory;
using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
namespace Ryujinx.HLE.HOS.Services.Ldn.UserServiceCreator
{
class IUserLocalCommunicationService : IpcService, IDisposable
{
public INetworkClient NetworkClient { get; private set; }
private const int NifmRequestID = 90;
private const string DefaultIPAddress = "127.0.0.1";
private const string DefaultSubnetMask = "255.255.255.0";
private const bool IsDevelopment = false;
private readonly KEvent _stateChangeEvent;
private NetworkState _state;
private DisconnectReason _disconnectReason;
private ResultCode _nifmResultCode;
private AccessPoint _accessPoint;
private Station _station;
public IUserLocalCommunicationService(ServiceCtx context)
{
_stateChangeEvent = new KEvent(context.Device.System.KernelContext);
_state = NetworkState.None;
_disconnectReason = DisconnectReason.None;
}
private ushort CheckDevelopmentChannel(ushort channel)
{
return (ushort)(!IsDevelopment ? 0 : channel);
}
private SecurityMode CheckDevelopmentSecurityMode(SecurityMode securityMode)
{
return !IsDevelopment ? SecurityMode.Retail : securityMode;
}
private bool CheckLocalCommunicationIdPermission(ServiceCtx context, ulong localCommunicationIdChecked)
{
// TODO: Call nn::arp::GetApplicationControlProperty here when implemented.
ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties;
foreach (var localCommunicationId in controlProperty.LocalCommunicationId.ItemsRo)
{
if (localCommunicationId == localCommunicationIdChecked)
{
return true;
}
}
return false;
}
[CommandCmif(0)]
// GetState() -> s32 state
public ResultCode GetState(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
context.ResponseData.Write((int)NetworkState.Error);
return ResultCode.Success;
}
// NOTE: Returns ResultCode.InvalidArgument if _state is null, doesn't occur in our case.
context.ResponseData.Write((int)_state);
return ResultCode.Success;
}
public void SetState()
{
_stateChangeEvent.WritableEvent.Signal();
}
public void SetState(NetworkState state)
{
_state = state;
SetState();
}
[CommandCmif(1)]
// GetNetworkInfo() -> buffer<network_info<0x480>, 0x1a>
public ResultCode GetNetworkInfo(ServiceCtx context)
{
ulong bufferPosition = context.Request.RecvListBuff[0].Position;
MemoryHelper.FillWithZeros(context.Memory, bufferPosition, 0x480);
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
ResultCode resultCode = GetNetworkInfoImpl(out NetworkInfo networkInfo);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
ulong infoSize = MemoryHelper.Write(context.Memory, bufferPosition, networkInfo);
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize(infoSize);
return ResultCode.Success;
}
private ResultCode GetNetworkInfoImpl(out NetworkInfo networkInfo)
{
if (_state == NetworkState.StationConnected)
{
networkInfo = _station.NetworkInfo;
}
else if (_state == NetworkState.AccessPointCreated)
{
networkInfo = _accessPoint.NetworkInfo;
}
else
{
networkInfo = new NetworkInfo();
return ResultCode.InvalidState;
}
return ResultCode.Success;
}
private NodeLatestUpdate[] GetNodeLatestUpdateImpl(int count)
{
if (_state == NetworkState.StationConnected)
{
return _station.LatestUpdates.ConsumeLatestUpdate(count);
}
else if (_state == NetworkState.AccessPointCreated)
{
return _accessPoint.LatestUpdates.ConsumeLatestUpdate(count);
}
else
{
return Array.Empty<NodeLatestUpdate>();
}
}
[CommandCmif(2)]
// GetIpv4Address() -> (u32 ip_address, u32 subnet_mask)
public ResultCode GetIpv4Address(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
// NOTE: Return ResultCode.InvalidArgument if ip_address and subnet_mask are null, doesn't occur in our case.
if (_state == NetworkState.AccessPointCreated || _state == NetworkState.StationConnected)
{
(_, UnicastIPAddressInformation unicastAddress) = NetworkHelpers.GetLocalInterface(context.Device.Configuration.MultiplayerLanInterfaceId);
if (unicastAddress == null)
{
context.ResponseData.Write(NetworkHelpers.ConvertIpv4Address(DefaultIPAddress));
context.ResponseData.Write(NetworkHelpers.ConvertIpv4Address(DefaultSubnetMask));
}
else
{
Logger.Info?.Print(LogClass.ServiceLdn, $"Console's LDN IP is \"{unicastAddress.Address}\".");
context.ResponseData.Write(NetworkHelpers.ConvertIpv4Address(unicastAddress.Address));
context.ResponseData.Write(NetworkHelpers.ConvertIpv4Address(unicastAddress.IPv4Mask));
}
}
else
{
return ResultCode.InvalidArgument;
}
return ResultCode.Success;
}
[CommandCmif(3)]
// GetDisconnectReason() -> u16 disconnect_reason
public ResultCode GetDisconnectReason(ServiceCtx context)
{
// NOTE: Returns ResultCode.InvalidArgument if _disconnectReason is null, doesn't occur in our case.
context.ResponseData.Write((short)_disconnectReason);
return ResultCode.Success;
}
public void SetDisconnectReason(DisconnectReason reason)
{
if (_state != NetworkState.Initialized)
{
_disconnectReason = reason;
SetState(NetworkState.Initialized);
}
}
[CommandCmif(4)]
// GetSecurityParameter() -> bytes<0x20, 1> security_parameter
public ResultCode GetSecurityParameter(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
ResultCode resultCode = GetNetworkInfoImpl(out NetworkInfo networkInfo);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
SecurityParameter securityParameter = new()
{
Data = new Array16<byte>(),
SessionId = networkInfo.NetworkId.SessionId,
};
context.ResponseData.WriteStruct(securityParameter);
return ResultCode.Success;
}
[CommandCmif(5)]
// GetNetworkConfig() -> bytes<0x20, 8> network_config
public ResultCode GetNetworkConfig(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
ResultCode resultCode = GetNetworkInfoImpl(out NetworkInfo networkInfo);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
NetworkConfig networkConfig = new()
{
IntentId = networkInfo.NetworkId.IntentId,
Channel = networkInfo.Common.Channel,
NodeCountMax = networkInfo.Ldn.NodeCountMax,
LocalCommunicationVersion = networkInfo.Ldn.Nodes[0].LocalCommunicationVersion,
Reserved2 = new Array10<byte>(),
};
context.ResponseData.WriteStruct(networkConfig);
return ResultCode.Success;
}
[CommandCmif(100)]
// AttachStateChangeEvent() -> handle<copy>
public ResultCode AttachStateChangeEvent(ServiceCtx context)
{
if (context.Process.HandleTable.GenerateHandle(_stateChangeEvent.ReadableEvent, out int stateChangeEventHandle) != Result.Success)
{
throw new InvalidOperationException("Out of handles!");
}
context.Response.HandleDesc = IpcHandleDesc.MakeCopy(stateChangeEventHandle);
// Returns ResultCode.InvalidArgument if handle is null, doesn't occur in our case since we already throw an Exception.
return ResultCode.Success;
}
[CommandCmif(101)]
// GetNetworkInfoLatestUpdate() -> (buffer<network_info<0x480>, 0x1a>, buffer<node_latest_update, 0xa>)
public ResultCode GetNetworkInfoLatestUpdate(ServiceCtx context)
{
ulong bufferPosition = context.Request.RecvListBuff[0].Position;
MemoryHelper.FillWithZeros(context.Memory, bufferPosition, 0x480);
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
ResultCode resultCode = GetNetworkInfoImpl(out NetworkInfo networkInfo);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
ulong outputPosition = context.Request.RecvListBuff[0].Position;
ulong outputSize = context.Request.RecvListBuff[0].Size;
ulong latestUpdateSize = (ulong)Marshal.SizeOf<NodeLatestUpdate>();
int count = (int)(outputSize / latestUpdateSize);
NodeLatestUpdate[] latestUpdate = GetNodeLatestUpdateImpl(count);
MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize);
foreach (NodeLatestUpdate node in latestUpdate)
{
MemoryHelper.Write(context.Memory, outputPosition, node);
outputPosition += latestUpdateSize;
}
ulong infoSize = MemoryHelper.Write(context.Memory, bufferPosition, networkInfo);
context.Response.PtrBuff[0] = context.Response.PtrBuff[0].WithSize(infoSize);
return ResultCode.Success;
}
[CommandCmif(102)]
// Scan(u16 channel, bytes<0x60, 8> scan_filter) -> (u16 count, buffer<network_info, 0x22>)
public ResultCode Scan(ServiceCtx context)
{
return ScanImpl(context);
}
[CommandCmif(103)]
// ScanPrivate(u16 channel, bytes<0x60, 8> scan_filter) -> (u16 count, buffer<network_info, 0x22>)
public ResultCode ScanPrivate(ServiceCtx context)
{
return ScanImpl(context, true);
}
private ResultCode ScanImpl(ServiceCtx context, bool isPrivate = false)
{
ushort channel = (ushort)context.RequestData.ReadUInt64();
ScanFilter scanFilter = context.RequestData.ReadStruct<ScanFilter>();
(ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x22(0);
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (!isPrivate)
{
channel = CheckDevelopmentChannel(channel);
}
ResultCode resultCode = ResultCode.InvalidArgument;
if (bufferSize != 0)
{
if (bufferPosition != 0)
{
ScanFilterFlag scanFilterFlag = scanFilter.Flag;
if (!scanFilterFlag.HasFlag(ScanFilterFlag.NetworkType) || scanFilter.NetworkType <= NetworkType.All)
{
if (scanFilterFlag.HasFlag(ScanFilterFlag.Ssid))
{
if (scanFilter.Ssid.Length <= 31)
{
return resultCode;
}
}
if (!scanFilterFlag.HasFlag(ScanFilterFlag.MacAddress))
{
if (scanFilterFlag > ScanFilterFlag.All)
{
return resultCode;
}
if (_state - 3 >= NetworkState.AccessPoint)
{
resultCode = ResultCode.InvalidState;
}
else
{
if (scanFilter.NetworkId.IntentId.LocalCommunicationId == -1)
{
// TODO: Call nn::arp::GetApplicationControlProperty here when implemented.
ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties;
scanFilter.NetworkId.IntentId.LocalCommunicationId = (long)controlProperty.LocalCommunicationId[0];
}
resultCode = ScanInternal(context.Memory, channel, scanFilter, bufferPosition, bufferSize, out ulong counter);
context.ResponseData.Write(counter);
}
}
else
{
throw new NotSupportedException();
}
}
}
}
return resultCode;
}
private ResultCode ScanInternal(IVirtualMemoryManager memory, ushort channel, ScanFilter scanFilter, ulong bufferPosition, ulong bufferSize, out ulong counter)
{
ulong networkInfoSize = (ulong)Marshal.SizeOf(typeof(NetworkInfo));
ulong maxGames = bufferSize / networkInfoSize;
MemoryHelper.FillWithZeros(memory, bufferPosition, (int)bufferSize);
NetworkInfo[] availableGames = NetworkClient.Scan(channel, scanFilter);
counter = 0;
foreach (NetworkInfo networkInfo in availableGames)
{
MemoryHelper.Write(memory, bufferPosition + (networkInfoSize * counter), networkInfo);
if (++counter >= maxGames)
{
break;
}
}
return ResultCode.Success;
}
[CommandCmif(104)] // 5.0.0+
// SetWirelessControllerRestriction(u32 wireless_controller_restriction)
public ResultCode SetWirelessControllerRestriction(ServiceCtx context)
{
// NOTE: Return ResultCode.InvalidArgument if an internal IPAddress is null, doesn't occur in our case.
uint wirelessControllerRestriction = context.RequestData.ReadUInt32();
if (wirelessControllerRestriction > 1)
{
return ResultCode.InvalidArgument;
}
if (_state != NetworkState.Initialized)
{
return ResultCode.InvalidState;
}
// NOTE: WirelessControllerRestriction value is used for the btm service in SetWlanMode call.
// Since we use our own implementation we can do nothing here.
return ResultCode.Success;
}
[CommandCmif(200)]
// OpenAccessPoint()
public ResultCode OpenAccessPoint(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (_state != NetworkState.Initialized)
{
return ResultCode.InvalidState;
}
CloseStation();
SetState(NetworkState.AccessPoint);
_accessPoint = new AccessPoint(this);
// NOTE: Calls nifm service and return related result codes.
// Since we use our own implementation we can return ResultCode.Success.
return ResultCode.Success;
}
[CommandCmif(201)]
// CloseAccessPoint()
public ResultCode CloseAccessPoint(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
{
DestroyNetworkImpl(DisconnectReason.DestroyedByUser);
}
else
{
return ResultCode.InvalidState;
}
SetState(NetworkState.Initialized);
return ResultCode.Success;
}
private void CloseAccessPoint()
{
_accessPoint?.Dispose();
_accessPoint = null;
}
[CommandCmif(202)]
// CreateNetwork(bytes<0x44, 2> security_config, bytes<0x30, 1> user_config, bytes<0x20, 8> network_config)
public ResultCode CreateNetwork(ServiceCtx context)
{
return CreateNetworkImpl(context);
}
[CommandCmif(203)]
// CreateNetworkPrivate(bytes<0x44, 2> security_config, bytes<0x20, 1> security_parameter, bytes<0x30, 1>, bytes<0x20, 8> network_config, buffer<unknown, 9> address_entry, int count)
public ResultCode CreateNetworkPrivate(ServiceCtx context)
{
return CreateNetworkImpl(context, true);
}
public ResultCode CreateNetworkImpl(ServiceCtx context, bool isPrivate = false)
{
SecurityConfig securityConfig = context.RequestData.ReadStruct<SecurityConfig>();
SecurityParameter securityParameter = isPrivate ? context.RequestData.ReadStruct<SecurityParameter>() : new SecurityParameter();
UserConfig userConfig = context.RequestData.ReadStruct<UserConfig>();
context.RequestData.BaseStream.Seek(4, SeekOrigin.Current); // Alignment?
NetworkConfig networkConfig = context.RequestData.ReadStruct<NetworkConfig>();
if (networkConfig.IntentId.LocalCommunicationId == -1)
{
// TODO: Call nn::arp::GetApplicationControlProperty here when implemented.
ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties;
networkConfig.IntentId.LocalCommunicationId = (long)controlProperty.LocalCommunicationId[0];
}
bool isLocalCommunicationIdValid = CheckLocalCommunicationIdPermission(context, (ulong)networkConfig.IntentId.LocalCommunicationId);
if (!isLocalCommunicationIdValid)
{
return ResultCode.InvalidObject;
}
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
networkConfig.Channel = CheckDevelopmentChannel(networkConfig.Channel);
securityConfig.SecurityMode = CheckDevelopmentSecurityMode(securityConfig.SecurityMode);
if (networkConfig.NodeCountMax <= 8)
{
if ((((ulong)networkConfig.LocalCommunicationVersion) & 0x80000000) == 0)
{
if (securityConfig.SecurityMode <= SecurityMode.Retail)
{
if (securityConfig.Passphrase.Length <= 0x40)
{
if (_state == NetworkState.AccessPoint)
{
if (isPrivate)
{
ulong bufferPosition = context.Request.PtrBuff[0].Position;
ulong bufferSize = context.Request.PtrBuff[0].Size;
byte[] addressListBytes = new byte[bufferSize];
context.Memory.Read(bufferPosition, addressListBytes);
AddressList addressList = MemoryMarshal.Cast<byte, AddressList>(addressListBytes)[0];
_accessPoint.CreateNetworkPrivate(securityConfig, securityParameter, userConfig, networkConfig, addressList);
}
else
{
_accessPoint.CreateNetwork(securityConfig, userConfig, networkConfig);
}
return ResultCode.Success;
}
else
{
return ResultCode.InvalidState;
}
}
}
}
}
return ResultCode.InvalidArgument;
}
[CommandCmif(204)]
// DestroyNetwork()
public ResultCode DestroyNetwork(ServiceCtx context)
{
return DestroyNetworkImpl(DisconnectReason.DestroyedByUser);
}
private ResultCode DestroyNetworkImpl(DisconnectReason disconnectReason)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (disconnectReason - 3 <= DisconnectReason.DisconnectedByUser)
{
if (_state == NetworkState.AccessPointCreated)
{
CloseAccessPoint();
SetState(NetworkState.AccessPoint);
return ResultCode.Success;
}
CloseAccessPoint();
return ResultCode.InvalidState;
}
return ResultCode.InvalidArgument;
}
[CommandCmif(205)]
// Reject(u32 node_id)
public ResultCode Reject(ServiceCtx context)
{
uint nodeId = context.RequestData.ReadUInt32();
return RejectImpl(DisconnectReason.Rejected, nodeId);
}
private ResultCode RejectImpl(DisconnectReason disconnectReason, uint nodeId)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (_state != NetworkState.AccessPointCreated)
{
return ResultCode.InvalidState; // Must be network host to reject nodes.
}
return NetworkClient.Reject(disconnectReason, nodeId);
}
[CommandCmif(206)]
// SetAdvertiseData(buffer<advertise_data, 0x21>)
public ResultCode SetAdvertiseData(ServiceCtx context)
{
(ulong bufferPosition, ulong bufferSize) = context.Request.GetBufferType0x21(0);
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (bufferSize == 0 || bufferSize > 0x180)
{
return ResultCode.InvalidArgument;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
{
byte[] advertiseData = new byte[bufferSize];
context.Memory.Read(bufferPosition, advertiseData);
return _accessPoint.SetAdvertiseData(advertiseData);
}
else
{
return ResultCode.InvalidState;
}
}
[CommandCmif(207)]
// SetStationAcceptPolicy(u8 accept_policy)
public ResultCode SetStationAcceptPolicy(ServiceCtx context)
{
AcceptPolicy acceptPolicy = (AcceptPolicy)context.RequestData.ReadByte();
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (acceptPolicy > AcceptPolicy.WhiteList)
{
return ResultCode.InvalidArgument;
}
if (_state == NetworkState.AccessPoint || _state == NetworkState.AccessPointCreated)
{
return _accessPoint.SetStationAcceptPolicy(acceptPolicy);
}
else
{
return ResultCode.InvalidState;
}
}
[CommandCmif(208)]
// AddAcceptFilterEntry(bytes<6, 1> mac_address)
public ResultCode AddAcceptFilterEntry(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
// TODO
return ResultCode.Success;
}
[CommandCmif(209)]
// ClearAcceptFilter()
public ResultCode ClearAcceptFilter(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
// TODO
return ResultCode.Success;
}
[CommandCmif(300)]
// OpenStation()
public ResultCode OpenStation(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (_state != NetworkState.Initialized)
{
return ResultCode.InvalidState;
}
CloseAccessPoint();
SetState(NetworkState.Station);
_station?.Dispose();
_station = new Station(this);
// NOTE: Calls nifm service and returns related result codes.
// Since we use our own implementation we can return ResultCode.Success.
return ResultCode.Success;
}
[CommandCmif(301)]
// CloseStation()
public ResultCode CloseStation(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (_state == NetworkState.Station || _state == NetworkState.StationConnected)
{
DisconnectImpl(DisconnectReason.DisconnectedByUser);
}
else
{
return ResultCode.InvalidState;
}
SetState(NetworkState.Initialized);
return ResultCode.Success;
}
private void CloseStation()
{
_station?.Dispose();
_station = null;
}
[CommandCmif(302)]
// Connect(bytes<0x44, 2> security_config, bytes<0x30, 1> user_config, u32 local_communication_version, u32 option_unknown, buffer<network_info<0x480>, 0x19>)
public ResultCode Connect(ServiceCtx context)
{
return ConnectImpl(context);
}
[CommandCmif(303)]
// ConnectPrivate(bytes<0x44, 2> security_config, bytes<0x20, 1> security_parameter, bytes<0x30, 1> user_config, u32 local_communication_version, u32 option_unknown, bytes<0x20, 8> network_config)
public ResultCode ConnectPrivate(ServiceCtx context)
{
return ConnectImpl(context, true);
}
private ResultCode ConnectImpl(ServiceCtx context, bool isPrivate = false)
{
SecurityConfig securityConfig = context.RequestData.ReadStruct<SecurityConfig>();
SecurityParameter securityParameter = isPrivate ? context.RequestData.ReadStruct<SecurityParameter>() : new SecurityParameter();
UserConfig userConfig = context.RequestData.ReadStruct<UserConfig>();
uint localCommunicationVersion = context.RequestData.ReadUInt32();
uint optionUnknown = context.RequestData.ReadUInt32();
NetworkConfig networkConfig = new();
NetworkInfo networkInfo = new();
if (isPrivate)
{
context.RequestData.ReadUInt32(); // Padding.
networkConfig = context.RequestData.ReadStruct<NetworkConfig>();
}
else
{
ulong bufferPosition = context.Request.PtrBuff[0].Position;
ulong bufferSize = context.Request.PtrBuff[0].Size;
byte[] networkInfoBytes = new byte[bufferSize];
context.Memory.Read(bufferPosition, networkInfoBytes);
networkInfo = MemoryMarshal.Cast<byte, NetworkInfo>(networkInfoBytes)[0];
}
if (networkInfo.NetworkId.IntentId.LocalCommunicationId == -1)
{
// TODO: Call nn::arp::GetApplicationControlProperty here when implemented.
ApplicationControlProperty controlProperty = context.Device.Processes.ActiveApplication.ApplicationControlProperties;
networkInfo.NetworkId.IntentId.LocalCommunicationId = (long)controlProperty.LocalCommunicationId[0];
}
bool isLocalCommunicationIdValid = CheckLocalCommunicationIdPermission(context, (ulong)networkInfo.NetworkId.IntentId.LocalCommunicationId);
if (!isLocalCommunicationIdValid)
{
return ResultCode.InvalidObject;
}
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
securityConfig.SecurityMode = CheckDevelopmentSecurityMode(securityConfig.SecurityMode);
ResultCode resultCode = ResultCode.InvalidArgument;
if (securityConfig.SecurityMode - 1 <= SecurityMode.Debug)
{
if (optionUnknown <= 1 && (localCommunicationVersion >> 15) == 0 && securityConfig.PassphraseSize <= 64)
{
resultCode = ResultCode.VersionTooLow;
if (localCommunicationVersion >= 0)
{
resultCode = ResultCode.VersionTooHigh;
if (localCommunicationVersion <= short.MaxValue)
{
if (_state != NetworkState.Station)
{
resultCode = ResultCode.InvalidState;
}
else
{
if (isPrivate)
{
resultCode = _station.ConnectPrivate(securityConfig, securityParameter, userConfig, localCommunicationVersion, optionUnknown, networkConfig);
}
else
{
resultCode = _station.Connect(securityConfig, userConfig, localCommunicationVersion, optionUnknown, networkInfo);
}
}
}
}
}
}
return resultCode;
}
[CommandCmif(304)]
// Disconnect()
public ResultCode Disconnect(ServiceCtx context)
{
return DisconnectImpl(DisconnectReason.DisconnectedByUser);
}
private ResultCode DisconnectImpl(DisconnectReason disconnectReason)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
if (disconnectReason <= DisconnectReason.DisconnectedBySystem)
{
if (_state == NetworkState.StationConnected)
{
SetState(NetworkState.Station);
CloseStation();
_disconnectReason = disconnectReason;
return ResultCode.Success;
}
CloseStation();
return ResultCode.InvalidState;
}
return ResultCode.InvalidArgument;
}
[CommandCmif(400)]
// InitializeOld(pid)
public ResultCode InitializeOld(ServiceCtx context)
{
return InitializeImpl(context, context.Process.Pid, NifmRequestID);
}
[CommandCmif(401)]
// Finalize()
public ResultCode Finalize(ServiceCtx context)
{
if (_nifmResultCode != ResultCode.Success)
{
return _nifmResultCode;
}
// NOTE: Use true when its called in nn::ldn::detail::ISystemLocalCommunicationService
ResultCode resultCode = FinalizeImpl(false);
if (resultCode == ResultCode.Success)
{
SetDisconnectReason(DisconnectReason.None);
}
return resultCode;
}
private ResultCode FinalizeImpl(bool isCausedBySystem)
{
DisconnectReason disconnectReason;
switch (_state)
{
case NetworkState.None:
return ResultCode.Success;
case NetworkState.AccessPoint:
{
CloseAccessPoint();
break;
}
case NetworkState.AccessPointCreated:
{
if (isCausedBySystem)
{
disconnectReason = DisconnectReason.DestroyedBySystem;
}
else
{
disconnectReason = DisconnectReason.DestroyedByUser;
}
DestroyNetworkImpl(disconnectReason);
break;
}
case NetworkState.Station:
{
CloseStation();
break;
}
case NetworkState.StationConnected:
{
if (isCausedBySystem)
{
disconnectReason = DisconnectReason.DisconnectedBySystem;
}
else
{
disconnectReason = DisconnectReason.DisconnectedByUser;
}
DisconnectImpl(disconnectReason);
break;
}
}
SetState(NetworkState.None);
NetworkClient?.DisconnectAndStop();
NetworkClient = null;
return ResultCode.Success;
}
[CommandCmif(402)] // 7.0.0+
// Initialize(u64 ip_addresses, pid)
public ResultCode Initialize(ServiceCtx context)
{
_ = new IPAddress(context.RequestData.ReadUInt32());
_ = new IPAddress(context.RequestData.ReadUInt32());
// NOTE: It seems the guest can get ip_address and subnet_mask from nifm service and pass it through the initialize.
// This calls InitializeImpl() twice: The first time with NIFM_REQUEST_ID, and if it fails, a second time with nifm_request_id = 1.
return InitializeImpl(context, context.Process.Pid, NifmRequestID);
}
public ResultCode InitializeImpl(ServiceCtx context, ulong pid, int nifmRequestId)
{
ResultCode resultCode = ResultCode.InvalidArgument;
if (nifmRequestId <= 255)
{
if (_state != NetworkState.Initialized)
{
// NOTE: Service calls nn::ldn::detail::NetworkInterfaceManager::NetworkInterfaceMonitor::Initialize() with nifmRequestId as argument,
// then it stores the result code of it in a global variable. Since we use our own implementation, we can just check the connection
// and return related error codes.
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
MultiplayerMode mode = context.Device.Configuration.MultiplayerMode;
switch (mode)
{
case MultiplayerMode.Disabled:
NetworkClient = new DisabledLdnClient();
break;
}
// TODO: Call nn::arp::GetApplicationLaunchProperty here when implemented.
NetworkClient.SetGameVersion(context.Device.Processes.ActiveApplication.ApplicationControlProperties.DisplayVersion.Items.ToArray());
resultCode = ResultCode.Success;
_nifmResultCode = resultCode;
SetState(NetworkState.Initialized);
}
else
{
// NOTE: Service returns differents ResultCode here related to the nifm ResultCode.
resultCode = ResultCode.DeviceDisabled;
_nifmResultCode = resultCode;
}
}
}
return resultCode;
}
public void Dispose()
{
if (NetworkClient != null)
{
_station?.Dispose();
_accessPoint?.Dispose();
NetworkClient.DisconnectAndStop();
}
NetworkClient = null;
}
}
}
|