AuthenticateAsClient() public method

public AuthenticateAsClient ( string targetHost ) : void
targetHost string
return void
Ejemplo n.º 1
1
        static void Test()
        {
            // Connect as client to port 1300
            string server = "127.0.0.1";
            TcpClient client = new TcpClient(server, 1300);

            // Create a secure stream
            using (SslStream sslStream = new SslStream(client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
            {
                sslStream.AuthenticateAsClient(server);

                // ... Send and read data over the stream
                byte[] buffer = new byte[1024];
                int n = sslStream.Read(buffer, 0, 1024);


                string _message = System.Text.Encoding.UTF8.GetString(buffer, 0, n);
                System.Console.WriteLine("Client said: " + _message); 

            }

            // Disconnect and close the client
            client.Close();
        }
        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Use SSL to encrypt the communication
        /// </summary>
        public void EnableSsl()
        {
            SslStream sslStream = new SslStream(clientStream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            if (cCollection.Count > 0)
            {
                // A client side certificate was added, authenticate with certificate
                sslStream.AuthenticateAsClient(serverHostname, cCollection, System.Security.Authentication.SslProtocols.Default, true);
            }
            else
                sslStream.AuthenticateAsClient(serverHostname);

            streamToUse = sslStream;
        }
Ejemplo n.º 4
0
		/// <summary>
		/// Connect to SMTP server
		/// </summary>
		/// <param name="server">smtp server to connect to</param>
		/// <param name="port">port number (usually 25)</param>
		/// <param name="ssl">Use SSL</param>
		public void Connect(String server, int port, bool ssl)
		{
			_useSSL = ssl;

			_client.Connect(server, port);

			_networkStream = _client.GetStream();

			if (_useSSL)
			{
				_sslStream = new SslStream(_networkStream, true);

				try
				{
					_sslStream.AuthenticateAsClient(server);
				}
				catch (Exception ex)
				{
					throw new SmtpException(ex.Message + ". " + "If your using gmail, make sure to use port 465");
				}

				_stream = _sslStream;
			}
			else
			{
				_stream = _networkStream;
			}

			string response = Response();

			if (response.Substring(0, 3) != "220")
			{
				throw new SmtpException(response);
			}
		}
Ejemplo n.º 5
0
        public void Connect()
        {
            log.Debug("Connecting to newshost.");
            _tcpClient = new TcpClient(ConnectionInfo.Address, ConnectionInfo.Port);
            var stream = _tcpClient.GetStream();
            if(ConnectionInfo.UseSsl)
            {
                log.Debug("Using ssl.");
                var sslStream = new SslStream(stream, true, CertValidationCallback);
                sslStream.AuthenticateAsClient(ConnectionInfo.Address);
                _stream = sslStream;
            }
            else
            {
                _stream = stream;
            }
            _writer = new StreamWriter(_stream, iso88591Encoding);
            _writer.NewLine = "\r\n";  //Added for mono compatibility, nntp requires \r\n as newline char, not just \n as used by mono.
            _writer.AutoFlush = true;
            _reader = new StreamReader(_stream, iso88591Encoding);

            var connectResponse = ReadResponse();
            log.DebugFormat("NewsHost response: [{0}] {1}", connectResponse.ResponseCode, connectResponse.ResponseMessage);
            if (connectResponse.ResponseCode != Rfc977ResponseCodes.ServerReadyPostingAllowed)
                throw new Exception("Could not open a posting connection: " + connectResponse.ResponseMessage);

            Authenticate();
        }
Ejemplo n.º 6
0
        private bool ConnectSync(string sHost, int nPort)
        {
            bool result = false;
            try
            {
                var imapServer = new TcpClient(sHost, nPort);
                _imapSslStream = new SslStream(imapServer.GetStream(), false, ValidateServerCertificate, null);

                try
                {
                    _imapSslStream.AuthenticateAsClient(sHost, null, SslProtocols.Default, false);
                }
                catch (AuthenticationException authEx)
                {
                    _logger.Warn(authEx, "Authentication failed");
                    _imapSslStream.Dispose();
                    imapServer.Close();
                    return false;
                }
                _imapSslStreamReader = new StreamReader(_imapSslStream);
                var text = _imapSslStreamReader.ReadLine();
                if (text != null && text.StartsWith("* OK"))
                {
                    result = Capability();
                }
            }
            catch (IOException ioEx)
            {
                _logger.Warn(ioEx, "Failed to connect");
            }
            return result;
        }
Ejemplo n.º 7
0
        public void Connect(IPEndPoint endPoint, bool secure, bool rogue)
        {
            _connection = new TcpClient();

            _connection.Connect(endPoint);

            if (secure)
            {
                if (rogue)
                {
                    _stream = _connection.GetStream();

                    SendGarbage();
                }
                else
                {
                    var sslStream = new SslStream(_connection.GetStream(), false, (p1, p2, p3, p4) => true);

                    sslStream.AuthenticateAsClient(
                        "localhost",
                        null,
                        SslProtocols.Tls,
                        false
                    );

                    _stream = sslStream;
                }
            }
        }
Ejemplo n.º 8
0
        public StreamingAPIConnect(StreamingListener sl, string ip, int port, LoginResponse lr, bool secure)
        {
            this.sl = sl;
            this.streamingSessionId = lr.StreamingSessionId;
            apiSocket = new System.Net.Sockets.TcpClient(ip, port);
            if (secure)
            {
                SslStream ssl = new SslStream(apiSocket.GetStream());
                ssl.AuthenticateAsClient("xtb.com"); //hardcoded domain, because we use ip-version of the address
                apiWriteStream = new StreamWriter(ssl);
                apiBufferedReader = new StreamReader(ssl);
            }
            else
            {
                NetworkStream ns = apiSocket.GetStream();
                apiWriteStream = new StreamWriter(ns);
                apiBufferedReader = new StreamReader(ns);
            }

            Thread t = new Thread(delegate()
            {
                while (running)
                {
                    readStreamMessage();
                    Thread.Sleep(50);
                }
            });
            t.Start();
            //System.Threading.Timer t = new System.Threading.Timer(o => readStreamMessage(), null, 0, 10);
        }
        public static void connectForwardServerCallBack(IAsyncResult ar)
        {
            ProxyConnection conn = (ProxyConnection)ar.AsyncState;
            conn.serverSocket.EndConnect(ar);
            ProxySwapDataTask proxy = new ProxySwapDataTask(conn);

            //now we have both server socket and client socket, we can pass the data back and forth for both side
            System.Diagnostics.Debug.Assert(true == conn.clientSocket.Connected);
            System.Diagnostics.Debug.Assert(true == conn.serverSocket.Connected);

            WinTunnel.WriteTextToConsole(string.Format("ProxyConnection#{0}-- client socket or server socket start receiving data....",
                    conn.connNumber));
            WinTunnel.connMgr.AddConnection(conn);

            conn.clientStream =  conn.clientSocket.GetStream();
            if (conn.m_bHttpsClient)
            {
                SslStream sslStream = new SslStream(conn.clientSocket.GetStream(), false);
                sslStream.AuthenticateAsServer(WinTunnel.CertificateForClientConnection, false, SslProtocols.Tls, true);
                conn.clientStream = sslStream;
            }

            conn.serverStream = conn.serverSocket.GetStream();
            if (conn.m_bHttpsServer)
            {
                SslStream sslStream = new SslStream(conn.serverStream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                sslStream.AuthenticateAsClient(conn.serverName);
                conn.serverStream = sslStream;
            }

            conn.clientStream.BeginRead(conn.clientReadBuffer, 0, ProxyConnection.BUFFER_SIZE, new AsyncCallback(clientReadCallBack), conn);
            //Read data from the server socket
            conn.serverStream.BeginRead(conn.serverReadBuffer, 0, ProxyConnection.BUFFER_SIZE, new AsyncCallback(serverReadCallBack), conn);
        }
Ejemplo n.º 10
0
        private void runClient()
        {
            TcpClient client = new TcpClient(server, port);
            Console.WriteLine("Client connected ...");

            // Create ssl stream
            SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            stream.AuthenticateAsClient(server);

            // write message to server
            byte[] output = Encoding.UTF8.GetBytes("Message from client :D<EOF>");
            stream.Write(output);
            stream.Flush();

            // read message from server
            string input = readMessage(stream);
            Console.WriteLine("Received: {0}", input);

            // close everything
            stream.Close();
            client.Close();
            Console.WriteLine("Client closed connection ...");
            // Press any key to continue ...
            Console.ReadKey();
        }
Ejemplo n.º 11
0
        public override string Connect()
        {
            string response;
            try
            {
                _Client = new TcpClient();
                _Client.NoDelay = false;
                _Client.ReceiveTimeout = 60000;
                _Client.SendTimeout = 60000;

                _Client.Connect(_Address, _Port);
                NetworkStream netStream = _Client.GetStream();
                _SslStream = new SslStream(netStream, false, CertificationValidationCallback);
                _SslStream.ReadTimeout = 60000;
                _SslStream.WriteTimeout = 600000;

                _SslStream.AuthenticateAsClient(_CertificateAddress);
                response = GetMessage(_SslStream);
            }
            catch (Exception ex)
            {
                string err = "";
                err += "Problem occured while connecting. Address or Port may be invalid.";
                err += ex.Message;
                if (ex.InnerException != null)
                    err += ex.InnerException.Message;
                throw new ProtocolConnectionException(err);
            }
            return response;
        }
        private static TcpConnection CreateClient(string Hostname, int port, bool IsSecure)
        {
            var client = new TcpClient(Hostname, port);
            var stream = (Stream)client.GetStream();

            if (IsSecure)
            {
                var sslStream = (SslStream)null;
                try
                {
                    sslStream = new SslStream(stream);
                    sslStream.AuthenticateAsClient(Hostname);
                    stream = (Stream)sslStream;
                }
                catch
                {
                    if (sslStream != null)
                        sslStream.Dispose();
                    throw;
                }
            }

            return new TcpConnection()
            {
                HostName = Hostname,
                port = port,
                IsSecure = IsSecure,
                TcpClient = client,
                ServerStreamReader = new CustomBinaryReader(stream, Encoding.ASCII),
                Stream = stream
            };
        }
Ejemplo n.º 13
0
        public ImapClient(string host, int port, bool ssl = false)
        {
            try
            {
                _tcpClient = new System.Net.Sockets.TcpClient(host, port);

                if (ssl)
                {
                    var stream = new SslStream(_tcpClient.GetStream());
                    stream.AuthenticateAsClient(host);

                    _reader = new StreamReader(stream);
                    _writer = new StreamWriter(stream);
                }
                else
                {
                    var stream = _tcpClient.GetStream();
                    _reader = new StreamReader(stream);
                    _writer = new StreamWriter(stream);
                }
                string greeting = _reader.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 14
0
        static byte[] InternalSslSocketHttp(IPEndPoint endpoint, HttpArgs args, HttpMethod method, X509CertificateCollection certificates)
        {
            using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    client.Connect(endpoint);
                    if (client.Connected)
                    {
                        using (SslStream stream = new SslStream(new NetworkStream(client), false, ValidateServerCertificate, null))
                        {
                            stream.AuthenticateAsClient("ServerName", certificates, SslProtocols.Tls, false);
                            if (stream.IsAuthenticated)
                            {
                                //生成协议包
                                byte[] buff = HttpClient.ParseHttpArgs(method, args);
                                stream.Write(buff, 0, buff.Length);
                                stream.Flush();
                                return ParseSslResponse(endpoint, stream, args, certificates);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return null;
        }
Ejemplo n.º 15
0
        private async Task StartClientToServerComms()
        {
            string host = "10.1.1.84";
            int port = 58846;
            Console.WriteLine("[Relay] Connecting to {0}:{1}", host, port);

            using (var nextTcpClient = new TcpClient())
            {
                await nextTcpClient.ConnectAsync(host, port);
                Console.WriteLine("[Relay] Connected to server");
                byte[] clientBuffer = new byte[4096];
                using (var clientToServerNetworkStream = new SslStream(nextTcpClient.GetStream(), true,
                    (sender, certificate, chain, errors) => { return true; }))
                {

                    clientToServerNetworkStream.AuthenticateAsClient(host);
                    while (true)
                    {
                        var clientBytes = await clientToServerNetworkStream.ReadAsync(clientBuffer, 0, clientBuffer.Length);

                        if (clientBytes > 0)
                        {
                            Console.WriteLine("Client sent {0}", DelugeRPC.DelugeProtocol.DecompressAndDecode(clientBuffer).Dump());
                            await clientToServerNetworkStream.WriteAsync(clientBuffer, 0, clientBuffer.Length);
                        }
                    }
                }
            }
        }
 public static bool Validar(string host, int porta)
 {
     try
     {
         using (var client = new TcpClient())
         {
             client.Connect(host, porta);
             using (var stream = client.GetStream())
             using (var sslStream = new SslStream(stream))
             {
                 sslStream.AuthenticateAsClient(host);
                 using (var writer = new StreamWriter(sslStream))
                 using (var reader = new StreamReader(sslStream))
                 {
                     var retorno = reader.ReadLine();
                     return retorno != null && (retorno.Contains("250") || retorno.Contains("220"));
                 }
             }
         }
     }
     catch (Exception)
     {
         return false;
     }
 }
Ejemplo n.º 17
0
        public override Stream Connect(Uri uri, bool requireAuthentication) {
            var rawStream = base.Connect(uri, requireAuthentication);
            try {
                var sslStream = new SslStream(rawStream, false, (sender, cert, chain, errs) => {
                    if (errs == SslPolicyErrors.None || !requireAuthentication) {
                        return true;
                    }

                    string errText = string.Format("Could not establish secure connection to {0} because of the following SSL issues:\n\n", uri);
                    if ((errs & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) {
                        errText += "- no remote certificate provided\n";
                    }
                    if ((errs & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) {
                        errText += "- remote certificate name does not match hostname\n";
                    }
                    if ((errs & SslPolicyErrors.RemoteCertificateChainErrors) != 0) {
                        errText += "- remote certificate is not trusted\n";
                    }

                    throw new AuthenticationException(errText);
                });

                sslStream.AuthenticateAsClient(uri.Host);
                rawStream = null;
                return sslStream;
            } catch (IOException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
            } finally {
                if (rawStream != null) {
                    rawStream.Dispose();
                }
            }
        }
Ejemplo n.º 18
0
            public static string RunClient(string serverName,string activation_info,ref string buffer)
            {                                
                TcpClient client = new TcpClient(serverName,443);                
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );
              
                try
                {
                    sslStream.AuthenticateAsClient(serverName);
                }
                catch (AuthenticationException e)
                {   
                    if (e.InnerException != null)
                    {
                    }
                    client.Close();
                    Environment.Exit(-1);
                }

                byte[] messsage = Encoding.UTF8.GetBytes(activation_info + "\n<EOF>");                
                sslStream.Write(messsage);
                sslStream.Flush();               
                string serverMessage = ReadMessage(sslStream);                
                client.Close();                
                buffer = serverMessage;
                return serverMessage;
            }
Ejemplo n.º 19
0
        private void imapConnect(string server, int port, bool useSSL)
        {
            TcpClient myClient = new TcpClient(server, port);
            tcpStream = myClient.GetStream();

            if (useSSL)
            {
                SslStream mySSLStream = new SslStream(tcpStream, false, new RemoteCertificateValidationCallback(foo));
                mySSLStream.AuthenticateAsClient(server);
                myWriter = new StreamWriter(mySSLStream);
                myWriter.AutoFlush = true;
                myReader = new StreamReader(mySSLStream);
            }
            else
            {
                myWriter = new StreamWriter(tcpStream);
                myWriter.AutoFlush = true;
                myReader = new StreamReader(tcpStream);
            }

            string lineIn = myReader.ReadLine();

            // todo: support for PREAUTH
            if (lineIn.StartsWith("* BYE"))
                throw new Exception("Mail server didn't want us to connect, asked us to disconnect");
            if (!lineIn.StartsWith("* OK"))
                throw new Exception("Mail server didn't give the required connection banner");
        }
Ejemplo n.º 20
0
        public void handler()
        {
            DataPacket data = null;

            sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            try
            {
                sslStream.AuthenticateAsClient(ipAdress);
            }
            catch
            {
                Console.WriteLine("Could not connect to server.");
            }

            for(; ; )
            {
                if (sslStream != null && sslStream.CanRead)
                {
                    try
                    {
                        data = formatter.Deserialize(sslStream) as DataPacket;
                        handleDataPacket(data);
                    }
                    catch
                    {
                        Console.WriteLine("Received data from server.");
                        //disconnect();
                    }

                }

                Thread.Sleep(100);
            }
        }
Ejemplo n.º 21
0
        public static void RunClient()
        {
            IsReading = false;
            _client = new TcpClient();
            _client.Connect(NetworkSettings.ServerIP, NetworkSettings.ServerPort);

            _totalBuffer = new List<byte>();

            // ReSharper disable once RedundantDelegateCreation
            _sslStream = new SslStream(_client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

            try
            {
                _sslStream.AuthenticateAsClient(NetworkSettings.ServerIP);
            }

            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);

                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }

                Console.WriteLine("Authentication failed - closing the connection.");

                StopClient();
            }

            // Signal that connected
            Console.WriteLine("TCPController: Connection active");
        }
Ejemplo n.º 22
0
 public SslClient(string ip, int port, UserCertificate certificate = null, int bufferSize = 1024) : base(ip, port)
 {
     try
     {
         _bufferSize = bufferSize;
         if (certificate != null)
         {
             _certificate = certificate;
         }
         else
         {
             _certificate = new X509Certificate2();
         }
         _stream = new SslStream(GetStream(), false, ServerCertificateValidation, UserCertificateSelection);
         _stream.AuthenticateAsClient(ip);
     }
     catch (AuthenticationException err)
     {
         ErrorOnAuthentication();
     }
     catch (SocketException)
     {
         ErrorOnAuthentication();
     }
     catch (Win32Exception)
     {
         ErrorOnAuthentication();
     }
 }
Ejemplo n.º 23
0
 internal static string OpenConnection()
 {
     errorMsg = string.Empty;
     _dataBuffer = string.Empty;
     int result = 0;
     int.TryParse(ConfigurationSupport.currentPort, out result);
     try
     {
         _client = new TcpClient(ConfigurationSupport.currentHost, result);
         string str = QuickRead(null);
         if (str != ConfigurationSupport.version)
         {
             errorMsg = errorMsg + "Mismatched versions." + Environment.NewLine;
             errorMsg = errorMsg + string.Format("SERVER: ({0})" + Environment.NewLine, str);
             errorMsg = errorMsg + string.Format("CLIENT: ({0})" + Environment.NewLine, ConfigurationSupport.version);
             CloseConnection();
         }
         if (_client.Connected)
         {
             StreamWriter writer = new StreamWriter(_client.GetStream());
             writer.WriteLine(string.Format("VersionInfo {{{0}}}", ConfigurationSupport.version));
             writer.Flush();
             _sslStreamReader = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallBack));
             try
             {
                 _sslStreamReader.AuthenticateAsClient(ConfigurationSupport.currentHost, null, SslProtocols.Ssl3, false);
             }
             catch (AuthenticationException exception)
             {
                 errorMsg = errorMsg + "SSL Authentication Error." + Environment.NewLine;
                 errorMsg = errorMsg + exception.ToString();
             }
             _sslStreamWriter = new StreamWriter(_sslStreamReader);
             _sslStreamWriter.AutoFlush = true;
             _sslStreamWriter.WriteLine(string.Format("ValidateUser {0} {1}", ConfigurationSupport.currentUsername, ConfigurationSupport.currentPassword));
             string str2 = QuickRead(_sslStreamReader);
             if (str2 == "UserID INVALID")
             {
                 CloseConnection();
                 errorMsg = "Invalid USERNAME and/or PASSWORD";
             }
             else
             {
                 isConnected = true;
                 ConfigurationSupport.userID = str2.Split(new char[0])[1];
             }
         }
     }
     catch (Exception ex)
     {
         isConnected = false;
         errorMsg = string.Format("Could not connect to {0}:{1}", ConfigurationSupport.currentHost, ConfigurationSupport.currentPort);
     }
     if (isConnected)
     {
         _readBuffer = new byte[0x100];
         _sslStreamReader.BeginRead(_readBuffer, 0, _readBuffer.Length, new AsyncCallback(SguildConnection.OnReceivedData), _client.GetStream());
     }
     return errorMsg;
 }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
Ejemplo n.º 25
0
        private void Parse()
        {
            TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
            tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
            sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
            //bool flag = sslstream.IsAuthenticated; // check flag
            System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
            System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
            sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
            sw.Flush(); // sent to server
            sw.WriteLine("PASS utybfkmyjcnm321");
            sw.Flush();
            sw.WriteLine("RETR 5");
            sw.Flush();
            sw.WriteLine("Quit "); // close the connection
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;

            while ((strTemp = reader.ReadLine()) != null)
            {
                if (".".Equals(strTemp))
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

            MessageBox.Show(str);
        }
Ejemplo n.º 26
0
    public void Connect(String server, int port, bool ssl)
    {
      String m_response = "";
      m_use_ssl = ssl;
      m_client.Connect(server, port);

      m_network_stream = m_client.GetStream();

      if (m_use_ssl)
      {
        m_ssl_stream = new SslStream((Stream)m_network_stream, true);
        m_ssl_stream.AuthenticateAsClient(server);

        m_stream = (Stream)m_ssl_stream;
      }
      else
      {
        m_stream = m_network_stream;
      }

      m_response = this.Response();

      if (m_response.Substring(0, 3) != "+OK")
      {
        throw new Pop3Exception(m_response);
      }
    }
        public override void Open()
        {
            base.Open();
            MailConnection.EmailStreamReader = new StreamReader(MailConnection.TcpClient.GetStream());
            MailConnection.EmailStream = MailConnection.TcpClient.GetStream();
            LoggerHolders.ConsoleLogger.Log(MailConnection.EmailStreamReader.ReadLine());
            MailCommand command = MailConnection.CreateCommand();
            command.Command = "STARTTLS";
            command.ExecuteCommand();

            LoggerHolders.ConsoleLogger.Log(command.Response);

            var sslStrm = new SslStream(MailConnection.TcpClient.GetStream(), false);

            try
            {
                sslStrm.AuthenticateAsClient(MailConnection.Host);
            }
            catch (AuthenticationException ex)
            {
                LoggerHolders.ConsoleLogger.Log("Exception", LogType.Critical, ex);
                if (ex.InnerException != null)
                {
                    LoggerHolders.ConsoleLogger.Log("Exception", LogType.Critical, ex.InnerException);
                }
                MailConnection.TcpClient.Close();
            }

            MailConnection.EmailStream = sslStrm;
            MailConnection.EmailStreamReader = new StreamReader(sslStrm);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Initializes a client instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="host">Network host.</param>
        /// <param name="port">Network port.</param>
        /// <param name="useTls">Use TLS layer?</param>
        /// <param name="noDelay">No delay?</param>
        /// <param name="ignoreSslPolicyErrors">Ignore SSL policy errors?</param>
        internal DesktopNetworkStream(string host, int port, bool useTls, bool noDelay, bool ignoreSslPolicyErrors)
        {
            this.Host = host;
            this.Port = port;
#if NETSTANDARD
            this.tcpClient = new TcpClient { NoDelay = noDelay };
            this.tcpClient.ConnectAsync(host, port).Wait();
#else
            this.tcpClient = new TcpClient(host, port) { NoDelay = noDelay };
#endif

            Stream stream = this.tcpClient.GetStream();
            if (useTls)
            {
                var ssl = new SslStream(
                    stream,
                    false,
                    (sender, certificate, chain, errors) => errors == SslPolicyErrors.None || ignoreSslPolicyErrors);
#if NETSTANDARD
                ssl.AuthenticateAsClientAsync(host).Wait();
#else
                ssl.AuthenticateAsClient(host);
#endif
                stream = ssl;
            }

            this.networkStream = stream;
        }
Ejemplo n.º 29
0
        public ServiceEndPoint Discover(Uri remoteUri)
        {
            try
            {
                using (var client = CreateTcpClient())
                {
                    client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout);
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(remoteUri, new X509Certificate2(ssl.RemoteCertificate).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
Ejemplo n.º 30
0
        public void doConnect()
        {

            if (TCP == null)
            {
                TCP = new TcpClient();
            }

            if (!TCP.Connected)
            {
                TCP.Connect(popServer, popPort);
            }

            if (isSecure) // starts SSL connection
            {
                SslStream iamSecure = new SslStream(TCP.GetStream()); //creates new Stream
                iamSecure.AuthenticateAsClient(popServer); //makes secure auth to Server
                popStream = iamSecure; //passes Secure Stream to POP Client Stream
                iamSecure = null; //resets Stream
            }

            else //if not SSL connection
                popStream = TCP.GetStream(); //passes unencrypted TCPClient Stream to POP Stream
                popWrite = new StreamWriter(popStream); //awaits for commands to POP Stream
                popRead = new StreamReader(popStream); //awaits to read commands from POP Stream
                doReadLine(); // drops a new line on popRead
                doLogin(); //initiate login using checkResponse
        }
Ejemplo n.º 31
0
        bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout)
        {
            //EB.Debug.Log("Try connect {0}:{1}", ip, port);

            if (_client.Client.AddressFamily != ip.AddressFamily)
            {
                _client.Close();
                _client         = new System.Net.Sockets.TcpClient(ip.AddressFamily);
                _client.NoDelay = true;
            }

            var async = _client.BeginConnect(ip, port, null, null);

            if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout)))
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            if (!async.IsCompleted)
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            _client.EndConnect(async);

            if (_client.Connected == false)
            {
                EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port);
                _error = NetworkFailure.CannotConnectToHost;
                return(false);
            }

            OnConnected();

            _net    = _client.GetStream();
            _stream = _net;

            if (_secure)
            {
                //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port);
                _ssl = new System.Net.Security.SslStream(_stream, true, RemoteCertificateValidationCallback, null);
                try
                {
                    _ssl.AuthenticateAsClient(hostname);
                }
                catch (System.Exception e)
                {
                    EB.Debug.LogError("Failed to authenticate: " + e);
                    return(false);
                }
                _stream = _ssl;
            }

            //EB.Debug.Log("Connected to {0}:{1}", ip, port);

            LastTime = System.DateTime.Now;

            return(true);
        }
        public void Scan(BackgroundWorker _bgWorker, SParams parm)
        {
            bgWorker = _bgWorker;

            cur_cursor = 0;
            buffer     = "";

            ConsoleSetSection(3);
            ConsoleAppend("Scan started");
            ConsoleFlush(Color.Blue);

            // TCPCLIENT!! dla reszty testów


            string url = parm.base_url;

            int from = parm.test_mode;
            int to   = parm.test_mode;

            if (parm.test_mode == 18) // select all
            {
                from = 3;
                to   = 18;
            }

            for (int i = from; i <= to; i++) // tests
            {
                if (i == 18)                 // 'select all' test
                {
                    continue;
                }

                results[i].full_response = "";
                results[i].full_request  = "";
                results[i].response      = "";
                results[i].request       = "";

                url = parm.base_url;

                ConsoleSeparator(Color.Black);
                ConsoleAppend(parm.test_names[i - 3]);
                //ConsoleSetSection(1);
                ConsoleFlush(Color.Black);

                results[i].name = parm.test_names[i - 3];

                // USING WEBREQUEST
                // POST, GET, HEAD, wrongmethod, OPTIONS, TRACE, PUT
                //if (  (i == 13) )
                if (false) /// CAN DELETE THIS
                {
                    if ((i == 13) && (parm.put_uri != ""))
                    {
                        url = parm.put_uri;
                    }

                    if (url.Contains("https"))
                    {
                        AllowInvalidCertificate();
                    }

                    var request = (HttpWebRequest)WebRequest.Create(url);

                    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
                    request.Headers.Add("Accept-Language", "en-US");
                    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    if (i == 7)
                    {
                        request.Method = WebRequestMethods.Http.Get;
                    }
                    else if (i == 6)
                    {
                        request.Method      = WebRequestMethods.Http.Post;
                        request.ContentType = "application/x-www-form-urlencoded";
                    }
                    else if (i == 14)
                    {
                        request.Method = WebRequestMethods.Http.Head;
                    }
                    else if (i == 11)
                    {
                        request.Method = "OPTIONS";
                    }
                    else if (i == 16)
                    {
                        request.Method = parm.wrongmethod_met;
                    }
                    else if (i == 9)
                    {
                        request.Method = "TRACE";
                    }
                    else if (i == 13)
                    {
                        request.Method      = WebRequestMethods.Http.Put;
                        request.ContentType = "application/octet-stream";
                    }

                    // request.Method = WebRequestMethods.Http.Put
                    //request.Method = WebRequestMethods.Http.Connect

                    request.KeepAlive   = false;
                    request.Proxy       = null;
                    request.Credentials = CredentialCache.DefaultCredentials;

                    if (i == 6) // post data
                    {
                        byte[] bytes = Encoding.ASCII.GetBytes(parm.post_data);
                        request.ContentLength = bytes.Length;

                        Stream stream = request.GetRequestStream();
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Close();
                    }

                    if (i == 13) // put data
                    {
                        if (parm.put_path == "")
                        {
                            request.ContentLength = 0;
                        }
                        else
                        {
                            FileStream ReadIn = new FileStream(parm.put_path, FileMode.Open, FileAccess.Read);
                            ReadIn.Seek(0, SeekOrigin.Begin);
                            request.ContentLength = ReadIn.Length;
                            Byte[] FileData   = new Byte[ReadIn.Length];
                            int    DataRead   = 0;
                            Stream tempStream = request.GetRequestStream();
                            do
                            {
                                DataRead = ReadIn.Read(FileData, 0, (Math.Min(2048, (int)ReadIn.Length)));
                                if (DataRead > 0)
                                {
                                    tempStream.Write(FileData, 0, DataRead);
                                    Array.Clear(FileData, 0, DataRead);
                                }
                            } while (DataRead > 0);

                            ReadIn.Close();
                            tempStream.Close();
                        }
                    }

                    HttpStatusCode  status   = 0;
                    HttpWebResponse response = null;

                    string send4 = request.Method + " ";

                    if (url.Substring(0, 7) == "http://")
                    {
                        url = url.Substring(7, url.Length - 7);
                    }
                    else if (url.Substring(0, 8) == "https://")
                    {
                        url = url.Substring(8, url.Length - 8);
                    }

                    int c = url.Length;
                    for (int b = 0; b < url.Length; b++)
                    {
                        if (url[b] == '/')
                        {
                            c = b;
                            break;
                        }
                    }
                    if (c == url.Length)
                    {
                        url = "/";
                    }
                    else
                    {
                        url = url.Substring(c, url.Length - c);
                    }

                    //HttpUtility.UrlEncode(url)
                    send4 += HttpUtility.UrlPathEncode(url) + " HTTP/1.1";

                    ConsoleSetSection(1);
                    ConsoleAppend(send4);
                    ConsoleFlush(Color.SlateGray);

                    results[i].request = send4;

                    results[i].full_request = "";

                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();

                        status = response.StatusCode;

                        Stream receiveStream = response.GetResponseStream();
                        // Encoding encode = System.Text.Encoding. GetEncoding("utf-8");
                        // Pipes the stream to a higher level stream reader with the required encoding format.
                        StreamReader readStream = new StreamReader(receiveStream);

                        results[i].full_response = readStream.ReadToEnd();
                        readStream.Close();

                        response.Close();
                    }
                    catch (WebException e)
                    {
                        if (e.Status == WebExceptionStatus.ProtocolError)
                        {
                            status = ((HttpWebResponse)e.Response).StatusCode;
                        }
                        //else
                        // e.Status.ToString();
                    }

                    int mt = ((int)status) / 100;

                    ConsoleSetSection(2);
                    ConsoleAppend(((int)status).ToString() + " " + status.ToString());

                    results[i].response = ((int)status).ToString() + " " + status.ToString();

                    if (mt == 2)
                    {
                        ConsoleFlush(Color.Green);
                    }
                    else if (mt == 4)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else if (mt == 5)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else
                    {
                        ConsoleFlush(Color.Black);
                    }
                }

                // USING TCPCLIENT
                // Fake End in URI, URI encoding, URI backslashes, Header multiple lines, HTTP wrong version,
                // CONNECT, PROPFIND, DELETE, POST, GET, OPTIONS
                // if ((i == 3) || (i == 4) || (i == 5) || (i == 6) || (i == 7) || (i == 8) || (i == 9)
                //    || (i == 11) || (i == 12) || (i == 14) || (i == 15) || (i==16) ||  (i == 17) || (i == 10))

                if (true)
                {
                    if ((i == 6) && (parm.post_uri != ""))
                    {
                        url = parm.post_uri;
                    }
                    else if ((i == 17) && (parm.propfind_uri != ""))
                    {
                        url = parm.propfind_uri;
                    }
                    else if ((i == 10) && (parm.delete_uri != ""))
                    {
                        url = parm.delete_uri;
                    }
                    else if ((i == 12) && (parm.connect_uri != ""))
                    {
                        url = parm.connect_uri;
                    }
                    else if ((i == 7) && (parm.get_uri != ""))
                    {
                        url = parm.get_uri;
                    }
                    else if ((i == 11) && (parm.options_uri != ""))
                    {
                        url = parm.options_uri;
                    }
                    else if ((i == 9) && (parm.trace_uri != ""))
                    {
                        url = parm.trace_uri;
                    }
                    else if ((i == 14) && (parm.head_uri != ""))
                    {
                        url = parm.head_uri;
                    }
                    else if ((i == 13) && (parm.put_uri != ""))
                    {
                        url = parm.put_uri;
                    }

                    bool is_https = false;
                    int  port     = 80;
                    if (url.Substring(0, 7) == "http://")
                    {
                        url = url.Substring(7, url.Length - 7);
                    }
                    else if (url.Substring(0, 8) == "https://")
                    {
                        url      = url.Substring(8, url.Length - 8);
                        is_https = true;
                        port     = 443;
                        AllowInvalidCertificate();
                    }

                    int c = url.Length;
                    for (int b = 0; b < url.Length; b++)
                    {
                        if (url[b] == '/')
                        {
                            c = b;
                            break;
                        }
                    }

                    string url2;
                    if (c == url.Length)
                    {
                        url2 = "/";
                    }
                    else
                    {
                        url2 = url.Substring(c, url.Length - c);
                    }
                    // /index.html

                    url = url.Substring(0, c); // www.site.com



                    //method
                    string send = "";

                    if (i == 12)
                    {
                        send += "CONNECT ";
                    }
                    else if (i == 17)
                    {
                        send += "PROPFIND ";
                    }
                    else if (i == 10)
                    {
                        send += "DELETE ";
                    }
                    else if (i == 6)
                    {
                        send += "POST ";
                    }
                    else if (i == 11)
                    {
                        send += "OPTIONS ";
                    }
                    else if (i == 9)
                    {
                        send += "TRACE ";
                    }
                    else if (i == 14)
                    {
                        send += "HEAD ";
                    }
                    else if (i == 16)
                    {
                        send += parm.wrongmethod_met + " ";
                    }
                    else if (i == 13)
                    {
                        send += "PUT ";
                    }
                    else
                    {
                        send += "GET ";
                    }

                    //URI
                    if (i == 3)
                    {
                        send += "/%20HTTP/1.1/../../ ";
                    }
                    else if (i == 4)
                    {
                        send += "/%2F ";// ??????????????????????
                    }
                    else if (i == 5)
                    {
                        send += "\\ ";
                    }
                    else if (i == 8)
                    {
                        send += "/ ";
                    }
                    else if (i == 15)
                    {
                        send += "/ ";
                    }
                    else if (i == 12)
                    {
                        send += url + " ";
                    }
                    else
                    {
                        send += url2 + " ";
                    }

                    //version
                    if (i == 15)
                    {
                        send += "HTTP/" + parm.wrongversion_ver;
                    }
                    else if (i == 5)
                    {
                        send += "HTTP\\1.1";
                    }
                    else
                    {
                        send += "HTTP/1.1";
                    }

                    ConsoleSetSection(1);
                    ConsoleAppend(send);
                    ConsoleFlush(Color.SlateGray);

                    results[i].request = send;

                    //newline
                    send += "\r\n";
                    if (i == 8)
                    {
                        send += "\r\n";
                    }

                    //

                    send += "Host: " + url + "\r\n";
                    send += "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0\r\n";
                    send += "Accept-Language: en-US\r\n";
                    send += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";

                    if (i == 6)
                    {
                        send += "Content-Type: application/x-www-form-urlencoded\r\n";
                        send += "Content-Length: " + System.Web.HttpUtility.UrlEncode(parm.post_data).Length.ToString() + "\r\n";
                        //send += "Expect: 100-continue\r\n";
                    }

                    Byte[] FileData      = null;
                    long   ContentLength = 0;

                    if (i == 13)
                    {
                        if (parm.put_path != "")
                        {
                            FileStream ReadIn = new FileStream(parm.put_path, FileMode.Open, FileAccess.Read);
                            ReadIn.Seek(0, SeekOrigin.Begin);
                            ContentLength = ReadIn.Length;
                            FileData      = new Byte[ReadIn.Length];
                            int DataRead = 0;
                            int offset   = 0;

                            int numBytesToRead = (int)ReadIn.Length;
                            int numBytesRead   = 0;
                            while (numBytesToRead > 0)
                            {
                                int n = ReadIn.Read(FileData, numBytesRead, numBytesToRead);

                                if (n == 0)
                                {
                                    break;
                                }

                                numBytesRead   += n;
                                numBytesToRead -= n;
                            }
                            numBytesToRead = (int)ReadIn.Length;

                            ReadIn.Close();
                        }
                        else
                        {
                            ContentLength = 0;
                        }

                        send += "Content-Type: application/octet-stream\r\n";
                        send += "Content-Length: " + ContentLength.ToString() + "\r\n";
                    }

                    send += "Connection: Close\r\n";
                    send += "\r\n";

                    if (i == 6)
                    {
                        send += System.Web.HttpUtility.UrlEncode(parm.post_data);
                    }
                    // if (i == 13)
                    // send += System.Text.Encoding.ASCII.GetString(FileData,0,(int)ContentLength);
                    //send += System.Text.Encoding.UTF8.GetString(FileData, 0, (int)ContentLength);
                    // send += BitConverter.ToString(FileData);
                    //BitConverter.

                    //results[i].full_request = send;

                    TcpClient tcp = new TcpClient(url, port);
                    tcp.SendTimeout    = 8000;
                    tcp.ReceiveTimeout = 8000;

                    StreamReader reader;
                    StreamWriter writer;
                    //SslStream gga= null;

                    SslStream     sstre = null;
                    NetworkStream nets  = null;

                    if (is_https)
                    {
                        sstre = new System.Net.Security.SslStream(tcp.GetStream(), true, allowCert, null);
                        sstre.AuthenticateAsClient(url);

                        reader = new StreamReader(sstre);
                        //writer = new StreamWriter(sstre);
                        //gga = sstre;
                    }
                    else
                    {
                        nets   = tcp.GetStream();
                        reader = new StreamReader(tcp.GetStream());
                        //writer = new StreamWriter(tcp.GetStream());
                    }

                    string respon = "";

                    byte[] sbyt = System.Text.Encoding.ASCII.GetBytes(send);

                    int    siz  = sbyt.Length + (int)ContentLength;
                    byte[] full = new byte[siz];
                    sbyt.CopyTo(full, 0);
                    if (FileData != null)
                    {
                        FileData.CopyTo(full, sbyt.Length);
                    }

                    results[i].full_request = System.Text.Encoding.ASCII.GetString(full, 0, siz);

                    try
                    {
                        if (is_https)
                        {
                            sstre.Write(full, 0, siz);
                            sstre.Flush();
                        }
                        else
                        {
                            nets.Write(full, 0, siz);
                            nets.Flush();
                        }
                        // writer.Write(send);

                        //writer.Flush();
                    }
                    catch (System.Net.Sockets.SocketException e)
                    {
                        respon = "ERROR";
                    }
                    catch (System.IO.IOException e2)
                    {
                        respon = "ERROR";
                    }

                    //char[] rbuff = null;
                    //rbuff = new char[2048];



                    try
                    {
                        string agg = reader.ReadToEnd();
                        //reader.Read(rbuff,0,2047);

                        results[i].full_response = agg;

                        bool t4   = false;
                        int  pos1 = 0;
                        int  pos2 = 0;
                        for (int h = 0; h < agg.Length; h++)
                        {
                            if (!t4)
                            {
                                if (agg[h] == ' ')
                                {
                                    pos1 = h + 1;
                                    t4   = true;
                                }
                            }
                            else
                            {
                                if ((agg[h] == '\r') || (agg[h] == '\n'))
                                {
                                    pos2   = h;
                                    respon = agg.Substring(pos1, pos2 - pos1);
                                    break;
                                }
                            }
                        }
                    }
                    catch (IOException e)
                    {
                        respon = "ERROR";
                    }

                    int mt = 4;
                    if ((respon != "") && (respon != "ERROR"))
                    {
                        mt = Convert.ToInt32(respon.Substring(0, 1));
                    }

                    //ConsoleSetSection(2);
                    //ConsoleAppend(((int)status).ToString() + " " + status.ToString());

                    ConsoleSetSection(2);
                    ConsoleAppend(respon);

                    results[i].response = respon;

                    if (mt == 2)
                    {
                        ConsoleFlush(Color.Green);
                    }
                    else if (mt == 4)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else if (mt == 5)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else
                    {
                        ConsoleFlush(Color.Black);
                    }
                }

                ConsoleSetSection(3);
                ConsoleAppend("Done.");
                //ConsoleNewline();
                ConsoleFlush(Color.Blue);

                if (bgWorker.CancellationPending == true)
                {
                    break;
                }
            }

            while (true)
            {
                if (a1.AddToConsoleStr.Count == 0)
                {
                    break;
                }

                Thread.Sleep(100);
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Uses a TCPClient and SSLStream to perform a POST.
        /// </summary>
        /// <param name="requestUrl">URL that the POST must be directed to.</param>
        /// <param name="body">Message that is to be sent.</param>
        /// <param name="user">UserId in your Zeep System. Only required if your sending a Single Message to a User.
        /// Otherwise, just send a string.Empty.</param>
        /// <returns>Response from the server. (although it will write the response to console)</returns>
        public static string SendSMS(string requestUrl, string body, string user)
        {
            string parameters     = "";
            string requestHeaders = "";
            string responseData   = "";

            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");

            // Clean the text to send
            body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

            if (user.Length > 0)
            {
                parameters += "user_id=" + user + "&";
            }
            if (body.Length > 0)
            {
                parameters += "body=" + body;
            }


            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac         = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            string auth = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);


            System.Uri uri = new Uri(requestUrl);
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
            string requestMethod = "POST " + uri.LocalPath + " HTTP/1.1\r\n";

            // Set Headers for the POST message
            requestHeaders += "Host: api.zeepmobile.com\r\n";
            requestHeaders += "Authorization: " + auth + "\r\n";
            requestHeaders += "Date: " + DateTime.UtcNow.ToString("r") + "\r\n";
            requestHeaders += "Content-Type: application/x-www-form-urlencoded\r\n";
            requestHeaders += "Content-Length: " + parameters.ToByteArray().Length + "\r\n";
            requestHeaders += "\r\n";


            // Get the data to be sent as a byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + "\r\n");
            // Send the message to the connected TcpServer.
            NetworkStream stream = client.GetStream();


            // SSL Authentication is used because the Server requires https.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                stream,
                false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(uri.Host);

            // Send the data over the SSL stream.
            sslStream.Write(data, 0, data.Length);
            sslStream.Flush();


            // Receive the TcpServer.response.
            for (int i = 0; i < 100; i++)
            {
                if (stream.DataAvailable)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Byte[] bytes = new byte[1024];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (stream.DataAvailable)
            {
                int count = sslStream.Read(bytes, 0, 1024);
                if (count == 0)
                {
                    break;
                }
                sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count));
            }

            responseData = sb.ToString();
            Console.WriteLine(responseData);
            // Close everything.
            client.Close();

            return(responseData);
        }
Ejemplo n.º 34
0
        public string DonwloadTimeSheetMail()
        {
            string sUserid, sPassword;

            GetMailUseridAndPassword(out sUserid, out sPassword);

            string sTempDir = GetTempDir();
            string sPrefix  = GetTempFileNamePrefix();
            string sLpath   = sTempDir + "\\" + sPrefix + "maillog.txt";
//			if (File.Exists(sLpath)) File.Delete(sLpath);
            string sDpath = sTempDir + "\\" + sPrefix + "mailtext.txt";
//			if (File.Exists(sDpath)) File.Delete(sDpath);
            string sEpath = sTempDir + "\\" + sPrefix + "timesheet";
            string sRes;

            StreamWriter strmlgw = new System.IO.StreamWriter(System.IO.File.Create(sLpath));
            TcpClient    tcpclnt = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
            SslStream    sslstrm = new System.Net.Security.SslStream(tcpclnt.GetStream());

            // There should be no gap between the imap command and the \r\n
            // sslstrm.read() -- while sslstrm.readbyte!= eof does not work
            // because there is no eof from server and  cannot check for \r\n
            // because in case of larger response from server ex:read email
            // message. There are lot of lines so \r\n appears at the end of
            // each line sslstrm.timeout sets the underlying tcp connections
            // timeout if the read or writetime out exceeds then the undelying
            // connectionis closed.

            strmlgw.WriteLine("### START ====================================", sslstrm);
            sslstrm.AuthenticateAsClient("imap.gmail.com");
            strmlgw.WriteLine("# Send blank =================================", sslstrm);
            SendImapCommand("", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'LOGIN' ===============================", sslstrm);
            SendImapCommand("$ LOGIN " + sUserid + " " + sPassword + "  \r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'SELECT INBOX' ========================", sslstrm);
            SendImapCommand("$ SELECT INBOX\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

//			strmlgw.WriteLine("# Send 'TATUS INBOX (MESSAGES)' ==============", sslstrm);
//			SendImapCommand("$ STATUS INBOX (MESSAGES)\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			int number = 1;
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODYSTRUCTURE' =======", sslstrm);
//			SendImapCommand("$ FETCH " + number + " bodystructure\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODY[HEADER]' ========", sslstrm);
//			SendImapCommand("$ FETCH " + number + " body[header]\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'FETCH 1 body[text]' ==================", sslstrm);
            SendImapCommand("$ FETCH 1 body[text]\r\n", sslstrm);
            ReceiveMailBody(sDpath, tcpclnt, sslstrm);

            string sTempTimeSheetPath = ExtractAttachedFile(sDpath, sEpath);

            strmlgw.WriteLine("# Send 'LOGOUT' ==============================", sslstrm);
            SendImapCommand("$ LOGOUT\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);
            strmlgw.WriteLine("### END ======================================", sslstrm);

            strmlgw.Close(); strmlgw.Dispose();
            sslstrm.Close(); sslstrm.Dispose();
            tcpclnt.Close();

            File.Delete(sLpath);
            File.Delete(sDpath);

            return(sTempTimeSheetPath);
        }