예제 #1
0
        private string sendAndExpect(string toSend, int statusCode)
        {
            if (toSend != null)
            {
                _writer.Write(toSend + "\r\n");
                _conversation.Add("> " + toSend);
                _log.Debug(8, "> " + toSend);
            }
            string response = "";
            Match  m;

            do
            {
                var line = _reader.ReadLine();
                _conversation.Add("< " + line);
                _log.Debug(8, "< " + line);
                m = Regex.Match(line, @"^(\d+)(-| |$)?(.*)?$");
                if (!m.Success)
                {
                    throw new RTSmtpException("Expected status code '{0}', got unexpected line: {1}".Fmt(statusCode, line), _conversation);
                }
                if (int.Parse(m.Groups[1].Value) != statusCode)
                {
                    throw new RTSmtpException("Expected status code '{0}', got: {1}.".Fmt(statusCode, line), _conversation);
                }
                response += m.Groups[3].Value.Trim() + Environment.NewLine;
            }while (m.Groups[2].Value == "-");
            return(response);
        }
예제 #2
0
        /// <summary>
        ///     Creates a connection to the SMTP server and authenticates the specified user.</summary>
        /// <param name="host">
        ///     SMTP host name.</param>
        /// <param name="port">
        ///     SMTP host port.</param>
        /// <param name="username">
        ///     SMTP username.</param>
        /// <param name="password">
        ///     SMTP password.</param>
        /// <param name="encryption">
        ///     Encryption mode.</param>
        /// <param name="log">
        ///     The SMTP client logs various messages to this log at various verbosity levels.</param>
        /// <param name="timeout">
        ///     Network stream read/write timeout, in milliseconds.</param>
        /// <exception cref="RTSmtpException">
        ///     SMTP protocol error, or authentication failed.</exception>
        /// <exception cref="IOException">
        ///     Network error or timeout.</exception>
        public RTSmtpClient(string host, int port, string username = null, string password = null, SmtpEncryption encryption = SmtpEncryption.None, LoggerBase log = null, int timeout = 10000)
        {
            _log = log ?? new NullLogger();
            _log.Debug(2, "Connecting to {0}:{1}...".Fmt(host, port));
            _tcp       = new TcpClient(host, port);
            _tcpStream = _tcp.GetStream();
            if (encryption == SmtpEncryption.Ssl || encryption == SmtpEncryption.SslIgnoreCert)
            {
                if (encryption == SmtpEncryption.Ssl)
                {
                    _sslStream = new SslStream(_tcpStream);
                }
                else
                {
                    _sslStream = new SslStream(_tcpStream, false, (_, __, ___, ____) => true);
                }
                _sslStream.AuthenticateAsClient(host);
                _log.Debug(3, "SSL: authenticated as client");
            }
            (_sslStream ?? _tcpStream).ReadTimeout  = timeout;
            (_sslStream ?? _tcpStream).WriteTimeout = timeout;
            _writer = new StreamWriter(_sslStream ?? _tcpStream, new UTF8Encoding(false))
            {
                NewLine = "\r\n", AutoFlush = true
            };
            _reader       = new StreamReader(_sslStream ?? _tcpStream, Encoding.UTF8);
            _conversation = new List <string>();

            sendAndExpect(null, 220);
            sendAndExpect("EHLO localhost", 250);
            if (username == null || password == null)
            {
                _log.Debug(3, "Connected without authentication.");
                return;
            }

            var result    = sendAndExpect("AUTH LOGIN", 334).Trim();
            var resultDec = Convert.FromBase64String(result).FromUtf8();

            if (resultDec != "Username:"******"Expected 'Username:'******'{0}'".Fmt(resultDec), _conversation);
            }
            result    = sendAndExpect(Convert.ToBase64String(username.ToUtf8()), 334).Trim();
            resultDec = Convert.FromBase64String(result).FromUtf8();
            if (resultDec != "Password:"******"Expected 'Password:'******'{0}'".Fmt(resultDec), _conversation);
            }
            sendAndExpect(Convert.ToBase64String(password.ToUtf8()), 235);
            _log.Debug(3, "Connected.");
        }
예제 #3
0
파일: HClient.cs 프로젝트: biorpg/RT.Util
        private HResponse performRequest(HttpWebRequest request)
        {
            Log.Debug(1, "Requested ({0}) URL \"{1}\"".Fmt(request.Method, request.RequestUri.OriginalString));
            for (int i = 0; i < request.Headers.Count; i++)
            {
                Log.Debug(3, "  " + request.Headers.AllKeys[i] + ": " + request.Headers[i]);
            }
            if (request.CookieContainer != null && request.CookieContainer.Count > 0)
            {
                Log.Debug(3, "  Cookie: " + request.CookieContainer.GetCookieHeader(request.RequestUri));
            }

            HResponse       result;
            HttpWebResponse resp;

            try
            {
                resp = (HttpWebResponse)request.GetResponse();
                if (resp == null)
                {
                    throw new WebException("Received a null response.");
                }
                result = new HResponse(resp);
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw new WebException("Caught WebException containing no response.", e);
                }
                else
                {
                    result = new HResponse(resp = (HttpWebResponse)e.Response);
                }
            }
            Log.Debug(2, "Response: " + result.StatusCode + " - " + result.DataString.SubstringSafe(0, 50));
            for (int i = 0; i < resp.Headers.Count; i++)
            {
                Log.Debug(3, "  " + resp.Headers.AllKeys[i] + ": " + resp.Headers[i]);
            }
            return(result);
        }
예제 #4
0
        /// <summary>
        ///     Creates a connection to the SMTP server and authenticates the specified user.</summary>
        /// <param name="host">
        ///     SMTP host name.</param>
        /// <param name="port">
        ///     SMTP host port.</param>
        /// <param name="username">
        ///     SMTP username.</param>
        /// <param name="password">
        ///     SMTP password.</param>
        /// <param name="encryption">
        ///     Encryption mode.</param>
        /// <param name="log">
        ///     The SMTP client logs various messages to this log at various verbosity levels.</param>
        /// <param name="timeout">
        ///     Network stream read/write timeout, in milliseconds.</param>
        /// <exception cref="RTSmtpException">
        ///     SMTP protocol error, or authentication failed.</exception>
        /// <exception cref="IOException">
        ///     Network error or timeout.</exception>
        public RTSmtpClient(string host, int port, string username, string password, SmtpEncryption encryption = SmtpEncryption.None, LoggerBase log = null, int timeout = 10000)
        {
            _log = log ?? new NullLogger();
            _log.Debug(2, "Connecting to {0}:{1}...".Fmt(host, port));
            _tcp = new TcpClient(host, port);
            _tcpStream = _tcp.GetStream();
            if (encryption == SmtpEncryption.Ssl || encryption == SmtpEncryption.SslIgnoreCert)
            {
                if (encryption == SmtpEncryption.Ssl)
                    _sslStream = new SslStream(_tcpStream);
                else
                    _sslStream = new SslStream(_tcpStream, false, (_, __, ___, ____) => true);
                _sslStream.AuthenticateAsClient(host);
                _log.Debug(3, "SSL: authenticated as client");
            }
            (_sslStream ?? _tcpStream).ReadTimeout = timeout;
            (_sslStream ?? _tcpStream).WriteTimeout = timeout;
            _writer = new StreamWriter(_sslStream ?? _tcpStream, new UTF8Encoding(false)) { NewLine = "\r\n", AutoFlush = true };
            _reader = new StreamReader(_sslStream ?? _tcpStream, Encoding.UTF8);
            _conversation = new List<string>();

            sendAndExpect(null, 220);
            sendAndExpect("EHLO localhost", 250);
            var result = sendAndExpect("AUTH LOGIN", 334).Trim();
            var resultDec = Convert.FromBase64String(result).FromUtf8();
            if (resultDec != "Username:"******"Expected 'Username:'******'{0}'".Fmt(resultDec), _conversation);
            result = sendAndExpect(Convert.ToBase64String(username.ToUtf8()), 334).Trim();
            resultDec = Convert.FromBase64String(result).FromUtf8();
            if (resultDec != "Password:"******"Expected 'Password:'******'{0}'".Fmt(resultDec), _conversation);
            sendAndExpect(Convert.ToBase64String(password.ToUtf8()), 235);
            _log.Debug(3, "Connected.");
        }