Beispiel #1
0
        public CrestronClientSocket(string host, int port)
        {
            Debug.WriteLine("Client Create and Connect ({0}:{1}", host, port);

            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            var ipaddresses = DnsEx.GetHostAddresses(host);

            if (ipaddresses.Length == 0)
            {
                throw new SocketException(SocketError.HostNotFound);
            }

            _client = new TCPClient
            {
                AddressClientConnectedTo = ipaddresses[0].ToString(),
                PortNumber = port,
                Nagle      = true
            };

            SetupClient();
        }
Beispiel #2
0
        private void AsyncConnectComplete(TCPClient client, object state)
        {
#if DEBUG
            if (_disposed != 0 || _client == null)
            {
                var ipaddrs        = DnsEx.GetHostAddresses(client.AddressClientConnectedTo);
                var remoteEndPoint = ipaddrs.Length == 0 ? new IPEndPoint(IPAddress.None, client.PortNumber) : new IPEndPoint(ipaddrs[0], client.PortNumber);

                Debug.WriteLine("Client ({0}): AsyncConnectComplete - client disposed [{1}]", remoteEndPoint, client.ClientStatus);
            }
            else
            {
                Debug.WriteLine("Client ({0}): AsyncConnectComplete", InternalRemoteEndPoint);
            }
#endif

            var acs = (AsyncConnectState)state;
            var iar = acs.AsyncResult;
            var cb  = acs.AsyncCallback;

            iar.IsCompleted = true;
            ((CEvent)iar.AsyncWaitHandle).Set();

            var scir = (SocketClientConnectAsyncResult)iar;
            scir.Status = client.ClientStatus;

            if (cb != null)
            {
                DoAsyncCallback(cb, iar);
            }
        }
Beispiel #3
0
        public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state)
        {
            CheckDisposed();

            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            var addresses = DnsEx.GetHostAddresses(host);

            return(BeginConnect(addresses, port, callback, state));
        }
Beispiel #4
0
        private String Find_MX_records(String pDomainName)
        {
            String dnsServer = "8.8.8.8"; //let's use Mr. Google.

            DnsEx.DnsServers = new string[] { dnsServer };
            DnsEx             dns      = new DnsEx();
            DnsServerResponse response = null;

            String hostname = pDomainName;

            try
            {
                response = dns.Query(hostname, QTYPE.MX);
            }
            catch (Exception ex)
            {
                //throw new Exception("Network: Failed due to network connectivity of DNS to 8.8.8.8" + ex.ToString());
                return("DNS queries to 8.8.8.8 are not allowed");
            }

            StringBuilder sb = new StringBuilder();

            foreach (object rec in response.Answers)
            {
                if (rec is NS_Record)
                {
                    sb.Append(((NS_Record)rec).NameServer + "\n");
                }
                else if (rec is CNAME_Record)
                {
                    sb.Append(((CNAME_Record)rec).Alias + "\n");
                }

                else if (rec is MX_Record)
                {
                    sb.Append(((MX_Record)rec).Host + " ");
                    sb.Append("(Preference: " + ((MX_Record)rec).Preference.ToString() + ") \n");
                }
            }

            if (sb.ToString() == "")
            {
                return("No MX records.");
            }
            else
            {
                return(sb.ToString());
            }
        }
        /// <summary>
        ///     Processes the record.
        /// </summary>
        protected override void ProcessRecord()
        {
            Hostname = Hostname ?? DnsEx.GetDnsHostName();

            try
            {
                using (var connection = GetConnection(Hostname, Credential.UserName, Credential.GetNetworkCredential().Password, UseTls))
                {
                    using (var model = connection.CreateModel())
                    {
                        if (model.IsOpen)
                        {
                            WriteVerbose("Connection successful");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Connection failed. There might be an issue with the installation. Please check the RabbitMq log files:" + ex.Message, ex);
            }
        }
        public void Connect(string hostname, int port)
        {
            CheckDisposed();

            if (hostname == null)
            {
                throw new ArgumentNullException("hostname");
            }

            if (port < 0 || port > 65535)
            {
                throw new ArgumentOutOfRangeException("port");
            }

            var addresses = DnsEx.GetHostAddresses(hostname);

            if (addresses.Length == 0)
            {
                throw new SocketException(SocketError.HostNotFound);
            }

            Connect(addresses, port);
        }
        internal static bool CheckSameOrigin(Uri uri, string domain)
        {
            if (!CheckPublicRoots(domain))
            {
                return(false);
            }

            IPAddress address;

#if SSHARP
            if (IPAddressTryParser.IPAddressTryParse(domain, out address))
#else
            if (IPAddress.TryParse(domain, out address))
#endif
            {
                if (domain[0] == '.')
                {
                    return(false);
                }

#if SSHARP
                foreach (var ip in DnsEx.GetHostAddresses(uri.DnsSafeHost))
#else
                foreach (var ip in Dns.GetHostAddresses(uri.DnsSafeHost))
#endif
                {
                    if (address.Equals(ip))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            return(CheckDomain(domain, uri.Host, false));
        }
Beispiel #8
0
        public static string AwaitDnsUpsert(FargateResourceV2 resource, FargateResourceV2 resourceNew, Route53Helper r53, int recordDnsUpdateTimeout)
        {
            var hostedZoneName = r53
                                 .GetHostedZoneAsync(resource.IsPublic ? resource.ZonePublic : resource.ZonePrivate)
                                 .Result.HostedZone.Name.TrimEnd('.');

            var uriNew           = $"{resourceNew.DNSCName}.{hostedZoneName}";
            var uri              = $"{resource.DNSCName}.{hostedZoneName}";
            var expectedHostName = DnsEx.GetHostName(uriNew, recordDnsUpdateTimeout / 2);

            string newRecord;
            var    sw = Stopwatch.StartNew();

            while ((newRecord = DnsEx.GetHostName(uri, recordDnsUpdateTimeout / 10)) != expectedHostName)
            {
                Task.Delay(1000);
                if (sw.ElapsedMilliseconds >= recordDnsUpdateTimeout)
                {
                    throw new Exception($"Failed to update Private DNS Record Set, expected: {expectedHostName}, got: {newRecord}, elapsed: {sw.ElapsedMilliseconds}/{recordDnsUpdateTimeout}");
                }
            }

            return(newRecord);
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="p_receipients"></param>
        /// <param name="p_reversePath"></param>
        /// <param name="p_message"></param>
        /// <returns></returns>
        private bool SendMessageToServer(string[] p_receipients, string p_reversePath, Stream p_message)
        {
            ArrayList _defectiveEmails = new ArrayList();

            Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                string _reply = "";

                var _SIZE_Support = false;
                var _8BIT_Support = false;
                var _BDAT_Support = false;

                if (UseSmartHost == true)
                {
                    IPEndPoint _ipdestination = new IPEndPoint(System.Net.Dns.GetHostEntry(SmartHost).AddressList[0], Port);
                    _socket.Connect(_ipdestination);
                }
                else
                {
                    //---- Parse e-domain -------------------------------//
                    string _emailDomain = p_receipients[0];

                    // eg. Ivx <*****@*****.**>
                    if (_emailDomain.IndexOf("<") > -1 && _emailDomain.IndexOf(">") > -1)
                    {
                        _emailDomain = _emailDomain.Substring(_emailDomain.IndexOf("<") + 1, _emailDomain.IndexOf(">") - _emailDomain.IndexOf("<") - 1);
                    }

                    if (_emailDomain.IndexOf("@") > -1)
                    {
                        _emailDomain = _emailDomain.Substring(_emailDomain.LastIndexOf("@") + 1);
                    }

                    //--- Get MX record -------------------------------------------//
                    DnsEx _dnsex = new DnsEx();
                    DnsEx.DnsServers = DnsServers;

                    MX_Record[]  _mxRecords = null;
                    DnsReplyCode _replyCode = _dnsex.GetMXRecords(_emailDomain, out _mxRecords);

                    switch (_replyCode)
                    {
                    case DnsReplyCode.Ok:
                        var _isConnected = false;

                        // Try all available hosts by MX preference order, if can't connect specified host.
                        foreach (MX_Record _mx in _mxRecords)
                        {
                            try
                            {
                                _socket.Connect(new IPEndPoint(System.Net.Dns.GetHostEntry(_mx.Host).AddressList[0], Port));

                                _isConnected = true;
                                break;
                            }
                            catch (Exception ex)
                            {
                                // Just skip and let for to try next host.
                                OnFaulted(SmtpErrorType.ConnectionError, p_receipients, "While retriveing MX-Servers, raise exception error: " + ex.Message);
                            }
                        }

                        if (_isConnected == false)
                        {
                            return(false);
                        }

                        break;

                    case DnsReplyCode.NoEntries:
                        /* Rfc 2821 5
                         * If   no MX records are found, but an A RR is found, the A RR is treated as
                         * if it was associated with an implicit MX RR, with a preference of 0,
                         * pointing to that host.
                         *
                         */
                        try     // Try to connect with A record
                        {
                            IPHostEntry _ipEntry = System.Net.Dns.GetHostEntry(_emailDomain);
                            _socket.Connect(new IPEndPoint(_ipEntry.AddressList[0], Port));
                        }
                        catch
                        {
                            OnFaulted(SmtpErrorType.InvalidEmailAddress, p_receipients, String.Format("email domain <{0}> is invalid", _emailDomain));

                            _defectiveEmails.AddRange(p_receipients);
                            return(false);
                        }
                        break;

                    case DnsReplyCode.TempError:
                        string _dnsServers = "";
                        foreach (string s in DnsServers)
                        {
                            _dnsServers += s + ";";
                        }

                        throw new Exception(String.Format("Error retrieving MX record for domain '{0}' with dns servers:{{{1}}}.", _emailDomain, _dnsServers));
                    }
                }

                string _sessionId   = _socket.GetHashCode().ToString();
                string _connectedip = SmtpCore.ParseIP_from_EndPoint(_socket.RemoteEndPoint.ToString());

                // Get 220 reply from server

                /* NOTE: reply may be multiline
                 *                 220 xx ready
                 *                  or
                 *                 220-someBull
                 *                 200 xx
                 */

                // Server must reply 220 - Server OK
                _reply = ReadLine(_socket, _sessionId, _connectedip, true);
                if (IsReplyCode("220", _reply) == false)
                {
                    OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                    SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                    return(false);
                }
                else
                {
                    // 220-xxx<CRLF>
                    // 220 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (_reply.IndexOf("220 ") == -1)
                    {
                        _reply += ReadLine(_socket, _sessionId, _connectedip, false);
                    }
                }

                // cmd EHLO/HELO

                // Send greeting to server
                SendLine(_socket, _sessionId, _connectedip, "EHLO " + SmtpCore.GetHostName(), true);

                _reply = ReadLine(_socket, _sessionId, _connectedip, true);
                if (IsReplyCode("250", _reply) == false)
                {
                    // EHLO failed, maybe server doesn't support it, try HELO

                    SendLine(_socket, _sessionId, _connectedip, "HELO " + SmtpCore.GetHostName(), true);

                    _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                    if (IsReplyCode("250", _reply) == false)
                    {
                        OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                        SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                        _defectiveEmails.AddRange(p_receipients);
                        return(false);
                    }
                    //	else
                    //  {
                    //		supports_ESMTP = false;
                    //	}
                }
                else
                {
                    // 250-xxx<CRLF>
                    // 250 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (_reply.IndexOf("250 ") == -1)
                    {
                        _reply += ReadLine(_socket, _sessionId, _connectedip, false);
                    }

                    // Check if SIZE argument is supported
                    if (_reply.ToUpper().IndexOf("SIZE") > -1)
                    {
                        _SIZE_Support = true;
                    }

                    // Check if 8BITMIME argument is supported
                    if (_reply.ToUpper().IndexOf("8BITMIME") > -1)
                    {
                        _8BIT_Support = true;
                    }

                    // Check if CHUNKING argument is supported
                    if (_reply.ToUpper().IndexOf("CHUNKING") > -1)
                    {
                        _BDAT_Support = true;
                    }
                }

                // If server doesn't support 8bit mime, check if message is 8bit.
                // If is we MAY NOT send this message or loss of data
                if (_8BIT_Support == false)
                {
                    if (Is8BitMime(p_message) == true)
                    {
                        OnFaulted(SmtpErrorType.NotSupported, p_receipients, "Message is 8-Bit mime and server doesn't support it.");
                        SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                        return(false);
                    }
                }

                // cmd MAIL
                // NOTE: Syntax:{MAIL FROM:<*****@*****.**> [SIZE=msgSize]<CRLF>}

                // Send Mail From
                if (_SIZE_Support == true)
                {
                    SendLine(_socket, _sessionId, _connectedip, String.Format("MAIL FROM:<{0}> SIZE={1}", p_reversePath, p_message.Length), true);
                }
                else
                {
                    SendLine(_socket, _sessionId, _connectedip, String.Format("MAIL FROM:<{0}>", p_reversePath), true);
                }

                _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                if (IsReplyCode("250", _reply) == false)
                {
                    // To Do: Check if size exceeded error:

                    OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                    SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                    _defectiveEmails.AddRange(p_receipients);
                    return(false);
                }

                // cmd RCPT
                // NOTE: Syntax:{RCPT TO:<*****@*****.**><CRLF>}

                var _isAnyValidEmail = false;
                foreach (string _receipt in p_receipients)
                {
                    // Send Mail To
                    SendLine(_socket, _sessionId, _connectedip, String.Format("RCPT TO:<{0}>", _receipt), true);

                    _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                    if (IsReplyCode("250", _reply) == false)
                    {
                        // Is unknown user
                        if (IsReplyCode("550", _reply))
                        {
                            OnFaulted(SmtpErrorType.InvalidEmailAddress, new string[] { _receipt }, _reply);
                        }
                        else
                        {
                            OnFaulted(SmtpErrorType.UnKnown, new string[] { _receipt }, _reply);
                        }

                        _defectiveEmails.Add(_receipt);
                    }
                    else
                    {
                        _isAnyValidEmail = true;
                    }
                }

                // If there isn't any valid email - quit.
                if (_isAnyValidEmail == false)
                {
                    SendLine(_socket, _sessionId, _connectedip, "QUIT", true);
                    return(false);
                }

                // cmd DATA

                if (_BDAT_Support == false)
                {
                    // Notify Data Start
                    SendLine(_socket, _sessionId, _connectedip, "DATA", false);

                    _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                    if (IsReplyCode("354", _reply) == false)
                    {
                        OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                        SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                        _defectiveEmails.AddRange(p_receipients);
                        return(false);
                    }

                    //------- Do period handling -----------------------------------------//
                    // If line starts with '.', add additional '.'.(Read rfc for more info)
                    MemoryStream _periodOk = SmtpCore.DoPeriodHandling(p_message, true, false);
                    //--------------------------------------------------------------------//

                    // Check if message ends with <CRLF>, if not add it. -------//
                    if (_periodOk.Length >= 2)
                    {
                        byte[] _byteEnd = new byte[2];
                        _periodOk.Position = _periodOk.Length - 2;
                        _periodOk.Read(_byteEnd, 0, 2);

                        if (_byteEnd[0] != (byte)'\r' && _byteEnd[1] != (byte)'\n')
                        {
                            _periodOk.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
                        }
                    }

                    _periodOk.Position = 0;
                    //-----------------------------------------------------------//

                    //---- Send message --------------------------------------------//
                    long _totalSent = 0;
                    long _totalSize = _periodOk.Length;

                    while (_totalSent < _totalSize)
                    {
                        byte[] _buffer = new byte[4000];

                        int _readSize = _periodOk.Read(_buffer, 0, _buffer.Length);
                        int _sentSize = _socket.Send(_buffer, 0, _readSize, SocketFlags.None);

                        _totalSent += _sentSize;
                        if (_sentSize != _readSize)
                        {
                            _periodOk.Position = _totalSent;
                        }

                        OnProgress(_sentSize, _totalSent, _totalSize);
                    }

                    //-------------------------------------------------------------//
                    _periodOk.Close();

                    // Notify End of Data
                    SendLine(_socket, _sessionId, _connectedip, ".", false);

                    _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                    if (IsReplyCode("250", _reply) == false)
                    {
                        OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                        SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                        _defectiveEmails.AddRange(p_receipients);
                        return(false);
                    }
                }

                // cmd BDAT

                if (_BDAT_Support)
                {
                    SendLine(_socket, _sessionId, _connectedip, String.Format("BDAT {0} LAST", (p_message.Length - p_message.Position)), false);

                    //---- Send message --------------------------------------------//
                    long _totalSent = 0;
                    long _totalSize = p_message.Length - p_message.Position;

                    while (_totalSent < _totalSize)
                    {
                        byte[] _buffer = new byte[4000];

                        int _readSize = p_message.Read(_buffer, 0, _buffer.Length);
                        int _sentSize = _socket.Send(_buffer, 0, _readSize, SocketFlags.None);

                        _totalSent += _sentSize;
                        if (_sentSize != _readSize)
                        {
                            p_message.Position = _totalSent;
                        }

                        OnProgress(_sentSize, _totalSent, _totalSize);
                    }
                    //-------------------------------------------------------------//

                    // Get store result
                    _reply = ReadLine(_socket, _sessionId, _connectedip, false);
                    if (_reply.StartsWith("250") == false)
                    {
                        OnFaulted(SmtpErrorType.UnKnown, p_receipients, _reply);
                        SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                        _defectiveEmails.AddRange(p_receipients);
                        return(false);
                    }
                }

                // cmd QUIT

                // Notify server - server can exit now
                SendLine(_socket, _sessionId, _connectedip, "QUIT", true);

                _reply = ReadLine(_socket, _sessionId, _connectedip, true);
            }
            catch (Exception ex)
            {
                OnFaulted(SmtpErrorType.UnKnown, p_receipients, ex.Message);

                _defectiveEmails.AddRange(p_receipients);
                return(false);
            }
            finally
            {
                // Raise event
                OnCompleted(Thread.CurrentThread.GetHashCode().ToString(), p_receipients, _defectiveEmails);

                _socket.Close();
            }

            return(true);
        }
Beispiel #10
0
        //---- SMTP implementation ----//

        #region function SendMessageToServer

        private bool SendMessageToServer(string[] to, string reverse_path, Stream message)
        {
            // Get email from to string
            for (int i = 0; i < to.Length; i++)
            {
                to[i] = (new LumiSoft.Net.Mime.Parser.eAddress(to[i])).Email;
            }

            ArrayList defectiveEmails = new ArrayList();

            Socket         so     = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            BufferedSocket socket = new BufferedSocket(so);

            SocketLogger logger = null;

            if (m_LogCmds && this.SessionLog != null)
            {
                logger           = new SocketLogger(so, this.SessionLog);
                logger.SessionID = socket.GetHashCode().ToString();
                socket.Logger    = logger;
            }

            try{
                string reply         = "";
                bool   supports_SIZE = false;
                bool   supports_8BIT = false;
                bool   supports_BDAT = false;
                #region connect to server
                if (m_UseSmartHost)
                {
                    socket.Connect(new IPEndPoint(System.Net.Dns.Resolve(m_SmartHost).AddressList[0], m_Port));
                }
                else
                {
                    //---- Parse e-domain -------------------------------//
                    string domain = to[0];

                    // eg. Ivx <*****@*****.**>
                    if (domain.IndexOf("<") > -1 && domain.IndexOf(">") > -1)
                    {
                        domain = domain.Substring(domain.IndexOf("<") + 1, domain.IndexOf(">") - domain.IndexOf("<") - 1);
                    }

                    if (domain.IndexOf("@") > -1)
                    {
                        domain = domain.Substring(domain.LastIndexOf("@") + 1);
                    }

                    if (domain.Trim().Length == 0)
                    {
                        if (logger != null)
                        {
                            logger.AddTextEntry("Destination address '" + to[0] + "' is invalid, aborting !");
                        }
                        return(false);
                    }

                    //System.Net.Dns.
                    //--- Get MX record -------------------------------------------//
                    DnsEx dns = new DnsEx();
                    DnsEx.DnsServers = m_DnsServers;
                    DnsServerResponse dnsResponse = dns.Query(domain, QTYPE.MX);

                    switch (dnsResponse.ResponseCode)
                    {
                    case RCODE.NO_ERROR:
                        MX_Record[] mxRecords = dnsResponse.GetMXRecords();

                        // Try all available hosts by MX preference order, if can't connect specified host.
                        foreach (MX_Record mx in mxRecords)
                        {
                            try{
                                if (logger != null)
                                {
                                    logger.AddTextEntry("Connecting with mx record to: " + mx.Host);
                                }
                                socket.Connect(new IPEndPoint(System.Net.Dns.Resolve(mx.Host).AddressList[0], m_Port));
                                break;
                            }
                            catch {                                    // Just skip and let for to try next host.
                                if (logger != null)
                                {
                                    logger.AddTextEntry("Failed connect to: " + mx.Host);
                                }
                            }
                        }

                        /* Rfc 2821 5
                         * If no MX records are found, but an A RR is found, the A RR is treated as
                         * if it was associated with an implicit MX RR, with a preference of 0,
                         * pointing to that host.
                         *
                         */
                        if (mxRecords.Length == 0)
                        {
                            // Try to connect with A record
                            IPHostEntry ipEntry = null;
                            try{
                                if (logger != null)
                                {
                                    logger.AddTextEntry("No mx record, trying to get A record for: " + domain);
                                }
                                ipEntry = System.Net.Dns.Resolve(domain);
                            }
                            catch {
                                if (logger != null)
                                {
                                    logger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                                }
                                OnError(SMTP_ErrorType.InvalidEmailAddress, to, "email domain <" + domain + "> is invalid");

                                defectiveEmails.AddRange(to);

                                if (logger != null)
                                {
                                    logger.Flush();
                                }
                                return(false);
                            }

                            try{
                                if (logger != null)
                                {
                                    logger.AddTextEntry("Connecting with A record to:" + domain);
                                }
                                socket.Connect(new IPEndPoint(ipEntry.AddressList[0], m_Port));
                            }
                            catch {
                                if (logger != null)
                                {
                                    logger.AddTextEntry("Failed connect to:" + domain);
                                }
                            }
                        }
                        break;

                    case RCODE.NAME_ERROR:
                        if (logger != null)
                        {
                            logger.AddTextEntry("Invalid domain,no MX or A record: " + domain);
                        }
                        OnError(SMTP_ErrorType.InvalidEmailAddress, to, "email domain <" + domain + "> is invalid");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);

                    case RCODE.SERVER_FAILURE:
                        if (logger != null)
                        {
                            logger.AddTextEntry("Dns server unvailable.");
                        }
                        OnError(SMTP_ErrorType.UnKnown, to, "Dns server unvailable.");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);
                    }
                }

                if (!socket.Connected)
                {
                    OnError(SMTP_ErrorType.UnKnown, to, "Unable connect to server !");

                    if (logger != null)
                    {
                        logger.Flush();
                    }
                    return(false);
                }

                #endregion
                #region Get 220 reply from server

                /* NOTE: reply may be multiline
                 * 220 xx ready
                 *  or
                 * 220-someBull
                 * 200 xx
                 */

                // Server must reply 220 - Server OK
                reply = socket.ReadLine();
                if (!IsReplyCode("220", reply))
                {
                    OnError(SMTP_ErrorType.UnKnown, to, reply);
                    socket.SendLine("QUIT");

                    if (logger != null)
                    {
                        logger.Flush();
                    }
                    return(false);
                }
                else
                {
                    // 220-xxx<CRLF>
                    // 220 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (reply.IndexOf("220 ") == -1)
                    {
                        reply += socket.ReadLine();
                    }
                }

                #endregion


                #region cmd EHLO/HELO

                // Send greeting to server
                socket.SendLine("EHLO " + m_HostName);

                reply = socket.ReadLine();
                if (!IsReplyCode("250", reply))
                {
                    // EHLO failed, mayby server doesn't support it, try HELO
                    socket.SendLine("HELO " + m_HostName);
                    reply = socket.ReadLine();
                    if (!IsReplyCode("250", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        socket.SendLine("QUIT");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);
                    }
                    //	else{
                    //		supports_ESMTP = false;
                    //	}
                }
                else
                {
                    // 250-xxx<CRLF>
                    // 250 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (reply.IndexOf("250 ") == -1)
                    {
                        reply += socket.ReadLine();
                    }

                    // Check if SIZE argument is supported
                    if (reply.ToUpper().IndexOf("SIZE") > -1)
                    {
                        supports_SIZE = true;
                    }

                    // Check if 8BITMIME argument is supported
                    if (reply.ToUpper().IndexOf("8BITMIME") > -1)
                    {
                        supports_8BIT = true;
                    }

                    // Check if CHUNKING argument is supported
                    if (reply.ToUpper().IndexOf("CHUNKING") > -1)
                    {
                        supports_BDAT = true;
                    }
                }

                #endregion

                // If server doesn't support 8bit mime, check if message is 8bit.
                // If is we MAY NOT send this message or loss of data

                /*		if(!supports_8BIT){
                 *                      if(Is8BitMime(message)){
                 *                              OnError(SMTP_ErrorType.NotSupported,to,"Message is 8-Bit mime and server doesn't support it.");
                 *                              socket.SendLine("QUIT");
                 *
                 *                              if(logger != null){
                 *                                      logger.Flush();
                 *                              }
                 *                              return false;
                 *                      }
                 *              }*/


                #region cmd AUTH

                if (this.m_Username != null && m_Username.Length > 0 && m_Password != null && m_Password.Length > 0)
                {
                    if (reply.ToUpper().IndexOf("AUTH") > -1)
                    {
                        if (reply.ToUpper().IndexOf("LOGIN") > -1)
                        {
                            socket.SendLine("AUTH LOGIN");
                            reply = socket.ReadLine();
                            if (!IsReplyCode("334", reply))
                            {
                                OnError(SMTP_ErrorType.NotAuthenticated, to, "Failed to authenticate");
                                socket.SendLine("QUIT");

                                if (logger != null)
                                {
                                    logger.Flush();
                                }
                                return(false);
                            }

                            socket.SendLine(Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(m_Username.ToCharArray())));
                            reply = socket.ReadLine();
                            if (!IsReplyCode("334", reply))
                            {
                                OnError(SMTP_ErrorType.NotAuthenticated, to, "Failed to authenticate");
                                socket.SendLine("QUIT");

                                if (logger != null)
                                {
                                    logger.Flush();
                                }
                                return(false);
                            }

                            socket.SendLine(Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(m_Password.ToCharArray())));
                            reply = socket.ReadLine();
                            if (!IsReplyCode("235", reply))
                            {
                                OnError(SMTP_ErrorType.NotAuthenticated, to, "Failed to authenticate");
                                socket.SendLine("QUIT");

                                if (logger != null)
                                {
                                    logger.Flush();
                                }
                                return(false);
                            }
                        }
//						if(reply.ToUpper().IndexOf("CRAM-MD5") > -1)
//						{
//							socket.SendLine("AUTH CRAM-MD5");
//							reply = socket.ReadLine();
//							if (IsReplyCode("334",auth))
//							{
//								socket.SendLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(m_Username.ToCharArray())));
//								socket.SendLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(m_Password.ToCharArray())));
//							}
//						}
                    }
                    else
                    {
                        //server did not support AUTH
                    }
                }

                #endregion

                #region cmd MAIL
                // NOTE: Syntax:{MAIL FROM:<*****@*****.**> [SIZE=msgSize]<CRLF>}

                // Send Mail From
                if (supports_SIZE)
                {
                    socket.SendLine("MAIL FROM:<" + reverse_path + "> SIZE=" + (message.Length - message.Position));
                }
                else
                {
                    socket.SendLine("MAIL FROM:<" + reverse_path + ">");
                }

                reply = socket.ReadLine();
                if (!IsReplyCode("250", reply))
                {
                    // To Do: Check if size exceeded error:

                    OnError(SMTP_ErrorType.UnKnown, to, reply);
                    socket.SendLine("QUIT");

                    defectiveEmails.AddRange(to);

                    if (logger != null)
                    {
                        logger.Flush();
                    }
                    return(false);
                }

                #endregion

                #region cmd RCPT
                // NOTE: Syntax:{RCPT TO:<*****@*****.**><CRLF>}

                bool isAnyValidEmail = false;
                foreach (string rcpt in to)
                {
                    // Send Mail To
                    socket.SendLine("RCPT TO:<" + rcpt + ">");

                    reply = socket.ReadLine();
                    if (!IsReplyCode("250", reply))
                    {
                        // Is unknown user
                        if (IsReplyCode("550", reply))
                        {
                            OnError(SMTP_ErrorType.InvalidEmailAddress, new string[] { rcpt }, reply);
                        }
                        else
                        {
                            OnError(SMTP_ErrorType.UnKnown, new string[] { rcpt }, reply);
                        }

                        defectiveEmails.Add(rcpt);
                    }
                    else
                    {
                        isAnyValidEmail = true;
                    }
                }

                // If there isn't any valid email - quit.
                if (!isAnyValidEmail)
                {
                    socket.SendLine("QUIT");

                    if (logger != null)
                    {
                        logger.Flush();
                    }
                    return(false);
                }
                //---------------------------------------------//

                #endregion


                #region cmd DATA

                if (!supports_BDAT)
                {
                    // Notify Data Start
                    socket.SendLine("DATA");

                    reply = socket.ReadLine();
                    if (!IsReplyCode("354", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        socket.SendLine("QUIT");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);
                    }

                    //------- Do period handling -----------------------------------------//
                    // If line starts with '.', add additional '.'.(Read rfc for more info)
                    MemoryStream msgStrmPeriodOk = Core.DoPeriodHandling(message, true, false);
                    //--------------------------------------------------------------------//

                    // Check if message ends with <CRLF>, if not add it. -------//
                    if (msgStrmPeriodOk.Length >= 2)
                    {
                        byte[] byteEnd = new byte[2];
                        msgStrmPeriodOk.Position = msgStrmPeriodOk.Length - 2;
                        msgStrmPeriodOk.Read(byteEnd, 0, 2);

                        if (byteEnd[0] != (byte)'\r' && byteEnd[1] != (byte)'\n')
                        {
                            msgStrmPeriodOk.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
                        }
                    }
                    msgStrmPeriodOk.Position = 0;
                    //-----------------------------------------------------------//

                    //---- Send message --------------------------------------------//
                    long totalSent   = 0;
                    long totalLength = msgStrmPeriodOk.Length;
                    while (totalSent < totalLength)
                    {
                        byte[] dataBuf     = new byte[4000];
                        int    nCount      = msgStrmPeriodOk.Read(dataBuf, 0, dataBuf.Length);
                        int    countSended = socket.Send(dataBuf, 0, nCount, SocketFlags.None);
                        totalSent += countSended;

                        if (countSended != nCount)
                        {
                            msgStrmPeriodOk.Position = totalSent;
                        }

                        OnPartOfMessageIsSent(countSended, totalSent, totalLength);
                    }
                    //-------------------------------------------------------------//
                    msgStrmPeriodOk.Close();

                    // Notify End of Data
                    socket.SendLine(".");

                    reply = socket.ReadLine();
                    if (!IsReplyCode("250", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        socket.SendLine("QUIT");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);
                    }
                }

                #endregion

                #region cmd BDAT

                if (supports_BDAT)
                {
                    socket.SendLine("BDAT " + (message.Length - message.Position) + " LAST");

                    //---- Send message --------------------------------------------//
                    long totalSent   = 0;
                    long totalLength = message.Length - message.Position;
                    while (totalSent < totalLength)
                    {
                        byte[] dataBuf     = new byte[4000];
                        int    nCount      = message.Read(dataBuf, 0, dataBuf.Length);
                        int    countSended = socket.Send(dataBuf, 0, nCount, SocketFlags.None);
                        totalSent += countSended;

                        if (countSended != nCount)
                        {
                            message.Position = totalSent;
                        }

                        OnPartOfMessageIsSent(countSended, totalSent, totalLength);
                    }
                    //-------------------------------------------------------------//

                    // Get store result
                    reply = socket.ReadLine();
                    if (!reply.StartsWith("250"))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        socket.SendLine("QUIT");

                        defectiveEmails.AddRange(to);

                        if (logger != null)
                        {
                            logger.Flush();
                        }
                        return(false);
                    }
                }

                #endregion

                #region cmd QUIT

                // Notify server - server can exit now
                socket.SendLine("QUIT");

                //	reply = socket.ReadLine();

                #endregion
            }
            catch (Exception x) {
                OnError(SMTP_ErrorType.UnKnown, to, x.Message);

                defectiveEmails.AddRange(to);

                if (logger != null)
                {
                    logger.Flush();
                }
                return(false);
            }
            //finally{
            // Raise event
            //OnSendJobCompleted(Thread.CurrentThread.GetHashCode().ToString(),to,defectiveEmails);
            OnSendJobCompleted(Thread.CurrentThread.Name, to, defectiveEmails);
            //}

            if (logger != null)
            {
                logger.Flush();
            }

            return(true);
        }
        private static EndPointListener GetEPListener(string host, int port, HttpListener listener, bool secure)
        {
            IPAddress addr;

            if (host == "*")
            {
                addr = IPAddress.Any;
            }
#if SSHARP
            else if (IPAddressTryParser.IPAddressTryParse(host, out addr) == false)
#else
            else if (IPAddress.TryParse(host, out addr) == false)
#endif
            {
                try
                {
#if SSHARP
                    IPAddress[] addrs = DnsEx.GetHostAddresses(host);
                    if (addrs.Length != 0)
                    {
                        addr = addrs[0];
                    }
#else
                    IPHostEntry iphost = Dns.GetHostByName(host);
                    if (iphost != null)
                    {
                        addr = iphost.AddressList[0];
                    }
#endif
                    else
                    {
                        addr = IPAddress.Any;
                    }
                }
                catch
                {
                    addr = IPAddress.Any;
                }
            }
            Hashtable p = null;             // Dictionary<int, EndPointListener>
            if (ip_to_endpoints.ContainsKey(addr))
            {
                p = (Hashtable)ip_to_endpoints[addr];
            }
            else
            {
                p = new Hashtable();
                ip_to_endpoints[addr] = p;
            }

            EndPointListener epl = null;
            if (p.ContainsKey(port))
            {
                epl = (EndPointListener)p[port];
            }
            else
            {
                epl     = new EndPointListener(addr, port, secure);
                p[port] = epl;
            }

            return(epl);
        }
Beispiel #12
0
        //---- SMTP implementation ----//

        #region function SendMessageToServer

        private bool SendMessageToServer(string[] to, string reverse_path, Stream message)
        {
            // Get email from to string
            for (int i = 0; i < to.Length; i++)
            {
                to[i] = (new LumiSoft.Net.Mime.Parser.eAddress(to[i])).Email;
            }

            ArrayList defectiveEmails = new ArrayList();

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try{
                string reply         = "";
                bool   supports_SIZE = false;
                bool   supports_8BIT = false;
                bool   supports_BDAT = false;

                if (m_UseSmartHost)
                {
                    IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(m_SmartHost).AddressList[0], m_Port);
                    socket.Connect(ipdest);
                }
                else
                {
                    //---- Parse e-domain -------------------------------//
                    string domain = to[0];

                    // eg. Ivx <*****@*****.**>
                    if (domain.IndexOf("<") > -1 && domain.IndexOf(">") > -1)
                    {
                        domain = domain.Substring(domain.IndexOf("<") + 1, domain.IndexOf(">") - domain.IndexOf("<") - 1);
                    }

                    if (domain.IndexOf("@") > -1)
                    {
                        domain = domain.Substring(domain.LastIndexOf("@") + 1);
                    }

                    //--- Get MX record -------------------------------------------//
                    DnsEx dns = new DnsEx();
                    DnsEx.DnsServers = m_DnsServers;
                    MX_Record[]  mxRecords = null;
                    DnsReplyCode replyCode = dns.GetMXRecords(domain, out mxRecords);
                    switch (replyCode)
                    {
                    case DnsReplyCode.Ok:
                        // Try all available hosts by MX preference order, if can't connect specified host.
                        foreach (MX_Record mx in mxRecords)
                        {
                            try{
                                socket.Connect(new IPEndPoint(System.Net.Dns.Resolve(mx.Host).AddressList[0], m_Port));
                                break;
                            }
                            catch {                                    // Just skip and let for to try next host.
                            }
                        }
                        break;

                    case DnsReplyCode.NoEntries:
                        /* Rfc 2821 5
                         * If   no MX records are found, but an A RR is found, the A RR is treated as
                         * if it was associated with an implicit MX RR, with a preference of 0,
                         * pointing to that host.
                         *
                         */
                        try                                 // Try to connect with A record
                        {
                            IPHostEntry ipEntry = System.Net.Dns.Resolve(domain);
                            socket.Connect(new IPEndPoint(ipEntry.AddressList[0], m_Port));
                        }
                        catch {
                            OnError(SMTP_ErrorType.InvalidEmailAddress, to, "email domain <" + domain + "> is invalid");

                            defectiveEmails.AddRange(to);
                            return(false);
                        }
                        break;

                    case DnsReplyCode.TempError:
                        string dnsServers = "";
                        foreach (string s in m_DnsServers)
                        {
                            dnsServers += s + ";";
                        }
                        throw new Exception("Error retrieving MX record for domain '" + domain + "' with dns servers:{" + dnsServers + "}.");
                    }
                }


                #region Get 220 reply from server

                /* NOTE: reply may be multiline
                 * 220 xx ready
                 *  or
                 * 220-someBull
                 * 200 xx
                 */

                // Server must reply 220 - Server OK
                reply = ReadLine(socket);
                if (!IsReplyCode("220", reply))
                {
                    OnError(SMTP_ErrorType.UnKnown, to, reply);
                    SendLine(socket, "QUIT");
                    return(false);
                }
                else
                {
                    // 220-xxx<CRLF>
                    // 220 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (reply.IndexOf("220 ") == -1)
                    {
                        reply += ReadLine(socket);
                    }
                }

                #endregion


                #region cmd EHLO/HELO

                // Send greeting to server
                SendLine(socket, "EHLO " + m_HostName);

                reply = ReadLine(socket);
                if (!IsReplyCode("250", reply))
                {
                    // EHLO failed, mayby server doesn't support it, try HELO
                    SendLine(socket, "HELO " + m_HostName);
                    reply = ReadLine(socket);
                    if (!IsReplyCode("250", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        SendLine(socket, "QUIT");

                        defectiveEmails.AddRange(to);
                        return(false);
                    }
                    //	else{
                    //		supports_ESMTP = false;
                    //	}
                }
                else
                {
                    // 250-xxx<CRLF>
                    // 250 aa<CRLF> - means end
                    // reply isn't complete, get more
                    while (reply.IndexOf("250 ") == -1)
                    {
                        reply += ReadLine(socket);
                    }

                    // Check if SIZE argument is supported
                    if (reply.ToUpper().IndexOf("SIZE") > -1)
                    {
                        supports_SIZE = true;
                    }

                    // Check if 8BITMIME argument is supported
                    if (reply.ToUpper().IndexOf("8BITMIME") > -1)
                    {
                        supports_8BIT = true;
                    }

                    // Check if CHUNKING argument is supported
                    if (reply.ToUpper().IndexOf("CHUNKING") > -1)
                    {
                        supports_BDAT = true;
                    }
                }

                #endregion

                // If server doesn't support 8bit mime, check if message is 8bit.
                // If is we MAY NOT send this message or loss of data
                if (!supports_8BIT)
                {
                    if (Is8BitMime(message))
                    {
                        OnError(SMTP_ErrorType.NotSupported, to, "Message is 8-Bit mime and server doesn't support it.");
                        SendLine(socket, "QUIT");
                        return(false);
                    }
                }

                #region cmd MAIL
                // NOTE: Syntax:{MAIL FROM:<*****@*****.**> [SIZE=msgSize]<CRLF>}

                // Send Mail From
                if (supports_SIZE)
                {
                    SendLine(socket, "MAIL FROM:<" + reverse_path + "> SIZE=" + message.Length.ToString());
                }
                else
                {
                    SendLine(socket, "MAIL FROM:<" + reverse_path + ">");
                }

                reply = ReadLine(socket);
                if (!IsReplyCode("250", reply))
                {
                    // To Do: Check if size exceeded error:

                    OnError(SMTP_ErrorType.UnKnown, to, reply);
                    SendLine(socket, "QUIT");

                    defectiveEmails.AddRange(to);
                    return(false);
                }

                #endregion

                #region cmd RCPT
                // NOTE: Syntax:{RCPT TO:<*****@*****.**><CRLF>}

                bool isAnyValidEmail = false;
                foreach (string rcpt in to)
                {
                    // Send Mail To
                    SendLine(socket, "RCPT TO:<" + rcpt + ">");

                    reply = ReadLine(socket);
                    if (!IsReplyCode("250", reply))
                    {
                        // Is unknown user
                        if (IsReplyCode("550", reply))
                        {
                            OnError(SMTP_ErrorType.InvalidEmailAddress, new string[] { rcpt }, reply);
                        }
                        else
                        {
                            OnError(SMTP_ErrorType.UnKnown, new string[] { rcpt }, reply);
                        }

                        defectiveEmails.Add(rcpt);
                    }
                    else
                    {
                        isAnyValidEmail = true;
                    }
                }

                // If there isn't any valid email - quit.
                if (!isAnyValidEmail)
                {
                    SendLine(socket, "QUIT");
                    return(false);
                }
                //---------------------------------------------//

                #endregion


                #region cmd DATA

                if (!supports_BDAT)
                {
                    // Notify Data Start
                    SendLine(socket, "DATA");

                    reply = ReadLine(socket);
                    if (!IsReplyCode("354", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        SendLine(socket, "QUIT");

                        defectiveEmails.AddRange(to);
                        return(false);
                    }

                    //------- Do period handling -----------------------------------------//
                    // If line starts with '.', add additional '.'.(Read rfc for more info)
                    MemoryStream msgStrmPeriodOk = Core.DoPeriodHandling(message, true, false);
                    //--------------------------------------------------------------------//

                    // Check if message ends with <CRLF>, if not add it. -------//
                    if (msgStrmPeriodOk.Length >= 2)
                    {
                        byte[] byteEnd = new byte[2];
                        msgStrmPeriodOk.Position = msgStrmPeriodOk.Length - 2;
                        msgStrmPeriodOk.Read(byteEnd, 0, 2);

                        if (byteEnd[0] != (byte)'\r' && byteEnd[1] != (byte)'\n')
                        {
                            msgStrmPeriodOk.Write(new byte[] { (byte)'\r', (byte)'\n' }, 0, 2);
                        }
                    }
                    msgStrmPeriodOk.Position = 0;
                    //-----------------------------------------------------------//

                    //---- Send message --------------------------------------------//
                    long totalSent   = 0;
                    long totalLength = msgStrmPeriodOk.Length;
                    while (totalSent < totalLength)
                    {
                        byte[] dataBuf     = new byte[4000];
                        int    nCount      = msgStrmPeriodOk.Read(dataBuf, 0, dataBuf.Length);
                        int    countSended = socket.Send(dataBuf, 0, nCount, SocketFlags.None);
                        totalSent += countSended;

                        if (countSended != nCount)
                        {
                            msgStrmPeriodOk.Position = totalSent;
                        }

                        OnPartOfMessageIsSent(countSended, totalSent, totalLength);
                    }
                    //-------------------------------------------------------------//
                    msgStrmPeriodOk.Close();

                    // Notify End of Data
                    SendLine(socket, ".");

                    reply = ReadLine(socket);
                    if (!IsReplyCode("250", reply))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        SendLine(socket, "QUIT");

                        defectiveEmails.AddRange(to);
                        return(false);
                    }
                }

                #endregion

                #region cmd BDAT

                if (supports_BDAT)
                {
                    SendLine(socket, "BDAT " + (message.Length - message.Position) + " LAST");

                    //---- Send message --------------------------------------------//
                    long totalSent   = 0;
                    long totalLength = message.Length - message.Position;
                    while (totalSent < totalLength)
                    {
                        byte[] dataBuf     = new byte[4000];
                        int    nCount      = message.Read(dataBuf, 0, dataBuf.Length);
                        int    countSended = socket.Send(dataBuf, 0, nCount, SocketFlags.None);
                        totalSent += countSended;

                        if (countSended != nCount)
                        {
                            message.Position = totalSent;
                        }

                        OnPartOfMessageIsSent(countSended, totalSent, totalLength);
                    }
                    //-------------------------------------------------------------//

                    // Get store result
                    reply = ReadLine(socket);
                    if (!reply.StartsWith("250"))
                    {
                        OnError(SMTP_ErrorType.UnKnown, to, reply);
                        SendLine(socket, "QUIT");

                        defectiveEmails.AddRange(to);
                        return(false);
                    }
                }

                #endregion

                #region cmd QUIT

                // Notify server - server can exit now
                SendLine(socket, "QUIT");

                reply = ReadLine(socket);

                #endregion
            }
            catch (Exception x) {
                OnError(SMTP_ErrorType.UnKnown, to, x.Message);

                defectiveEmails.AddRange(to);
                return(false);
            }
            finally{
                // Raise event
                OnSendJobCompleted(Thread.CurrentThread.GetHashCode().ToString(), to, defectiveEmails);

                socket.Close();
            }

            return(true);
        }