Inheritance: Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
Esempio n. 1
1
        public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, int optionValueSeconds)
        {
            IOControlKeepAlive ioControlKeepAlive = s_socketKeepAliveTable.GetOrCreateValue(handle);

            if (optionName == SocketOptionName.TcpKeepAliveTime)
            {
                ioControlKeepAlive._timeMs = SecondsToMilliseconds(optionValueSeconds);
            }
            else
            {
                ioControlKeepAlive._intervalMs = SecondsToMilliseconds(optionValueSeconds);
            }

            byte[] buffer = s_keepAliveValuesBuffer ?? (s_keepAliveValuesBuffer = new byte[3 * sizeof(uint)]);
            ioControlKeepAlive.Fill(buffer);
            int realOptionLength = 0;

            return(SocketPal.WindowsIoctl(handle, unchecked ((int)IOControlCode.KeepAliveValues), buffer, null, out realOptionLength));
        }
Esempio n. 2
0
        public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle?fileHandle, ReadOnlySpan <byte> preBuffer, ReadOnlySpan <byte> postBuffer, TransmitFileOptions flags)
        {
            fixed(byte *prePinnedBuffer = preBuffer)
            fixed(byte *postPinnedBuffer = postBuffer)
            {
                bool success = TransmitFileHelper(handle, fileHandle, null, (IntPtr)prePinnedBuffer, preBuffer.Length, (IntPtr)postPinnedBuffer, postBuffer.Length, flags);

                return(success ? SocketError.Success : GetLastSocketError());
            }
        }
Esempio n. 3
0
        public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds)
        {
            if (optionValueSeconds == null ||
                optionValueSeconds.Length < sizeof(int))
            {
                return(SocketError.Fault);
            }

            return(Set(handle, optionName, BitConverter.ToInt32(optionValueSeconds, 0)));
        }
Esempio n. 4
0
        public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, SelectMode mode, out bool status)
        {
            bool refAdded = false;

            try
            {
                handle.DangerousAddRef(ref refAdded);

                IntPtr  rawHandle         = handle.DangerousGetHandle();
                IntPtr *fileDescriptorSet = stackalloc IntPtr[2] {
                    (IntPtr)1, rawHandle
                };
                Interop.Winsock.TimeValue IOwait = default;

                // A negative timeout value implies an indefinite wait.
                int socketCount;
                if (microseconds != -1)
                {
                    MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
                    socketCount =
                        Interop.Winsock.select(
                            0,
                            mode == SelectMode.SelectRead ? fileDescriptorSet : null,
                            mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
                            mode == SelectMode.SelectError ? fileDescriptorSet : null,
                            ref IOwait);
                }
                else
                {
                    socketCount =
                        Interop.Winsock.select(
                            0,
                            mode == SelectMode.SelectRead ? fileDescriptorSet : null,
                            mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
                            mode == SelectMode.SelectError ? fileDescriptorSet : null,
                            IntPtr.Zero);
                }

                if ((SocketError)socketCount == SocketError.SocketError)
                {
                    status = false;
                    return(GetLastSocketError());
                }

                status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
                return(SocketError.Success);
            }
            finally
            {
                if (refAdded)
                {
                    handle.DangerousRelease();
                }
            }
        }
Esempio n. 5
0
        public T GetDelegate <T>(SafeSocketHandle socketHandle)
            where T : class
        {
            if (typeof(T) == typeof(AcceptExDelegate))
            {
                EnsureAcceptEx(socketHandle);
                Debug.Assert(_acceptEx != null);
                return((T)(object)_acceptEx);
            }
            else if (typeof(T) == typeof(GetAcceptExSockaddrsDelegate))
            {
                EnsureGetAcceptExSockaddrs(socketHandle);
                Debug.Assert(_getAcceptExSockaddrs != null);
                return((T)(object)_getAcceptExSockaddrs);
            }
            else if (typeof(T) == typeof(ConnectExDelegate))
            {
                EnsureConnectEx(socketHandle);
                Debug.Assert(_connectEx != null);
                return((T)(object)_connectEx);
            }
            else if (typeof(T) == typeof(DisconnectExDelegate))
            {
                EnsureDisconnectEx(socketHandle);
                Debug.Assert(_disconnectEx != null);
                return((T)(object)_disconnectEx);
            }
            else if (typeof(T) == typeof(DisconnectExDelegateBlocking))
            {
                EnsureDisconnectEx(socketHandle);
                Debug.Assert(_disconnectExBlocking != null);
                return((T)(object)_disconnectExBlocking);
            }
            else if (typeof(T) == typeof(WSARecvMsgDelegate))
            {
                EnsureWSARecvMsg(socketHandle);
                Debug.Assert(_recvMsg != null);
                return((T)(object)_recvMsg);
            }
            else if (typeof(T) == typeof(WSARecvMsgDelegateBlocking))
            {
                EnsureWSARecvMsgBlocking(socketHandle);
                Debug.Assert(_recvMsgBlocking != null);
                return((T)(object)_recvMsgBlocking);
            }
            else if (typeof(T) == typeof(TransmitPacketsDelegate))
            {
                EnsureTransmitPackets(socketHandle);
                Debug.Assert(_transmitPackets != null);
                return((T)(object)_transmitPackets);
            }

            Debug.Fail("Invalid type passed to DynamicWinsockMethods.GetDelegate");
            return(null);
        }
Esempio n. 6
0
        public static SocketError Get(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds, ref int optionLength)
        {
            if (optionValueSeconds == null ||
                !BitConverter.TryWriteBytes(optionValueSeconds.AsSpan(), Get(handle, optionName)))
            {
                return(SocketError.Fault);
            }

            optionLength = optionValueSeconds.Length;
            return(SocketError.Success);
        }
Esempio n. 7
0
        public static SocketError GetAvailable(SafeSocketHandle handle, out int available)
        {
            int         value     = 0;
            SocketError errorCode = Interop.Winsock.ioctlsocket(
                handle,
                Interop.Winsock.IoctlSocketConstants.FIONREAD,
                ref value);

            available = value;
            return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 8
0
        public static SocketError Accept(SafeSocketHandle listenSocket, byte[] socketAddress, ref int socketAddressSize, out SafeSocketHandle socket)
        {
            IntPtr handle = Interop.Winsock.accept(listenSocket, socketAddress, ref socketAddressSize);

            socket = new SafeSocketHandle(handle, ownsHandle: true);
            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(null, socket);
            }

            return(socket.IsInvalid ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 9
0
        public static int Get(SafeSocketHandle handle, SocketOptionName optionName)
        {
            if (s_socketKeepAliveTable.TryGetValue(handle, out IOControlKeepAlive ioControlKeepAlive))
            {
                return(optionName == SocketOptionName.TcpKeepAliveTime ?
                       MillisecondsToSeconds(ioControlKeepAlive._timeMs) :
                       MillisecondsToSeconds(ioControlKeepAlive._intervalMs));
            }

            return(optionName == SocketOptionName.TcpKeepAliveTime ?
                   MillisecondsToSeconds(WindowsDefaultTimeMs) :
                   MillisecondsToSeconds(WindowsDefaultIntervalMs));
        }
Esempio n. 10
0
        public static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen)
        {
            SocketError errorCode = Interop.Winsock.WSAConnect(
                handle,
                peerAddress,
                peerAddressLen,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero);

            return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 11
0
        private static SafeSocketHandle CreateSocket(InnerSafeCloseSocket socket)
        {
            SafeSocketHandle ret = new SafeSocketHandle();

            CreateSocket(socket, ret);

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(null, ret);
            }

            return(ret);
        }
Esempio n. 12
0
        public unsafe SafeNativeOverlapped(SafeSocketHandle socketHandle, NativeOverlapped *handle)
            : this((IntPtr)handle)
        {
            _socketHandle = socketHandle;

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"socketHandle:{socketHandle}");
            }

#if DEBUG
            _socketHandle.AddRef();
#endif
        }
Esempio n. 13
0
        public static unsafe SocketError SetRawSockOpt(SafeSocketHandle handle, int optionLevel, int optionName, ReadOnlySpan <byte> optionValue)
        {
            fixed(byte *optionValuePtr = optionValue)
            {
                SocketError errorCode = Interop.Winsock.setsockopt(
                    handle,
                    (SocketOptionLevel)optionLevel,
                    (SocketOptionName)optionName,
                    optionValuePtr,
                    optionValue.Length);

                return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
            }
        }
Esempio n. 14
0
            internal unsafe bool AcceptEx(SafeSocketHandle listenSocketHandle, SafeSocketHandle acceptSocketHandle, IntPtr buffer, int len, int localAddressLength, int remoteAddressLength, out int bytesReceived, NativeOverlapped *overlapped)
            {
                IntPtr __listenSocketHandle_gen_native = default;
                IntPtr __acceptSocketHandle_gen_native = default;

                bytesReceived = default;
                bool __retVal;
                int  __retVal_gen_native = default;
                //
                // Setup
                //
                bool listenSocketHandle__addRefd = false;
                bool acceptSocketHandle__addRefd = false;

                try
                {
                    //
                    // Marshal
                    //
                    listenSocketHandle.DangerousAddRef(ref listenSocketHandle__addRefd);
                    __listenSocketHandle_gen_native = listenSocketHandle.DangerousGetHandle();
                    acceptSocketHandle.DangerousAddRef(ref acceptSocketHandle__addRefd);
                    __acceptSocketHandle_gen_native = acceptSocketHandle.DangerousGetHandle();
                    fixed(int *__bytesReceived_gen_native = &bytesReceived)
                    {
                        __retVal_gen_native = ((delegate * unmanaged <IntPtr, IntPtr, IntPtr, int, int, int, int *, NativeOverlapped *, int>)_target)(__listenSocketHandle_gen_native, __acceptSocketHandle_gen_native, buffer, len, localAddressLength, remoteAddressLength, __bytesReceived_gen_native, overlapped);
                    }
                    Marshal.SetLastPInvokeError(Marshal.GetLastSystemError());
                    //
                    // Unmarshal
                    //
                    __retVal = __retVal_gen_native != 0;
                }
                finally
                {
                    //
                    // Cleanup
                    //
                    if (listenSocketHandle__addRefd)
                    {
                        listenSocketHandle.DangerousRelease();
                    }
                    if (acceptSocketHandle__addRefd)
                    {
                        acceptSocketHandle.DangerousRelease();
                    }
                }

                return(__retVal);
            }
Esempio n. 15
0
 private void EnsureConnectEx(SafeSocketHandle socketHandle)
 {
     if (_connectEx == null)
     {
         lock (_lockObject)
         {
             if (_connectEx == null)
             {
                 Guid   guid         = new Guid("{0x25a207b9,0x0ddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}");
                 IntPtr ptrConnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid);
                 Volatile.Write(ref _connectEx, Marshal.GetDelegateForFunctionPointer <ConnectExDelegate>(ptrConnectEx));
             }
         }
     }
 }
Esempio n. 16
0
 private void EnsureGetAcceptExSockaddrs(SafeSocketHandle socketHandle)
 {
     if (_getAcceptExSockaddrs == null)
     {
         lock (_lockObject)
         {
             if (_getAcceptExSockaddrs == null)
             {
                 Guid   guid = new Guid("{0xb5367df2,0xcbac,0x11cf,{0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}");
                 IntPtr ptrGetAcceptExSockaddrs = LoadDynamicFunctionPointer(socketHandle, ref guid);
                 Volatile.Write(ref _getAcceptExSockaddrs, Marshal.GetDelegateForFunctionPointer <GetAcceptExSockaddrsDelegate>(ptrGetAcceptExSockaddrs));
             }
         }
     }
 }
Esempio n. 17
0
 private void EnsureWSARecvMsgBlocking(SafeSocketHandle socketHandle)
 {
     if (_recvMsgBlocking == null)
     {
         lock (_lockObject)
         {
             if (_recvMsgBlocking == null)
             {
                 Guid   guid          = new Guid("{0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}");
                 IntPtr ptrWSARecvMsg = LoadDynamicFunctionPointer(socketHandle, ref guid);
                 Volatile.Write(ref _recvMsgBlocking, Marshal.GetDelegateForFunctionPointer <WSARecvMsgDelegateBlocking>(ptrWSARecvMsg));
             }
         }
     }
 }
Esempio n. 18
0
 private void EnsureTransmitPackets(SafeSocketHandle socketHandle)
 {
     if (_transmitPackets == null)
     {
         lock (_lockObject)
         {
             if (_transmitPackets == null)
             {
                 Guid   guid = new Guid("{0xd9689da0,0x1f90,0x11d3,{0x99,0x71,0x00,0xc0,0x4f,0x68,0xc8,0x76}}");
                 IntPtr ptrTransmitPackets = LoadDynamicFunctionPointer(socketHandle, ref guid);
                 Volatile.Write(ref _transmitPackets, Marshal.GetDelegateForFunctionPointer <TransmitPacketsDelegate>(ptrTransmitPackets));
             }
         }
     }
 }
Esempio n. 19
0
 private void EnsureDisconnectEx(SafeSocketHandle socketHandle)
 {
     if (_disconnectEx == null)
     {
         lock (_lockObject)
         {
             if (_disconnectEx == null)
             {
                 Guid   guid            = new Guid("{0x7fda2e11,0x8630,0x436f,{0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}");
                 IntPtr ptrDisconnectEx = LoadDynamicFunctionPointer(socketHandle, ref guid);
                 _disconnectExBlocking = Marshal.GetDelegateForFunctionPointer <DisconnectExDelegateBlocking>(ptrDisconnectEx);
                 Volatile.Write(ref _disconnectEx, Marshal.GetDelegateForFunctionPointer <DisconnectExDelegate>(ptrDisconnectEx));
             }
         }
     }
 }
Esempio n. 20
0
        public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue)
        {
            Interop.Winsock.Linger lngopt = default;
            lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
            lngopt.Time  = (ushort)optionValue.LingerTime;

            // This can throw ObjectDisposedException.
            SocketError errorCode = Interop.Winsock.setsockopt(
                handle,
                SocketOptionLevel.Socket,
                SocketOptionName.Linger,
                ref lngopt,
                4);

            return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 21
0
        public void CompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressLen, SocketError errorCode)
        {
            _buffer   = null;
            _numBytes = 0;

            if (errorCode == SocketError.Success)
            {
                Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
                System.Buffer.BlockCopy(socketAddress, 0, remoteSocketAddress.Buffer, 0, socketAddressLen);

                _acceptedSocket = _listenSocket.CreateAcceptSocket(
                    SafeSocketHandle.CreateSocket(acceptedFileDescriptor),
                    _listenSocket._rightEndPoint.Create(remoteSocketAddress));
            }

            base.CompletionCallback(0, errorCode);
        }
Esempio n. 22
0
        public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
        {
            Interop.Winsock.IPv6MulticastRequest ipmr = default;

            ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
            ipmr.InterfaceIndex   = unchecked ((int)optionValue.InterfaceIndex);

            // This can throw ObjectDisposedException.
            SocketError errorCode = Interop.Winsock.setsockopt(
                handle,
                SocketOptionLevel.IPv6,
                optionName,
                ipmr,
                Interop.Winsock.IPv6MulticastRequest.Size);

            return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 23
0
        public static unsafe SocketError GetRawSockOpt(SafeSocketHandle handle, int optionLevel, int optionName, Span <byte> optionValue, ref int optionLength)
        {
            Debug.Assert((uint)optionLength <= optionValue.Length);

            SocketError errorCode;

            fixed(byte *optionValuePtr = optionValue)
            {
                errorCode = Interop.Winsock.getsockopt(
                    handle,
                    (SocketOptionLevel)optionLevel,
                    (SocketOptionName)optionName,
                    optionValuePtr,
                    ref optionLength);
                return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
            }
        }
Esempio n. 24
0
        public static unsafe SocketError SendTo(SafeSocketHandle handle, ReadOnlySpan <byte> buffer, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
        {
            int bytesSent;

            fixed(byte *bufferPtr = &MemoryMarshal.GetReference(buffer))
            {
                bytesSent = Interop.Winsock.sendto(handle, bufferPtr, buffer.Length, socketFlags, peerAddress, peerAddressSize);
            }

            if (bytesSent == (int)SocketError.SocketError)
            {
                bytesTransferred = 0;
                return(GetLastSocketError());
            }

            bytesTransferred = bytesSent;
            return(SocketError.Success);
        }
Esempio n. 25
0
        public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, Span <byte> buffer, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
        {
            int bytesReceived;

            fixed(byte *bufferPtr = &MemoryMarshal.GetReference(buffer))
            {
                bytesReceived = Interop.Winsock.recvfrom(handle, bufferPtr, buffer.Length, socketFlags, socketAddress, ref addressLength);
            }

            if (bytesReceived == (int)SocketError.SocketError)
            {
                bytesTransferred = 0;
                return(GetLastSocketError());
            }

            bytesTransferred = bytesReceived;
            return(SocketError.Success);
        }
Esempio n. 26
0
        public static SocketError SetBlocking(SafeSocketHandle handle, bool shouldBlock, out bool willBlock)
        {
            int intBlocking = shouldBlock ? 0 : -1;

            SocketError errorCode;

            errorCode = Interop.Winsock.ioctlsocket(
                handle,
                Interop.Winsock.IoctlSocketConstants.FIONBIO,
                ref intBlocking);

            if (errorCode == SocketError.SocketError)
            {
                errorCode = GetLastSocketError();
            }

            willBlock = intBlocking == 0;
            return(errorCode);
        }
Esempio n. 27
0
            internal unsafe bool ConnectEx(SafeSocketHandle socketHandle, IntPtr socketAddress, int socketAddressSize, IntPtr buffer, int dataLength, out int bytesSent, NativeOverlapped *overlapped)
            {
                IntPtr __socketHandle_gen_native = default;

                bytesSent = default;
                bool __retVal;
                int  __retVal_gen_native = default;
                //
                // Setup
                //
                bool socketHandle__addRefd = false;

                try
                {
                    //
                    // Marshal
                    //
                    socketHandle.DangerousAddRef(ref socketHandle__addRefd);
                    __socketHandle_gen_native = socketHandle.DangerousGetHandle();
                    fixed(int *__bytesSent_gen_native = &bytesSent)
                    {
                        __retVal_gen_native = ((delegate * unmanaged <IntPtr, IntPtr, int, IntPtr, int, int *, NativeOverlapped *, int>)_target)(__socketHandle_gen_native, socketAddress, socketAddressSize, buffer, dataLength, __bytesSent_gen_native, overlapped);
                    }
                    Marshal.SetLastPInvokeError(Marshal.GetLastSystemError());
                    //
                    // Unmarshal
                    //
                    __retVal = __retVal_gen_native != 0;
                }
                finally
                {
                    //
                    // Cleanup
                    //
                    if (socketHandle__addRefd)
                    {
                        socketHandle.DangerousRelease();
                    }
                }

                return(__retVal);
            }
Esempio n. 28
0
        public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]?optionInValue, byte[]?optionOutValue, out int optionLength)
        {
            if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
            {
                throw new InvalidOperationException(SR.net_sockets_useblocking);
            }

            SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
                handle,
                ioControlCode,
                optionInValue,
                optionInValue != null ? optionInValue.Length : 0,
                optionOutValue,
                optionOutValue != null ? optionOutValue.Length : 0,
                out optionLength,
                IntPtr.Zero,
                IntPtr.Zero);

            return(errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success);
        }
Esempio n. 29
0
        public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption?optionValue)
        {
            int optlen = Interop.Winsock.IPv6MulticastRequest.Size;

            // This can throw ObjectDisposedException.
            SocketError errorCode = Interop.Winsock.getsockopt(
                handle,
                SocketOptionLevel.IP,
                optionName,
                out Interop.Winsock.IPv6MulticastRequest ipmr,
                ref optlen);

            if (errorCode == SocketError.SocketError)
            {
                optionValue = default(IPv6MulticastOption);
                return(GetLastSocketError());
            }

            optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
            return(SocketError.Success);
        }
Esempio n. 30
0
        public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption?optionValue)
        {
            int optlen = 4;

            // This can throw ObjectDisposedException.
            SocketError errorCode = Interop.Winsock.getsockopt(
                handle,
                SocketOptionLevel.Socket,
                SocketOptionName.Linger,
                out Interop.Winsock.Linger lngopt,
                ref optlen);

            if (errorCode == SocketError.SocketError)
            {
                optionValue = default(LingerOption);
                return(GetLastSocketError());
            }

            optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
            return(SocketError.Success);
        }
Esempio n. 31
0
		static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 32
0
		public IAsyncResult BeginConnect (EndPoint end_point, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (end_point == null)
				throw new ArgumentNullException ("end_point");

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
				EndPoint = end_point,
			};

			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (end_point is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) end_point;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return sockares;
				}
			}

			int error = 0;

			if (connect_in_progress) {
				// This could happen when multiple IPs are used
				// Calling connect() again will reset the connection attempt and cause
				// an error. Better to just close the socket and move on.
				connect_in_progress = false;
				safe_handle.Dispose ();
				safe_handle = new SafeSocketHandle (Socket_internal (address_family, socket_type, protocol_type, out error), true);
				if (error != 0)
					throw new SocketException (error);
			}

			bool blk = is_blocking;
			if (blk)
				Blocking = false;
			Connect_internal (safe_handle, end_point.Serialize (), out error);
			if (blk)
				Blocking = true;

			if (error == 0) {
				// succeeded synch
				is_connected = true;
				is_bound = true;
				sockares.Complete (true);
				return sockares;
			}

			if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
				// error synch
				is_connected = false;
				is_bound = false;
				sockares.Complete (new SocketException (error), true);
				return sockares;
			}

			// continue asynch
			is_connected = false;
			is_bound = false;
			connect_in_progress = true;

			IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));

			return sockares;
		}
Esempio n. 33
0
		static void Listen_internal (SafeSocketHandle safeHandle, int backlog, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Listen_internal (safeHandle.DangerousGetHandle (), backlog, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 34
0
		private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Bind_internal (safeHandle.DangerousGetHandle (), sa, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 35
0
		//internal Socket (AddressFamily family, SocketType type, ProtocolType proto, IntPtr sock)

		bool EnsureSocket ()
		{
			lock (_lock) {
				if (nl_sock != null)
					return true;
				IntPtr fd = CreateNLSocket ();
				if (fd.ToInt64 () == -1)
					return false;

				var safeHandle = new SafeSocketHandle (fd, true);

				nl_sock = new Socket (0, SocketType.Raw, ProtocolType.Udp, safeHandle);
				nl_args = new SocketAsyncEventArgs ();
				nl_args.SetBuffer (new byte [8192], 0, 8192);
				nl_args.Completed += OnDataAvailable;
				nl_sock.ReceiveAsync (nl_args);
			}
			return true;
		}
Esempio n. 36
0
		static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 37
0
		static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return IOControl_internal (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 38
0
		public SocketInformation DuplicateAndClose (int targetProcessId)
		{
			var si = new SocketInformation ();
			si.Options =
				(is_listening      ? SocketInformationOptions.Listening : 0) |
				(is_connected      ? SocketInformationOptions.Connected : 0) |
				(is_blocking       ? 0 : SocketInformationOptions.NonBlocking) |
				(use_overlapped_io ? SocketInformationOptions.UseOnlyOverlappedIO : 0);

			si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, is_bound ? 1 : 0, (long)Handle);
			safe_handle = null;

			return si;
		}
Esempio n. 39
0
		static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 40
0
		/* private constructor used by Accept, which already has a socket handle to use */
		internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeSocketHandle safe_handle)
		{
			this.address_family = family;
			this.socket_type = type;
			this.protocol_type = proto;
			
			this.safe_handle = safe_handle;
			this.is_connected = true;
		}
Esempio n. 41
0
		static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 42
0
		public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
		{
			this.address_family = addressFamily;
			this.socket_type = socketType;
			this.protocol_type = protocolType;

			int error;
			this.safe_handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);

			if (error != 0)
				throw new SocketException (error);

			SocketDefaults ();
		}
Esempio n. 43
0
		public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
		{
#if NET_2_1 && !MOBILE
			switch (addressFamily) {
			case AddressFamily.InterNetwork:    // ok
			case AddressFamily.InterNetworkV6:  // ok
			case AddressFamily.Unknown:         // SocketException will be thrown later (with right error #)
				break;
			// case AddressFamily.Unspecified:
			default:
				throw new ArgumentException ("addressFamily");
			}

			switch (socketType) {
			case SocketType.Stream:             // ok
			case SocketType.Unknown:            // SocketException will be thrown later (with right error #)
				break;
			default:
				throw new ArgumentException ("socketType");
			}

			switch (protocolType) {
			case ProtocolType.Tcp:              // ok
			case ProtocolType.Unspecified:      // ok
			case ProtocolType.Unknown:          // SocketException will be thrown later (with right error #)
				break;
			default:
				throw new ArgumentException ("protocolType");
			}
#endif
			this.address_family = addressFamily;
			this.socket_type = socketType;
			this.protocol_type = protocolType;

			int error;
			this.safe_handle = new SafeSocketHandle (Socket_internal (addressFamily, socketType, protocolType, out error), true);

			if (error != 0)
				throw new SocketException (error);

#if !NET_2_1 || MOBILE
			SocketDefaults ();
#endif
		}
Esempio n. 44
0
		static int Available_internal (SafeSocketHandle safeHandle, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Available_internal (safeHandle.DangerousGetHandle (), out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 45
0
		static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Disconnect_internal (safeHandle.DangerousGetHandle (), reuse, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 46
0
		static SocketAddress RemoteEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return RemoteEndPoint_internal (safeHandle.DangerousGetHandle (), family, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 47
0
		public Socket (SocketInformation socketInformation)
		{
			this.is_listening      = (socketInformation.Options & SocketInformationOptions.Listening) != 0;
			this.is_connected      = (socketInformation.Options & SocketInformationOptions.Connected) != 0;
			this.is_blocking       = (socketInformation.Options & SocketInformationOptions.NonBlocking) == 0;
			this.use_overlapped_io = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;

			var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);

			this.address_family = (AddressFamily) (int) result [0];
			this.socket_type = (SocketType) (int) result [1];
			this.protocol_type = (ProtocolType) (int) result [2];
			this.is_bound = (ProtocolType) (int) result [3] != 0;
			this.safe_handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);

			SocketDefaults ();
		}
Esempio n. 48
0
		IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (end_point == null)
				throw new ArgumentNullException ("end_point");

			SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
			req.EndPoint = end_point;

			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (end_point is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) end_point;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return req;
				}
			}

			int error = 0;
			if (connect_in_progress) {
				// This could happen when multiple IPs are used
				// Calling connect() again will reset the connection attempt and cause
				// an error. Better to just close the socket and move on.
				connect_in_progress = false;
				socket.Dispose ();
				var handle = Socket_internal (address_family, socket_type, protocol_type, out error);
				socket = new SafeSocketHandle (handle, true);
				if (error != 0)
					throw new SocketException (error);
			}
			bool blk = blocking;
			if (blk)
				Blocking = false;
			SocketAddress serial = end_point.Serialize ();
			Connect_internal (socket, serial, out error);
			if (blk)
				Blocking = true;
			if (error == 0) {
				// succeeded synch
				connected = true;
				isbound = true;
				req.Complete (true);
				return req;
			}

			if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
				// error synch
				connected = false;
				isbound = false;
				req.Complete (new SocketException (error), true);
				return req;
			}

			// continue asynch
			connected = false;
			isbound = false;
			connect_in_progress = true;
			socket_pool_queue (Worker.Dispatcher, req);
			return req;
		}
Esempio n. 49
0
		static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 50
0
		private static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle,
			SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val,
			out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				GetSocketOption_arr_internal (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 51
0
		static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 52
0
		// private constructor used by Accept, which already
		// has a socket handle to use
		internal Socket(AddressFamily family, SocketType type,
			       ProtocolType proto, SafeSocketHandle sock)
		{
			address_family=family;
			socket_type=type;
			protocol_type=proto;
			
			socket=sock;
			connected=true;
		}
Esempio n. 53
0
		static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				SetSocketOption_internal (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 54
0
		private static int RecvFrom_internal (SafeSocketHandle safeHandle,
							    byte[] buffer,
							    int offset,
							    int count,
							    SocketFlags flags,
							    ref SocketAddress sockaddr,
							    out int error)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return RecvFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}
Esempio n. 55
0
		static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Shutdown_internal (safeHandle.DangerousGetHandle (), how, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 56
0
		public Socket (SocketInformation socketInformation)
		{
			var options = socketInformation.Options;
			islistening = (options & SocketInformationOptions.Listening) != 0;
			connected   = (options & SocketInformationOptions.Connected) != 0;
			blocking    = (options & SocketInformationOptions.NonBlocking) == 0;
			useoverlappedIO = (options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;

			var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);
			
			address_family = (AddressFamily) (int) result [0];
			socket_type = (SocketType) (int) result [1];
			protocol_type = (ProtocolType) (int) result [2];
			isbound = (ProtocolType) (int) result [3] != 0;
			socket = new SafeSocketHandle ((IntPtr) (long) result [4], true);
			SocketDefaults ();
		}
Esempio n. 57
0
		static void Blocking_internal (SafeSocketHandle safeHandle, bool block, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Blocking_internal (safeHandle.DangerousGetHandle (), block, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 58
0
		public SocketInformation DuplicateAndClose (int targetProcessId)
		{
			var si = new SocketInformation ();
			si.Options =
				(is_listening      ? SocketInformationOptions.Listening : 0) |
				(is_connected      ? SocketInformationOptions.Connected : 0) |
				(is_blocking       ? 0 : SocketInformationOptions.NonBlocking) |
				(useOverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);

			MonoIOError error;
			IntPtr duplicateHandle;
			if (!MonoIO.DuplicateHandle (System.Diagnostics.Process.GetCurrentProcess ().Handle, Handle, new IntPtr (targetProcessId), out duplicateHandle, 0, 0, 0x00000002 /* DUPLICATE_SAME_ACCESS */, out error))
				throw MonoIO.GetException (error);

			si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)addressFamily, (int)socketType, (int)protocolType, is_bound ? 1 : 0, (long)duplicateHandle);
 			m_Handle = null;
 
 			return si;
		}
Esempio n. 59
0
		static bool Poll_internal (SafeSocketHandle safeHandle, SelectMode mode, int timeout, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Poll_internal (safeHandle.DangerousGetHandle (), mode, timeout, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}
Esempio n. 60
0
		static SafeSocketHandle Accept_internal (SafeSocketHandle safeHandle, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				var ret = Accept_internal (safeHandle.DangerousGetHandle (), out error, blocking);
				return new SafeSocketHandle (ret, true);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}