dnsmail-cvs Mailing List for DnsMail (Page 2)
Brought to you by:
ethem
You can subscribe to this list here.
2006 |
Jan
|
Feb
|
Mar
(7) |
Apr
(1) |
May
(72) |
Jun
(22) |
Jul
(4) |
Aug
(52) |
Sep
|
Oct
|
Nov
|
Dec
(2) |
---|
From: Ethem E. <et...@us...> - 2006-08-07 11:02:43
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv20640/dnsmail/DnsMail Modified Files: MxRecord.cs Log Message: Coding art. tabs, spaces, etc... :) Index: MxRecord.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/MxRecord.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** MxRecord.cs 21 Mar 2006 18:51:02 -0000 1.2 --- MxRecord.cs 7 Aug 2006 11:02:38 -0000 1.3 *************** *** 40,48 **** #region Constructors ! private MxRecord(bool ignore) : this(null, 0) { ignore = !!ignore; } ! public MxRecord(string nameExchange) : this(nameExchange, 0){} public MxRecord(string nameExchange, short priority) { --- 40,49 ---- #region Constructors ! private MxRecord(bool ignore) ! : this(null, 0) { ignore = !!ignore; } ! public MxRecord(string nameExchange) : this(nameExchange, 0) { } public MxRecord(string nameExchange, short priority) { *************** *** 51,55 **** this.addresses = new ArrayList(2); } ! #endregion --- 52,56 ---- this.addresses = new ArrayList(2); } ! #endregion *************** *** 74,78 **** #region ISerializable ! internal MxRecord(SerializationInfo info, StreamingContext context) { nameexchange = info.GetString("NameExchange"); --- 75,79 ---- #region ISerializable ! internal MxRecord(SerializationInfo info, StreamingContext context) { nameexchange = info.GetString("NameExchange"); *************** *** 91,107 **** #region operators ! public static bool operator ==(MxRecord mx1, MxRecord mx2) { return mx1.Equals(mx2); } ! public static bool operator !=(MxRecord mx1, MxRecord mx2) { return !mx1.Equals(mx2); } ! public static MxRecord operator +(MxRecord mx, IPAddress ip) { ! if (! (ip == null || mx.IsNull || mx.IPAddresses.Contains(ip))) mx.IPAddresses.Add(ip); --- 92,108 ---- #region operators ! public static bool operator ==(MxRecord mx1, MxRecord mx2) { return mx1.Equals(mx2); } ! public static bool operator !=(MxRecord mx1, MxRecord mx2) { return !mx1.Equals(mx2); } ! public static MxRecord operator +(MxRecord mx, IPAddress ip) { ! if (!(ip == null || mx.IsNull || mx.IPAddresses.Contains(ip))) mx.IPAddresses.Add(ip); *************** *** 109,113 **** } ! public static MxRecord operator -(MxRecord mx, IPAddress ip) { if (!(ip == null || mx.IsNull)) --- 110,114 ---- } ! public static MxRecord operator -(MxRecord mx, IPAddress ip) { if (!(ip == null || mx.IsNull)) *************** *** 117,123 **** } ! public override bool Equals(Object obj) { ! if (!(obj is MxRecord)) return false; --- 118,124 ---- } ! public override bool Equals(Object obj) { ! if (!(obj is MxRecord)) return false; *************** *** 128,140 **** #endregion ! public override int GetHashCode() { return ToString().GetHashCode(); } ! public override string ToString() { return NameExchange + ":" + Priority.ToString(); } } ! }; \ No newline at end of file --- 129,141 ---- #endregion ! public override int GetHashCode() { return ToString().GetHashCode(); } ! public override string ToString() { return NameExchange + ":" + Priority.ToString(); } } ! }; |
From: Ethem E. <et...@us...> - 2006-08-07 11:00:31
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv19570/dnsmail/DnsMail Modified Files: MailInfo.cs Log Message: Encoding added. ToString() returns all headers. Index: MailInfo.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/MailInfo.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** MailInfo.cs 2 Mar 2006 17:01:09 -0000 1.1 --- MailInfo.cs 7 Aug 2006 11:00:27 -0000 1.2 *************** *** 3,7 **** --- 3,10 ---- { using System; + using System.Text; using System.Collections; + using HttpContext = System.Web.HttpContext; + using HttpRequest = System.Web.HttpRequest; public class MailInfo *************** *** 9,15 **** --- 12,22 ---- private const string LOCALHOST = "localhost"; internal static readonly string DefaultCharset = System.Text.Encoding.Default.BodyName; + private static readonly Encoding DefaultEncoder = Encoding.GetEncoding(DefaultCharset); + private string mailserver; private string mailserveruser; private string mailserverpass; + internal Encoding encoder = DefaultEncoder; + private MailInfo(bool useMailServer) { *************** *** 17,22 **** } ! public MailInfo() : this(false) {} ! public MailInfo(string from, string to, string subject, string body) : this(false) { From = from; --- 24,30 ---- } ! public MailInfo() : this(false) { } ! public MailInfo(string from, string to, string subject, string body) ! : this(false) { From = from; *************** *** 25,33 **** Body = body; } ! public MailInfo(string mailServer) : this(true) { SetUpMailServer(mailServer); } ! public MailInfo(string mailServer, string msUsername, string msPassword) : this(true) { SetUpMailServer(mailServer); --- 33,43 ---- Body = body; } ! public MailInfo(string mailServer) ! : this(true) { SetUpMailServer(mailServer); } ! public MailInfo(string mailServer, string msUsername, string msPassword) ! : this(true) { SetUpMailServer(mailServer); *************** *** 39,43 **** { if (server == null || server == string.Empty) ! this.mailserver = LOCALHOST; else this.mailserver = server.Trim(); --- 49,53 ---- { if (server == null || server == string.Empty) ! this.mailserver = LOCALHOST; else this.mailserver = server.Trim(); *************** *** 45,49 **** private RecipientCollection recipients; ! public RecipientCollection Recipients { get { return recipients; } --- 55,59 ---- private RecipientCollection recipients; ! public RecipientCollection Recipients { get { return recipients; } *************** *** 52,68 **** private ArrayList headers; ! public ArrayList Headers { ! get { if (headers == null) headers = new ArrayList(2); ! return headers; } } private ContentType ct = Erle.DnsMail.ContentType.Text; ! public ContentType ContentType { get { return ct; } --- 62,78 ---- private ArrayList headers; ! public ArrayList Headers { ! get { if (headers == null) headers = new ArrayList(2); ! return headers; } } private ContentType ct = Erle.DnsMail.ContentType.Text; ! public ContentType ContentType { get { return ct; } *************** *** 71,84 **** private string charset = DefaultCharset; ! public String Charset { ! get { return charset; } ! set ! { ! if (value!=null && value!=string.Empty) { value = value.Trim(); ! if( value!=string.Empty) ! charset = value; } } --- 81,104 ---- private string charset = DefaultCharset; ! public String Charset { ! get { return charset; } ! set ! { ! if (value != null && value != string.Empty) { value = value.Trim(); ! if (value != string.Empty) ! { ! try ! { ! Encoding enc = Encoding.GetEncoding(value); ! charset = value; ! encoder = enc; ! } ! catch ! { ! } ! } } } *************** *** 86,161 **** private string _mailFrom = string.Empty; ! public String From { ! get { return _mailFrom; } set { _mailFrom = value.Trim(); } } private string _mailFromName; ! public String FromName { ! get { return _mailFromName; } set { _mailFromName = value.Trim(); } } private string _mailReplyTo; ! public String ReplyTo { ! get { return _mailReplyTo; } set { _mailReplyTo = value.Trim(); } } private string _mailSubject; ! public String Subject { ! get { return _mailSubject; } set { _mailSubject = value.Trim(); } } private bool _senddata = true; ! public bool SendMail { ! get { return _senddata; } set { _senddata = value; } } internal bool sent; ! public bool Sent { ! get { return sent; } } private string _mailBody = string.Empty; ! public String Body { ! get { return _mailBody; } set { _mailBody = value; } } ! public string MailServer { ! get { return mailserver; } } ! public string MailServerUserName { ! get { return mailserveruser; } } public string MailServerPassword { ! get { return mailserverpass; } } ! internal bool UsernamePasswordOK { ! get { ! return ! ( ! mailserveruser != null && ! mailserverpass != null && ! mailserveruser != String.Empty && ! mailserverpass != String.Empty ! ); } } } --- 106,234 ---- private string _mailFrom = string.Empty; ! public String From { ! get { return _mailFrom; } set { _mailFrom = value.Trim(); } } private string _mailFromName; ! public String FromName { ! get { return _mailFromName; } set { _mailFromName = value.Trim(); } } private string _mailReplyTo; ! public String ReplyTo { ! get { return _mailReplyTo; } set { _mailReplyTo = value.Trim(); } } private string _mailSubject; ! public String Subject { ! get { return _mailSubject; } set { _mailSubject = value.Trim(); } } private bool _senddata = true; ! public bool SendMail { ! get { return _senddata; } set { _senddata = value; } } internal bool sent; ! public bool Sent { ! get { return sent; } } private string _mailBody = string.Empty; ! public String Body { ! get { return _mailBody; } set { _mailBody = value; } } ! public string MailServer { ! get { return mailserver; } } ! public string MailServerUserName { ! get { return mailserveruser; } } public string MailServerPassword { ! get { return mailserverpass; } } ! public override string ToString() { ! return ToString(From, 1); ! } ! ! public string ToString(string to, int rcptcount) ! { ! StringBuilder header = new StringBuilder(); ! String __sd = DateTime.Now.ToUniversalTime().ToString("R", System.Globalization.DateTimeFormatInfo.InvariantInfo); ! // Received, Date, X-Mailer, Standard Headers ! if (HttpContext.Current != null) { ! HttpRequest req = HttpContext.Current.Request; ! Object o = req.Headers["X-Forwarded-For"]; ! String userip = (o == null) ? req.UserHostAddress : o.ToString(); ! header.AppendFormat("Received: from [{0}]{1}\t by {2}{3}\t with HTTP", ! userip, "\r\n", req.Url.Host, "\r\n"); ! if (rcptcount == 1) ! header.AppendFormat("\r\n" + "\t for <{0}>", to); ! ! header.AppendFormat("; {0}" + "\r\n", __sd); } + header.AppendFormat("Date: {0}" + "\r\n", __sd); + header.Append("X-Mailer: Erle.DnsMail.v0.4.0.0" + "\r\n"); + + // Subject: + if ((Subject != null) && (Subject != string.Empty)) + header.Append("Subject: " + + MIME.BEncode(encoder.GetBytes(Subject), Charset) + + "\r\n"); + // From: + if (FromName == null || FromName == string.Empty) + header.AppendFormat("From: <{0}>" + "\r\n", From); + else + header.AppendFormat("From: \"{0}\" <{1}>" + "\r\n", + MIME.BEncode(encoder.GetBytes(FromName), Charset), + From); + // To: + if (rcptcount == 1) + header.AppendFormat("To: <{0}>" + "\r\n", to); + else + header.Append("To: <Undisclosed-Recipient:;>" + "\r\n"); + // Reply-To: + if (ReplyTo != null && ReplyTo != string.Empty) + header.Append("Reply-To: <" + ReplyTo + ">" + "\r\n"); + + // Custom headers: + foreach (String val in Headers) + { + if (val != null && val != String.Empty && + val.IndexOf(": ", 0, val.Length) != -1 && + val.IndexOf('\n', 0, val.Length) == -1 + ) header.Append(val.Trim() + "\r\n"); + } + + // Body + if (Body != null && Body.Length > 0) + { + header.Append("MIME-Version: 1.0" + "\r\n"); + header.AppendFormat("Content-Type: text/{0}; charset={1}" + "\r\n", + ContentType == ContentType.Html ? "html" : "plain", Charset); + header.Append("Content-Transfer-Encoding: quoted-printable" + "\r\n"); + } + header.Append("\r\n"); + return header.ToString(); } } |
From: Ethem E. <et...@us...> - 2006-08-07 10:57:18
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv18257/dnsmail/DnsMail Modified Files: EIDFE.cs Log Message: Coding art. tabs, spaces, etc... :) Index: EIDFE.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/EIDFE.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EIDFE.cs 22 Mar 2006 11:03:15 -0000 1.3 --- EIDFE.cs 7 Aug 2006 10:57:09 -0000 1.4 *************** *** 6,20 **** #region Enums - - public enum Commands : byte - { - Pending = 0, - Info, - Ok, - More, - Reject, - Error - } - public enum ContentType { --- 6,9 ---- *************** *** 44,52 **** public delegate void HostResolvedHandler(String host, ICollection mx); public delegate void ConnectedHandler(String connectedIP); - public delegate void AuthenticatedHandler(); public delegate void RecipientsAddedHandler(RecipientCollection recipients); public delegate void ReadyToSendMassMailHandler(MailInfo mailInfo); public delegate void ProgressHandler(Int32 bytesSent, Int32 bytesRemaining); - public delegate void SentHandler(); public delegate void ClosedHandler(String logs); public delegate void SentByOneStatusHandler(SentByOneStatusEventArgs e); --- 33,39 ---- *************** *** 81,98 **** #region Exceptions ! public class EmailException : Exception { ! public EmailException(String s) : base(s) {} } ! public class DnsException : Exception { ! public DnsException(String s) : base(s) {} } public class MailServerException : Exception { ! public MailServerException(String s) : base(s) {} } --- 68,85 ---- #region Exceptions ! public class EmailException : Exception { ! public EmailException(String s) : base(s) { } } ! public class DnsException : Exception { ! public DnsException(String s) : base(s) { } } public class MailServerException : Exception { ! public MailServerException(String s) : base(s) { } } |
From: Ethem E. <et...@us...> - 2006-08-07 10:55:06
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv17182/dnsmail Modified Files: SmtpClient.cs Log Message: $Id$ added. Index: SmtpClient.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/SmtpClient.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** SmtpClient.cs 7 Aug 2006 10:17:47 -0000 1.1 --- SmtpClient.cs 7 Aug 2006 10:55:01 -0000 1.2 *************** *** 1,2 **** --- 1,3 ---- + // $Id$ namespace Erle { |
From: Ethem E. <et...@us...> - 2006-08-07 10:18:29
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv2849/dnsmail Removed Files: SmtpStream.cs Log Message: SmtpStream removed, SmtpClient derived from TcpStream added. --- SmtpStream.cs DELETED --- |
From: Ethem E. <et...@us...> - 2006-08-07 10:17:51
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv2476/dnsmail Modified Files: Erle.DnsMail.csproj Added Files: SmtpClient.cs Log Message: SmtpStream removed, SmtpClient derived from TcpStream added. Index: Erle.DnsMail.csproj =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/Erle.DnsMail.csproj,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Erle.DnsMail.csproj 7 Aug 2006 08:43:41 -0000 1.6 --- Erle.DnsMail.csproj 7 Aug 2006 10:17:47 -0000 1.7 *************** *** 110,114 **** /> <File ! RelPath = "SmtpStream.cs" SubType = "Code" BuildAction = "Compile" --- 110,114 ---- /> <File ! RelPath = "SmtpClient.cs" SubType = "Code" BuildAction = "Compile" *************** *** 158,159 **** --- 158,160 ---- </CSHARP> </VisualStudioProject> + --- NEW FILE: SmtpClient.cs --- namespace Erle { using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Net.Sockets; using MailServerException = Erle.DnsMail.MailServerException; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; internal class SmtpClient : TcpClient, IDisposable { private IntPtr sslContext = IntPtr.Zero; private IntPtr sslSession = IntPtr.Zero; private NetworkStream dataStream = null; #region .ctor .cctor .dtor private static readonly String _sslVersion; private static readonly bool _sslAvailable; static SmtpClient() { try { UnsafeOpenSsl.SSL_load_error_strings(); UnsafeOpenSsl.SSL_library_init(); IntPtr tmpctx = IntPtr.Zero; try { tmpctx = UnsafeOpenSsl.SSL_CTX_new(UnsafeOpenSsl.TLSv1_method()); uint version = UnsafeOpenSsl.SSLeay(); _sslAvailable = true; _sslVersion = "OpenSSL(0x0" + version.ToString("x") + ")"; } finally { if (tmpctx != IntPtr.Zero) UnsafeOpenSsl.SSL_CTX_free(tmpctx); } } catch { _sslAvailable = false; _sslVersion = String.Empty; } } public SmtpClient(IPEndPoint remote, IPEndPoint local) : base(local) { NoDelay = true; ReceiveTimeout = 3000000; SendTimeout = 3000000; LingerState = new LingerOption(true, 5); Connect(remote); if (!Client.Poll(21000000, SelectMode.SelectRead) || SendAndReceive(null) != Commands.Ok) { throw new MailServerException(LastResponse); } dataStream = GetStream(); recvBuffer = new byte[256]; esmtp = (LastAnswer.ToLower().IndexOf("esmtp") != -1); } ~SmtpClient() { Dispose(false); } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } public new void Close() { ((IDisposable)this).Dispose(); } private bool disposed = false; protected override void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { UseLog = false; x509cert = null; recvBuffer = null; } if (dataStream != null) { try { if (Client.Poll(1000, SelectMode.SelectWrite)) SendAndReceive(quitcmd); } catch { throw; } finally { // Don't close dataStream. SSL session needs it. // base.Dispose() closes datastream. dataStream = null; } } if (_sslAvailable) { if (sslSession != IntPtr.Zero) { try { UnsafeOpenSsl.SSL_free(sslSession); } catch { throw; } finally { sslSession = IntPtr.Zero; } } if (sslContext != IntPtr.Zero) { try { UnsafeOpenSsl.SSL_CTX_free(sslContext); } catch { throw; } finally { sslContext = IntPtr.Zero; } } } } base.Dispose(disposing); } #endregion #region Properties private X509Certificate x509cert; public X509Certificate X509Certificate { get { return x509cert; } } public bool SslActive { get { if (_sslAvailable && !disposed) { return handshake; } return false; } } private bool uselog; internal StringBuilder logs; public bool UseLog { get { return uselog; } set { if (value) { if (logs == null) logs = new StringBuilder(); uselog = true; } else { uselog = false; if (logs != null) { logs.Length = 0; logs = null; } } } } private bool esmtp = false; public bool ESmtp { get { return esmtp; } } private int lastcode; public int LastCode { get { return lastcode; } } private string lastanswer = String.Empty; public string LastAnswer { get { return lastanswer; } } public string LastResponse { get { return LastCode.ToString() + " " + LastAnswer; } } public new int Available { get { if (handshake && !disposed) { int available = 0; byte[] p = new byte[1]; unsafe { fixed (byte* y = p) { available = UnsafeOpenSsl.SSL_peek(sslSession, y, 1); } } return available; } return base.Available; } } #region Static Properties public static String OpenSslVersion { get { return _sslVersion; } } public static bool SslAvailable { get { return _sslAvailable; } } #endregion #endregion #region StartTls private bool handshake = false; public bool StartTls(bool cerrequest) { bool ret = false; if (_sslAvailable && !disposed && !handshake && (Client.RemoteEndPoint != null)) { if (SendAndReceive("STARTTLS\r\n") != Commands.Ok) { SendAndReceive("RSET\r\n"); return ret; } if (IntPtr.Zero != (sslContext = UnsafeOpenSsl.SSL_CTX_new(UnsafeOpenSsl.TLSv1_method())) && IntPtr.Zero != (sslSession = UnsafeOpenSsl.SSL_new(sslContext))) { const int SSL_CTRL_OPTIONS = 32; const int SSL_OP_ALL = 0x00000FFF; UnsafeOpenSsl.SSL_set_quiet_shutdown(sslSession, 1); UnsafeOpenSsl.SSL_ctrl(sslSession, SSL_CTRL_OPTIONS, SSL_OP_ALL, IntPtr.Zero); UnsafeOpenSsl.SSL_set_fd(sslSession, Client.Handle); bool oldblock = Client.Blocking; if (oldblock) Client.Blocking = false; int error; StringBuilder errors = new StringBuilder(); while (((error = UnsafeOpenSsl.SSL_connect(sslSession)) <= 0) && handle_ssl_error(error, errors)) ; if (Client.Blocking != oldblock) Client.Blocking = oldblock; if (error <= 0) { try { if (errors.Length > 0) { throw new Exception(errors.ToString()); } if (error == 0) { throw new Exception("Connection closed"); } throw new Exception("Unknown SSL exception"); } finally { Close(); } } handshake = true; // opened #region get certificate if (cerrequest) { IntPtr cer = IntPtr.Zero; try { if (IntPtr.Zero != (cer = UnsafeOpenSsl.SSL_get_peer_certificate(sslSession))) { unsafe { int required = UnsafeOpenSsl.i2d_X509(cer, (byte**)0); if (required > 0 && required < 16384) { byte[] buf = new byte[required]; fixed (byte* pBuf = buf) { byte* pp = pBuf; UnsafeOpenSsl.i2d_X509(cer, &pp); x509cert = new X509Certificate(buf); } } } } } catch { } finally { if (cer != IntPtr.Zero) { try { UnsafeOpenSsl.X509_free(cer); } catch { } } } } #endregion ret = true; } else { Close(); } } return ret; } #endregion #region handle_ssl_error private enum SslError { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_WANT_X509_LOOKUP = 4, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, SSL_ERROR_WANT_CONNECT = 7, SSL_ERROR_WANT_ACCEPT = 8 } private bool handle_ssl_error(int c, StringBuilder errstack) { SslError err = (SslError)UnsafeOpenSsl.SSL_get_error(sslSession, c); bool retry = true; switch (err) { case SslError.SSL_ERROR_ZERO_RETURN: /* SSL terminated (but socket may still be active) */ retry = false; break; case SslError.SSL_ERROR_WANT_READ: case SslError.SSL_ERROR_WANT_WRITE: /* re-negotiation || perhaps the SSL layer needs more packets */ Thread.Sleep(50); break; case SslError.SSL_ERROR_SYSCALL: if (UnsafeOpenSsl.ERR_peek_error() == 0) { retry = false; break; } goto default; default: { const int SSL_R_NO_SHARED_CIPHER = 193; int ecode = UnsafeOpenSsl.ERR_get_error(); switch ((int)(ecode & 0xfff)) // reason { case SSL_R_NO_SHARED_CIPHER: { /* no suitable shared cipher could be used */ retry = false; break; } default: { do { StringBuilder s = new StringBuilder(512); UnsafeOpenSsl.ERR_error_string_n(ecode, s, 510); s.Insert(0, "["); s.Append("]"); errstack.Append(s.ToString() + "\r\n"); } while ((ecode = UnsafeOpenSsl.ERR_get_error()) != 0); break; } } retry = false; break; } } return retry; } #endregion #region Send & Receive private byte[] recvBuffer; private const int MaxBuffer = 8192; private const string quitcmd = "QUIT\r\n"; internal enum Commands : byte { Pending = 0, Info, Ok, More, Reject, Error } public Commands SendAndReceive(String val) { bool quit = (val == quitcmd); if (val != null) { byte[] sendBuffer = Encoding.ASCII.GetBytes(val); Write(sendBuffer, 0, sendBuffer.Length); } int breceived = 0; String tmpResp = String.Empty; do { int bytes = Read(recvBuffer, 0, recvBuffer.Length); if (bytes <= 0 || breceived > MaxBuffer) { break; } breceived += bytes; tmpResp += Encoding.ASCII.GetString(recvBuffer, 0, bytes); } while (tmpResp[tmpResp.Length - 1] != '\n' && Client.Poll(500, SelectMode.SelectRead)); if (tmpResp.Length < 4) throw new Exception((SslActive ? "SSL_" : "") + "SOCKET READ ERROR"); if (UseLog) logs.Append(tmpResp); if (!quit) { string log = tmpResp.Trim(); lastcode = int.Parse(log.Substring(0, 3)); lastanswer = log.Substring(4); } return (Commands)Convert.ToByte(tmpResp[0]); } unsafe public int Read(byte[] buffer, int offset, int count) { int read = -1; if (handshake) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count"); } fixed (byte* ptr = &buffer[offset]) { try { read = UnsafeOpenSsl.SSL_read(sslSession, ptr, count); } catch { read = -1; } } } else { read = dataStream.Read(buffer, offset, count); } return read; } unsafe public void Write(byte[] buffer, int offset, int count) { if (handshake) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count"); } fixed (byte* ptr = &buffer[offset]) { while (count > 0) { int sent = UnsafeOpenSsl.SSL_write(sslSession, &ptr[offset], count); if (sent <= 0) { throw new Exception("ERR::SSL_write::memory{0x" + ((int)ptr).ToString("x") + "} index[" + offset + "]"); } offset += sent; count -= sent; } } } else { dataStream.Write(buffer, offset, count); } } public bool Poll(int microSeconds, SelectMode mode) { return Client.Poll(microSeconds, mode); } #endregion #region Hello public void SayHello(string HeloDomain) { if (SendAndReceive("HELO " + HeloDomain + "\r\n") != Commands.Ok) { throw new MailServerException(LastResponse); } } #endregion #region Login public bool Login(string username, string password, Encoding enc) { if (!ESmtp || username == null || password == null || username == String.Empty || password == String.Empty) { return false; } if (SendAndReceive("AUTH LOGIN\r\n") != Commands.More) { SendAndReceive("RSET\r\n"); return false; } if (SendAndReceive(Convert.ToBase64String(enc.GetBytes(username)) + "\r\n") != Commands.More) throw new MailServerException(LastResponse); if (SendAndReceive(Convert.ToBase64String(enc.GetBytes(password)) + "\r\n") != Commands.Ok) throw new MailServerException(LastResponse); return true; } #endregion #region MailFrom public bool MailFrom(string from) { return (SendAndReceive("MAIL FROM:<" + from + ">\r\n") == Commands.Ok); } #endregion #region RcptTo public bool RcptTo(string to) { return (SendAndReceive("RCPT TO:<" + to + ">\r\n") == Commands.Ok); } #endregion #region StartData public bool StartData() { return (SendAndReceive("DATA\r\n") == Commands.More); } #endregion } }; |
From: Ethem E. <et...@us...> - 2006-08-07 10:12:33
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv456/dnsmail Modified Files: DnsCache.cs Log Message: InternalResolve prototype changed. Coding art. tabs, spaces, etc... :) Index: DnsCache.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsCache.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** DnsCache.cs 7 Aug 2006 08:43:41 -0000 1.5 --- DnsCache.cs 7 Aug 2006 10:12:29 -0000 1.6 *************** *** 8,15 **** using Erle.DnsMail; using System.Net; ! internal sealed class DnsCache { ! private DnsCache(){} private const double REMOVECACHEAFTER = 10.0D; private static Hashtable m_CacheTbl = new Hashtable(); --- 8,15 ---- using Erle.DnsMail; using System.Net; ! internal sealed class DnsCache { ! private DnsCache() { } private const double REMOVECACHEAFTER = 10.0D; private static Hashtable m_CacheTbl = new Hashtable(); *************** *** 33,37 **** } #endregion ! internal static MxRecord[] GetFromCache(String domain) { --- 33,37 ---- } #endregion ! internal static MxRecord[] GetFromCache(String domain) { *************** *** 49,53 **** } } ! catch {} return null; } --- 49,53 ---- } } ! catch { } return null; } *************** *** 63,79 **** m_CacheTbl[domain] = new CacheEntry(data); } ! catch{} finally { Monitor.Exit(m_CacheTbl); } } ! private static void DeleteAll() { m_NextUpdate = NextUpdate(); ! Monitor.Enter( m_CacheTbl ); try { m_CacheTbl.Clear(); } ! catch {} finally { --- 63,79 ---- m_CacheTbl[domain] = new CacheEntry(data); } ! catch { } finally { Monitor.Exit(m_CacheTbl); } } ! private static void DeleteAll() { m_NextUpdate = NextUpdate(); ! Monitor.Enter(m_CacheTbl); try { m_CacheTbl.Clear(); } ! catch { } finally { *************** *** 90,94 **** DeletedAll(typeof(DnsCache), e); } ! catch {} } --- 90,94 ---- DeletedAll(typeof(DnsCache), e); } ! catch { } } *************** *** 98,113 **** address == string.Empty || address.IndexOf('.') == -1) ! return false; ! int labelCount = 0, octet; ! string[] ips = address.Split(new char[] {'.'}); ! for(int i = 0; i < ips.Length; i++) { try { octet = int.Parse(ips[i]); ! if ( ( octet < 0 ) || ( octet > 255 ) ) return false; ! else labelCount++; } --- 98,113 ---- address == string.Empty || address.IndexOf('.') == -1) ! return false; ! int labelCount = 0, octet; ! string[] ips = address.Split(new char[] { '.' }); ! for (int i = 0; i < ips.Length; i++) { try { octet = int.Parse(ips[i]); ! if ((octet < 0) || (octet > 255)) return false; ! else labelCount++; } *************** *** 117,127 **** } } ! return ( (labelCount > 0) && (labelCount < 5) ); } internal static event EventHandler DeletedAll; ! internal static IPAddress[] InternalResolve(ref string mailHost, ref bool usedMx, ref MxRecord[] mxss) { ! if( mailHost == null || mailHost == String.Empty || mailHost == "localhost" || mailHost == "127.0.0.1") mailHost = DNSAPI.LocalHost; --- 117,127 ---- } } ! return ((labelCount > 0) && (labelCount < 5)); } internal static event EventHandler DeletedAll; ! internal static void InternalResolve(ref string mailHost, ref bool usedMx, out MxRecord[] mxss, out IPAddress[] ips) { ! if (mailHost == null || mailHost == String.Empty || mailHost == "localhost" || mailHost == "127.0.0.1") mailHost = DNSAPI.LocalHost; *************** *** 129,160 **** if (mailHost[0] >= '1' && mailHost[0] <= '9' && IsIp4(mailHost)) { usedMx = false; ! return new IPAddress[] { IPAddress.Parse(mailHost) }; } ! if(usedMx) { mxss = DNSAPI.GetMxRecords(mailHost); if (mxss != null && mxss.Length > 0) { ! usedMx = true; ! return null; } } ! try { ! IPAddress[] addresses = Dns.Resolve(mailHost).AddressList; ! if (addresses != null && addresses.Length > 0) { usedMx = false; ! return addresses; } } ! catch {} throw new DnsException(String.Format("No" + ! ( (usedMx) ? " MaileXchange (MX) or" : String.Empty ) ! + " IP (A) record could be found for {0}.", mailHost)); } static void Log(String log) { --- 129,164 ---- if (mailHost[0] >= '1' && mailHost[0] <= '9' && IsIp4(mailHost)) { + ips = new IPAddress[] { IPAddress.Parse(mailHost) }; + mxss = null; usedMx = false; ! return; } ! if (usedMx) { mxss = DNSAPI.GetMxRecords(mailHost); if (mxss != null && mxss.Length > 0) { ! ips = null; ! return; } } ! try { ! ips = Dns.Resolve(mailHost).AddressList; ! if (ips != null && ips.Length > 0) { + mxss = null; usedMx = false; ! return; } } ! catch { } throw new DnsException(String.Format("No" + ! ((usedMx) ? " MaileXchange (MX) or" : String.Empty) ! + " IP (A) record could be found for {0}.", mailHost)); } + static void Log(String log) { *************** *** 168,172 **** internal static void Debug() { ! if (m_CacheTbl == null) return; --- 172,176 ---- internal static void Debug() { ! if (m_CacheTbl == null) return; *************** *** 176,180 **** StringBuilder sb = new StringBuilder(); sb.Append("<ul>" + crlf); ! for(IDictionaryEnumerator iex = m_CacheTbl.GetEnumerator();iex.MoveNext();) { ce = (CacheEntry)iex.Value; --- 180,184 ---- StringBuilder sb = new StringBuilder(); sb.Append("<ul>" + crlf); ! for (IDictionaryEnumerator iex = m_CacheTbl.GetEnumerator(); iex.MoveNext(); ) { ce = (CacheEntry)iex.Value; *************** *** 183,191 **** MxRecord[] ht = ce.RecordObj as MxRecord[]; sb.Append("<li><b>" + iex.Key + "</b> (" + ce.DeleteTime + ")" + crlf + " <ul>" + crlf); ! for(int im = 0; im < ht.Length; im++) { sb.AppendFormat("\t<li>{0} (", ht[im].NameExchange); ArrayList ips = ht[im].IPAddresses; ! for(int i = 0; i < ips.Count; i++) sb.Append(ips[i].ToString() + ", "); sb.Append(")" + crlf); --- 187,195 ---- MxRecord[] ht = ce.RecordObj as MxRecord[]; sb.Append("<li><b>" + iex.Key + "</b> (" + ce.DeleteTime + ")" + crlf + " <ul>" + crlf); ! for (int im = 0; im < ht.Length; im++) { sb.AppendFormat("\t<li>{0} (", ht[im].NameExchange); ArrayList ips = ht[im].IPAddresses; ! for (int i = 0; i < ips.Count; i++) sb.Append(ips[i].ToString() + ", "); sb.Append(")" + crlf); *************** *** 196,200 **** sb.Append("</ul>" + crlf); System.Web.HttpContext.Current.Response.Write(sb.ToString()); ! } } --- 200,204 ---- sb.Append("</ul>" + crlf); System.Web.HttpContext.Current.Response.Write(sb.ToString()); ! } } |
From: Ethem E. <et...@us...> - 2006-08-07 09:59:56
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv27686/dnsmail Modified Files: DNSAPI.cs Log Message: Coding art. tabs, spaces, etc... :) Index: DNSAPI.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DNSAPI.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** DNSAPI.cs 7 Aug 2006 08:43:41 -0000 1.5 --- DNSAPI.cs 7 Aug 2006 09:59:51 -0000 1.6 *************** *** 10,17 **** using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; ! public sealed class DNSAPI { ! private DNSAPI(){} static DNSAPI() { --- 10,17 ---- using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; ! public sealed class DNSAPI { ! private DNSAPI() { } static DNSAPI() { *************** *** 25,33 **** localHost = null; hello = null; ! GC.Collect(); } #endregion ! #region LocalHost private static String localHost; --- 25,33 ---- localHost = null; hello = null; ! GC.Collect(); } #endregion ! #region LocalHost private static String localHost; *************** *** 52,56 **** if (hello == null) hello = NetDns.GetHostByAddress(NetDns.GetHostByName(LocalHost).AddressList[0]).HostName; ! return hello; } --- 52,56 ---- if (hello == null) hello = NetDns.GetHostByAddress(NetDns.GetHostByName(LocalHost).AddressList[0]).HostName; ! return hello; } *************** *** 75,92 **** private delegate MxRecord[] MxRecordsDelegate(string domain); private static readonly MxRecordsDelegate resolve = new MxRecordsDelegate(GetMxRecords); ! public static IAsyncResult BeginGetMxRecords(string domain, AsyncCallback callback, Object state) { ! if (domain == null) throw new ArgumentNullException("domain"); ! return resolve.BeginInvoke(domain, callback, state); } ! public static MxRecord[] EndGetMxRecords(IAsyncResult result) { ! if (result == null) throw new ArgumentNullException("result"); ! if(!result.IsCompleted) result.AsyncWaitHandle.WaitOne(); --- 75,92 ---- private delegate MxRecord[] MxRecordsDelegate(string domain); private static readonly MxRecordsDelegate resolve = new MxRecordsDelegate(GetMxRecords); ! public static IAsyncResult BeginGetMxRecords(string domain, AsyncCallback callback, Object state) { ! if (domain == null) throw new ArgumentNullException("domain"); ! return resolve.BeginInvoke(domain, callback, state); } ! public static MxRecord[] EndGetMxRecords(IAsyncResult result) { ! if (result == null) throw new ArgumentNullException("result"); ! if (!result.IsCompleted) result.AsyncWaitHandle.WaitOne(); *************** *** 106,119 **** IntPtr pQuery = IntPtr.Zero; ! UInt32 status = UnsafeNativeMethods.DnsQuery( ! domain, STRUCTURES.DNS_TYPE_MX, ! STRUCTURES.DNS_QUERY_STANDARD, ! IntPtr.Zero, ! ref pQuery, IntPtr.Zero ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try --- 106,119 ---- IntPtr pQuery = IntPtr.Zero; ! UInt32 status = UnsafeNativeMethods.DnsQuery( ! domain, STRUCTURES.DNS_TYPE_MX, ! STRUCTURES.DNS_QUERY_STANDARD, ! IntPtr.Zero, ! ref pQuery, IntPtr.Zero ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try *************** *** 121,135 **** STRUCTURES.DNS_RECORD dnsRec; ArrayList tmp = new ArrayList(); ! for(IntPtr pDnsRec = pQuery; pDnsRec != IntPtr.Zero; pDnsRec = dnsRec.pNext) { dnsRec = (STRUCTURES.DNS_RECORD)Marshal.PtrToStructure(pDnsRec, typeof(STRUCTURES.DNS_RECORD)); ! if( dnsRec.wType == STRUCTURES.DNS_TYPE_MX ) { - IntPtr pMxData = new IntPtr( pDnsRec.ToInt32() + STRUCTURES.DNS_RECORD.SIZE ); // jump to mxrecord - STRUCTURES.DNS_MX_DATA mxdata = (STRUCTURES.DNS_MX_DATA)Marshal.PtrToStructure(pMxData, typeof(STRUCTURES.DNS_MX_DATA)); - tmp.Add(new MxRecord(String.Copy(mxdata.pNameExchange), (short)mxdata.wPreference)); - } - else break; // no additional record } --- 121,134 ---- STRUCTURES.DNS_RECORD dnsRec; ArrayList tmp = new ArrayList(); ! for (IntPtr pDnsRec = pQuery; pDnsRec != IntPtr.Zero; pDnsRec = dnsRec.pNext) { dnsRec = (STRUCTURES.DNS_RECORD)Marshal.PtrToStructure(pDnsRec, typeof(STRUCTURES.DNS_RECORD)); ! if (dnsRec.wType != STRUCTURES.DNS_TYPE_MX) { break; // no additional record + } + IntPtr pMxData = new IntPtr(pDnsRec.ToInt32() + STRUCTURES.DNS_RECORD.SIZE); // jump to mxrecord + STRUCTURES.DNS_MX_DATA mxdata = (STRUCTURES.DNS_MX_DATA)Marshal.PtrToStructure(pMxData, typeof(STRUCTURES.DNS_MX_DATA)); + tmp.Add(new MxRecord(String.Copy(mxdata.pNameExchange), (short)mxdata.wPreference)); } *************** *** 142,158 **** // Resolve bool err = false; ! for(int i = 0; i < mxs.Length; i++) { try { IPAddress[] ipx = NetDns.GetHostByName(mxs[i].NameExchange).AddressList; - if (ipx == null || ipx.Length == 0) continue; - foreach(IPAddress ipadr in ipx) mxs[i] += ipadr; } ! catch(SocketException se) { ! if (11004 == se.ErrorCode) ! continue; // The requested name is valid, but no data of the requested type was found } catch --- 141,160 ---- // Resolve bool err = false; ! for (int i = 0; i < mxs.Length; i++) { try { IPAddress[] ipx = NetDns.GetHostByName(mxs[i].NameExchange).AddressList; + if (ipx != null && ipx.Length != 0) + { + foreach (IPAddress ipadr in ipx) + mxs[i] += ipadr; + } } ! catch (SocketException se) { ! if (11004 != se.ErrorCode) ! throw; // The requested name is valid, but no data of the requested type was found } catch |
From: Ethem E. <et...@us...> - 2006-08-07 08:43:45
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv29902/dnsmail Modified Files: DNSAPI.cs Erle.DnsMail.csproj Added Files: DnsCache.cs Log Message: Put back last commit. DnsCache is a good thing. Index: Erle.DnsMail.csproj =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/Erle.DnsMail.csproj,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Erle.DnsMail.csproj 4 Aug 2006 15:22:59 -0000 1.5 --- Erle.DnsMail.csproj 7 Aug 2006 08:43:41 -0000 1.6 *************** *** 100,103 **** --- 100,108 ---- /> <File + RelPath = "DnsCache.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "MIME.cs" SubType = "Code" *************** *** 153,155 **** </CSHARP> </VisualStudioProject> - --- 158,159 ---- Index: DNSAPI.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DNSAPI.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** DNSAPI.cs 4 Aug 2006 15:22:59 -0000 1.4 --- DNSAPI.cs 7 Aug 2006 08:43:41 -0000 1.5 *************** *** 10,18 **** using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; - using DnsException = Erle.DnsMail.DnsException; public sealed class DNSAPI { private DNSAPI(){} #region LocalHost --- 10,32 ---- using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; public sealed class DNSAPI { private DNSAPI(){} + static DNSAPI() + { + DnsCache.DeletedAll += new EventHandler(DeletedAll); + } + + #region DeletedAll + private static void DeletedAll(object sender, EventArgs e) + { + dnsServers = null; + localHost = null; + hello = null; + + GC.Collect(); + } + #endregion #region LocalHost *************** *** 87,90 **** --- 101,108 ---- return null; + MxRecord[] cache = DnsCache.GetFromCache(domain); + if (cache != null && cache.Length > 0) + return (cache); // struct-copy + IntPtr pQuery = IntPtr.Zero; UInt32 status = UnsafeNativeMethods.DnsQuery( *************** *** 97,101 **** ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try --- 115,119 ---- ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try *************** *** 123,126 **** --- 141,145 ---- // Resolve + bool err = false; for(int i = 0; i < mxs.Length; i++) { *************** *** 130,133 **** --- 149,153 ---- if (ipx == null || ipx.Length == 0) continue; foreach(IPAddress ipadr in ipx) mxs[i] += ipadr; + } catch(SocketException se) *************** *** 136,141 **** continue; // The requested name is valid, but no data of the requested type was found } ! catch {} } tmp.Clear(); return mxs; --- 156,168 ---- continue; // The requested name is valid, but no data of the requested type was found } ! catch ! { ! err = true; ! } } + + if (!err) + DnsCache.AddToCache(domain, mxs); + tmp.Clear(); return mxs; *************** *** 155,224 **** } #endregion - - #region InternalResolve - internal static IPAddress[] InternalResolve(ref string mailHost, ref bool usedMx, ref MxRecord[] mxss) - { - if( mailHost == null || mailHost == String.Empty || - mailHost == "localhost" || mailHost == "127.0.0.1") - mailHost = DNSAPI.LocalHost; - - if (mailHost[0] >= '1' && mailHost[0] <= '9' && IsIp4(mailHost)) - { - usedMx = false; - return new IPAddress[] { IPAddress.Parse(mailHost) }; - } - - if(usedMx) - { - mxss = DNSAPI.GetMxRecords(mailHost); - if (mxss != null && mxss.Length > 0) - { - usedMx = true; - return null; - } - } - - try - { - IPAddress[] addresses = Dns.Resolve(mailHost).AddressList; - if (addresses != null && addresses.Length > 0) - { - usedMx = false; - return addresses; - } - } - catch {} - throw new DnsException(String.Format("No" + - ( (usedMx) ? " MaileXchange (MX) or" : String.Empty ) - + " IP (A) record could be found for {0}.", mailHost)); - } - - private static bool IsIp4(string address) - { - if (address == null || - address == string.Empty || - address.IndexOf('.') == -1) - return false; - - int labelCount = 0, octet; - string[] ips = address.Split(new char[] {'.'}); - for(int i = 0; i < ips.Length; i++) - { - try - { - octet = int.Parse(ips[i]); - if ( ( octet < 0 ) || ( octet > 255 ) ) - return false; - else - labelCount++; - } - catch - { - return false; - } - } - return ( (labelCount > 0) && (labelCount < 5) ); - } - #endregion } }; --- 182,185 ---- --- NEW FILE: DnsCache.cs --- // $Id: DnsCache.cs,v 1.5 2006/08/07 08:43:41 ethem Exp $ namespace Erle { using System; using System.Text; using System.Threading; using System.Collections; using Erle.DnsMail; using System.Net; internal sealed class DnsCache { private DnsCache(){} private const double REMOVECACHEAFTER = 10.0D; private static Hashtable m_CacheTbl = new Hashtable(); private static DateTime m_NextUpdate = NextUpdate(); private static DateTime NextUpdate() { return DateTime.Now.AddMinutes(REMOVECACHEAFTER); } #region CacheEntry private struct CacheEntry { internal CacheEntry(MxRecord[] data) { // It will be deleted 2 minutes later. DeleteTime = unchecked(Environment.TickCount + 120000); RecordObj = data; } internal int DeleteTime; internal MxRecord[] RecordObj; } #endregion internal static MxRecord[] GetFromCache(String domain) { if (m_NextUpdate < DateTime.Now) DeleteAll(); try { object val = m_CacheTbl[domain]; if (val != null) { CacheEntry entry = (CacheEntry)val; if (entry.DeleteTime > Environment.TickCount) return entry.RecordObj; } } catch {} return null; } internal static void AddToCache(String domain, MxRecord[] data) { if ((domain == null) || (data == null)) throw new ArgumentNullException("data || domain"); Monitor.Enter(m_CacheTbl); try { m_CacheTbl[domain] = new CacheEntry(data); } catch{} finally { Monitor.Exit(m_CacheTbl); } } private static void DeleteAll() { m_NextUpdate = NextUpdate(); Monitor.Enter( m_CacheTbl ); try { m_CacheTbl.Clear(); } catch {} finally { Monitor.Exit(m_CacheTbl); } OnDeletedAll(EventArgs.Empty); } private static void OnDeletedAll(EventArgs e) { try { if (DeletedAll != null) DeletedAll(typeof(DnsCache), e); } catch {} } private static bool IsIp4(string address) { if (address == null || address == string.Empty || address.IndexOf('.') == -1) return false; int labelCount = 0, octet; string[] ips = address.Split(new char[] {'.'}); for(int i = 0; i < ips.Length; i++) { try { octet = int.Parse(ips[i]); if ( ( octet < 0 ) || ( octet > 255 ) ) return false; else labelCount++; } catch { return false; } } return ( (labelCount > 0) && (labelCount < 5) ); } internal static event EventHandler DeletedAll; internal static IPAddress[] InternalResolve(ref string mailHost, ref bool usedMx, ref MxRecord[] mxss) { if( mailHost == null || mailHost == String.Empty || mailHost == "localhost" || mailHost == "127.0.0.1") mailHost = DNSAPI.LocalHost; if (mailHost[0] >= '1' && mailHost[0] <= '9' && IsIp4(mailHost)) { usedMx = false; return new IPAddress[] { IPAddress.Parse(mailHost) }; } if(usedMx) { mxss = DNSAPI.GetMxRecords(mailHost); if (mxss != null && mxss.Length > 0) { usedMx = true; return null; } } try { IPAddress[] addresses = Dns.Resolve(mailHost).AddressList; if (addresses != null && addresses.Length > 0) { usedMx = false; return addresses; } } catch {} throw new DnsException(String.Format("No" + ( (usedMx) ? " MaileXchange (MX) or" : String.Empty ) + " IP (A) record could be found for {0}.", mailHost)); } static void Log(String log) { /* FileStream fs = new FileStream(@"C:\log.txt",FileMode.Append,FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.AutoFlush = true; sw.Write(DateTime.Now.ToString() + ": " + log + "\r\n"); sw.Close(); fs.Close(); fs = null; sw = null; log =null; */ } internal static void Debug() { if (m_CacheTbl == null) return; CacheEntry ce; String crlf = "\r\n"; StringBuilder sb = new StringBuilder(); sb.Append("<ul>" + crlf); for(IDictionaryEnumerator iex = m_CacheTbl.GetEnumerator();iex.MoveNext();) { ce = (CacheEntry)iex.Value; if (ce.RecordObj != null) { MxRecord[] ht = ce.RecordObj as MxRecord[]; sb.Append("<li><b>" + iex.Key + "</b> (" + ce.DeleteTime + ")" + crlf + " <ul>" + crlf); for(int im = 0; im < ht.Length; im++) { sb.AppendFormat("\t<li>{0} (", ht[im].NameExchange); ArrayList ips = ht[im].IPAddresses; for(int i = 0; i < ips.Count; i++) sb.Append(ips[i].ToString() + ", "); sb.Append(")" + crlf); } sb.Append(" </ul>" + crlf + "</li>" + crlf); } } sb.Append("</ul>" + crlf); System.Web.HttpContext.Current.Response.Write(sb.ToString()); } } }; |
From: Ethem E. <et...@us...> - 2006-08-07 08:43:45
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv29902/dnsmail/DnsMail Modified Files: DnsMail.cs Log Message: Put back last commit. DnsCache is a good thing. Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** DnsMail.cs 4 Aug 2006 15:23:00 -0000 1.8 --- DnsMail.cs 7 Aug 2006 08:43:41 -0000 1.9 *************** *** 474,478 **** MxRecord[] mxs = new MxRecord[0]; ! IPAddress[] ips = DNSAPI.InternalResolve(ref resDom, ref usedMx, ref mxs); #region resolved --- 474,478 ---- MxRecord[] mxs = new MxRecord[0]; ! IPAddress[] ips = DnsCache.InternalResolve(ref resDom, ref usedMx, ref mxs); #region resolved |
From: Ethem E. <et...@us...> - 2006-08-07 08:25:17
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv22821/dnsmail Modified Files: UnsafeNativeMethods.cs Log Message: Coding art. tabs, spaces, etc... :) Index: UnsafeNativeMethods.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/UnsafeNativeMethods.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** UnsafeNativeMethods.cs 4 Aug 2006 12:53:36 -0000 1.4 --- UnsafeNativeMethods.cs 7 Aug 2006 08:25:14 -0000 1.5 *************** *** 10,14 **** internal sealed class STRUCTURES { ! private STRUCTURES(){} internal const UInt32 SUCCESS = 0; internal const UInt32 DNS_QUERY_STANDARD = 0; --- 10,14 ---- internal sealed class STRUCTURES { ! private STRUCTURES() { } internal const UInt32 SUCCESS = 0; internal const UInt32 DNS_QUERY_STANDARD = 0; *************** *** 37,45 **** internal IntPtr pNext; internal String pName; ! [MarshalAs(UnmanagedType.U2)]internal UInt16 wType; ! [MarshalAs(UnmanagedType.U2)]internal UInt16 wDataLength; ! [MarshalAs(UnmanagedType.U4)]internal UInt32 flags; ! [MarshalAs(UnmanagedType.U4)]internal UInt32 dwTtl; ! [MarshalAs(UnmanagedType.U4)]internal UInt32 dwReserved; internal static readonly int SIZE = Marshal.SizeOf(typeof(DNS_RECORD)); } --- 37,50 ---- internal IntPtr pNext; internal String pName; ! [MarshalAs(UnmanagedType.U2)] ! internal UInt16 wType; ! [MarshalAs(UnmanagedType.U2)] ! internal UInt16 wDataLength; ! [MarshalAs(UnmanagedType.U4)] ! internal UInt32 flags; ! [MarshalAs(UnmanagedType.U4)] ! internal UInt32 dwTtl; ! [MarshalAs(UnmanagedType.U4)] ! internal UInt32 dwReserved; internal static readonly int SIZE = Marshal.SizeOf(typeof(DNS_RECORD)); } *************** *** 53,65 **** internal struct FIXED_INFO { ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst=132)]internal string HostName; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst=132)]internal string DomainName; internal IntPtr CurrentDnsServer; // pointer to IP_ADDR_STRING internal IP_ADDR_STRING DnsServerList; internal UInt32 NodeType; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]internal string ScopeId; ! internal UInt32 EnableRouting; ! internal UInt32 EnableProxy; ! internal UInt32 EnableDns; } #endregion --- 58,73 ---- internal struct FIXED_INFO { ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 132)] ! internal string HostName; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 132)] ! internal string DomainName; internal IntPtr CurrentDnsServer; // pointer to IP_ADDR_STRING internal IP_ADDR_STRING DnsServerList; internal UInt32 NodeType; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] ! internal string ScopeId; ! internal bool EnableRouting; ! internal bool EnableProxy; ! internal bool EnableDns; } #endregion *************** *** 73,87 **** { internal IntPtr Next; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]internal string IpAddress; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst=16)]internal string IpMask; ! internal UInt32 Context; } #endregion } ! [SuppressUnmanagedCodeSecurityAttribute()] internal sealed class UnsafeNativeMethods { ! private UnsafeNativeMethods(){} private const String DNS_API_DLL = "dnsapi.dll"; private const String DNS_API_QUERY = "DnsQuery_A"; --- 81,97 ---- { internal IntPtr Next; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] ! internal string IpAddress; ! [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] ! internal string IpMask; ! internal uint Context; } #endregion } ! [SuppressUnmanagedCodeSecurityAttribute()] internal sealed class UnsafeNativeMethods { ! private UnsafeNativeMethods() { } private const String DNS_API_DLL = "dnsapi.dll"; private const String DNS_API_QUERY = "DnsQuery_A"; *************** *** 93,104 **** /// DnsQuery /// </summary> ! [DllImport(DNS_API_DLL,EntryPoint=DNS_API_QUERY,CharSet=CharSet.Auto,SetLastError=true)] internal static extern UInt32 DnsQuery( ! [In, MarshalAs(UnmanagedType.LPStr)] String lpstrName, ! [In, MarshalAs(UnmanagedType.U2)] UInt16 wType, ! [In, MarshalAs(UnmanagedType.U4)] UInt32 fOptions, ! [In] IntPtr aipServers, ! [In, Out] ref IntPtr ppQueryResults, ! [In, Out] IntPtr pReserved ); #endregion --- 103,114 ---- /// DnsQuery /// </summary> ! [DllImport(DNS_API_DLL, EntryPoint = DNS_API_QUERY, CharSet = CharSet.Auto, SetLastError = true)] internal static extern UInt32 DnsQuery( ! [In, MarshalAs(UnmanagedType.LPStr)] String lpstrName, ! [In, MarshalAs(UnmanagedType.U2)] UInt16 wType, ! [In, MarshalAs(UnmanagedType.U4)] UInt32 fOptions, ! [In] IntPtr aipServers, ! [In, Out] ref IntPtr ppQueryResults, ! [In, Out] IntPtr pReserved ); #endregion *************** *** 119,123 **** /// GetNetworkParams /// </summary> ! [DllImport(IP_HELP_API_DLL, CharSet=CharSet.Auto, SetLastError=true)] private static extern UInt32 GetNetworkParams( IntPtr pMemory, --- 129,133 ---- /// GetNetworkParams /// </summary> ! [DllImport(IP_HELP_API_DLL, CharSet = CharSet.Auto, SetLastError = true)] private static extern UInt32 GetNetworkParams( IntPtr pMemory, *************** *** 148,152 **** iptemp = new ArrayList(); fi = (STRUCTURES.FIXED_INFO)Marshal.PtrToStructure(pMemory, typeof(STRUCTURES.FIXED_INFO)); ! if(fi.DnsServerList.IpAddress!=null && fi.DnsServerList.IpAddress!=String.Empty) { iptemp.Add(String.Copy(fi.DnsServerList.IpAddress)); --- 158,162 ---- iptemp = new ArrayList(); fi = (STRUCTURES.FIXED_INFO)Marshal.PtrToStructure(pMemory, typeof(STRUCTURES.FIXED_INFO)); ! if (fi.DnsServerList.IpAddress != null && fi.DnsServerList.IpAddress != String.Empty) { iptemp.Add(String.Copy(fi.DnsServerList.IpAddress)); *************** *** 156,160 **** { serv = (STRUCTURES.IP_ADDR_STRING)Marshal.PtrToStructure(pAddrStr, typeof(STRUCTURES.IP_ADDR_STRING)); ! if(serv.IpAddress!=null && serv.IpAddress!=String.Empty) iptemp.Add(String.Copy(serv.IpAddress)); --- 166,170 ---- { serv = (STRUCTURES.IP_ADDR_STRING)Marshal.PtrToStructure(pAddrStr, typeof(STRUCTURES.IP_ADDR_STRING)); ! if (serv.IpAddress != null && serv.IpAddress != String.Empty) iptemp.Add(String.Copy(serv.IpAddress)); *************** *** 164,168 **** } Marshal.DestroyStructure(pMemory, typeof(STRUCTURES.FIXED_INFO)); ! if(iptemp.Count > 0) { String[] servers = (String[])iptemp.ToArray(typeof(String)); --- 174,178 ---- } Marshal.DestroyStructure(pMemory, typeof(STRUCTURES.FIXED_INFO)); ! if (iptemp.Count > 0) { String[] servers = (String[])iptemp.ToArray(typeof(String)); *************** *** 171,175 **** } else ! return new string[0]{}; //length=0 } finally --- 181,185 ---- } else ! return new string[0] { }; //length=0 } finally *************** *** 188,219 **** internal unsafe sealed class UnsafeOpenSsl { ! private UnsafeOpenSsl(){} private const String LIB_EAY = @"libeay32.dll"; private const String LIB_SSL = @"ssleay32.dll"; ! [DllImport(LIB_SSL)] internal static extern int SSL_library_init(); ! [DllImport(LIB_SSL)] internal static extern void SSL_load_error_strings(); ! [DllImport(LIB_SSL)] internal static extern IntPtr TLSv1_method(); ! [DllImport(LIB_SSL)] internal static extern IntPtr SSL_CTX_new(IntPtr method); ! [DllImport(LIB_SSL)] internal static extern void SSL_CTX_free(IntPtr ctx); ! [DllImport(LIB_SSL)] internal static extern IntPtr SSL_new(IntPtr ctx); ! [DllImport(LIB_SSL)] internal static extern void SSL_free(IntPtr ssl); ! [DllImport(LIB_SSL)] internal static extern int SSL_shutdown(IntPtr ssl); ! [DllImport(LIB_SSL)] internal static extern int SSL_set_fd(IntPtr ssl, IntPtr sockHandle); ! [DllImport(LIB_SSL)] internal static extern void SSL_set_quiet_shutdown(IntPtr ssl, int mode); ! [DllImport(LIB_SSL)] internal static extern int SSL_ctrl(IntPtr ssl, int cmd, int larg, IntPtr parg); ! [DllImport(LIB_SSL)] internal static extern int SSL_connect(IntPtr ssl); ! [DllImport(LIB_SSL)] internal static extern int SSL_read(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] internal static extern int SSL_write(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] internal static extern int SSL_peek(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] internal static extern IntPtr SSL_get_peer_certificate(IntPtr ssl); ! [DllImport(LIB_SSL)] internal static extern int SSL_get_error(IntPtr ssl, int ret); ! [DllImport(LIB_EAY)] internal static extern uint SSLeay(); ! [DllImport(LIB_EAY)] internal static extern int ERR_get_error(); ! [DllImport(LIB_EAY)] internal static extern int ERR_peek_error(); ! [DllImport(LIB_EAY)] internal static extern String ERR_error_string_n(int e, System.Text.StringBuilder sb, int l); ! [DllImport(LIB_EAY)] internal static extern void X509_free(IntPtr x509); ! [DllImport(LIB_EAY)] internal static extern int i2d_X509(IntPtr cer, byte** ppOut); } }; --- 198,252 ---- internal unsafe sealed class UnsafeOpenSsl { ! private UnsafeOpenSsl() { } private const String LIB_EAY = @"libeay32.dll"; private const String LIB_SSL = @"ssleay32.dll"; ! [DllImport(LIB_SSL)] ! internal static extern int SSL_library_init(); ! [DllImport(LIB_SSL)] ! internal static extern void SSL_load_error_strings(); ! [DllImport(LIB_SSL)] ! internal static extern IntPtr TLSv1_method(); ! [DllImport(LIB_SSL)] ! internal static extern IntPtr SSL_CTX_new(IntPtr method); ! [DllImport(LIB_SSL)] ! internal static extern void SSL_CTX_free(IntPtr ctx); ! [DllImport(LIB_SSL)] ! internal static extern IntPtr SSL_new(IntPtr ctx); ! [DllImport(LIB_SSL)] ! internal static extern void SSL_free(IntPtr ssl); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_shutdown(IntPtr ssl); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_set_fd(IntPtr ssl, IntPtr sockHandle); ! [DllImport(LIB_SSL)] ! internal static extern void SSL_set_quiet_shutdown(IntPtr ssl, int mode); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_ctrl(IntPtr ssl, int cmd, int larg, IntPtr parg); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_connect(IntPtr ssl); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_read(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_write(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_peek(IntPtr ssl, byte* buf, int num); ! [DllImport(LIB_SSL)] ! internal static extern IntPtr SSL_get_peer_certificate(IntPtr ssl); ! [DllImport(LIB_SSL)] ! internal static extern int SSL_get_error(IntPtr ssl, int ret); ! [DllImport(LIB_EAY)] ! internal static extern uint SSLeay(); ! [DllImport(LIB_EAY)] ! internal static extern int ERR_get_error(); ! [DllImport(LIB_EAY)] ! internal static extern int ERR_peek_error(); ! [DllImport(LIB_EAY)] ! internal static extern String ERR_error_string_n(int e, System.Text.StringBuilder sb, int l); ! [DllImport(LIB_EAY)] ! internal static extern void X509_free(IntPtr x509); ! [DllImport(LIB_EAY)] ! internal static extern int i2d_X509(IntPtr cer, byte** ppOut); } }; |
From: Ethem E. <et...@us...> - 2006-08-07 08:15:39
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv18842/dnsmail Modified Files: MIME.cs Log Message: QPEncode optimised. Index: MIME.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/MIME.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** MIME.cs 4 Aug 2006 09:52:19 -0000 1.2 --- MIME.cs 7 Aug 2006 08:15:36 -0000 1.3 *************** *** 17,23 **** public sealed class MIME { ! private MIME() {} ! private static readonly byte[] crlf = Encoding.ASCII.GetBytes("\r\n"); ! private static readonly byte[] eq_crlf = Encoding.ASCII.GetBytes("=\r\n"); private static readonly byte[] eq_crlf_crlf = Encoding.ASCII.GetBytes("=\r\n\r\n"); private static readonly char[] hexChars = --- 17,23 ---- public sealed class MIME { ! private MIME() { } ! private static readonly byte[] crlf = Encoding.ASCII.GetBytes("\r\n"); ! private static readonly byte[] eq_crlf = Encoding.ASCII.GetBytes("=\r\n"); private static readonly byte[] eq_crlf_crlf = Encoding.ASCII.GetBytes("=\r\n\r\n"); private static readonly char[] hexChars = *************** *** 32,42 **** #region encodemap ! private const byte NUL = 0x00; // don't encode ! private const byte ESC = 0x01; // always encode ! private const byte SPC = 0x02; // horizontal whitespace ! private const byte BOL = 0x03; // encode if at beginning of line ! private const byte CR = 0x04; // carriage return ! private const byte LF = 0x05; // linefeed ! private static readonly byte[] encodemap = { ESC, ESC, ESC, ESC, ESC, ESC, ESC, ESC, // 000-007 --- 32,42 ---- #region encodemap ! private const byte NUL = 0x00; // don't encode ! private const byte ESC = 0x01; // always encode ! private const byte SPC = 0x02; // horizontal whitespace ! private const byte BOL = 0x03; // encode if at beginning of line ! private const byte CR = 0x04; // carriage return ! private const byte LF = 0x05; // linefeed ! private static readonly byte[] encodemap = { ESC, ESC, ESC, ESC, ESC, ESC, ESC, ESC, // 000-007 *************** *** 81,87 **** private const byte DNUL = 0x7F; private const byte DESC = 0x7E; ! private const byte DCR = 0x7D; ! private const byte DLF = 0x7C; ! private static readonly byte[] decodemap = { DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, // 000-007 --- 81,87 ---- private const byte DNUL = 0x7F; private const byte DESC = 0x7E; ! private const byte DCR = 0x7D; ! private const byte DLF = 0x7C; ! private static readonly byte[] decodemap = { DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, DNUL, // 000-007 *************** *** 134,192 **** return null; - byte b, c; byte lastByte = NUL; bool hadWhitespace = false; int column = 0, buflen = originalBuffer.Length; MemoryStream ms = new MemoryStream(); ! try { ! for(int i = 0; i < buflen; i++) { ! b = originalBuffer[i]; ! c = encodemap[b]; ! ! if (c == NUL) ! { ! ms.WriteByte(b); ! column++; ! hadWhitespace = false; ! } ! else if (c == SPC) ! { ! ms.WriteByte(b); ! column++; ! hadWhitespace = true; ! } ! else if (c == LF && lastByte == CR) ! { ! // ignore ! } ! else if (c == CR || c == LF) { ! if (hadWhitespace) ! { ! ms.Write(eq_crlf_crlf, 0, eq_crlf_crlf.Length); hadWhitespace = false; ! } ! else ! ms.Write(crlf, 0, crlf.Length); ! column ^= column; ! } ! else if ((c == BOL) && (column != 0) && ((flags & SmtpEncode.Dot) != SmtpEncode.None)) ! { ! ms.WriteByte(b); ! column++; ! hadWhitespace = false; ! } ! else ! { ! ms.Write(new byte[] { (byte)'=', hex[0x0f & (b >> 4)], hex[0x0f & b] }, 0, 3); ! column += 3; ! hadWhitespace = false; } lastByte = c; // ASSERT: Debug.Assert(column <= 76); ! if (column >= 73) { ms.Write(eq_crlf, 0, eq_crlf.Length); --- 134,201 ---- return null; byte lastByte = NUL; bool hadWhitespace = false; int column = 0, buflen = originalBuffer.Length; MemoryStream ms = new MemoryStream(); ! try { ! for (int i = 0; i < buflen; i++) { ! byte b = originalBuffer[i]; ! byte c = encodemap[b]; ! switch (c) { ! case NUL: ! ms.WriteByte(b); ! column++; hadWhitespace = false; ! break; ! case SPC: ! ms.WriteByte(b); ! column++; ! hadWhitespace = true; ! break; ! ! default: ! if (c != LF || lastByte != CR) ! { ! switch (c) ! { ! case CR: ! case LF: ! if (hadWhitespace) ! { ! ms.Write(eq_crlf_crlf, 0, eq_crlf_crlf.Length); ! hadWhitespace = false; ! } ! else ! { ! ms.Write(crlf, 0, crlf.Length); ! } ! column ^= column; ! break; ! ! default: ! if ((c == BOL) && (column != 0) && ((flags & SmtpEncode.Dot) != SmtpEncode.None)) ! { ! ms.WriteByte(b); ! column++; ! hadWhitespace = false; ! } ! else ! { ! ms.Write(new byte[] { (byte)'=', hex[0x0f & (b >> 4)], hex[0x0f & b] }, 0, 3); ! column += 3; ! hadWhitespace = false; ! } ! break; ! } ! } ! break; } lastByte = c; // ASSERT: Debug.Assert(column <= 76); ! if (column >= 73) { ms.Write(eq_crlf, 0, eq_crlf.Length); *************** *** 203,207 **** return ret; } ! catch { return null; --- 212,216 ---- return ret; } ! catch { return null; *************** *** 210,216 **** { ms.SetLength(0L); ! ms.Capacity=0; ms.Close(); ! ms=null; } } --- 219,225 ---- { ms.SetLength(0L); ! ms.Capacity = 0; ms.Close(); ! ms = null; } } *************** *** 227,235 **** byte[] token = new byte[3]; int tokenLength = 0, i = 0; ! try { while (i < buflen) { ! if (tokenLength == 0) { int j = i; --- 236,244 ---- byte[] token = new byte[3]; int tokenLength = 0, i = 0; ! try { while (i < buflen) { ! if (tokenLength == 0) { int j = i; *************** *** 241,245 **** break; } ! byte b = decodedBuffer[i++]; byte c = decodemap[b]; --- 250,254 ---- break; } ! byte b = decodedBuffer[i++]; byte c = decodemap[b]; *************** *** 255,265 **** if (n1 == DCR || n1 == DLF) { // "=\r", "=\n", or "=\r\n" ! if (n1 == DLF || n2 != DLF) { ! if (n2 == DESC) { token[0] = token[2]; tokenLength = 1; ! } else { --- 264,274 ---- if (n1 == DCR || n1 == DLF) { // "=\r", "=\n", or "=\r\n" ! if (n1 == DLF || n2 != DLF) { ! if (n2 == DESC) { token[0] = token[2]; tokenLength = 1; ! } else { *************** *** 283,294 **** catch { ! ret = null; } finally { ms.SetLength(0L); ! ms.Capacity=0; ms.Close(); ! ms=null; } } --- 292,303 ---- catch { ! ret = null; } finally { ms.SetLength(0L); ! ms.Capacity = 0; ms.Close(); ! ms = null; } } *************** *** 301,310 **** internal static String QEncode(byte[] bufferOriginal, string charSet) { ! if (bufferOriginal == null)return String.Empty; int bufferLen = bufferOriginal.Length; ! if (bufferLen == 0) return String.Empty; ! if (charSet==null||charSet==string.Empty) charSet = Erle.DnsMail.MailInfo.DefaultCharset; ! try { int nRead = 0; StringBuilder sb = new StringBuilder(); --- 310,319 ---- internal static String QEncode(byte[] bufferOriginal, string charSet) { ! if (bufferOriginal == null) return String.Empty; int bufferLen = bufferOriginal.Length; ! if (bufferLen == 0) return String.Empty; ! if (charSet == null || charSet == string.Empty) charSet = Erle.DnsMail.MailInfo.DefaultCharset; ! try { int nRead = 0; StringBuilder sb = new StringBuilder(); *************** *** 319,330 **** continue; } ! sb.Append( '=' ); ! sb.Append( hexChars[(ch >> 4) & 0x0f] ); ! sb.Append( hexChars[ch & 0x0f] ); } sb.Append("?="); return sb.ToString(); } ! catch { return String.Empty; --- 328,339 ---- continue; } ! sb.Append('='); ! sb.Append(hexChars[(ch >> 4) & 0x0f]); ! sb.Append(hexChars[ch & 0x0f]); } sb.Append("?="); return sb.ToString(); } ! catch { return String.Empty; *************** *** 340,357 **** internal static String BEncode(byte[] bufferOriginal, string charSet) { ! if (bufferOriginal == null)return String.Empty; int bufferLen = bufferOriginal.Length; ! if (bufferLen == 0) return String.Empty; ! if (charSet==null||charSet==string.Empty) charSet = Erle.DnsMail.MailInfo.DefaultCharset; ! try { StringBuilder sb = new StringBuilder(); sb.Append("=?" + charSet + "?B?"); ! sb.Append(Convert.ToBase64String(bufferOriginal)); sb.Append("?="); return sb.ToString(); } ! catch { return String.Empty; --- 349,366 ---- internal static String BEncode(byte[] bufferOriginal, string charSet) { ! if (bufferOriginal == null) return String.Empty; int bufferLen = bufferOriginal.Length; ! if (bufferLen == 0) return String.Empty; ! if (charSet == null || charSet == string.Empty) charSet = Erle.DnsMail.MailInfo.DefaultCharset; ! try { StringBuilder sb = new StringBuilder(); sb.Append("=?" + charSet + "?B?"); ! sb.Append(Convert.ToBase64String(bufferOriginal)); sb.Append("?="); return sb.ToString(); } ! catch { return String.Empty; *************** *** 364,366 **** #endregion } ! }; \ No newline at end of file --- 373,375 ---- #endregion } ! }; |
From: Ethem E. <et...@us...> - 2006-08-04 16:52:56
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv25687/dnsmail Modified Files: SmtpStream.cs Log Message: $Id$ added; Merged from DNSMAIL_03_STABLE. Index: SmtpStream.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/SmtpStream.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SmtpStream.cs 4 Aug 2006 13:35:21 -0000 1.2 --- SmtpStream.cs 4 Aug 2006 16:52:53 -0000 1.3 *************** *** 1,2 **** --- 1,3 ---- + // $Id$ namespace Erle { |
From: Ethem E. <et...@us...> - 2006-08-04 16:50:51
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv24963/dnsmail Modified Files: Tag: DNSMAIL_03_STABLE SmtpStream.cs Log Message: $Id$ added Index: SmtpStream.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/SmtpStream.cs,v retrieving revision 1.2 retrieving revision 1.2.2.1 diff -C2 -d -r1.2 -r1.2.2.1 *** SmtpStream.cs 4 Aug 2006 13:35:21 -0000 1.2 --- SmtpStream.cs 4 Aug 2006 16:50:46 -0000 1.2.2.1 *************** *** 1,2 **** --- 1,3 ---- + // $Id$ namespace Erle { |
From: Ethem E. <et...@us...> - 2006-08-04 15:23:04
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv25008/dnsmail Modified Files: DNSAPI.cs Erle.DnsMail.csproj Removed Files: DnsCache.cs Log Message: DnsCache removed. Index: Erle.DnsMail.csproj =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/Erle.DnsMail.csproj,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Erle.DnsMail.csproj 4 Aug 2006 12:53:36 -0000 1.4 --- Erle.DnsMail.csproj 4 Aug 2006 15:22:59 -0000 1.5 *************** *** 100,108 **** /> <File - RelPath = "DnsCache.cs" - SubType = "Code" - BuildAction = "Compile" - /> - <File RelPath = "MIME.cs" SubType = "Code" --- 100,103 ---- *************** *** 158,159 **** --- 153,155 ---- </CSHARP> </VisualStudioProject> + Index: DNSAPI.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DNSAPI.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** DNSAPI.cs 21 Mar 2006 18:52:32 -0000 1.3 --- DNSAPI.cs 4 Aug 2006 15:22:59 -0000 1.4 *************** *** 10,32 **** using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; public sealed class DNSAPI { private DNSAPI(){} - static DNSAPI() - { - DnsCache.DeletedAll += new EventHandler(DeletedAll); - } - - #region DeletedAll - private static void DeletedAll(object sender, EventArgs e) - { - dnsServers = null; - localHost = null; - hello = null; - - GC.Collect(); - } - #endregion #region LocalHost --- 10,18 ---- using MxRecord = Erle.DnsMail.MxRecord; using MxRecordComparer = Erle.DnsMail.MxRecordComparer; + using DnsException = Erle.DnsMail.DnsException; public sealed class DNSAPI { private DNSAPI(){} #region LocalHost *************** *** 101,108 **** return null; - MxRecord[] cache = DnsCache.GetFromCache(domain); - if (cache != null && cache.Length > 0) - return (cache); // struct-copy - IntPtr pQuery = IntPtr.Zero; UInt32 status = UnsafeNativeMethods.DnsQuery( --- 87,90 ---- *************** *** 115,119 **** ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try --- 97,101 ---- ); ! if (status == STRUCTURES.SUCCESS && pQuery != IntPtr.Zero) { try *************** *** 141,145 **** // Resolve - bool err = false; for(int i = 0; i < mxs.Length; i++) { --- 123,126 ---- *************** *** 149,153 **** if (ipx == null || ipx.Length == 0) continue; foreach(IPAddress ipadr in ipx) mxs[i] += ipadr; - } catch(SocketException se) --- 130,133 ---- *************** *** 156,168 **** continue; // The requested name is valid, but no data of the requested type was found } ! catch ! { ! err = true; ! } } - - if (!err) - DnsCache.AddToCache(domain, mxs); - tmp.Clear(); return mxs; --- 136,141 ---- continue; // The requested name is valid, but no data of the requested type was found } ! catch {} } tmp.Clear(); return mxs; *************** *** 182,185 **** --- 155,224 ---- } #endregion + + #region InternalResolve + internal static IPAddress[] InternalResolve(ref string mailHost, ref bool usedMx, ref MxRecord[] mxss) + { + if( mailHost == null || mailHost == String.Empty || + mailHost == "localhost" || mailHost == "127.0.0.1") + mailHost = DNSAPI.LocalHost; + + if (mailHost[0] >= '1' && mailHost[0] <= '9' && IsIp4(mailHost)) + { + usedMx = false; + return new IPAddress[] { IPAddress.Parse(mailHost) }; + } + + if(usedMx) + { + mxss = DNSAPI.GetMxRecords(mailHost); + if (mxss != null && mxss.Length > 0) + { + usedMx = true; + return null; + } + } + + try + { + IPAddress[] addresses = Dns.Resolve(mailHost).AddressList; + if (addresses != null && addresses.Length > 0) + { + usedMx = false; + return addresses; + } + } + catch {} + throw new DnsException(String.Format("No" + + ( (usedMx) ? " MaileXchange (MX) or" : String.Empty ) + + " IP (A) record could be found for {0}.", mailHost)); + } + + private static bool IsIp4(string address) + { + if (address == null || + address == string.Empty || + address.IndexOf('.') == -1) + return false; + + int labelCount = 0, octet; + string[] ips = address.Split(new char[] {'.'}); + for(int i = 0; i < ips.Length; i++) + { + try + { + octet = int.Parse(ips[i]); + if ( ( octet < 0 ) || ( octet > 255 ) ) + return false; + else + labelCount++; + } + catch + { + return false; + } + } + return ( (labelCount > 0) && (labelCount < 5) ); + } + #endregion } }; --- DnsCache.cs DELETED --- |
From: Ethem E. <et...@us...> - 2006-08-04 15:23:04
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv25008/dnsmail/DnsMail Modified Files: DnsMail.cs Log Message: DnsCache removed. Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** DnsMail.cs 4 Aug 2006 13:52:56 -0000 1.7 --- DnsMail.cs 4 Aug 2006 15:23:00 -0000 1.8 *************** *** 474,478 **** MxRecord[] mxs = new MxRecord[0]; ! IPAddress[] ips = DnsCache.InternalResolve(ref resDom, ref usedMx, ref mxs); #region resolved --- 474,478 ---- MxRecord[] mxs = new MxRecord[0]; ! IPAddress[] ips = DNSAPI.InternalResolve(ref resDom, ref usedMx, ref mxs); #region resolved |
From: Ethem E. <et...@us...> - 2006-08-04 13:53:00
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv22789/dnsmail Modified Files: AssemblyInfo.cs Log Message: Bumped to 0.4.0.0 (Dev) Index: AssemblyInfo.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/AssemblyInfo.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AssemblyInfo.cs 22 May 2006 09:46:57 -0000 1.3 --- AssemblyInfo.cs 4 Aug 2006 13:52:56 -0000 1.4 *************** *** 11,15 **** // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: ! [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyTitle("Erle.DnsMail")] --- 11,15 ---- // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: ! [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyTitle("Erle.DnsMail")] |
From: Ethem E. <et...@us...> - 2006-08-04 13:53:00
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv22789/dnsmail/DnsMail Modified Files: DnsMail.cs Log Message: Bumped to 0.4.0.0 (Dev) Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** DnsMail.cs 4 Aug 2006 12:53:36 -0000 1.6 --- DnsMail.cs 4 Aug 2006 13:52:56 -0000 1.7 *************** *** 700,704 **** } header.AppendFormat("Date: {0}" + CRLF, __sd); ! header.Append("X-Mailer: Erle.DnsMail.v0.3.0.0" + CRLF); // Subject: --- 700,704 ---- } header.AppendFormat("Date: {0}" + CRLF, __sd); ! header.Append("X-Mailer: Erle.DnsMail.v0.4.0.0" + CRLF); // Subject: |
From: Ethem E. <et...@us...> - 2006-08-04 13:35:24
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv15791/dnsmail Modified Files: SmtpStream.cs Log Message: Some debug information removed and paramater validation added. Index: SmtpStream.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/SmtpStream.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** SmtpStream.cs 4 Aug 2006 12:59:04 -0000 1.1 --- SmtpStream.cs 4 Aug 2006 13:35:21 -0000 1.2 *************** *** 157,165 **** #region Handshake - public static void write(string x) - { - System.Web.HttpContext.Current.Response.Write(x + "<br />"); - } - private bool handshake = false; public bool Handshake(bool cerrequest) --- 157,160 ---- *************** *** 174,178 **** const int SSL_OP_ALL = 0x00000FFF; ! //UnsafeOpenSsl.SSL_set_quiet_shutdown(sslSession, 1); UnsafeOpenSsl.SSL_ctrl(sslSession, SSL_CTRL_OPTIONS, SSL_OP_ALL, IntPtr.Zero); UnsafeOpenSsl.SSL_set_fd(sslSession, Socket.Handle); --- 169,173 ---- const int SSL_OP_ALL = 0x00000FFF; ! UnsafeOpenSsl.SSL_set_quiet_shutdown(sslSession, 1); UnsafeOpenSsl.SSL_ctrl(sslSession, SSL_CTRL_OPTIONS, SSL_OP_ALL, IntPtr.Zero); UnsafeOpenSsl.SSL_set_fd(sslSession, Socket.Handle); *************** *** 183,192 **** Socket.Blocking = false; ! int err, cnt = 0; ! while (((err=UnsafeOpenSsl.SSL_connect(sslSession)) <= 0) && handle_ssl_error(err, errors)) ! cnt++; if (Socket.Blocking != oldblock) ! Socket.Blocking = oldblock; if (err <= 0) --- 178,186 ---- Socket.Blocking = false; ! int err; ! while (((err=UnsafeOpenSsl.SSL_connect(sslSession)) <= 0) && handle_ssl_error(err, errors)); if (Socket.Blocking != oldblock) ! Socket.Blocking = oldblock; if (err <= 0) *************** *** 194,200 **** try { ! if (errors.Length > 0) throw new Exception(errors.ToString()); ! else if (err == 0) throw new Exception("Connection closed"); ! else throw new Exception("Unknown SSL exception"); } finally --- 188,200 ---- try { ! if (errors.Length > 0) ! { ! throw new Exception(errors.ToString()); ! } ! if (err == 0) ! { ! throw new Exception("Connection closed"); ! } ! throw new Exception("Unknown SSL exception"); } finally *************** *** 334,337 **** --- 334,349 ---- if (handshake) { + if (buffer == null) + { + throw new ArgumentNullException("buffer"); + } + if (offset < 0 || offset > buffer.Length) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (count < 0 || count > buffer.Length-offset) + { + throw new ArgumentOutOfRangeException("count"); + } fixed(byte* ptr = &buffer[offset]) { *************** *** 357,360 **** --- 369,384 ---- if (handshake) { + if (buffer == null) + { + throw new ArgumentNullException("buffer"); + } + if (offset < 0 || offset > buffer.Length) + { + throw new ArgumentOutOfRangeException("offset"); + } + if (count < 0 || count > buffer.Length-offset) + { + throw new ArgumentOutOfRangeException("count"); + } fixed(byte* ptr = &buffer[offset]) { |
From: Ethem E. <et...@us...> - 2006-08-04 12:59:08
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv1481/dnsmail Added Files: SmtpStream.cs Log Message: - OpensslStream class removed and new SmtpStream class derived from NetworkStream added. - New class handles normal and ssl connections automatically. - Socket and OpenSslStream removed from DnsMail client. New SmtpStream member added. --- NEW FILE: SmtpStream.cs --- namespace Erle { using System; using System.IO; using System.Text; using System.Threading; using System.Net.Sockets; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; internal class SmtpStream : NetworkStream, IDisposable { private IntPtr sslSession = IntPtr.Zero; private IntPtr sslContext = IntPtr.Zero; private X509Certificate x509cert = null; #region .ctor .cctor and .dtor private static readonly String _sslVersion; private static readonly bool _sslAvailable; static SmtpStream() { try { UnsafeOpenSsl.SSL_load_error_strings(); UnsafeOpenSsl.SSL_library_init(); IntPtr tmpctx = IntPtr.Zero; try { tmpctx = UnsafeOpenSsl.SSL_CTX_new(UnsafeOpenSsl.TLSv1_method()); uint version = UnsafeOpenSsl.SSLeay(); _sslAvailable = true; _sslVersion = "OpenSSL(0x0" + version.ToString("x") + ")"; } finally { if (tmpctx != IntPtr.Zero) UnsafeOpenSsl.SSL_CTX_free(tmpctx); } } catch { _sslAvailable = false; _sslVersion = String.Empty; } } public SmtpStream(Socket s) : this(s, false) {} public SmtpStream(Socket s, bool ownsSocket) : base(s, FileAccess.ReadWrite, ownsSocket) {} ~SmtpStream() { Dispose(false); } public override void Close() { ((IDisposable)this).Dispose(); } void IDisposable.Dispose() { Flush(); Dispose(true); GC.SuppressFinalize(this); } private bool disposed = false; protected override void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { x509cert = null; } if (sslSession != IntPtr.Zero) { try { UnsafeOpenSsl.SSL_free(sslSession); } catch {throw;} sslSession = IntPtr.Zero; } if (sslContext != IntPtr.Zero) { try { UnsafeOpenSsl.SSL_CTX_free(sslContext); } catch {throw;} sslContext = IntPtr.Zero; } } base.Dispose(disposing); } #endregion #region Properties public X509Certificate X509Certificate { get { return x509cert; } } public bool SslActive { get { return _sslAvailable && !disposed && handshake; } } public override bool CanRead { get { return !disposed && base.CanRead; } } public override bool CanWrite { get { return !disposed && base.CanWrite; } } public unsafe override bool DataAvailable { get { if (handshake && !disposed) { int r = 0; byte[] t = new byte[1]; fixed (byte* y = &t[0]) { r = UnsafeOpenSsl.SSL_peek(sslSession, y, 1); } return (r > 0); } else { return base.DataAvailable; } } } public static String OpenSslVersion { get { return _sslVersion; } } public static bool SslAvailable { get { return _sslAvailable; } } #endregion #region Handshake public static void write(string x) { System.Web.HttpContext.Current.Response.Write(x + "<br />"); } private bool handshake = false; public bool Handshake(bool cerrequest) { bool ret = false; if (_sslAvailable && !disposed && !handshake && (Socket.RemoteEndPoint != null)) { if (IntPtr.Zero != (sslContext = UnsafeOpenSsl.SSL_CTX_new(UnsafeOpenSsl.TLSv1_method())) && IntPtr.Zero != (sslSession = UnsafeOpenSsl.SSL_new(sslContext))) { const int SSL_CTRL_OPTIONS = 32; const int SSL_OP_ALL = 0x00000FFF; //UnsafeOpenSsl.SSL_set_quiet_shutdown(sslSession, 1); UnsafeOpenSsl.SSL_ctrl(sslSession, SSL_CTRL_OPTIONS, SSL_OP_ALL, IntPtr.Zero); UnsafeOpenSsl.SSL_set_fd(sslSession, Socket.Handle); StringBuilder errors = new StringBuilder(); bool oldblock = Socket.Blocking; if (oldblock) Socket.Blocking = false; int err, cnt = 0; while (((err=UnsafeOpenSsl.SSL_connect(sslSession)) <= 0) && handle_ssl_error(err, errors)) cnt++; if (Socket.Blocking != oldblock) Socket.Blocking = oldblock; if (err <= 0) { try { if (errors.Length > 0) throw new Exception(errors.ToString()); else if (err == 0) throw new Exception("Connection closed"); else throw new Exception("Unknown SSL exception"); } finally { Close(); } } handshake = true; // opened #region get certificate if (cerrequest) { IntPtr cer = IntPtr.Zero; try { if (IntPtr.Zero != (cer = UnsafeOpenSsl.SSL_get_peer_certificate(sslSession))) { unsafe { int required = UnsafeOpenSsl.i2d_X509(cer, (byte**)0); if (required > 0 && required < 16384) { byte[] buf = new byte[required]; fixed(byte* pBuf = buf) { byte* pp = pBuf; UnsafeOpenSsl.i2d_X509(cer, &pp); x509cert = new X509Certificate(buf); } } } } } catch {} finally { if (cer != IntPtr.Zero) { try { UnsafeOpenSsl.X509_free(cer); } catch{} } } } #endregion ret = true; } else { Close(); } } return ret; } #endregion #region handle_ssl_error private enum SslError { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_WANT_X509_LOOKUP = 4, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, SSL_ERROR_WANT_CONNECT = 7, SSL_ERROR_WANT_ACCEPT = 8 } private bool handle_ssl_error(int c, StringBuilder errstack) { SslError err = (SslError)UnsafeOpenSsl.SSL_get_error(sslSession, c); bool retry = true; switch(err) { case SslError.SSL_ERROR_ZERO_RETURN: /* SSL terminated (but socket may still be active) */ retry = false; break; case SslError.SSL_ERROR_WANT_READ: case SslError.SSL_ERROR_WANT_WRITE: /* re-negotiation || perhaps the SSL layer needs more packets */ Thread.Sleep(50); break; case SslError.SSL_ERROR_SYSCALL: if (UnsafeOpenSsl.ERR_peek_error() == 0) { retry = false; break; } goto default; default: { const int SSL_R_NO_SHARED_CIPHER = 193; int ecode = UnsafeOpenSsl.ERR_get_error(); switch((int)(ecode&0xfff)) // reason { case SSL_R_NO_SHARED_CIPHER: { /* no suitable shared cipher could be used */ retry = false; break; } default: { do { StringBuilder s = new StringBuilder(512); UnsafeOpenSsl.ERR_error_string_n(ecode, s, 510); s.Insert(0, "["); s.Append("]"); errstack.Append(s.ToString() + "\r\n"); } while((ecode = UnsafeOpenSsl.ERR_get_error()) != 0); break; } } retry = false; break; } } return retry; } #endregion #region Read && Write unsafe public override int Read(byte[] buffer, int offset, int count) { int read = -1; if (handshake) { fixed(byte* ptr = &buffer[offset]) { try { read = UnsafeOpenSsl.SSL_read(sslSession, ptr, count); } catch { read = -1; } } } else { read = base.Read(buffer, offset, count); } return read; } unsafe public override void Write(byte[] buffer, int offset, int count) { if (handshake) { fixed(byte* ptr = &buffer[offset]) { while (count > 0) { int sent = UnsafeOpenSsl.SSL_write(sslSession, &ptr[offset], count); if (sent <= 0) { throw new Exception("ERR::SSL_write::memory{0x" + ((int)ptr).ToString("x") + "} index[" + offset + "]"); } offset += sent; count -= sent; } } } else { base.Write(buffer, offset, count); } } public bool Poll(int microSeconds, SelectMode mode) { return Socket.Poll(microSeconds, mode); } #endregion } }; |
From: Ethem E. <et...@us...> - 2006-08-04 12:53:40
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv31965/dnsmail Modified Files: Erle.DnsMail.csproj Erle.DnsMail.csproj.user UnsafeNativeMethods.cs Log Message: - OpensslStream class removed and new SmtpStream class derived from NetworkStream added. - New class handles normal and ssl connections automatically. - Socket and OpenSslStream removed from DnsMail client. New SmtpStream member added. Index: Erle.DnsMail.csproj =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/Erle.DnsMail.csproj,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Erle.DnsMail.csproj 22 May 2006 09:54:56 -0000 1.3 --- Erle.DnsMail.csproj 4 Aug 2006 12:53:36 -0000 1.4 *************** *** 110,113 **** --- 110,118 ---- /> <File + RelPath = "SmtpStream.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "UnsafeNativeMethods.cs" SubType = "Code" *************** *** 140,148 **** /> <File - RelPath = "DnsMail\OpenSslStream.cs" - SubType = "Code" - BuildAction = "Compile" - /> - <File RelPath = "DnsMail\Recipient.cs" SubType = "Code" --- 145,148 ---- Index: UnsafeNativeMethods.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/UnsafeNativeMethods.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** UnsafeNativeMethods.cs 22 May 2006 10:27:56 -0000 1.3 --- UnsafeNativeMethods.cs 4 Aug 2006 12:53:36 -0000 1.4 *************** *** 206,209 **** --- 206,210 ---- [DllImport(LIB_SSL)] internal static extern int SSL_read(IntPtr ssl, byte* buf, int num); [DllImport(LIB_SSL)] internal static extern int SSL_write(IntPtr ssl, byte* buf, int num); + [DllImport(LIB_SSL)] internal static extern int SSL_peek(IntPtr ssl, byte* buf, int num); [DllImport(LIB_SSL)] internal static extern IntPtr SSL_get_peer_certificate(IntPtr ssl); [DllImport(LIB_SSL)] internal static extern int SSL_get_error(IntPtr ssl, int ret); Index: Erle.DnsMail.csproj.user =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/Erle.DnsMail.csproj.user,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Erle.DnsMail.csproj.user 22 May 2006 09:56:39 -0000 1.2 --- Erle.DnsMail.csproj.user 4 Aug 2006 12:53:36 -0000 1.3 *************** *** 46,47 **** --- 46,48 ---- </CSHARP> </VisualStudioProject> + |
From: Ethem E. <et...@us...> - 2006-08-04 12:53:40
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv31965/dnsmail/DnsMail Modified Files: DnsMail.cs Removed Files: OpenSslStream.cs Log Message: - OpensslStream class removed and new SmtpStream class derived from NetworkStream added. - New class handles normal and ssl connections automatically. - Socket and OpenSslStream removed from DnsMail client. New SmtpStream member added. --- OpenSslStream.cs DELETED --- Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** DnsMail.cs 4 Aug 2006 09:52:19 -0000 1.5 --- DnsMail.cs 4 Aug 2006 12:53:36 -0000 1.6 *************** *** 35,40 **** #region Class Members ! private Socket m_Client; // Mail Client ! private OpenSslStream m_Ssl; // SSL Stream private Int32 m_RcptCount; // Recipient OK Count private Encoding m_Enc; // Charset Encoder --- 35,39 ---- #region Class Members ! private SmtpStream m_Stream; // Data Stream private Int32 m_RcptCount; // Recipient OK Count private Encoding m_Enc; // Charset Encoder *************** *** 167,175 **** #region ssl section - - private bool normalconn = true; public bool SslActive { ! get { return (!normalconn); } } --- 166,172 ---- #region ssl section public bool SslActive { ! get { return (m_Stream != null && m_Stream.SslActive); } } *************** *** 263,292 **** * Release UNmanaged objects... **************************************************/ ! // Socket release ! if( m_Client != null ) { try { ! if( m_Client.Poll(1000, SelectMode.SelectWrite) ) SendAndReceive("QUIT\r\n"); } catch {} ! ! if (m_Ssl != null) ! { ! normalconn = true; ! try { m_Ssl.Close(); } ! catch {} ! m_Ssl = null; ! } ! ! try { m_Client.Shutdown(SocketShutdown.Receive); } ! catch {} ! finally ! { ! m_Client.Close(); ! m_Client = null; ! } ! OnClosed(EventArgs.Empty); } --- 260,273 ---- * Release UNmanaged objects... **************************************************/ ! if( m_Stream != null ) { try { ! if( m_Stream.Poll(1000, SelectMode.SelectWrite) ) SendAndReceive("QUIT\r\n"); } catch {} ! m_Stream.Close(); ! m_Stream = null; OnClosed(EventArgs.Empty); } *************** *** 402,406 **** bool isok; string[] pars; - Recipient rec; m_RcptCount = 1; StringBuilder sb; --- 383,386 ---- *************** *** 408,414 **** string originalSubject = mi.Subject; bool readycontrol = false, senddatax = false, sendersent = true; ! for(IEnumerator ien = mi.Recipients.GetEnumerator(); ien.MoveNext(); ) { - rec = ien.Current as Recipient; try { --- 388,393 ---- string originalSubject = mi.Subject; bool readycontrol = false, senddatax = false, sendersent = true; ! foreach(Recipient rec in mi.Recipients) { try { *************** *** 562,586 **** private bool isready(IPAddress ip) { ! if (ip == null) return false; ! try { ! m_Client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); ! m_Client.Bind(LocalPoint); ! m_Client.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.NoDelay,1); ! m_Client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,TimeOut); ! m_Client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,TimeOut); ! m_Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 5)); ! m_Client.Connect( new IPEndPoint(ip, Port) ); ! if( m_Client.Poll(7 * TimeOut, SelectMode.SelectRead) && SendAndReceive(null)==Commands.Ok) { ! esmtp = (LastAnswer.ToLower().IndexOf("esmtp") != -1); ! OnConnect( ip.ToString() ); ! return true; } } ! catch {} ! m_Client.Close(); ! m_Client = null; ! return false; } --- 541,578 ---- private bool isready(IPAddress ip) { ! bool ret = false; ! if (ip != null) { ! Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ! try { ! s.Bind(LocalPoint); ! s.SetSocketOption(SocketOptionLevel.Tcp,SocketOptionName.NoDelay,1); ! s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,TimeOut); ! s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,TimeOut); ! s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 5)); ! s.Connect( new IPEndPoint(ip, Port) ); ! if( s.Poll(7 * TimeOut, SelectMode.SelectRead) ) ! { ! m_Stream = new SmtpStream(s, true); ! if (SendAndReceive(null) == Commands.Ok) ! { ! esmtp = (LastAnswer.ToLower().IndexOf("esmtp") != -1); ! OnConnect( ip.ToString() ); ! ret = true; ! } ! } ! } ! catch ! { ! s.Close(); ! if (m_Stream != null) ! { ! m_Stream.Close(); ! m_Stream = null; ! } } } ! return ret; } *************** *** 596,618 **** return; ! if (!normalconn) ! return; ! ! m_Ssl = new OpenSslStream(true); ! if (!m_Ssl.InitOk) ! { ! m_Ssl = null; return; - } if( SendAndReceive("STARTTLS\r\n") != Commands.Ok ) { - m_Ssl.Close(); m_Ssl = null; SendAndReceive("RSET\r\n"); return; } ! normalconn = (false == m_Ssl.Open(m_Client)); ! sayhello(); } --- 588,604 ---- return; ! if (!SmtpStream.SslAvailable || m_Stream == null || m_Stream.SslActive) return; if( SendAndReceive("STARTTLS\r\n") != Commands.Ok ) { SendAndReceive("RSET\r\n"); return; } ! if (m_Stream.Handshake(true)) ! { ! sayhello(); // say hello again. ! } } *************** *** 825,829 **** OnSendProgress(totalsent, remain); buffer = null; ! if ((totalsent < len) && m_Client.Connected) { goto Label_loop; --- 811,815 ---- OnSendProgress(totalsent, remain); buffer = null; ! if ((totalsent < len) && m_Stream.Poll(500, SelectMode.SelectWrite)) { goto Label_loop; *************** *** 841,845 **** try { ! if (m_Client != null && m_Client.Connected && m_Client.Poll(TimeOut, SelectMode.SelectWrite)) SocketWrite(crlf_dot_crlf, crlf_dot_crlf.Length); } --- 827,831 ---- try { ! if (m_Stream != null && m_Stream.Poll(TimeOut, SelectMode.SelectWrite)) SocketWrite(crlf_dot_crlf, crlf_dot_crlf.Length); } *************** *** 866,875 **** int bytes, breceived = 0; String tmpResp = String.Empty; do { ! bytes = (normalconn) ? ! m_Client.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None) : ! m_Ssl.Read(recvBuffer, 0, recvBuffer.Length); ! if (bytes<=0 || breceived>MaxBuffer) break; breceived += bytes; --- 852,859 ---- int bytes, breceived = 0; String tmpResp = String.Empty; + do { ! bytes = m_Stream.Read(recvBuffer, 0, recvBuffer.Length); if (bytes<=0 || breceived>MaxBuffer) break; breceived += bytes; *************** *** 880,884 **** break; } ! } while(m_Client.Poll(500, SelectMode.SelectRead)); if (tmpResp.Length < 4) --- 864,868 ---- break; } ! } while(m_Stream.Poll(500, SelectMode.SelectRead)); if (tmpResp.Length < 4) *************** *** 899,906 **** private int SocketWrite(byte[] buf, int len) { ! if (normalconn) ! return m_Client.Send(buf, 0, len, SocketFlags.None); ! ! m_Ssl.Write(buf, 0, len); return len; } --- 883,887 ---- private int SocketWrite(byte[] buf, int len) { ! m_Stream.Write(buf, 0, len); return len; } |
From: Ethem E. <et...@us...> - 2006-08-04 09:52:23
|
Update of /cvsroot/dnsmail/dnsmail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv31716/dnsmail Modified Files: MIME.cs Log Message: Merged from DNSMAIL_02 Index: MIME.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/MIME.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** MIME.cs 2 Mar 2006 16:26:54 -0000 1.1 --- MIME.cs 4 Aug 2006 09:52:19 -0000 1.2 *************** *** 123,127 **** #endregion - #region QPEncode public static byte[] QPEncode(byte[] originalBuffer) --- 123,126 ---- *************** *** 221,290 **** public static byte[] QPDecode(byte[] decodedBuffer) { ! if (decodedBuffer == null) ! return null; ! ! int buflen = decodedBuffer.Length; ! MemoryStream ms = new MemoryStream(); ! byte[] token = new byte[3]; ! int tokenLength = 0, i = 0, j; ! try { ! for(byte b,c,n1,n2; i < buflen; ) { ! if (tokenLength == 0) { ! j = i; ! while(i<buflen && decodemap[decodedBuffer[i]]!=DESC)i++; ! if (i!=j)ms.Write(decodedBuffer,j,i-j); ! if (i>=buflen)break; ! } ! b = decodedBuffer[i++]; ! c = decodemap[b]; ! ! token[tokenLength++] = b; ! ! if (tokenLength != 3) ! continue; ! ! tokenLength ^= tokenLength; // set 0 ! ! // assert (decodemap[token[0]] == DESC) ! n1 = decodemap[token[1]]; ! n2 = decodemap[token[2]]; ! if (n1 == DCR || n1 == DLF) ! { // "=\r", "=\n", or "=\r\n" ! if (n1 == DLF || n2 != DLF) { ! if (n2 == DESC) ! { ! token[0] = token[2]; ! tokenLength = 1; ! } else ! ms.WriteByte(token[2]); } ! } ! else if (n1 <= 15 || n2 <= 15) ! ms.WriteByte((byte)((n1 << 4) | n2)); ! else ! ms.Write(token, 0, token.Length); } - byte[] ret = ms.ToArray(); - return ret; - } - catch - { - return null; - } - finally - { - ms.SetLength(0L); - ms.Capacity=0; - ms.Close(); - ms=null; } } #endregion --- 220,298 ---- public static byte[] QPDecode(byte[] decodedBuffer) { ! byte[] ret = null; ! if (decodedBuffer != null) { ! int buflen = decodedBuffer.Length; ! MemoryStream ms = new MemoryStream(); ! byte[] token = new byte[3]; ! int tokenLength = 0, i = 0; ! try { ! while (i < buflen) { ! if (tokenLength == 0) ! { ! int j = i; ! while (i < buflen && decodemap[decodedBuffer[i]] != DESC) ! i++; ! if (i != j) ! ms.Write(decodedBuffer, j, i - j); ! if (i >= buflen) ! break; ! } ! byte b = decodedBuffer[i++]; ! byte c = decodemap[b]; ! token[tokenLength++] = b; ! if (tokenLength == 3) { ! tokenLength ^= tokenLength; ! // assert (decodemap[token[0]] == DESC) ! byte n1 = decodemap[token[1]]; ! byte n2 = decodemap[token[2]]; ! if (n1 == DCR || n1 == DLF) ! { // "=\r", "=\n", or "=\r\n" ! if (n1 == DLF || n2 != DLF) ! { ! if (n2 == DESC) ! { ! token[0] = token[2]; ! tokenLength = 1; ! } ! else ! { ! ms.WriteByte(token[2]); ! } ! } ! } else ! { ! if (n1 <= 15 || n2 <= 15) ! { ! ms.WriteByte((byte)((n1 << 4) | n2)); ! continue; ! } ! ms.Write(token, 0, token.Length); ! } } ! } ! ret = ms.ToArray(); ! } ! catch ! { ! ret = null; ! } ! finally ! { ! ms.SetLength(0L); ! ms.Capacity=0; ! ms.Close(); ! ms=null; } } + return ret; + } #endregion |
From: Ethem E. <et...@us...> - 2006-08-04 09:52:22
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv31716/dnsmail/DnsMail Modified Files: DnsMail.cs Log Message: Merged from DNSMAIL_02 Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** DnsMail.cs 17 Jul 2006 12:55:29 -0000 1.4 --- DnsMail.cs 4 Aug 2006 09:52:19 -0000 1.5 *************** *** 33,37 **** #endregion ! #region Class Members private Socket m_Client; // Mail Client --- 33,37 ---- #endregion ! #region Class Members private Socket m_Client; // Mail Client *************** *** 157,173 **** { get ! { if (m_LocalPoint == null) ! { ! IPHostEntry iphostentry = Dns.GetHostByName(DNSAPI.LocalHost); ! foreach(IPAddress ip in iphostentry.AddressList) ! { ! if (! IPAddress.IsLoopback(ip)) ! { ! m_LocalPoint = new IPEndPoint(ip, 0); ! break; ! } ! } ! } return m_LocalPoint; } --- 157,164 ---- { get ! { if (m_LocalPoint == null) ! m_LocalPoint = new IPEndPoint(IPAddress.Any, 0); ! return m_LocalPoint; } *************** *** 788,835 **** private void sendbuffereddata(StringBuilder header) { ! byte[] buffer; int len; ! try { // :::::::::::::: Send Headers :::::::::::: buffer = m_Enc.GetBytes( header.ToString() ); ! header.Remove(0, header.Length); header = null; int sent = SocketWrite(buffer, buffer.Length); if (sent <= 0 || sent != buffer.Length) throw new Exception("Headers couldn't be sent!"); ! // ::::::::::::::::: Send Body ::::::::::::::::: ! if (mi.Body != null && (len=mi.Body.Length) > 0) { ! String body = mi.Body; ! char[] buffchar = new char[MaxBuffer]; ! int totalsent = 0, remain, tosend; ! bool finalbuffer = false; ! remain = len; ! do { ! if (remain > MaxBuffer) ! tosend = MaxBuffer; ! else ! { ! tosend = remain; ! finalbuffer = true; ! } ! body.CopyTo(totalsent, buffchar, 0, tosend); ! //qp encode ! buffer = MIME.QPEncode( ! m_Enc.GetBytes(buffchar, 0, tosend), ! finalbuffer ? SmtpEncode.All : SmtpEncode.Dot ! ); ! // send ! sent = SocketWrite(buffer, buffer.Length); ! if((sent<=0)||(sent!=buffer.Length)) break; ! totalsent += tosend; remain -= tosend; ! OnSendProgress(totalsent, remain); ! buffer = null; } - while( totalsent < len && m_Client.Connected); - Array.Clear(buffchar, 0, buffchar.Length); - body = null; buffchar = null; } len = sent = 0; } --- 779,838 ---- private void sendbuffereddata(StringBuilder header) { ! byte[] buffer; ! try { + int len, tosend; // :::::::::::::: Send Headers :::::::::::: buffer = m_Enc.GetBytes( header.ToString() ); ! header.Remove(0, header.Length); ! header = null; int sent = SocketWrite(buffer, buffer.Length); if (sent <= 0 || sent != buffer.Length) throw new Exception("Headers couldn't be sent!"); ! if (mi.Body == null || (len=mi.Body.Length) <= 0) ! goto Label_finish; ! ! int remain = len; ! int totalsent = 0; ! bool finalbuffer = false; ! ! String body = mi.Body; ! char[] buffchar = new char[MaxBuffer]; ! ! Label_loop: ! ! if (remain > MaxBuffer) ! tosend = MaxBuffer; ! else { ! tosend = remain; ! finalbuffer = true; ! } ! ! body.CopyTo(totalsent, buffchar, 0, tosend); ! //qp encode ! buffer = MIME.QPEncode( ! m_Enc.GetBytes(buffchar, 0, tosend), ! finalbuffer ? SmtpEncode.All : SmtpEncode.Dot ! ); ! // send ! sent = SocketWrite(buffer, buffer.Length); ! if ((sent > 0) && sent == buffer.Length) ! { ! totalsent += tosend; ! remain -= tosend; ! OnSendProgress(totalsent, remain); ! buffer = null; ! if ((totalsent < len) && m_Client.Connected) { ! goto Label_loop; } } + + body = null; + buffchar = null; + + Label_finish: len = sent = 0; } *************** *** 838,843 **** try { ! if (m_Client != null && m_Client.Connected && ! m_Client.Poll(TimeOut, SelectMode.SelectWrite)) SocketWrite(crlf_dot_crlf, crlf_dot_crlf.Length); } --- 841,845 ---- try { ! if (m_Client != null && m_Client.Connected && m_Client.Poll(TimeOut, SelectMode.SelectWrite)) SocketWrite(crlf_dot_crlf, crlf_dot_crlf.Length); } *************** *** 846,850 **** } } ! private byte[] recvBuffer; private Commands SendAndReceive(String val) --- 848,852 ---- } } ! private byte[] recvBuffer; private Commands SendAndReceive(String val) |
From: Ethem E. <et...@us...> - 2006-08-04 07:43:44
|
Update of /cvsroot/dnsmail/dnsmail/DnsMail In directory sc8-pr-cvs12.sourceforge.net:/tmp/cvs-serv19568/dnsmail/DnsMail Modified Files: Tag: DNSMAIL_02 DnsMail.cs Log Message: If LocalPoint is null, IPAddress.Any is used by default. Index: DnsMail.cs =================================================================== RCS file: /cvsroot/dnsmail/dnsmail/DnsMail/DnsMail.cs,v retrieving revision 1.2.4.2 retrieving revision 1.2.4.3 diff -C2 -d -r1.2.4.2 -r1.2.4.3 *** DnsMail.cs 2 Aug 2006 17:06:14 -0000 1.2.4.2 --- DnsMail.cs 4 Aug 2006 07:43:40 -0000 1.2.4.3 *************** *** 33,37 **** #endregion ! #region Class Members private Socket m_Client; // Mail Client --- 33,37 ---- #endregion ! #region Class Members private Socket m_Client; // Mail Client *************** *** 157,173 **** { get ! { if (m_LocalPoint == null) ! { ! IPHostEntry iphostentry = Dns.GetHostByName(DNSAPI.LocalHost); ! foreach(IPAddress ip in iphostentry.AddressList) ! { ! if (! IPAddress.IsLoopback(ip)) ! { ! m_LocalPoint = new IPEndPoint(ip, 0); ! break; ! } ! } ! } return m_LocalPoint; } --- 157,164 ---- { get ! { if (m_LocalPoint == null) ! m_LocalPoint = new IPEndPoint(IPAddress.Any, 0); ! return m_LocalPoint; } |