Close() public method

Forces a SecureSocket connection to close.
public Close ( ) : void
return void
 public void Start()
 {
     // create a new ManualResetEvent. This will be used to make the main application
     // thread wait until the full server reply has been received.
     m_ResetEvent = new ManualResetEvent(false);
     // initialize the security options
     SecurityOptions options = new SecurityOptions(
         SecureProtocol.Ssl3 | SecureProtocol.Tls1,	// use SSL3 or TLS1
         null,										// do not use client authentication
         ConnectionEnd.Client,						// this is the client side
         CredentialVerification.None,				// do not check the certificate -- this should not be used in a real-life application :-)
         null,										// not used with automatic certificate verification
         "www.microsoft.com",						// this is the common name of the Microsoft web server
         SecurityFlags.Default,						// use the default security flags
         SslAlgorithms.SECURE_CIPHERS,				// only use secure ciphers
         null);										// do not process certificate requests.
     try {
         // create the securesocket with the specified security options
         m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // resolve www.microsoft.com
         IPEndPoint endpoint = new IPEndPoint(Dns.GetHostEntry("www.microsoft.com").AddressList[0], 443);
         // start connecting to www.microsoft.com
         m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
         // wait until the entire web page has been received
         m_ResetEvent.WaitOne();
         // close the SecureSocket
         m_Socket.Close();
     } catch {
         OnError("Could not connect to the website");
     }
 }
 /// <summary>
 /// Closes the stream and optionally closes the underlying <see cref="SecureSocket"/>.
 /// </summary>
 /// <remarks>
 /// The Close method frees resources used by the SecureNetworkStream instance and, if the SecureNetworkStream owns the underlying socket, closes the underlying socket.
 /// </remarks>
 public override void Close()
 {
     if (m_OwnsSocket)
     {
         try {
             Socket.Shutdown(SocketShutdown.Both);
         } catch {
         } finally {
             Socket.Close();
         }
     }
 }
Exemplo n.º 3
0
 private void DownloadFile(Url url, int choice)
 {
     SecurityOptions options = new SecurityOptions(SecureProtocol.None);;
     m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
     // connect to the FTP server using a normal TCP connection
     m_Socket.Connect(new IPEndPoint(Dns.GetHostEntry(url.Host).AddressList[0], url.Port));
     // wait for the server hello
     ReceiveReply();
     // if the user selected to use the AUTH command..
     if (choice == 2) {
         // ..send the command to the server and start the SSL handshake
         DoAuthCommand(url.Host);
     }
     // log on and quit
     if (!SendCommand("USER " + url.Username))
         return;
     if (!SendCommand("PASS " + url.Password))
         return;
     if (!SendCommand("QUIT"))
         return;
     // clean up
     m_Socket.Shutdown(SocketShutdown.Both);
     m_Socket.Close();
 }
        private void HandleAcceptedClient(SecureSocket incomingClient, ALPNExtensionMonitor monitor)
        {
            bool backToHttp11 = false;
            string selectedProtocol = Protocols.Http1;
            
            if (_useHandshake)
            {
                try
                {
                    if (_options.Protocol != SecureProtocol.None)
                    {
                        incomingClient.MakeSecureHandshake(_options);
                        selectedProtocol = incomingClient.SelectedProtocol;
                    }
                }
                catch (SecureHandshakeException ex)
                {
                    switch (ex.Reason)
                    {
                        case SecureHandshakeFailureReason.HandshakeInternalError:
                            backToHttp11 = true;
                            break;
                        case SecureHandshakeFailureReason.HandshakeTimeout:
                            incomingClient.Close();
                            Http2Logger.LogError("Handshake timeout. Client was disconnected.");
                            return;
                        default:
                            incomingClient.Close();
                            Http2Logger.LogError("Unknown error occurred during secure handshake");
                            return;
                    }
                }
                catch (Exception e)
                {
                    Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                    incomingClient.Close();
                    return;
                }
            }

            var clientStream = new DuplexStream(incomingClient, true);
            var transportInfo = GetTransportInfo(incomingClient);

            monitor.Dispose();

            try
            {
                HandleRequest(clientStream, selectedProtocol, transportInfo, backToHttp11);
            }
            catch (Exception e)
            {
                Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                incomingClient.Close();
            }
        }
Exemplo n.º 5
0
		//sendraw SSL
		public string sendraw (string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, int retry, bool useSSL) {
			
			IPHostEntry IPHost = Dns.Resolve(ipRaw); 
			string []aliases = IPHost.Aliases; 
			IPAddress[] addr = IPHost.AddressList; 
			IPEndPoint iep ;
			SecureProtocol sp;
			sp=SecureProtocol.Ssl3;
			SecureSocket s=null; 
			SecurityOptions options = new SecurityOptions(sp);
			options.Certificate = null;
			options.Protocol=SecureProtocol.Ssl3;
			options.Entity = ConnectionEnd.Client;
			options.CommonName = ipRaw;
			options.VerificationType = CredentialVerification.None;
			options.Flags = SecurityFlags.IgnoreMaxProtocol;
			options.AllowedAlgorithms = SslAlgorithms.ALL;

			while (retry>0){
				try {
				
					s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
					s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000);
					s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000);
			
					iep	= new IPEndPoint(addr[0],Convert.ToInt32(portRaw));
					s.Connect(iep);

					ASCIIEncoding asen= new ASCIIEncoding();
					byte[] ba=asen.GetBytes(payloadRaw);
					s.Send(ba,ba.Length,System.Net.Sockets.SocketFlags.None);
					

					byte[] bb=new byte[size];
					
					int k=1;
					string response="";
					while (k>0){
						k=s.Receive(bb,size,System.Net.Sockets.SocketFlags.None);					
						response+=Encoding.Default.GetString(bb,0,k);
					}
					s.Close();
					GC.Collect();
					GC.WaitForPendingFinalizers();

					return response;

				}
				catch(Exception ex) {
					retry--;
					Thread.Sleep(1000);
				}
			}
			
			return "Timeout or retry count exceeded";
		}
Exemplo n.º 6
0
        public static void Http11SendResponse(SecureSocket socket)
        {
            string[] headers = GetHttp11Headers(socket);
            string filename = GetFileName(headers);

            if (headers.Length == 0)
            {
                Http2Logger.LogError("Request headers empty!");
            }

            string path = Path.GetFullPath(AssemblyPath + @"\root" + filename);
            string contentType = ContentTypes.GetTypeFromFileName(filename);
            if (!File.Exists(path))
            {
                Http2Logger.LogError("File " + filename + " not found");
                SendResponse(socket, new byte[0], StatusCode.Code404NotFound, contentType);
                socket.Close();
                return;
            }

            try
            {
                using (var sr = new StreamReader(path))
                {
                    string file = sr.ReadToEnd();

                    var fileBytes = Encoding.UTF8.GetBytes(file);

                    int sent = SendResponse(socket, fileBytes, StatusCode.Code200Ok, contentType);
                    Http2Logger.LogDebug(string.Format("Sent: {0} bytes", sent));
                    Http2Logger.LogInfo("File sent: " + filename);

                    socket.Close();

                    if (OnSocketClosed != null)
                    {
                        OnSocketClosed(null, new SocketCloseEventArgs());
                    }
                }
            }
            catch (Exception ex)
            {
                var msgBytes = Encoding.UTF8.GetBytes(ex.Message);
                SendResponse(socket, msgBytes, StatusCode.Code500InternalServerError, contentType);
                Http2Logger.LogError(ex.Message);
            }
        }
Exemplo n.º 7
0
        public static void Http11DownloadResource(SecureSocket socket, Uri requestUri)
        {
            byte[] headersBytes = Encoding.UTF8.GetBytes(ConstructHeaders(requestUri));
            int sent = socket.Send(headersBytes);

            string[] responseHeaders = ReadHeaders(socket);

            var buffer = new byte[128 * 1024]; //128 kb
            using (var stream = new MemoryStream(128 * 1024))
            {
                while (true)
                {
                    int received = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                    if (received == 0)
                        break;

                    stream.Write(buffer, 0, received);
                }

                var fileBuffer = new byte[stream.Position];
                Buffer.BlockCopy(stream.GetBuffer(), 0, fileBuffer, 0, fileBuffer.Length);
                int fileNameIndex = requestUri.AbsolutePath.LastIndexOf("/");
                string fileName = requestUri.AbsolutePath.Substring(fileNameIndex);

                string directory = AssemblyPath;
                SaveFile(directory, fileName, fileBuffer);

                if (OnDownloadSuccessful != null)
                {
                    OnDownloadSuccessful(null, new Http11ResourceDownloadedEventArgs(fileBuffer.Length, fileName));
                }

                socket.Close();

                if (OnSocketClosed != null)
                {
                    OnSocketClosed(null, new SocketCloseEventArgs());
                }
            }
        }
Exemplo n.º 8
0
        private void HandleAcceptedClient(SecureSocket incomingClient)
        {
            bool backToHttp11 = false;
            string alpnSelectedProtocol = "http/2.0";
            var handshakeEnvironment = MakeHandshakeEnvironment(incomingClient);
            IDictionary<string, object> handshakeResult = null;

            //Think out smarter way to get handshake result.
            //DO NOT change Middleware function. If you will do so, server will not even launch. (It's owin's problem)
            Func<Task> handshakeAction = () =>
                {
                    var handshakeTask = new Task(() =>
                        {
                            handshakeResult = HandshakeManager.GetHandshakeAction(handshakeEnvironment).Invoke();
                        });
                    return handshakeTask;
                };
            
            if (_useHandshake)
            {
                var environment = new Dictionary<string, object>
                    {
                        //Sets the handshake action depends on port.
                        {"HandshakeAction", handshakeAction},
                    };

                try
                {
                    var handshakeTask = _next(environment);
                    
                    handshakeTask.Start();
                    if (!handshakeTask.Wait(6000))
                    {
                        incomingClient.Close();
                        Console.WriteLine("Handshake timeout. Connection dropped.");
                        return;
                    }
                    
                    alpnSelectedProtocol = incomingClient.SelectedProtocol;
                }
                catch (Http2HandshakeFailed ex)
                {
                    if (ex.Reason == HandshakeFailureReason.InternalError)
                    {
                        backToHttp11 = true;
                    }
                    else
                    {
                        incomingClient.Close();
                        Console.WriteLine("Handshake timeout. Client was disconnected.");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occured. Closing client's socket. " + e.Message);
                    incomingClient.Close();
                    return;
                }
            }
            try
            {
                HandleRequest(incomingClient, alpnSelectedProtocol, backToHttp11, handshakeResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured. Closing client's socket. " + e.Message);
                incomingClient.Close();
            }
        }
Exemplo n.º 9
0
        private void HandleRequest(SecureSocket incomingClient, string alpnSelectedProtocol, 
                                   bool backToHttp11, IDictionary<string, object> handshakeResult)
        {
            if (backToHttp11 || alpnSelectedProtocol == "http/1.1")
            {
                Console.WriteLine("Sending with http11");
                Http11Manager.Http11SendResponse(incomingClient);
                return;
            }

            if (GetSessionHeaderAndVerifyIt(incomingClient))
            {
                OpenHttp2Session(incomingClient, handshakeResult);
            }
            else
            {
                Console.WriteLine("Client has wrong session header. It was disconnected");
                incomingClient.Close();
            }
        }
Exemplo n.º 10
0
        private void HandleRequest(SecureSocket incomingClient, string alpnSelectedProtocol, 
                                   bool backToHttp11, IDictionary<string, object> environment)
        {
            if (backToHttp11 || alpnSelectedProtocol == Protocols.Http1)
            {
                Http2Logger.LogDebug("Sending with http11");
                Http11Manager.Http11SendResponse(incomingClient);
                return;
            }

            if (GetSessionHeaderAndVerifyIt(incomingClient))
            {
                OpenHttp2Session(incomingClient, environment);
            }
            else
            {
                Http2Logger.LogError("Client has wrong session header. It was disconnected");
                incomingClient.Close();
            }
        }
Exemplo n.º 11
0
        public string sendraw(string ipRaw, string portRaw, string payloadRaw, int size, int TimeOut, bool useSSL)
        {
            int retry = (int)updownRetryTCP.Value;
            IPHostEntry IPHost = Dns.GetHostEntry(ipRaw);
            //IPHostEntry IPHost = Dns.Resolve(ipRaw); 
            string[] aliases = IPHost.Aliases;
            IPAddress[] addr = IPHost.AddressList;
            IPEndPoint iep;
            SecureProtocol sp;
            sp = SecureProtocol.Ssl3;
            SecureSocket s = null;
            SecurityOptions options = new SecurityOptions(sp);
            options.Certificate = null;
            options.Protocol = SecureProtocol.Ssl3;
            options.Entity = ConnectionEnd.Client;
            options.CommonName = ipRaw;
            options.VerificationType = CredentialVerification.None;
            options.Flags = SecurityFlags.IgnoreMaxProtocol;
            options.AllowedAlgorithms = SslAlgorithms.ALL;

            while (retry > 0)
            {
                try
                {

                    s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 4000);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 4000);

                    iep = new IPEndPoint(addr[0], Convert.ToInt32(portRaw));


                    s.Connect(iep);


                    ASCIIEncoding asen = new ASCIIEncoding();
                    byte[] ba = asen.GetBytes(payloadRaw);
                    s.Send(ba, ba.Length, System.Net.Sockets.SocketFlags.None);

                    byte[] bb = new byte[size];


                    string response = "";
                    int k = 1;
                    while (k > 0)
                    {
                        k = s.Receive(bb, size, System.Net.Sockets.SocketFlags.None);
                        for (int i = 0; i < k; i++)
                        {
                            response += Convert.ToChar(bb[i]);
                        }
                    }
                    s.Close();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    return response;

                }


                catch
                {
                    retry--;
                    lblStatus.Text = "Network problem - retrying\r\n";
                    lblNiktoAI.Text = "Network problem - retrying\r\n";
                    Thread.Sleep(1000);
                }
            }

            return "Retry count (" + updownRetryTCP.Value.ToString() + ") exceeded";
        }
Exemplo n.º 12
0
        private void HandleAcceptedClient(SecureSocket incomingClient)
        {
            bool backToHttp11 = false;
            string selectedProtocol = Protocols.Http2;
            var handshakeEnv = MakeHandshakeEnvironment(incomingClient);
            var environmentCopy = new Dictionary<string, object>(_environment);

            if (_useHandshake)
            {
                try
                {
                    //_next(environmentCopy);

                    bool wasHandshakeFinished = true;
                    var handshakeTask = Task.Factory.StartNew(HandshakeManager.GetHandshakeAction(handshakeEnv));

                    if (!handshakeTask.Wait(6000))
                    {
                        wasHandshakeFinished = false;
                    }

                    if (!wasHandshakeFinished)
                    {
                        throw new Http2HandshakeFailed(HandshakeFailureReason.Timeout);
                    }

                    environmentCopy.Add("HandshakeResult", handshakeTask.Result);
                    selectedProtocol = incomingClient.SelectedProtocol;
                }
                catch (Http2HandshakeFailed ex)
                {
                    if (ex.Reason == HandshakeFailureReason.InternalError)
                    {
                        backToHttp11 = true;
                    }
                    else
                    {
                        incomingClient.Close();
                        Http2Logger.LogError("Handshake timeout. Client was disconnected.");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                    incomingClient.Close();
                    return;
                }
            }
            try
            {
                HandleRequest(incomingClient, selectedProtocol, backToHttp11, environmentCopy);
            }
            catch (Exception e)
            {
                Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
                incomingClient.Close();
            }
        }
        private SecureSocket CreateSocketByUri(Uri uri)
        {
            if (!String.Equals(uri.Scheme, "http", StringComparison.OrdinalIgnoreCase) &&
                !String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("Unrecognized scheme: " + uri.Scheme);

            SecurityOptions options;
            var extensions = new ExtensionType[] { ExtensionType.Renegotiation, ExtensionType.ALPN };
            if (!String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
            {
                options = new SecurityOptions(SecureProtocol.None, null, ConnectionEnd.Client);
            }
            else
            {
                options = new SecurityOptions(SecureProtocol.Tls1, extensions, ConnectionEnd.Client);
            }

            options.Entity = ConnectionEnd.Client;
            options.CommonName = uri.Host;
            options.VerificationType = CredentialVerification.None;
            options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(@"certificate.pfx");
            options.Flags = SecurityFlags.Default;
            options.AllowedAlgorithms = SslAlgorithms.RSA_AES_128_SHA | SslAlgorithms.NULL_COMPRESSION;

            var s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
            s.OnClose += SocketOnClose;

            try
            {
                if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                {
                    s.OnHandshakeFinish += this.HandshakeFinishedHandler;
                }

                s.Connect(new Net.DnsEndPoint(uri.Host, uri.Port));

                if (String.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                {

                    this.handshakeFinishedEventRaised.WaitOne(60000);

                    if (!s.IsNegotiationCompleted)
                    {
                        throw new Exception("Handshake failed");
                    }

                    if (!s.Connected)
                    {
                        throw new Exception("Connection was lost!");
                    }

                    s.OnHandshakeFinish -= this.HandshakeFinishedHandler;

                    this.ApplyProtocolSelectionResults(options.GetSelectedProtocol());
                }
            }
            catch (Exception ex)
            {
                s.Close();
                // Emitting protocol error. It will emit session OnError
                if (OnError != null)
                    this.OnError(this, new ProtocolErrorEventArgs(ex));

                throw;
            }

            return s;
        }
Exemplo n.º 14
0
        public static void Http11SendResponse(SecureSocket socket)
        {
            string[] headers = GetHttp11Headers(socket);
            string filename = GetFileName(headers);

            //No headers where received
            if (headers.Length == 0)
            {
                socket.Close();
            }

            string path = Path.GetFullPath(AssemblyPath + @"\root" + filename);

            if (!File.Exists(path))
            {
                Console.WriteLine("File " + filename + " not found");
                return;
            }

            try
            {
                using (var sr = new StreamReader(path))
                {
                    string file = sr.ReadToEnd();
                    SendHeaders(socket, null, file.Length);

                    var fileBytes = Encoding.UTF8.GetBytes(file);

                    int sent = socket.Send(fileBytes);
                    Console.WriteLine("Sent: " + sent);
                    Console.WriteLine("File sent: " + filename);

                    socket.Close();

                    if (OnSocketClosed != null)
                    {
                        OnSocketClosed(null, new SocketCloseEventArgs());
                    }
                }
            }
            catch (Exception ex)
            {
                var msgBytes = Encoding.UTF8.GetBytes(ex.Message);
                socket.Send(msgBytes);

                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 15
0
 public void Start()
 {
     try {
         // ask the user for SMTP server, port and the type of connection
         Console.Write("Host to connect to: ");
         string server = Console.ReadLine().Trim();
         Console.Write("Port: ");
         string port = Console.ReadLine().Trim();
         Console.Write("Connection type [0 = normal connection, 1 = direct TLS connection, 2 = indirect TLS connection (using STARTTLS command)]: ");
         string type = Console.ReadLine().Trim();
         if (Array.IndexOf(new string[]{"0", "1", "2"}, type) == -1) {
             Console.WriteLine("Invalid connection type.");
             return;
         }
         Console.WriteLine("Please enter the email address you wish to send an email to:");
         string address = Console.ReadLine().Trim();
         // create a new SecurityOptions instance
         SecurityOptions options = new SecurityOptions(SecureProtocol.None);
         // allow only secure ciphers to be used. Currently, the seure ciphers are:
         // the AES algorithm [128 or 256 bit keys], the RC4 algorithm [128 bit keys]
         // or TipleDES [168 bit keys]
         options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
         // the SecureSocket should be a client socket
         options.Entity = ConnectionEnd.Client;
         // we will use manual verification of the server certificate
         options.VerificationType = CredentialVerification.Manual;
         // when the server certificate is receives, the SecureSocket should call
         // the OnVerify method
         options.Verifier = new CertVerifyEventHandler(OnVerify);
         // use the default flags
         options.Flags = SecurityFlags.Default;
         // the common name is the domain name or IP address of the server
         options.CommonName = server;
         // if the user chose a direct TLS connection, set the protocol to TLS1
         if (type == "1") {
             options.Protocol = SecureProtocol.Tls1;
         }
         // create the new secure socket
         Connection = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // connect to the SMTP server
         Connection.Connect(new IPEndPoint(Dns.GetHostEntry(server).AddressList[0], int.Parse(port)));
         // wait for the server hello message
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("Server disallowed connection.");
             return;
         }
         // if the user selected an indirect TLS connection, issue
         // a EHLO command. Otherwise, stick to the standard HELO command.
         if (type == "2") // STARTTLS connection
             Send("EHLO SmtpClient.Mentalis.org\r\n");
         else
             Send("HELO SmtpClient.Mentalis.org\r\n");
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("HELLO failed.");
             return;
         }
         // if the user selected an indirect TLS connection, issue
         // the STARTTLS command
         if (type == "2") {
             // send the STARTTLS command to the server
             Send("STARTTLS\r\n");
             // make sure the server supports the STARTTLS command
             if (!IsReplyOK(Receive())) {
                 Console.WriteLine("STARTTLS failed.");
                 return;
             }
             // change the protocol from SecureProtocol.None
             // to SecureProtocol.Tls1
             options.Protocol = SecureProtocol.Tls1;
             // start the TLS handshake
             Connection.ChangeSecurityProtocol(options);
             // after this line, we're using an encrypted TLS connection
         }
         // from here on, act as if the SecureSocket is a normal Socket
         Send("MAIL FROM: [email protected]\r\n"); // [email protected] is not a real email address
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("MAIL FROM failed.");
             return;
         }
         Send("RCPT TO:" + address + "\r\n");
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("RCPT TO failed.");
             return;
         }
         Send("DATA\r\n");
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("DATA failed.");
             return;
         }
         Send(TestMail.Replace("#ADDRESS#", address) + "\r\n.\r\n");
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("Sending of e-mail failed.");
             return;
         }
         Send("QUIT\r\n");
         if (!IsReplyOK(Receive())) {
             Console.WriteLine("QUIT failed.");
         }
         Connection.Shutdown(SocketShutdown.Both);
     } catch (Exception e) {
         Console.WriteLine("An error occurred [" + e.Message + "]");
         Console.WriteLine(e);
     } finally {
         if (Connection != null) {
             Connection.Close();
         }
     }
 }
Exemplo n.º 16
0
 /// <summary>
 /// Download a file using the synchronous Socket methods.
 /// </summary>
 /// <param name="url">The URL to download.
 /// </param>
 /// <param name="sp">The protocol to use.</param>
 protected void DownloadFile(Url url, SecureProtocol sp)
 {
     string request = GetHttpRequest(url); // holds the HTTP request for the given URL
     SecureSocket s;
     try {
         // First we create a new SecurityOptions instance
         // SecurityOptions objects hold information about the security
         // protocols the SecureSocket should use and how the SecureSocket
         // should react in certain situations.
         SecurityOptions options = new SecurityOptions(sp);
         // The Certificate field holds a certificate associated with
         // a client [you, for instance]. Because client certificates
         // are not often used for HTTP over SSL or TLS, we'll simply
         // set this field to a null reference.
         options.Certificate = null;
         // The Entity specifies whether the SecureSocket should act
         // as a client socket or as a server socket. In this case,
         // it should act as a client socket.
         options.Entity = ConnectionEnd.Client;
         // The CommonName field specifies the name of the remote
         // party we're connecting to. This is usually the domain name
         // of the remote host.
         options.CommonName = url.Host;
         // The VerificationType field specifies how we intend to verify
         // the certificate. In this case, we tell the SecureSocket that
         // we will manually verify the certificate. Look in the documentation
         // for other options.
         options.VerificationType = CredentialVerification.Manual;
         // When specifying the CredentialVerification.Manual option, we
         // must also specify a CertVerifyEventHandler delegate that will
         // be called when the SecureSocket receives the remote certificate.
         // The Verifier field holds this delegate. If no manual verification
         // is done, this field can be set to a null reference.
         options.Verifier = new CertVerifyEventHandler(OnVerify);
         // The Flags field specifies which flags should be used for the
         // connection. In this case, we will simply use the default behavior.
         options.Flags = SecurityFlags.Default;
         // Allow only secure ciphers to be used. If the server only supports
         // weak encryption, the connections will be shut down.
         options.AllowedAlgorithms = SslAlgorithms.SECURE_CIPHERS;
         // create a new SecureSocket instance and initialize it with
         // the security options we specified above.
         s = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
         // connect to the remote host
         s.Connect(new IPEndPoint(Dns.GetHostEntry(url.Host).AddressList[0], url.Port));
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while connecting: " + e.ToString());
         return;
     }
     // send the HTTP request to the remote host
     Console.Write("HTTP Query string:\r\n------------------\r\n" + request);
     try {
         byte[] reqBytes = Encoding.ASCII.GetBytes(request);
         int sent = s.Send(reqBytes, 0, reqBytes.Length, SocketFlags.None);
         while(sent != reqBytes.Length) {
             sent += s.Send(reqBytes, sent, reqBytes.Length - sent, SocketFlags.None);
         }
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while sending: " + e.ToString());
         return;
     }
     // receive the reply
     Console.WriteLine("HTTP Server reply:\r\n------------------");
     try {
         byte[] buffer = new byte[4096];
         int ret = s.Receive(buffer);
         while(ret != 0) {
             Console.Write(Encoding.ASCII.GetString(buffer, 0, ret));
             ret = s.Receive(buffer);
         }
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while receiving: " + e.ToString());
         return;
     }
     try {
         s.Shutdown(SocketShutdown.Both); // shut down the TCP connection
     } catch (Exception e) {
         Console.WriteLine("Exception occurred while shutting the connection down: " + e.ToString());
         return;
     }
     s.Close();
 }