forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetSocket.cs
More file actions
671 lines (613 loc) · 24.2 KB
/
NetSocket.cs
File metadata and controls
671 lines (613 loc) · 24.2 KB
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
#if UNITY_IOS && !UNITY_EDITOR
using UnityEngine;
#endif
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace LiteNetLib
{
#if UNITY_IOS && !UNITY_EDITOR
public class UnitySocketFix : MonoBehaviour
{
internal IPAddress BindAddrIPv4;
internal IPAddress BindAddrIPv6;
internal bool Reuse;
internal IPv6Mode IPv6;
internal int Port;
internal bool Paused;
internal NetSocket Socket;
internal bool ManualMode;
private void Update()
{
if (Socket == null)
Destroy(gameObject);
}
private void OnApplicationPause(bool pause)
{
if (Socket == null)
return;
if (pause)
{
Paused = true;
Socket.Close(true);
}
else if (Paused)
{
if (!Socket.Bind(BindAddrIPv4, BindAddrIPv6, Port, Reuse, IPv6, ManualMode))
{
NetDebug.WriteError("[S] Cannot restore connection \"{0}\",\"{1}\" port {2}", BindAddrIPv4, BindAddrIPv6, Port);
Socket.OnErrorRestore();
}
}
}
}
#endif
internal sealed class NetSocket
{
private const int ReceivePollingTime = 500000; //0.5 second
private Socket _udpSocketv4;
private Socket _udpSocketv6;
private Thread _threadv4;
private Thread _threadv6;
private IPEndPoint _bufferEndPointv4;
private IPEndPoint _bufferEndPointv6;
#if !LITENETLIB_UNSAFE
[ThreadStatic] private static byte[] _sendToBuffer;
#endif
[ThreadStatic] private static byte[] _endPointBuffer;
private readonly NetManager _listener;
private bool _useNativeSockets;
private readonly Dictionary<NativeAddr, IPEndPoint> _nativeAddrMap = new Dictionary<NativeAddr, IPEndPoint>();
private const int SioUdpConnreset = -1744830452; //SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12
private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse("ff02::1");
internal static readonly bool IPv6Support;
#if UNITY_IOS && !UNITY_EDITOR
private UnitySocketFix _unitySocketFix;
public void OnErrorRestore()
{
Close(false);
_listener.OnMessageReceived(null, SocketError.NotConnected, new IPEndPoint(0,0));
}
#endif
public int LocalPort { get; private set; }
public volatile bool IsRunning;
public short Ttl
{
get
{
#if UNITY_SWITCH
return 0;
#else
if (_udpSocketv4.AddressFamily == AddressFamily.InterNetworkV6)
return (short)_udpSocketv4.GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.HopLimit);
return _udpSocketv4.Ttl;
#endif
}
set
{
#if !UNITY_SWITCH
if (_udpSocketv4.AddressFamily == AddressFamily.InterNetworkV6)
_udpSocketv4.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
else
_udpSocketv4.Ttl = value;
#endif
}
}
static NetSocket()
{
#if DISABLE_IPV6
IPv6Support = false;
#elif !UNITY_2019_1_OR_NEWER && !UNITY_2018_4_OR_NEWER && (!UNITY_EDITOR && ENABLE_IL2CPP)
string version = UnityEngine.Application.unityVersion;
IPv6Support = Socket.OSSupportsIPv6 && int.Parse(version.Remove(version.IndexOf('f')).Split('.')[2]) >= 6;
#else
IPv6Support = Socket.OSSupportsIPv6;
#endif
}
public NetSocket(NetManager listener)
{
_listener = listener;
}
private bool IsActive()
{
#if UNITY_IOS && !UNITY_EDITOR
var unitySocketFix = _unitySocketFix; //save for multithread
if (unitySocketFix != null && unitySocketFix.Paused)
return false;
#endif
return IsRunning;
}
public void RegisterEndPoint(IPEndPoint ep)
{
if (_useNativeSockets && ep is NativeEndPoint nep)
{
_nativeAddrMap.Add(new NativeAddr(nep.NativeAddress, nep.NativeAddress.Length), nep);
}
}
public void UnregisterEndPoint(IPEndPoint ep)
{
if (_useNativeSockets && ep is NativeEndPoint nep)
{
var nativeAddr = new NativeAddr(nep.NativeAddress, nep.NativeAddress.Length);
_nativeAddrMap.Remove(nativeAddr);
}
}
private bool ProcessError(SocketException ex, EndPoint bufferEndPoint)
{
switch (ex.SocketErrorCode)
{
#if UNITY_IOS && !UNITY_EDITOR
case SocketError.NotConnected:
#endif
case SocketError.Interrupted:
case SocketError.NotSocket:
case SocketError.OperationAborted:
return true;
case SocketError.ConnectionReset:
case SocketError.MessageSize:
case SocketError.TimedOut:
//NetDebug.Write($"[R]Ignored error: {(int)ex.SocketErrorCode} - {ex}");
break;
default:
NetDebug.WriteError($"[R]Error code: {(int)ex.SocketErrorCode} - {ex}");
_listener.OnMessageReceived(null, ex.SocketErrorCode, (IPEndPoint)bufferEndPoint);
break;
}
return false;
}
public void ManualReceive()
{
if (_udpSocketv4 != null)
ManualReceive(_udpSocketv4, _bufferEndPointv4);
if (_udpSocketv6 != null && _udpSocketv6 != _udpSocketv4)
ManualReceive(_udpSocketv6, _bufferEndPointv6);
}
private bool ManualReceive(Socket socket, EndPoint bufferEndPoint)
{
//Reading data
try
{
int available = socket.Available;
if (available == 0)
return false;
while (available > 0)
{
var packet = _listener.NetPacketPool.GetPacket(NetConstants.MaxPacketSize);
packet.Size = socket.ReceiveFrom(packet.RawData, 0, NetConstants.MaxPacketSize, SocketFlags.None,
ref bufferEndPoint);
//NetDebug.Write(NetLogLevel.Trace, $"[R]Received data from {bufferEndPoint}, result: {packet.Size}");
_listener.OnMessageReceived(packet, 0, (IPEndPoint)bufferEndPoint);
available -= packet.Size;
}
}
catch (SocketException ex)
{
return ProcessError(ex, bufferEndPoint);
}
catch (ObjectDisposedException)
{
return true;
}
return false;
}
private void NativeReceiveLogic(object state)
{
Socket socket = (Socket)state;
IntPtr socketHandle = socket.Handle;
byte[] addrBuffer = new byte[socket.AddressFamily == AddressFamily.InterNetwork
? NativeSocket.IPv4AddrSize
: NativeSocket.IPv6AddrSize];
int addrSize = addrBuffer.Length;
IPEndPoint endPoint = null;
NetPacket packet = _listener.NetPacketPool.GetPacket(NetConstants.MaxPacketSize);
while (IsActive())
{
//Reading data
packet.Size = NativeSocket.RecvFrom(socketHandle, packet.RawData, NetConstants.MaxPacketSize, addrBuffer, ref addrSize);
if (packet.Size == 0)
return;
if (packet.Size == -1)
{
SocketError errorCode = NativeSocket.GetSocketError();
if (errorCode == SocketError.WouldBlock || errorCode == SocketError.TimedOut) //Linux timeout EAGAIN
continue;
if (ProcessError(new SocketException((int)errorCode), endPoint))
return;
continue;
}
NativeAddr nativeAddr = new NativeAddr(addrBuffer, addrSize);
if (!_nativeAddrMap.TryGetValue(nativeAddr, out endPoint))
endPoint = new NativeEndPoint(addrBuffer);
//All ok!
//NetDebug.WriteForce($"[R]Received data from {endPoint}, result: {packet.Size}");
_listener.OnMessageReceived(packet, 0, endPoint);
packet = _listener.NetPacketPool.GetPacket(NetConstants.MaxPacketSize);
}
}
private void ReceiveLogic(object state)
{
Socket socket = (Socket)state;
EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
while (IsActive())
{
NetPacket packet;
//Reading data
try
{
if (socket.Available == 0 && !socket.Poll(ReceivePollingTime, SelectMode.SelectRead))
continue;
packet = _listener.NetPacketPool.GetPacket(NetConstants.MaxPacketSize);
packet.Size = socket.ReceiveFrom(packet.RawData, 0, NetConstants.MaxPacketSize, SocketFlags.None,
ref bufferEndPoint);
}
catch (SocketException ex)
{
if (ProcessError(ex, bufferEndPoint))
return;
continue;
}
catch (ObjectDisposedException)
{
return;
}
//All ok!
//NetDebug.Write(NetLogLevel.Trace, $"[R]Received data from {bufferEndPoint}, result: {packet.Size}");
_listener.OnMessageReceived(packet, 0, (IPEndPoint)bufferEndPoint);
}
}
public bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool reuseAddress, IPv6Mode ipv6Mode, bool manualMode)
{
if (IsActive())
return false;
_useNativeSockets = _listener.UseNativeSockets && NativeSocket.IsSupported;
bool dualMode = ipv6Mode == IPv6Mode.DualMode && IPv6Support;
_udpSocketv4 = new Socket(
dualMode ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
if (!BindSocket(_udpSocketv4, new IPEndPoint(dualMode ? addressIPv6 : addressIPv4, port), reuseAddress, ipv6Mode))
return false;
LocalPort = ((IPEndPoint) _udpSocketv4.LocalEndPoint).Port;
#if UNITY_IOS && !UNITY_EDITOR
if (_unitySocketFix == null)
{
var unityFixObj = new GameObject("LiteNetLib_UnitySocketFix");
GameObject.DontDestroyOnLoad(unityFixObj);
_unitySocketFix = unityFixObj.AddComponent<UnitySocketFix>();
_unitySocketFix.Socket = this;
_unitySocketFix.BindAddrIPv4 = addressIPv4;
_unitySocketFix.BindAddrIPv6 = addressIPv6;
_unitySocketFix.Reuse = reuseAddress;
_unitySocketFix.Port = LocalPort;
_unitySocketFix.IPv6 = ipv6Mode;
_unitySocketFix.ManualMode = manualMode;
}
else
{
_unitySocketFix.Paused = false;
}
#endif
if (dualMode)
_udpSocketv6 = _udpSocketv4;
IsRunning = true;
if (!manualMode)
{
ParameterizedThreadStart ts = ReceiveLogic;
if (_useNativeSockets)
ts = NativeReceiveLogic;
_threadv4 = new Thread(ts)
{
Name = $"SocketThreadv4({LocalPort})",
IsBackground = true
};
_threadv4.Start(_udpSocketv4);
}
else
{
_bufferEndPointv4 = new IPEndPoint(IPAddress.Any, 0);
}
//Check IPv6 support
if (!IPv6Support || ipv6Mode != IPv6Mode.SeparateSocket)
return true;
_udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
//Use one port for two sockets
if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort), reuseAddress, ipv6Mode))
{
if (manualMode)
{
_bufferEndPointv6 = new IPEndPoint(IPAddress.IPv6Any, 0);
}
else
{
ParameterizedThreadStart ts = ReceiveLogic;
if (_useNativeSockets)
ts = NativeReceiveLogic;
_threadv6 = new Thread(ts)
{
Name = $"SocketThreadv6({LocalPort})",
IsBackground = true
};
_threadv6.Start(_udpSocketv6);
}
}
return true;
}
private bool BindSocket(Socket socket, IPEndPoint ep, bool reuseAddress, IPv6Mode ipv6Mode)
{
//Setup socket
socket.ReceiveTimeout = 500;
socket.SendTimeout = 500;
socket.ReceiveBufferSize = NetConstants.SocketBufferSize;
socket.SendBufferSize = NetConstants.SocketBufferSize;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
socket.IOControl(SioUdpConnreset, new byte[] {0}, null);
}
catch
{
//ignored
}
}
try
{
socket.ExclusiveAddressUse = !reuseAddress;
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, reuseAddress);
}
catch
{
//Unity with IL2CPP throws an exception here, it doesn't matter in most cases so just ignore it
}
if (socket.AddressFamily == AddressFamily.InterNetwork)
{
Ttl = NetConstants.SocketTTL;
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
try
{
socket.DontFragment = true;
}
catch (SocketException e)
{
NetDebug.WriteError($"[B]DontFragment error: {e.SocketErrorCode}");
}
}
try { socket.EnableBroadcast = true; }
catch (SocketException e)
{
NetDebug.WriteError($"[B]Broadcast error: {e.SocketErrorCode}");
}
}
else //IPv6 specific
{
if (ipv6Mode == IPv6Mode.DualMode)
{
try
{
//Disable IPv6 only mode
socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
}
catch(Exception e)
{
NetDebug.WriteError($"[B]Bind exception (dualmode setting): {e}");
}
}
}
//Bind
try
{
socket.Bind(ep);
NetDebug.Write(NetLogLevel.Trace, $"[B]Successfully binded to port: {((IPEndPoint)socket.LocalEndPoint).Port}, AF: {socket.AddressFamily}");
//join multicast
if (socket.AddressFamily == AddressFamily.InterNetworkV6)
{
try
{
#if !UNITY_2018_3_OR_NEWER
socket.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
new IPv6MulticastOption(MulticastAddressV6));
#endif
}
catch (Exception)
{
// Unity3d throws exception - ignored
}
}
}
catch (SocketException bindException)
{
switch (bindException.SocketErrorCode)
{
//IPv6 bind fix
case SocketError.AddressAlreadyInUse:
if (socket.AddressFamily == AddressFamily.InterNetworkV6 && ipv6Mode != IPv6Mode.DualMode)
{
try
{
//Set IPv6Only
socket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, true);
socket.Bind(ep);
}
catch (SocketException ex)
{
//because its fixed in 2018_3
NetDebug.WriteError($"[B]Bind exception: {ex}, errorCode: {ex.SocketErrorCode}");
return false;
}
return true;
}
break;
//hack for iOS (Unity3D)
case SocketError.AddressFamilyNotSupported:
return true;
}
NetDebug.WriteError($"[B]Bind exception: {bindException}, errorCode: {bindException.SocketErrorCode}");
return false;
}
return true;
}
public bool SendBroadcast(byte[] data, int size, int port)
{
if (!IsActive())
return false;
bool broadcastSuccess = false;
bool multicastSuccess = false;
try
{
broadcastSuccess = _udpSocketv4.SendTo(
data,
0,
size,
SocketFlags.None,
new IPEndPoint(IPAddress.Broadcast, port)) > 0;
if (_udpSocketv6 != null)
{
multicastSuccess = _udpSocketv6.SendTo(
data,
0,
size,
SocketFlags.None,
new IPEndPoint(MulticastAddressV6, port)) > 0;
}
}
catch (Exception ex)
{
NetDebug.WriteError($"[S][MCAST] {ex}");
return broadcastSuccess;
}
return broadcastSuccess || multicastSuccess;
}
public int SendTo(byte[] data, int offset, int size, IPEndPoint remoteEndPoint, ref SocketError errorCode)
{
if (!IsActive())
return 0;
try
{
var socket = _udpSocketv4;
if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
{
socket = _udpSocketv6;
if (socket == null)
return 0;
}
int result;
if (_useNativeSockets)
{
byte[] socketAddress;
if (remoteEndPoint is NativeEndPoint nep)
{
socketAddress = nep.NativeAddress;
}
else //Convert endpoint to raw
{
if (_endPointBuffer == null)
_endPointBuffer = new byte[NativeSocket.IPv6AddrSize];
socketAddress = _endPointBuffer;
bool ipv4 = remoteEndPoint.AddressFamily == AddressFamily.InterNetwork;
short addressFamily = NativeSocket.GetNativeAddressFamily(remoteEndPoint);
socketAddress[0] = (byte)(addressFamily);
socketAddress[1] = (byte)(addressFamily >> 8);
socketAddress[2] = (byte)(remoteEndPoint.Port >> 8);
socketAddress[3] = (byte)(remoteEndPoint.Port);
if (ipv4)
{
#pragma warning disable 618
long addr = remoteEndPoint.Address.Address;
#pragma warning restore 618
socketAddress[4] = (byte)(addr);
socketAddress[5] = (byte)(addr >> 8);
socketAddress[6] = (byte)(addr >> 16);
socketAddress[7] = (byte)(addr >> 24);
}
else
{
#if NETCOREAPP || NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER
remoteEndPoint.Address.TryWriteBytes(new Span<byte>(socketAddress, 8, 16), out _);
#else
byte[] addrBytes = remoteEndPoint.Address.GetAddressBytes();
Buffer.BlockCopy(addrBytes, 0, socketAddress, 8, 16);
#endif
}
}
#if LITENETLIB_UNSAFE
unsafe
{
fixed (byte* dataWithOffset = &data[offset])
{
result = NativeSocket.SendTo(socket.Handle, dataWithOffset, size, socketAddress, socketAddress.Length);
}
}
#else
if (offset > 0)
{
if (_sendToBuffer == null)
_sendToBuffer = new byte[NetConstants.MaxPacketSize];
Buffer.BlockCopy(data, offset, _sendToBuffer, 0, size);
data = _sendToBuffer;
}
result = NativeSocket.SendTo(socket.Handle, data, size, socketAddress, socketAddress.Length);
#endif
if (result == -1)
throw NativeSocket.GetSocketException();
}
else
{
result = socket.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint);
}
//NetDebug.WriteForce("[S]Send packet to {0}, result: {1}", remoteEndPoint, result);
return result;
}
catch (SocketException ex)
{
switch (ex.SocketErrorCode)
{
case SocketError.NoBufferSpaceAvailable:
case SocketError.Interrupted:
return 0;
case SocketError.MessageSize: //do nothing
break;
default:
NetDebug.WriteError($"[S] {ex}");
break;
}
errorCode = ex.SocketErrorCode;
return -1;
}
catch (Exception ex)
{
NetDebug.WriteError($"[S] {ex}");
return -1;
}
}
public void Close(bool suspend)
{
if (!suspend)
{
IsRunning = false;
#if UNITY_IOS && !UNITY_EDITOR
_unitySocketFix.Socket = null;
_unitySocketFix = null;
#endif
}
//cleanup dual mode
if (_udpSocketv4 == _udpSocketv6)
_udpSocketv6 = null;
_udpSocketv4?.Close();
_udpSocketv6?.Close();
_udpSocketv4 = null;
_udpSocketv6 = null;
if (_threadv4 != null && _threadv4 != Thread.CurrentThread)
_threadv4.Join();
if (_threadv6 != null && _threadv6 != Thread.CurrentThread)
_threadv6.Join();
_threadv4 = null;
_threadv6 = null;
}
}
}