BeginRead() public method

public BeginRead ( byte buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState ) : IAsyncResult
buffer byte
offset int
count int
asyncCallback AsyncCallback
asyncState object
return IAsyncResult
Esempio n. 1
0
        public void ConnectSecure(string hostname, int port, bool useEvents = true, bool validateServerCertificate = true)
        {
            if (Client.Connected)
            {
                throw new InvalidOperationException("Unable to connect: client is already connected");
            }

            Client.Connect(hostname, port);
            if (OnLocalPortKnown != null)
            {
                Task.Run(() => OnLocalPortKnown(((IPEndPoint)Client.Client.LocalEndPoint).Port));
            }
            var sslStream = new SslStream(Client.GetStream(), false, validateServerCertificate ? new RemoteCertificateValidationCallback(ValidateServerCertificate) : null, null);
            sslStream.AuthenticateAsClient(hostname);

            Log(string.Format("SSL Connection established: Cipher: {0}-bit {1}; KEX: {2} {3}-bit; Hash: {4} {5}-bit",
                sslStream.CipherStrength, sslStream.CipherAlgorithm,
                sslStream.KeyExchangeAlgorithm, sslStream.KeyExchangeStrength,
                sslStream.HashAlgorithm, sslStream.HashStrength));
            ConnectionStream = sslStream;

            readBuffer = new byte[Client.ReceiveBufferSize];
            if (useEvents)
            {
                EnterReadLoop();
                sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, Client);
            }
        }
        /// <summary>Connects the client to the server.</summary>
        /// <param name="serverPort">The port for the server to use for this connection</param>
        /// <param name="machineName">The host running the server application</param>
        /// <param name="serverName">The machine name for the server, must match the machine name in the server certificate</param>
        /// <param name="stream"></param>
        /// <param name="fileSize"></param>
        /// <param name="offset"></param>
        private void Connect(int serverPort, string machineName, string serverName, FileStream stream, long fileSize, long offset)
        {
            // Create a TCP/IP client socket.
            // Set up a temporary connection that is unencrypted, used to transfer the certificates?
            try {
                client = new TcpClient(machineName, serverPort);
                Debug.WriteLine("Client connected.");
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Host or machine name is null", argExp);
            } catch (ArgumentOutOfRangeException argORExp) {
                throw new ConnectionException("The Port is incorrect", argORExp);
            } catch (SocketException argSExp) {
                throw new ConnectionException("There is a problem with the Socket", argSExp);
            }

            // Create an SSL stream that will close the client's stream.
            // TODO: The validate server certificate allways returns true
            //       If the validation fails we should ask the user to connect anyway
            sslStream = new SslStream(client.GetStream(),
                                      false,
                                      ValidateServerCertificate,
                                      null);

            // The server name must match the name on the server certificate.
            try {
                sslStream.AuthenticateAsClient(serverName);
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Target host is null", argExp);
            } catch (AuthenticationException argExp) {
                throw new ConnectionException("The authentication failed and left this object in an unusable state.", argExp);
            } catch (InvalidOperationException argExp) {
                throw new ConnectionException("Authentication has already occurred or Server authentication using this SslStream was tried previously org Authentication is already in progress.", argExp);
            }

            // When we are connected we can now set up our receive mechanism
            var readBuffer = new byte[BUFFER_SIZE];
            var stateObj = new FileTransferStateObject();
            stateObj.fileSize = fileSize;
            stateObj.sslStream = sslStream;
            stateObj.target = stream;
            stateObj.transferBuffer = readBuffer;
            stateObj.transferOffset = offset;

            TimeOfLastNotify = DateTime.Now;

            sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, stateObj);
        }
Esempio n. 3
0
        public async Task ConnectSecureAsync(string hostname, int port, bool useEvents = true, bool validateServerCertificate = true)
        {
            var t = Client.ConnectAsync(hostname, port);
            await t;
            if (OnLocalPortKnown != null)
            {
                t = Task.Run(() => OnLocalPortKnown(((IPEndPoint)Client.Client.LocalEndPoint).Port));
            }
            var sslStream = new SslStream(Client.GetStream(), false, validateServerCertificate ? new RemoteCertificateValidationCallback(ValidateServerCertificate) : null, null);
            var result = sslStream.AuthenticateAsClientAsync(hostname);
            ConnectionStream = sslStream;

            readBuffer = new byte[Client.ReceiveBufferSize];
            if (useEvents)
            {
                await result;
                Log(string.Format("SSL Connection established: Cipher: {1} ({0}-bit); KEX: {2} ({3}-bit); Hash: {4} ({5}-bit)",
                    sslStream.CipherStrength, sslStream.CipherAlgorithm,
                    sslStream.KeyExchangeAlgorithm, sslStream.KeyExchangeStrength,
                    sslStream.HashAlgorithm, sslStream.HashStrength));
                EnterReadLoop();
                sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, Client);
            }
        }
        private static void HandleSslConnect(ConnectToRemoteState state)
        {
            var connectStreamWriter = new StreamWriter(state.ClientStream);
            connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
            connectStreamWriter.WriteLine("Timestamp: {0}", DateTime.Now);
            connectStreamWriter.WriteLine("Proxy-agent: GOS Proxy Service");
            connectStreamWriter.WriteLine();
            connectStreamWriter.Flush();

            var sslStream = new SslStream(state.ClientStream, false);
            try
            {
                var certProvider = new CertificateProvider();

                bool created;
                var certificate = certProvider.LoadOrCreateCertificate(state.RemoteHost, out created);
                sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
            }
            catch (Exception ex)
            {
                WriteLog(state.Session, 0, "ERR", ex.Message);
                sslStream.Close();
                state.ClientStream.Close();
                connectStreamWriter.Close();
                return;
            }

            var nstate = new ClientConnectionState
            {
                Session = state.Session,
                Client = state.Client,
                ClientStream = sslStream,
                ClientStreamBase = (NetworkStream)state.ClientStream,
                Buffer = new byte[Globals.BufferSize],
                MessageStream = new MemoryStream(),
                IsSsl = true,
            };

            try
            {
                sslStream.BeginRead(nstate.Buffer, 0, nstate.Buffer.Length, ReadFromClient.Run, nstate);
            }
            catch (Exception ex)
            {
                WriteLog(state.Session, 0, "ERR", ex.Message);
                sslStream.Close();
                state.ClientStream.Close();
            }
        }
 /// <summary>
 ///     Assign a socket to this channel
 /// </summary>
 /// <param name="socket">Connected socket</param>
 /// <remarks>
 ///     the channel will start receive new messages as soon as you've called assign.
 /// </remarks>
 public void Assign(Socket socket)
 {
     _stream = _sslStreamBuilder.Build(this, socket);
     _stream.BeginRead(_readBuffer.Buffer, _readBuffer.Offset, _readBuffer.Capacity, OnReadCompleted, null);
 }
        private void AcceptCallback(IAsyncResult result)
        {
            // accept the client
            TcpListener listener = (TcpListener)result.AsyncState;
            TcpClient client = listener.EndAcceptTcpClient(result);
            ViewModel.TS_LogMessage("Client connected!");

            // set up SSL
            SslStream sslStream = new SslStream(client.GetStream(), false);
            sslStream.AuthenticateAsServer(ServerCertificate, false, SslProtocols.Tls, true);

            // create the user session
            ConnectionStateObject state = new ConnectionStateObject();
            state.client = client;
            state.stream = sslStream;

            // begin reading from the client
            ViewModel.TS_LogMessage("Awaiting client message...");
            sslStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ReceiveCallback), state);

            // start accepting again
            listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), listener);
        }
        public bool Connect()
        {
            try
            {
                client = new TcpClient(serverEndPoint.Address.ToString(), serverEndPoint.Port);
            }
            catch (SocketException e)
            {
                Console.WriteLine("failed to connect to notification server: " + e.Message);
                if (e.InnerException != null) Console.WriteLine(e.InnerException);
                return false;
            }

            sslStream = new SslStream(client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateRemoteCertificate));

            // Set timeouts
            sslStream.ReadTimeout = timeout;
            sslStream.WriteTimeout = timeout;

            try
            {
                sslStream.AuthenticateAsClient(serverEndPoint.Address.ToString(), clientCerts,
                    SslProtocols.Tls, false);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("authenticating notification SSL client failed, "
                    + e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("inner exception: "
                        + e.InnerException.Message);
                }
                client.Close();
                return false;
            }

            Console.WriteLine("ssl connection established to notification server");

            sslStream.BeginRead(recvBuf, 0, recvBuf.Length, new AsyncCallback(Receive), this);

            //generateNotification(NotificationMessage.Type.test, "Test.Notification-Wut");

            return true;
        }
        /// <summary>
        ///     Assign a socket to this channel
        /// </summary>
        /// <param name="socket">Connected socket</param>
        /// <remarks>
        ///     the channel will start receive new messages as soon as you've called assign.
        /// </remarks>
        public void Assign(Socket socket)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            if (MessageReceived == null)
                throw new InvalidOperationException("Must handle the MessageReceived callback before invoking this method.");

            _stream = _sslStreamBuilder.Build(this, socket);
            _stream.BeginRead(_readBuffer.Buffer, _readBuffer.Offset, _readBuffer.Capacity, OnReadCompleted, null);
        }
Esempio n. 9
0
        /// <summary>Connects the client to the server.</summary>
        /// <param name="serverPort">The port for the server to use for this connection</param>
        /// <param name="machineName">The host running the server application</param>
        /// <param name="serverName">The machine name for the server, must match the machine name in the server certificate</param>
        private void Connect(int serverPort, string machineName, string serverName)
        {
            // Create a TCP/IP client socket.
            // Set up a temporary connection that is unencrypted, used to transfer the certificates?
            try {
                client = new TcpClient(machineName, serverPort);
                Debug.WriteLine("Client connected.");
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("HostOrMachineNameIsNull", argExp);
            } catch (ArgumentOutOfRangeException argORExp) {
                throw new ConnectionException("ThePortIsIncorrect", argORExp);
            } catch (SocketException argSExp) {
                var errorMessage = new StringBuilder();
                if (argSExp.ErrorCode == 11001) {
                    errorMessage.Append("HostNotFound");
                } else if (argSExp.ErrorCode == 10065) {
                    errorMessage.Append("NoRouteToTost");
                } else if (argSExp.ErrorCode == 10061) {
                    errorMessage.Append("ConnectionRefused");
                } else {
                    errorMessage.Append("ErrorNotRecognized" + " Socket error code: '" + argSExp.ErrorCode + "'");
                }

                //TODO: Add more error codes from: http://msdn2.microsoft.com/en-us/library/ms740668.aspx

                throw new ConnectionException(errorMessage.ToString(), argSExp);
            }

            // Create an SSL stream that will close the client's stream.
            // TODO: The validate server certificate allways returns true
            //      If the validation fails we should ask the user to connect anyway
            sslStream = new SslStream(client.GetStream(), false, ValidateServerCertificate, null);

            // The server name must match the name on the server certificate.
            try {
                sslStream.AuthenticateAsClient(serverName);
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Target host is null", argExp);
            } catch (AuthenticationException argExp) {
                throw new ConnectionException("The authentication failed and left this object in an unusable state.", argExp);
            } catch (InvalidOperationException argExp) {
                throw new ConnectionException("Authentication has already occurred or Server authentication using this SslStream was tried previously org Authentication is already in progress.", argExp);
            }

            // When we are connected we can now set up our receive mechanism
            var readBuffer = new byte[buffer_size];
            sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, readBuffer);
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            MySocket socket = new MySocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
            socket.Connect(iep);
            MyNetworkStream stream = new MyNetworkStream(socket);
            SslStream sslStream = new SslStream(stream,false,new RemoteCertificateValidationCallback(ValidateServerCertificate),null );
            string msg = "hellodsffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffsdf,sdfwewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwfawwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww";
            byte[] data = Encoding.UTF8.GetBytes(msg);
            byte[] packet = new byte[6 + data.Length];
            byte[] lengthBytes = data.Length.ToCustomerBytes();
            Buffer.BlockCopy(lengthBytes, 0, packet, 2, lengthBytes.Length);
            Buffer.BlockCopy(data, 0, packet, 6, data.Length);
            sslStream.AuthenticateAsClient("127.0.0.1");
            Client client = new Client(sslStream);

            byte[] head = new byte[6];
            int contentLength = 50;
            byte[] contentLengthBytes = contentLength.ToCustomerBytes();
            Array.Copy(contentLengthBytes, 0, head, 2, contentLengthBytes.Length);
            client.Write(head);

            Thread.Sleep(1000);

            int firstPart = 25;
            client.Write(new byte[firstPart]);

            Thread.Sleep(1000);
            client.Write(new byte[contentLength - firstPart]);

            byte[] buff = new byte[1024];
            sslStream.BeginRead(buff, 0, buff.Length, ar =>
                {
                    int len=sslStream.EndRead(ar);
                    Console.WriteLine(len);
                }, null);
            Console.Read();
        }