public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error)
 {
   error = (byte) 0;
   byte[] numArray1 = new byte[4]{ (byte) 95, (byte) 36, (byte) 19, (byte) 246 };
   if (endPoint == null)
     throw new NullReferenceException("Null EndPoint provided");
   if (endPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint" && endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint")
     throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint  required");
   if (endPoint.GetType().FullName == "UnityEngine.XboxOne.XboxOneEndPoint")
   {
     EndPoint endPoint1 = endPoint;
     if (endPoint1.AddressFamily != AddressFamily.InterNetworkV6)
       throw new ArgumentException("XboxOneEndPoint has an invalid family");
     SocketAddress socketAddress = endPoint1.Serialize();
     if (socketAddress.Size != 14)
       throw new ArgumentException("XboxOneEndPoint has an invalid size");
     if ((int) socketAddress[0] != 0 || (int) socketAddress[1] != 0)
       throw new ArgumentException("XboxOneEndPoint has an invalid family signature");
     if ((int) socketAddress[2] != (int) numArray1[0] || (int) socketAddress[3] != (int) numArray1[1] || ((int) socketAddress[4] != (int) numArray1[2] || (int) socketAddress[5] != (int) numArray1[3]))
       throw new ArgumentException("XboxOneEndPoint has an invalid signature");
     byte[] numArray2 = new byte[8];
     for (int index = 0; index < numArray2.Length; ++index)
       numArray2[index] = socketAddress[6 + index];
     IntPtr num = new IntPtr(BitConverter.ToInt64(numArray2, 0));
     if (num == IntPtr.Zero)
       throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer");
     byte[] destination = new byte[2];
     Marshal.Copy(num, destination, 0, destination.Length);
     if (((int) destination[1] << 8) + (int) destination[0] != 23)
       throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer");
     return NetworkTransport.Internal_ConnectEndPoint(hostId, num, 128, exceptionConnectionId, out error);
   }
   SocketAddress socketAddress1 = endPoint.Serialize();
   if (socketAddress1.Size != 16)
     throw new ArgumentException("EndPoint has an invalid size");
   if ((int) socketAddress1[0] != socketAddress1.Size)
     throw new ArgumentException("EndPoint has an invalid size value");
   if ((int) socketAddress1[1] != 2)
     throw new ArgumentException("EndPoint has an invalid family value");
   byte[] source = new byte[16];
   for (int index = 0; index < source.Length; ++index)
     source[index] = socketAddress1[index];
   IntPtr num1 = Marshal.AllocHGlobal(source.Length);
   Marshal.Copy(source, 0, num1, source.Length);
   int num2 = NetworkTransport.Internal_ConnectEndPoint(hostId, num1, 16, exceptionConnectionId, out error);
   Marshal.FreeHGlobal(num1);
   return num2;
 }
 internal static bool DoesEndPointUsePlatformProtocols(EndPoint endPoint)
 {
   if (endPoint.GetType().FullName == "UnityEngine.PS4.SceEndPoint")
   {
     SocketAddress socketAddress = endPoint.Serialize();
     if ((int) socketAddress[8] != 0 || (int) socketAddress[9] != 0)
       return true;
   }
   return false;
 }
Example #3
0
        //
        // socketAddress must always be the result of remoteEP.Serialize()
        //
        private void CheckCacheRemote(SocketAddress socketAddress, EndPoint remoteEP, bool isOverwrite) {
            // We remember the first peer we have communicated with
            if (m_PermittedRemoteAddress != null && m_PermittedRemoteAddress.Equals(socketAddress)) {
                return;
            }
            //
            // for now SocketPermission supports only IPEndPoint
            //
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                //
                // cast the EndPoint to IPEndPoint
                //
                IPEndPoint remoteIPEndPoint = (IPEndPoint)remoteEP;
                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Connect,
                        Transport,
                        remoteIPEndPoint.Address.ToString(),
                        remoteIPEndPoint.Port);
                //
                // demand for them
                //
                socketPermission.Demand();
            }
            else {
                //
                // for V1 we will demand permission to run UnmanagedCode for
                // an EndPoint that is not an IPEndPoint until we figure out how these fit
                // into the whole picture of SocketPermission
                //

                (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
            }
            //cache only the first peer we communicated with
            if (m_PermittedRemoteAddress == null || isOverwrite) {
                m_PermittedRemoteAddress = socketAddress;
            }
        }
Example #4
0
        public static LocalAddress Register(IChannel channel, LocalAddress oldLocalAddress, EndPoint localAddress)
        {
            if (oldLocalAddress != null)
                throw new HeliosException("already bound");

            if (!(localAddress is LocalAddress))
            {
                throw new HeliosException($"Unsupported address type {localAddress.GetType()}");
            }

            var addr = (LocalAddress) localAddress;
            if (LocalAddress.Any.Equals(addr))
            {
                addr = new LocalAddress(channel);
            }

            if (BoundChannels.ContainsKey(addr))
                throw new HeliosException($"address {addr} is already in use ");

            var boundChannel = BoundChannels.GetOrAdd(addr, channel);
            return addr;
        }
Example #5
0
        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.ReceiveFrom"]/*' />
        /// <devdoc>
        ///    <para>Receives a datagram into a specific location in the data buffer and stores
        ///       the end point.</para>
        /// </devdoc>
        public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (buffer==null) {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }
            if (offset<0 || offset>buffer.Length) {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size<0 || size>buffer.Length-offset) {
                throw new ArgumentOutOfRangeException("size");
            }

            ValidateBlockingMode();

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::ReceiveFrom() remoteEP:" + remoteEP.ToString());

            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            SocketAddress socketAddressOriginal = endPointSnapshot.Serialize();
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            // This will check the permissions for connect.
            // We need this because remoteEP may differ from one used in Connect or
            // there was no Connect called.
            CheckCacheRemote(socketAddress, endPointSnapshot, false);

            GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr pinnedBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.recvfrom(
                    m_Handle,
                    pinnedBuffer,
                    size,
                    socketFlags,
                    socketAddress.m_Buffer,
                    ref socketAddress.m_Size );

            gcHandle.Free();

            if (!socketAddressOriginal.Equals(socketAddress)) {
                try {
                    remoteEP = endPointSnapshot.Create(socketAddress);
                }
                catch {
                }
                if (m_RightEndPoint==null) {
                    //
                    // save a copy of the EndPoint so we can use it for Create()
                    //
                    m_RightEndPoint = endPointSnapshot;
                }
            }


            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode==SocketErrors.SocketError) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException();
                UpdateStatusAfterSocketError();
                throw socketException;
            }

            return errorCode;
        }
Example #6
0
        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.SendTo"]/*' />
        /// <devdoc>
        ///    <para>Sends data to a specific end point, starting at the indicated location in the
        ///       data.</para>
        /// </devdoc>
        public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (buffer==null) {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }
            if (offset<0 || offset>buffer.Length) {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size<0 || size>buffer.Length-offset) {
                throw new ArgumentOutOfRangeException("size");
            }

            ValidateBlockingMode();

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::SendTo() size:" + size.ToString() + " remoteEP:" + remoteEP.ToString());

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            //That will check ConnectPermission for remoteEP
            CheckCacheRemote(socketAddress, endPointSnapshot, false);

            GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            IntPtr pinnedBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.sendto(
                    m_Handle,
                    pinnedBuffer,
                    size,
                    socketFlags,
                    socketAddress.m_Buffer,
                    socketAddress.m_Size );

            gcHandle.Free();

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode==SocketErrors.SocketError) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException();
                UpdateStatusAfterSocketError();
                throw socketException;
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }


            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::SendTo() returning errorCode:" + errorCode.ToString());

            return errorCode;
        }
Example #7
0
        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.Connect"]/*' />
        /// <devdoc>
        ///    <para>Establishes a connection to a remote system.</para>
        /// </devdoc>
        public void Connect(EndPoint remoteEP) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }
            ValidateBlockingMode();

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Connect() remoteEP:" + remoteEP.ToString());

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            //This will check the permissions for connect
            CheckCacheRemote(socketAddress, endPointSnapshot, true);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.connect(
                    m_Handle,
                    socketAddress.m_Buffer,
                    socketAddress.m_Size );

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketErrors.Success) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException();
                UpdateStatusAfterSocketError();
                throw socketException;
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Connect() now connected to:" + endPointSnapshot.ToString());

            //
            // update state and performance counter
            //
            SetToConnected();
        }
Example #8
0
        /*++

        Routine Description:

           BeginReceiveFrom - Async implimentation of RecvFrom call,

           Called when we want to start an async receive.
           We kick off the receive, and if it completes synchronously we'll
           call the callback. Otherwise we'll return an IASyncResult, which
           the caller can use to wait on or retrieve the final status, as needed.

           Uses Winsock 2 overlapped I/O.

        Arguments:

           ReadBuffer - status line that we wish to parse
           Index - Offset into ReadBuffer to begin reading from
           Request - Size of Buffer to recv
           Flags - Additonal Flags that may be passed to the underlying winsock call
           remoteEP - EndPoint that are to receive from
           Callback - Delegate function that holds callback, called on completeion of I/O
           State - State used to track callback, set by caller, not required

        Return Value:

           IAsyncResult - Async result used to retreive result

        --*/

        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.BeginReceiveFrom"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, Object state) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (buffer==null) {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }
            if (offset<0 || offset>buffer.Length) {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size<0 || size>buffer.Length-offset) {
                throw new ArgumentOutOfRangeException("size");
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveFrom() size:" + size.ToString());

            //
            // Allocate the async result and the event we'll pass to the
            // thread pool.
            //
            OverlappedAsyncResult asyncResult =
                new OverlappedAsyncResult(
                    this,
                    state,
                    callback );

            //
            // Set up asyncResult for overlapped WSARecvFrom.
            // This call will use
            // completion ports on WinNT and Overlapped IO on Win9x.
            //
            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            asyncResult.SetUnmanagedStructures(
                                          buffer,
                                          offset,
                                          size,
                                          socketFlags,
                                          endPointSnapshot,
                                          true // pin remoteEP
                                          );

            // save a copy of the original EndPoint in the asyncResult
            asyncResult.m_SocketAddressOriginal = endPointSnapshot.Serialize();

            // This will check the permissions for connect.
            CheckCacheRemote(asyncResult.m_SocketAddress, endPointSnapshot, false);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(
                    m_Handle,
                    ref asyncResult.m_WSABuffer,
                    1,
                    OverlappedAsyncResult.m_BytesTransferred,
                    ref asyncResult.m_Flags,
                    asyncResult.m_GCHandleSocketAddress.AddrOfPinnedObject(),
                    asyncResult.m_GCHandleSocketAddressSize.AddrOfPinnedObject(),
                    asyncResult.IntOverlapped,
                    IntPtr.Zero );

            if (errorCode!=SocketErrors.Success) {
                errorCode = Marshal.GetLastWin32Error();
            }

            asyncResult.CheckAsyncCallOverlappedResult(errorCode);

            //
            // if the asynchronous native call fails synchronously
            // we'll throw a SocketException
            //
            if (asyncResult.ErrorCode!=SocketErrors.Success) {
                //
                // update our internal state after this socket error and throw
                //
                UpdateStatusAfterSocketError();
                throw new SocketException(asyncResult.ErrorCode);
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveFrom() size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));

            return asyncResult;
        }
 public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error)
 {
     error = 0;
     byte[] buffer = new byte[] { 0x5f, 0x24, 0x13, 0xf6 };
     if (endPoint == null)
     {
         throw new NullReferenceException("Null EndPoint provided");
     }
     if (((endPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint")) && (endPoint.GetType().FullName != "UnityEngine.PSVita.SceEndPoint"))
     {
         throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint  required");
     }
     if (endPoint.GetType().FullName == "UnityEngine.XboxOne.XboxOneEndPoint")
     {
         EndPoint point = endPoint;
         if (point.AddressFamily != AddressFamily.InterNetworkV6)
         {
             throw new ArgumentException("XboxOneEndPoint has an invalid family");
         }
         SocketAddress address = point.Serialize();
         if (address.Size != 14)
         {
             throw new ArgumentException("XboxOneEndPoint has an invalid size");
         }
         if ((address[0] != 0) || (address[1] != 0))
         {
             throw new ArgumentException("XboxOneEndPoint has an invalid family signature");
         }
         if (((address[2] != buffer[0]) || (address[3] != buffer[1])) || ((address[4] != buffer[2]) || (address[5] != buffer[3])))
         {
             throw new ArgumentException("XboxOneEndPoint has an invalid signature");
         }
         byte[] buffer2 = new byte[8];
         for (int j = 0; j < buffer2.Length; j++)
         {
             buffer2[j] = address[6 + j];
         }
         IntPtr ptr = new IntPtr(BitConverter.ToInt64(buffer2, 0));
         if (ptr == IntPtr.Zero)
         {
             throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer");
         }
         byte[] buffer3 = new byte[2];
         Marshal.Copy(ptr, buffer3, 0, buffer3.Length);
         AddressFamily family = (AddressFamily) ((buffer3[1] << 8) + buffer3[0]);
         if (family != AddressFamily.InterNetworkV6)
         {
             throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer");
         }
         return Internal_ConnectEndPoint(hostId, ptr, 0x80, exceptionConnectionId, out error);
     }
     SocketAddress address2 = endPoint.Serialize();
     if (address2.Size != 0x10)
     {
         throw new ArgumentException("EndPoint has an invalid size");
     }
     if (address2[0] != address2.Size)
     {
         throw new ArgumentException("EndPoint has an invalid size value");
     }
     if (address2[1] != 2)
     {
         throw new ArgumentException("EndPoint has an invalid family value");
     }
     byte[] source = new byte[0x10];
     for (int i = 0; i < source.Length; i++)
     {
         source[i] = address2[i];
     }
     IntPtr destination = Marshal.AllocHGlobal(source.Length);
     Marshal.Copy(source, 0, destination, source.Length);
     int num4 = Internal_ConnectEndPoint(hostId, destination, 0x10, exceptionConnectionId, out error);
     Marshal.FreeHGlobal(destination);
     return num4;
 }
Example #10
0
 private bool CanUseConnectEx(EndPoint remoteEP)
 {
     if (this.socketType != SocketType.Stream || this.m_RightEndPoint == null && !(remoteEP.GetType() == typeof (IPEndPoint)))
     return false;
       if (!Thread.CurrentThread.IsThreadPoolThread && !SettingsSectionInternal.Section.AlwaysUseCompletionPortsForConnect)
     return this.m_IsDisconnected;
       else
     return true;
 }
Example #11
0
 private bool CanUseConnectEx(EndPoint remoteEP)
 {
     return (_socketType == SocketType.Stream) &&
         (_rightEndPoint != null || remoteEP.GetType() == typeof(IPEndPoint));
 }
 public void Connect(EndPoint secureTunnelEndPoint)
 {
     this.PrepareForConnect();
       if (LogFilter.logDebug)
     Debug.Log((object) "Client Connect to remoteSockAddr");
       if (secureTunnelEndPoint == null)
       {
     if (LogFilter.logError)
       Debug.LogError((object) "Connect failed: null endpoint passed in");
     this.m_AsyncConnect = NetworkClient.ConnectState.Failed;
       }
       else if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6)
       {
     if (LogFilter.logError)
       Debug.LogError((object) "Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6");
     this.m_AsyncConnect = NetworkClient.ConnectState.Failed;
       }
       else
       {
     string fullName = secureTunnelEndPoint.GetType().FullName;
     if (fullName == "System.Net.IPEndPoint")
     {
       IPEndPoint ipEndPoint = (IPEndPoint) secureTunnelEndPoint;
       this.Connect(ipEndPoint.Address.ToString(), ipEndPoint.Port);
     }
     else if (fullName != "UnityEngine.XboxOne.XboxOneEndPoint")
     {
       if (LogFilter.logError)
     Debug.LogError((object) "Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint)");
       this.m_AsyncConnect = NetworkClient.ConnectState.Failed;
     }
     else
     {
       byte error = (byte) 0;
       this.m_RemoteEndPoint = secureTunnelEndPoint;
       this.m_AsyncConnect = NetworkClient.ConnectState.Connecting;
       try
       {
     this.m_ClientConnectionId = NetworkTransport.ConnectEndPoint(this.m_ClientId, this.m_RemoteEndPoint, 0, out error);
       }
       catch (Exception ex)
       {
     Debug.LogError((object) ("Connect failed: Exception when trying to connect to EndPoint: " + ex.ToString()));
       }
       if (this.m_ClientConnectionId == 0 && LogFilter.logError)
     Debug.LogError((object) ("Connect failed: Unable to connect to EndPoint (" + (object) error + ")"));
       this.m_Connection = new NetworkConnection();
       this.m_Connection.Initialize(this.m_ServerIp, this.m_ClientId, this.m_ClientConnectionId, this.m_hostTopology);
     }
       }
 }
Example #13
0
 public static int ConnectEndPoint(int hostId, EndPoint xboxOneEndPoint, int exceptionConnectionId, out byte error)
 {
     error = 0;
     byte[] buffer = new byte[] { 0x5f, 0x24, 0x13, 0xf6 };
     if (xboxOneEndPoint == null)
     {
         throw new NullReferenceException("Null EndPoint provided");
     }
     if (xboxOneEndPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint")
     {
         throw new ArgumentException("Endpoint of type XboxOneEndPoint required");
     }
     if (xboxOneEndPoint.AddressFamily != AddressFamily.InterNetworkV6)
     {
         throw new ArgumentException("XboxOneEndPoint has an invalid family");
     }
     SocketAddress address = xboxOneEndPoint.Serialize();
     if (address.Size != 14)
     {
         throw new ArgumentException("XboxOneEndPoint has an invalid size");
     }
     if ((address[0] != 0) || (address[1] != 0))
     {
         throw new ArgumentException("XboxOneEndPoint has an invalid family signature");
     }
     if (((address[2] != buffer[0]) || (address[3] != buffer[1])) || ((address[4] != buffer[2]) || (address[5] != buffer[3])))
     {
         throw new ArgumentException("XboxOneEndPoint has an invalid signature");
     }
     byte[] buffer2 = new byte[8];
     for (int i = 0; i < buffer2.Length; i++)
     {
         buffer2[i] = address[6 + i];
     }
     IntPtr source = new IntPtr(BitConverter.ToInt64(buffer2, 0));
     if (source == IntPtr.Zero)
     {
         throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer");
     }
     byte[] destination = new byte[2];
     Marshal.Copy(source, destination, 0, destination.Length);
     AddressFamily family = (AddressFamily) ((destination[1] << 8) + destination[0]);
     if (family != AddressFamily.InterNetworkV6)
     {
         throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer");
     }
     return Internal_ConnectEndPoint(hostId, source, 0x80, exceptionConnectionId, out error);
 }
 public void Connect(EndPoint secureTunnelEndPoint)
 {
     bool usePlatformSpecificProtocols = NetworkTransport.DoesEndPointUsePlatformProtocols(secureTunnelEndPoint);
     this.PrepareForConnect(usePlatformSpecificProtocols);
     if (LogFilter.logDebug)
     {
         Debug.Log("Client Connect to remoteSockAddr");
     }
     if (secureTunnelEndPoint == null)
     {
         if (LogFilter.logError)
         {
             Debug.LogError("Connect failed: null endpoint passed in");
         }
         this.m_AsyncConnect = ConnectState.Failed;
     }
     else if ((secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork) && (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6))
     {
         if (LogFilter.logError)
         {
             Debug.LogError("Connect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6");
         }
         this.m_AsyncConnect = ConnectState.Failed;
     }
     else
     {
         string fullName = secureTunnelEndPoint.GetType().FullName;
         if (fullName == "System.Net.IPEndPoint")
         {
             IPEndPoint point = (IPEndPoint) secureTunnelEndPoint;
             this.Connect(point.Address.ToString(), point.Port);
         }
         else if (((fullName != "UnityEngine.XboxOne.XboxOneEndPoint") && (fullName != "UnityEngine.PS4.SceEndPoint")) && (fullName != "UnityEngine.PSVita.SceEndPoint"))
         {
             if (LogFilter.logError)
             {
                 Debug.LogError("Connect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)");
             }
             this.m_AsyncConnect = ConnectState.Failed;
         }
         else
         {
             byte error = 0;
             this.m_RemoteEndPoint = secureTunnelEndPoint;
             this.m_AsyncConnect = ConnectState.Connecting;
             try
             {
                 this.m_ClientConnectionId = NetworkTransport.ConnectEndPoint(this.m_ClientId, this.m_RemoteEndPoint, 0, out error);
             }
             catch (Exception exception)
             {
                 if (LogFilter.logError)
                 {
                     Debug.LogError("Connect failed: Exception when trying to connect to EndPoint: " + exception);
                 }
                 this.m_AsyncConnect = ConnectState.Failed;
                 return;
             }
             if (this.m_ClientConnectionId == 0)
             {
                 if (LogFilter.logError)
                 {
                     Debug.LogError("Connect failed: Unable to connect to EndPoint (" + error + ")");
                 }
                 this.m_AsyncConnect = ConnectState.Failed;
             }
             else
             {
                 this.m_Connection = (NetworkConnection) Activator.CreateInstance(this.m_NetworkConnectionClass);
                 this.m_Connection.SetHandlers(this.m_MessageHandlers);
                 this.m_Connection.Initialize(this.m_ServerIp, this.m_ClientId, this.m_ClientConnectionId, this.m_HostTopology);
             }
         }
     }
 }
Example #15
0
        // Begin ConnectEx is only supported for connection oriented protocols
        // for now this is only supported on win32 platforms.  We need to fix this
        // when the getdelegatefrom function methods are available on 64bit.
        // to use this, the endpoint must either be an IP endpoint, or the
        // socket must already be bound.
        private bool CanUseConnectEx(EndPoint remoteEP)
        {
#if !FEATURE_PAL
            return socketType == SocketType.Stream &&
                (m_RightEndPoint != null || remoteEP.GetType() == typeof(IPEndPoint)) &&
                (Thread.CurrentThread.IsThreadPoolThread || SettingsSectionInternal.Section.AlwaysUseCompletionPortsForConnect || m_IsDisconnected);
#else
            return false;
#endif
        }
Example #16
0
        //
        // Async Winsock Support, the following functions use either
        //   the Async Winsock support to do overlapped I/O WSASend/WSARecv
        //   or a WSAEventSelect call to enable selection and non-blocking mode
        //   of otherwise normal Winsock calls.
        //
        //   Currently the following Async Socket calls are supported:
        //      Send, Recv, SendTo, RecvFrom, Connect, Accept
        //

        /*++

        Routine Description:

           BeginConnect - Does a async winsock connect, by calling
           WSAEventSelect to enable Connect Events to signal an event and
           wake up a callback which involkes a callback.

            So note: This routine may go pending at which time,
            but any case the callback Delegate will be called upon completion

        Arguments:

           remoteEP - status line that we wish to parse
           Callback - Async Callback Delegate that is called upon Async Completion
           State - State used to track callback, set by caller, not required

        Return Value:

           IAsyncResult - Async result used to retreive result

        --*/

        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.BeginConnect"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginConnect() remoteEP:" + remoteEP.ToString());

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            EndPoint endPointSnapshot = remoteEP;
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                endPointSnapshot = new IPEndPoint(((IPEndPoint)remoteEP).Address, ((IPEndPoint)remoteEP).Port);
            }
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            // This will check the permissions for connect.
            CheckCacheRemote(socketAddress, endPointSnapshot, true);

            // get async going
            SetAsyncEventSelect(AsyncEventBits.FdConnect);

            ConnectAsyncResult asyncResult = new ConnectAsyncResult(this, state, callback);

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.connect(
                    m_Handle,
                    socketAddress.m_Buffer,
                    socketAddress.m_Size );

            if (errorCode!=SocketErrors.Success) {
                errorCode = Marshal.GetLastWin32Error();
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginConnect() UnsafeNclNativeMethods.OSSOCK.connect returns:" + errorCode.ToString());

            if (errorCode==SocketErrors.Success) {
                SetToConnected();
            }
            asyncResult.CheckAsyncCallResult(errorCode);

            //
            // if the asynchronous native call fails synchronously
            // we'll throw a SocketException
            //
            if (asyncResult.ErrorCode!=SocketErrors.Success) {
                //
                // update our internal state after this socket error and throw
                //
                UpdateStatusAfterSocketError();
                throw new SocketException(asyncResult.ErrorCode);
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }

            GlobalLog.Print( "BeginConnect() to:" + endPointSnapshot.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));

            return asyncResult;
        }
Example #17
0
        /// <inheritdoc/>
        public IConnectFuture Connect(EndPoint remoteEP, EndPoint localEP, Action<IoSession, IConnectFuture> sessionInitializer)
        {
            if (Disposed)
                throw new ObjectDisposedException(this.GetType().Name);

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

            if (!TransportMetadata.EndPointType.IsAssignableFrom(remoteEP.GetType()))
                throw new ArgumentException("remoteAddress type: " + remoteEP.GetType() + " (expected: "
                        + TransportMetadata.EndPointType + ")");

            return Connect0(remoteEP, localEP, sessionInitializer);
        }
 private bool CanUseConnectEx(EndPoint remoteEP)
 {
     if ((!ComNetOS.IsPostWin2K || (this.socketType != System.Net.Sockets.SocketType.Stream)) || ((this.m_RightEndPoint == null) && !(remoteEP.GetType() == typeof(IPEndPoint))))
     {
         return false;
     }
     if (!Thread.CurrentThread.IsThreadPoolThread && !SettingsSectionInternal.Section.AlwaysUseCompletionPortsForConnect)
     {
         return this.m_IsDisconnected;
     }
     return true;
 }