File: PeerUnsafeNativeMethods.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (374 lines) | stat: -rw-r--r-- 14,612 bytes parent folder | download | duplicates (9)
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    using Microsoft.Win32.SafeHandles;

    static class PeerWinsock
    {
        [DllImport("ws2_32.dll", SetLastError = true, EntryPoint = "WSAIoctl")]
        internal static extern int WSAIoctl(
                [In] IntPtr socketHandle,
                [In] int ioControlCode,
                [In] IntPtr inBuffer,
                [In] int inBufferSize,
                [Out] IntPtr outBuffer,
                [In] int outBufferSize,
                [Out] out int bytesTransferred,
                [In] IntPtr overlapped,
                [In] IntPtr completionRoutine);
    }

    [Serializable, StructLayout(LayoutKind.Sequential)]
    struct SocketAddress
    {
        IntPtr sockAddr;
        int sockAddrLength;

        public IntPtr SockAddr { get { return sockAddr; } }
        public int SockAddrLength { get { return sockAddrLength; } }

        public void InitializeFromCriticalAllocHandleSocketAddress(CriticalAllocHandleSocketAddress sockAddr)
        {
            this.sockAddr = (IntPtr)sockAddr;
            this.sockAddrLength = sockAddr.Size;
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct SocketAddressList
    {
        int count;
        internal const int maxAddresses = 50;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = maxAddresses)]
        SocketAddress[] addresses;

        public SocketAddress[] Addresses { get { return addresses; } }
        public int Count { get { return count; } }

        public SocketAddressList(SocketAddress[] addresses, int count)
        {
            this.addresses = addresses;
            this.count = count;
        }

        public static ReadOnlyCollection<IPAddress> SortAddresses(Socket socket, IPAddress listenAddress, ReadOnlyCollection<IPAddress> addresses)
        {
            ReadOnlyCollection<IPAddress> sortedAddresses = null;

            // Skip sort if ipv6 isn't installed or if address array has a single address
            if (socket == null || addresses.Count <= 1)
            {
                sortedAddresses = addresses;
            }
            else
            {
                CriticalAllocHandleSocketAddressList inputBuffer = null;
                CriticalAllocHandleSocketAddressList outputBuffer = null;
                try
                {
                    inputBuffer = CriticalAllocHandleSocketAddressList.FromAddressList(addresses);
                    outputBuffer = CriticalAllocHandleSocketAddressList.FromAddressCount(0);
                    // Invoke ioctl to sort the addresses
                    int realOutputBufferSize;
                    int error = UnsafeNativeMethods.ERROR_SUCCESS;
                    int errorCode = PeerWinsock.WSAIoctl(socket.Handle,
                                                         unchecked((int)IOControlCode.AddressListSort),
                                                         (IntPtr)inputBuffer,
                                                         inputBuffer.Size,
                                                         (IntPtr)outputBuffer,
                                                         outputBuffer.Size,
                                                         out realOutputBufferSize,
                                                         IntPtr.Zero,
                                                         IntPtr.Zero);
                    if (errorCode == -1)
                    {
                        // Get the Win32 error code before doing anything else
                        error = Marshal.GetLastWin32Error();
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException(error));
                    }

                    // Marshal the sorted SOCKET_ADDRESS_LIST into IPAddresses
                    sortedAddresses = outputBuffer.ToAddresses();
                }
                finally
                {
                    if (inputBuffer != null) inputBuffer.Dispose();
                    if (outputBuffer != null) outputBuffer.Dispose();
                }
            }
            return sortedAddresses;
        }
    }

    // Type that converts from sockaddr_in6 to IPAddress and vice-versa
    [Serializable, StructLayout(LayoutKind.Sequential)]
    struct sockaddr_in6
    {
        short sin6_family;
        ushort sin6_port;
        uint sin6_flowinfo;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = addrByteCount)]
        byte[] sin6_addr;
        uint sin6_scope_id;

        const int addrByteCount = 16;

        // if the addr is v4-mapped-v6, 10th and 11th byte contain 0xFF. the last 4 bytes contain the ipv4 address
        const int v4MapIndex = 10;
        const int v4Index = v4MapIndex + 2;

        public sockaddr_in6(IPAddress address)
        {
            if (address.AddressFamily == AddressFamily.InterNetworkV6)
            {
                this.sin6_addr = address.GetAddressBytes();
                this.sin6_scope_id = (uint)address.ScopeId;
            }
            else
            {
                // Map v4 address to v4-mapped v6 addr (i.e., ::FFFF:XX.XX.XX.XX)
                byte[] v4AddressBytes = address.GetAddressBytes();

                this.sin6_addr = new byte[addrByteCount];
                for (int i = 0; i < v4MapIndex; i++)
                    this.sin6_addr[i] = 0;
                this.sin6_addr[v4MapIndex] = 0xff;
                this.sin6_addr[v4MapIndex + 1] = 0xff;
                for (int i = v4Index; i < addrByteCount; i++)
                    this.sin6_addr[i] = v4AddressBytes[i - v4Index];

                this.sin6_scope_id = 0;     // V4 address doesn't have a scope ID
            }

            this.sin6_family = (short)AddressFamily.InterNetworkV6;
            this.sin6_port = 0;
            this.sin6_flowinfo = 0;
        }

        public short Family { get { return this.sin6_family; } }
        public uint FlowInfo { get { return this.sin6_flowinfo; } }

        // Returns true if the address is a v4-mapped v6 address
        // Adapted from ws2ipdef.w's IN6_IS_ADDR_V4MAPPED macro
        private bool IsV4Mapped
        {
            get
            {
                // A v4-mapped v6 address will have the last 4 bytes contain the IPv4 address. 
                // The preceding 2 bytes contain 0xFFFF. All others are 0.
                if (sin6_addr[v4MapIndex] != 0xff || sin6_addr[v4MapIndex + 1] != 0xff)
                    return false;

                for (int i = 0; i < v4MapIndex; i++)
                    if (sin6_addr[i] != 0)
                        return false;

                return true;
            }
        }

        public ushort Port { get { return this.sin6_port; } }

        // Converts a sockaddr_in6 to IPAddress
        // A v4 mapped v6 address is converted to a v4 address
        public IPAddress ToIPAddress()
        {
            if (!(this.sin6_family == (short)AddressFamily.InterNetworkV6))
            {
                throw Fx.AssertAndThrow("AddressFamily expected to be InterNetworkV6");
            }

            if (IsV4Mapped)
            {
                byte[] addr = 
                {
                    this.sin6_addr[v4Index],
                    this.sin6_addr[v4Index + 1],
                    this.sin6_addr[v4Index + 2],
                    this.sin6_addr[v4Index + 3] 
                };
                return new IPAddress(addr);
            }
            else
            {
                return new IPAddress(this.sin6_addr, this.sin6_scope_id);
            }
        }
    }

    class CriticalAllocHandleSocketAddressList : CriticalAllocHandle
    {
        int count;
        int size;
        CriticalAllocHandleSocketAddress[] socketHandles;

        public int Count { get { return count; } }
        public int Size { get { return size; } }

        public static CriticalAllocHandleSocketAddressList FromAddressList(ICollection<IPAddress> addresses)
        {
            if (addresses == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addresses");
            }
            int count = addresses.Count;

            CriticalAllocHandleSocketAddress[] socketHandles = new CriticalAllocHandleSocketAddress[SocketAddressList.maxAddresses];
            SocketAddressList socketAddressList = new SocketAddressList(new SocketAddress[SocketAddressList.maxAddresses], count);
            int i = 0;
            foreach (IPAddress address in addresses)
            {
                if (i == SocketAddressList.maxAddresses) break; // due to Marshalling fixed sized array of SocketAddresses.
                socketHandles[i] = CriticalAllocHandleSocketAddress.FromIPAddress(address);
                socketAddressList.Addresses[i].InitializeFromCriticalAllocHandleSocketAddress(socketHandles[i]);
                ++i;
            }

            int size = Marshal.SizeOf(socketAddressList);
            CriticalAllocHandleSocketAddressList result = CriticalAllocHandleSocketAddressList.FromSize(size);
            result.count = count;
            result.socketHandles = socketHandles;
            Marshal.StructureToPtr(socketAddressList, result, false);
            return result;
        }

        public static CriticalAllocHandleSocketAddressList FromAddressCount(int count)
        {
            SocketAddressList socketAddressList = new SocketAddressList(new SocketAddress[SocketAddressList.maxAddresses], 0);
            int size = Marshal.SizeOf(socketAddressList);
            CriticalAllocHandleSocketAddressList result = CriticalAllocHandleSocketAddressList.FromSize(size);
            result.count = count;
            Marshal.StructureToPtr(socketAddressList, result, false);
            return result;
        }

        static new CriticalAllocHandleSocketAddressList FromSize(int size)
        {
            CriticalAllocHandleSocketAddressList result = new CriticalAllocHandleSocketAddressList();
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                result.SetHandle(Marshal.AllocHGlobal(size));
                result.size = size;
            }
            return result;
        }

        public ReadOnlyCollection<IPAddress> ToAddresses()
        {
            SocketAddressList socketAddressList = (SocketAddressList)Marshal.PtrToStructure(this, typeof(SocketAddressList));
            IPAddress[] addresses = new IPAddress[socketAddressList.Count];
            for (int i = 0; i < addresses.Length; i++)
            {
                if (!(socketAddressList.Addresses[i].SockAddrLength == Marshal.SizeOf(typeof(sockaddr_in6))))
                {
                    throw Fx.AssertAndThrow("sockAddressLength in SOCKET_ADDRESS expected to be valid");
                }
                sockaddr_in6 sockAddr = (sockaddr_in6)Marshal.PtrToStructure(socketAddressList.Addresses[i].SockAddr, typeof(sockaddr_in6));
                addresses[i] = sockAddr.ToIPAddress();
            }

            return Array.AsReadOnly<IPAddress>(addresses);
        }
    }

    class CriticalAllocHandleSocketAddress : CriticalAllocHandle
    {
        int size;

        public int Size { get { return size; } }

        public static CriticalAllocHandleSocketAddress FromIPAddress(IPAddress input)
        {
            if (input == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("input");
            }

            CriticalAllocHandleSocketAddress result = null;
            int size = Marshal.SizeOf(typeof(sockaddr_in6));
            result = CriticalAllocHandleSocketAddress.FromSize(size);
            sockaddr_in6 sa = new sockaddr_in6(input);
            Marshal.StructureToPtr(sa, (IntPtr)result, false);
            return result;
        }

        public static new CriticalAllocHandleSocketAddress FromSize(int size)
        {
            CriticalAllocHandleSocketAddress result = new CriticalAllocHandleSocketAddress();
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                result.SetHandle(Marshal.AllocHGlobal(size));
                result.size = size;
            }
            return result;
        }
    }

    class CriticalAllocHandle : CriticalHandleZeroOrMinusOneIsInvalid
    {
        [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        public static implicit operator IntPtr(CriticalAllocHandle safeHandle)
        {
            return (safeHandle != null) ? safeHandle.handle : (IntPtr)null;
        }

        protected override bool ReleaseHandle()
        {
            Marshal.FreeHGlobal(handle);
            return true;
        }

        public static CriticalAllocHandle FromSize(int size)
        {
            CriticalAllocHandle result = new CriticalAllocHandle();
            RuntimeHelpers.PrepareConstrainedRegions();
            try { }
            finally
            {
                result.SetHandle(Marshal.AllocHGlobal(size));
            }
            return result;
        }
    }

    class CriticalAllocHandleBlob : CriticalAllocHandle
    {
        [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical]
        public static CriticalAllocHandle FromBlob<T>(T id)
        {
            int size = Marshal.SizeOf(typeof(T));
            CriticalAllocHandle result = CriticalAllocHandle.FromSize(size);
            Marshal.StructureToPtr(id, (IntPtr)result, false);
            return result;
        }
    }

    class CriticalAllocHandleGuid : CriticalAllocHandle
    {
        public static CriticalAllocHandle FromGuid(Guid input)
        {
            int guidSize = Marshal.SizeOf(typeof(Guid));
            CriticalAllocHandle result = CriticalAllocHandle.FromSize(guidSize);
            Marshal.Copy(input.ToByteArray(), 0, (IntPtr)result, guidSize);
            return result;
        }
    }
}