This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
SafeSocketHandle.Unix.cs
426 lines (372 loc) · 17 KB
/
SafeSocketHandle.Unix.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
public partial class SafeSocketHandle
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
private bool _underlyingHandleNonBlocking;
private SocketAsyncContext _asyncContext;
private TrackedSocketOptions _trackedOptions;
internal bool LastConnectFailed { get; set; }
internal bool DualMode { get; set; }
internal bool ExposedHandleOrUntrackedConfiguration { get; private set; }
internal void RegisterConnectResult(SocketError error)
{
switch (error)
{
case SocketError.Success:
case SocketError.WouldBlock:
break;
default:
LastConnectFailed = true;
break;
}
}
internal void TransferTrackedState(SafeSocketHandle target)
{
target._trackedOptions = _trackedOptions;
target.LastConnectFailed = LastConnectFailed;
target.DualMode = DualMode;
target.ExposedHandleOrUntrackedConfiguration = ExposedHandleOrUntrackedConfiguration;
}
internal void SetExposed() => ExposedHandleOrUntrackedConfiguration = true;
internal bool IsTrackedOption(TrackedSocketOptions option) => (_trackedOptions & option) != 0;
internal void TrackOption(SocketOptionLevel level, SocketOptionName name)
{
// As long as only these options are set, we can support Connect{Async}(IPAddress[], ...).
switch (level)
{
case SocketOptionLevel.Tcp:
switch (name)
{
case SocketOptionName.NoDelay: _trackedOptions |= TrackedSocketOptions.NoDelay; return;
}
break;
case SocketOptionLevel.IP:
switch (name)
{
case SocketOptionName.DontFragment: _trackedOptions |= TrackedSocketOptions.DontFragment; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.IPv6:
switch (name)
{
case SocketOptionName.IPv6Only: _trackedOptions |= TrackedSocketOptions.DualMode; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.Socket:
switch (name)
{
case SocketOptionName.Broadcast: _trackedOptions |= TrackedSocketOptions.EnableBroadcast; return;
case SocketOptionName.Linger: _trackedOptions |= TrackedSocketOptions.LingerState; return;
case SocketOptionName.ReceiveBuffer: _trackedOptions |= TrackedSocketOptions.ReceiveBufferSize; return;
case SocketOptionName.ReceiveTimeout: _trackedOptions |= TrackedSocketOptions.ReceiveTimeout; return;
case SocketOptionName.SendBuffer: _trackedOptions |= TrackedSocketOptions.SendBufferSize; return;
case SocketOptionName.SendTimeout: _trackedOptions |= TrackedSocketOptions.SendTimeout; return;
}
break;
}
// For any other settings, we need to track that they were used so that we can error out
// if a Connect{Async}(IPAddress[],...) attempt is made.
ExposedHandleOrUntrackedConfiguration = true;
}
internal SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
return _asyncContext;
}
}
// This will set the underlying OS handle to be nonblocking, for whatever reason --
// performing an async operation or using a timeout will cause this to happen.
// Once the OS handle is nonblocking, it never transitions back to blocking.
private void SetHandleNonBlocking()
{
// We don't care about synchronization because this is idempotent
if (!_underlyingHandleNonBlocking)
{
AsyncContext.SetNonBlocking();
_underlyingHandleNonBlocking = true;
}
}
internal bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
SetHandleNonBlocking();
}
}
}
internal bool IsUnderlyingBlocking
{
get
{
return !_underlyingHandleNonBlocking;
}
}
internal int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_receiveTimeout = value;
}
}
internal int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_sendTimeout = value;
}
}
internal bool IsDisconnected { get; private set; } = false;
internal void SetToDisconnected()
{
IsDisconnected = true;
}
internal static unsafe SafeSocketHandle CreateSocket(IntPtr fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
internal static unsafe SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeSocketHandle socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
internal static unsafe SocketError Accept(SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeSocketHandle socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private bool DoReleaseHandle()
{
// If we've aborted async operations, return true to cause an abortive close.
return _asyncContext?.StopAndAbort() ?? false;
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private Interop.Error CloseHandle(IntPtr handle)
{
Interop.Error errorCode = Interop.Error.SUCCESS;
bool remappedError = false;
if (Interop.Sys.Close(handle) != 0)
{
errorCode = Interop.Sys.GetLastError();
if (errorCode == Interop.Error.ECONNRESET)
{
// Some Unix platforms (e.g. FreeBSD) non-compliantly return ECONNRESET from close().
// For our purposes, we want to ignore such a "failure" and treat it as success.
// In such a case, the file descriptor was still closed and there's no corrective
// action to take.
errorCode = Interop.Error.SUCCESS;
remappedError = true;
}
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, remappedError ?
$"handle:{handle}, close():ECONNRESET, but treating it as SUCCESS" :
$"handle:{handle}, close():{errorCode}");
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode(errorCode);
#endif
return errorCode;
}
private unsafe SocketError InnerReleaseHandle()
{
Interop.Error errorCode = Interop.Error.SUCCESS;
// If _abortive was set to false in Close, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (!_abortive)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'non-abortive' branch.");
// Close, and if its errno is other than EWOULDBLOCK, there's nothing more to do - we either succeeded or failed.
errorCode = CloseHandle(handle);
if (errorCode != Interop.Error.EWOULDBLOCK)
{
return SocketPal.GetSocketErrorForErrorCode(errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
if (Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0) == 0)
{
// The socket successfully made blocking; retry the close().
return SocketPal.GetSocketErrorForErrorCode(CloseHandle(handle));
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if the non-abortive path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption
{
OnOff = 1,
Seconds = 0
};
errorCode = Interop.Sys.SetLingerOption(handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode(errorCode);
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
switch (errorCode)
{
case Interop.Error.SUCCESS:
case Interop.Error.EINVAL:
case Interop.Error.ENOPROTOOPT:
errorCode = CloseHandle(handle);
break;
// For other errors, it's too dangerous to try closesocket() - it might block!
}
return SocketPal.GetSocketErrorForErrorCode(errorCode);
}
internal static InnerSafeCloseSocket CreateSocket(IntPtr fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle(fileDescriptor);
return res;
}
internal static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
IntPtr fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != (IntPtr)(-1), "fd should not be -1");
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for normal AF_INET6 sockets.
// This fails on raw sockets so we just let them be in default state.
if (addressFamily == AddressFamily.InterNetworkV6 && socketType != SocketType.Raw)
{
int on = 1;
error = Interop.Sys.SetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close(fd);
fd = (IntPtr)(-1);
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == (IntPtr)(-1), $"Unexpected fd: {fd}");
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle(fd);
return res;
}
internal static unsafe InnerSafeCloseSocket Accept(SafeSocketHandle socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
IntPtr acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, out acceptedFd);
}
else
{
bool completed = SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
if (!completed)
{
errorCode = SocketError.WouldBlock;
}
}
var res = new InnerSafeCloseSocket();
res.SetHandle(acceptedFd);
return res;
}
internal unsafe bool TryUnblockSocket(bool abortive)
{
// Calling 'close' on a socket that has pending blocking calls (e.g. recv, send, accept, ...)
// may block indefinitely. This is a best-effort attempt to not get blocked and make those operations return.
// We need to ensure we keep the expected TCP behavior that is observed by the socket peer (FIN vs RST close).
// What we do here isn't specified by POSIX and doesn't work on all OSes.
// On Linux this works well.
// On OSX, TCP connections will be closed with a FIN close instead of an abortive RST close.
// And, pending TCP connect operations and UDP receive are not abortable.
// Unless we're doing an abortive close, don't touch sockets which don't have the CLOEXEC flag set.
// These may be shared with other processes and we want to avoid disconnecting them.
if (!abortive)
{
int fdFlags = Interop.Sys.Fcntl.GetFD(this);
if (fdFlags == 0)
{
return false;
}
}
int type = 0;
int optLen = sizeof(int);
Interop.Error err = Interop.Sys.GetSockOpt(this, SocketOptionLevel.Socket, SocketOptionName.Type, (byte*)&type, &optLen);
if (err == Interop.Error.SUCCESS)
{
if (type == (int)SocketType.Stream)
{
Interop.Sys.Disconnect(this);
}
else
{
Interop.Sys.Shutdown(this, SocketShutdown.Both);
}
}
// We've cancelled on-going operations, return true to cause an abortive close.
return true;
}
}
}
/// <summary>Flags that correspond to exposed options on Socket.</summary>
[Flags]
internal enum TrackedSocketOptions : short
{
DontFragment = 0x1,
DualMode = 0x2,
EnableBroadcast = 0x4,
LingerState = 0x8,
NoDelay = 0x10,
ReceiveBufferSize = 0x20,
ReceiveTimeout = 0x40,
SendBufferSize = 0x80,
SendTimeout = 0x100,
Ttl = 0x200,
}
}