/// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            // We need to buffer all body data, otherwise we don't know if we have readed all data 
            // from stream.
            MemoryStream msBuffer = new MemoryStream();
            Net_Utils.StreamCopy(stream,msBuffer,32000);
            msBuffer.Position = 0;

            SmartStream parseStream = new SmartStream(msBuffer,true);

            MIME_b_MessageDeliveryStatus retVal = new MIME_b_MessageDeliveryStatus();
            //Pare per-message fields.
            retVal.m_pMessageFields.Parse(parseStream);

            // Parse per-recipient fields.
            while(parseStream.Position - parseStream.BytesInReadBuffer < parseStream.Length){
                MIME_h_Collection recipientFields = new MIME_h_Collection(new MIME_h_Provider());
                recipientFields.Parse(parseStream);
                retVal.m_pRecipientBlocks.Add(recipientFields);                
            }                     

            return retVal;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            string mediaType = null;
            try{
                mediaType = owner.ContentType.TypeWithSubtype;
            }
            catch{
                mediaType = "unparsable/unparsable";
            }

            MIME_b_Unknown retVal = new MIME_b_Unknown(mediaType);
            Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000);

            return retVal;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            MIME_b_Text retVal = null;
            if(owner.ContentType != null){
                retVal = new MIME_b_Text(owner.ContentType.TypeWithSubtype);
            }
            else{
                retVal = new MIME_b_Text(defaultContentType.TypeWithSubtype);
            }

            Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000);
            retVal.SetModified(false);

            return retVal;
        }
Ejemplo n.º 4
0
                /// <summary>
                /// Assigns data line info from rea line operation.
                /// </summary>
                /// <param name="op">Read line operation.</param>
                /// <exception cref="ArgumentNullException">Is raised when <b>op</b> is null reference.</exception>
                public void AssignFrom(SmartStream.ReadLineAsyncOP op)
                {
                    if(op == null){
                        throw new ArgumentNullException();
                    }

                    m_BytesInBuffer = op.BytesInBuffer;
                    Array.Copy(op.Buffer,m_pLineBuffer,op.BytesInBuffer);
                }
Ejemplo n.º 5
0
      internal bool Start(SmartStream stream)
      {   
          // TODO: Clear old data, if any.
          m_IsCompleted   = false;
          m_BytesInBuffer = 0;
          m_pException    = null;
 
          return DoLineReading();
      }
Ejemplo n.º 6
0
        /// <summary>
        /// Parses MIME entity body from specified stream.
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="stream">Stream from where to parse entity body.</param>
        /// <param name="defaultContentType">Default content type.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>, <b>strean</b> or <b>defaultContentType</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when header field parsing errors.</exception>
        public MIME_b Parse(MIME_Entity owner,SmartStream stream,MIME_h_ContentType defaultContentType)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }

            string mediaType = defaultContentType.TypeWithSubype;
            if(owner.ContentType != null){
                mediaType = owner.ContentType.TypeWithSubype;
            }

            Type bodyType = null;

            // We have exact body provider for specified mediaType.
            if(m_pBodyTypes.ContainsKey(mediaType)){
                bodyType = m_pBodyTypes[mediaType];
            }
            // Use default mediaType.
            else{
                // Registered list of mediaTypes are available: http://www.iana.org/assignments/media-types/.

                string mediaRootType = mediaType.Split('/')[0].ToLowerInvariant();
                if(mediaRootType == "application"){
                    bodyType = typeof(MIME_b_Application);
                }
                else if(mediaRootType == "audio"){
                    bodyType = typeof(MIME_b_Audio);
                }
                else if(mediaRootType == "image"){
                    bodyType = typeof(MIME_b_Image);
                }
                else if(mediaRootType == "message"){
                    bodyType = typeof(MIME_b_Message);
                }
                else if(mediaRootType == "multipart"){
                    bodyType = typeof(MIME_b_Multipart);
                }
                else if(mediaRootType == "text"){
                    bodyType = typeof(MIME_b_Text);
                }
                else if(mediaRootType == "video"){
                    bodyType = typeof(MIME_b_Video);
                }
                else{
                    throw new ParseException("Invalid media-type '" + mediaType + "'.");
                }
            }

            return (MIME_b)bodyType.GetMethod("Parse",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy).Invoke(null,new object[]{owner,mediaType,stream});
        }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="stream">Source stream.</param>
        /// <param name="access">Specifies stream access mode.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
        public QuotedPrintableStream(SmartStream stream,FileAccess access)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            m_pStream    = stream;
            m_AccessMode = access;

            m_pDecodedBuffer = new byte[32000];
            m_pEncodedBuffer = new byte[78];
        }
Ejemplo n.º 8
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                if(m_IsDisposed){
                    return;
                }
                m_IsDisposed = true;

                m_pOwner       = null;
                m_pBuffer      = null;
                m_pException   = null;
                this.Completed = null;
            }
Ejemplo n.º 9
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            throw new NotImplementedException("Body provider class does not implement required Parse method.");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822();
            retVal.m_pMessage = Mail_Message.ParseFromStream(stream);

            return retVal;
        }
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            MIME_b_ApplicationPkcs7Mime retVal = new MIME_b_ApplicationPkcs7Mime();
            Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000);

            return retVal;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="mediaType">MIME media type. For example: text/plain.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>strean</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,string mediaType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(mediaType == null){
                throw new ArgumentNullException("mediaType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            MIME_b_Audio retVal = new MIME_b_Audio(mediaType);

            Net_Utils.StreamCopy(stream,retVal.EncodedStream,32000);

            return retVal;
        }
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="mediaType">MIME media type. For example: text/plain.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,string mediaType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(mediaType == null){
                throw new ArgumentNullException("mediaType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(owner.ContentType == null || owner.ContentType.Param_Boundary == null){
                throw new ParseException("Multipart entity has not required 'boundary' paramter.");
            }

            MIME_b_MultipartRelated retVal = new MIME_b_MultipartRelated(owner.ContentType);
            ParseInternal(owner,mediaType,stream,retVal);

            return retVal;
        }
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(owner.ContentType == null || owner.ContentType.Param_Boundary == null){
                throw new ParseException("Multipart entity has not required 'boundary' paramter.");
            }
            
            MIME_b_MultipartParallel retVal = new MIME_b_MultipartParallel(owner.ContentType);
            ParseInternal(owner,owner.ContentType.TypeWithSubtype,stream,retVal);

            return retVal;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public override void Dispose()
        {
            if(m_IsDisposed){
                return;
            }
            if(!m_IsTerminated){
                try{
                    Disconnect();
                }
                catch{
                    // Skip disconnect errors.
                }
            }
            m_IsDisposed = true;

            // We must call disposed event before we release events.
            try{
                OnDisposed();
            }
            catch{
                // We never should get exception here, user should handle it, just skip it.
            }

            m_pLocalEP = null;
            m_pRemoteEP = null;
            m_pCertificate = null;
            if(m_pTcpStream != null){
                m_pTcpStream.Dispose();
            }
            m_pTcpStream = null;
            if(m_pRawTcpStream != null){
                m_pRawTcpStream.Close();
            }
            m_pRawTcpStream = null;
            m_pTags = null;

            // Release events.
            this.IdleTimeout = null;
            this.Disonnected  = null;
            this.Disposed    = null;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Parses body from the specified stream
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="defaultContentType">Default content-type for this body.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <returns>Returns parsed body.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>defaultContentType</b> or <b>strean</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static new MIME_b Parse(MIME_Entity owner,MIME_h_ContentType defaultContentType,SmartStream stream)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            MIME_b_Application retVal = null;
            if(owner.ContentType != null){
                retVal = new MIME_b_Application(owner.ContentType.TypeWithSubtype);
            }
            else{
                retVal = new MIME_b_Application(defaultContentType.TypeWithSubtype);
            }

            Net_Utils.StreamCopy(stream,retVal.EncodedStream,stream.LineBufferSize);

            return retVal;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Completes DATA command.
        /// </summary>
        /// <param name="startTime">Time DATA command started.</param>
        /// <param name="op">Read period-terminated opeartion.</param>
        private void DATA_End(DateTime startTime,SmartStream.ReadPeriodTerminatedAsyncOP op)
        {
            try{
                if(op.Error != null){
                    if(op.Error is LineSizeExceededException){
                        WriteLine("500 Line too long.");
                    }
                    else if(op.Error is DataSizeExceededException){
                        WriteLine("552 Too much mail data.");
                    }
                    else{
                        OnError(op.Error);
                    }

                    OnMessageStoringCanceled();
                }
                else{
                    SMTP_Reply reply = new SMTP_Reply(250,"DATA completed in " + (DateTime.Now - startTime).TotalSeconds.ToString("f2") + " seconds.");

                    reply = OnMessageStoringCompleted(reply);

                    WriteLine(reply.ToString());
                }
            }
            catch(Exception x){
                OnError(x);                
            }

            Reset();
            BeginReadCmd();
        }
Ejemplo n.º 18
0
            /// <summary>
            /// Is called when read line has completed.
            /// </summary>
            /// <param name="op">Asynchronous operation.</param>
            /// <returns>Returns true if multiline response has more response lines.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>op</b> is null reference.</exception>
            private bool ReadLineCompleted(SmartStream.ReadLineAsyncOP op)
            {
                if(op == null){
                    throw new ArgumentNullException("op");
                }

                try{
                    // Line reading failed, we are done.
                    if(op.Error != null){
                        m_pException = op.Error;
                    }
                    // Line reading succeeded.
                    else{
                        // Log.
                        m_pSmtpClient.LogAddRead(op.BytesInBuffer,op.LineUtf8);

                        SMTP_t_ReplyLine replyLine = SMTP_t_ReplyLine.Parse(op.LineUtf8);
                        m_pReplyLines.Add(replyLine);

                        return !replyLine.IsLastLine;
                    }                    
                }
                catch(Exception x){
                    m_pException = x;
                }

                return false;
            }
Ejemplo n.º 19
0
            /// <summary>
            /// Is called when DATA command message sending has completed.
            /// </summary>
            /// <param name="op">Asynchronous operation.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>op</b> is null reference.</exception>
            private void DataMsgSendingCompleted(SmartStream.WritePeriodTerminatedAsyncOP op)
            {
                if(op == null){
                    throw new ArgumentNullException("op");
                }

                try{
                    if(op.Error != null){
                        m_pException = op.Error;
                        m_pSmtpClient.LogAddException("Exception: " + m_pException.Message,m_pException);
                        SetState(AsyncOP_State.Completed);
                    }
                    else{
                        // Log
                        m_pSmtpClient.LogAddWrite(op.BytesWritten,"Sent message " + op.BytesWritten + " bytes.");
                                                                       
                        // Read DATA command final response.
                        ReadResponseAsyncOP readResponseOP = new ReadResponseAsyncOP();
                        readResponseOP.CompletedAsync += delegate(object s,EventArgs<ReadResponseAsyncOP> e){
                            DataReadFinalResponseCompleted(readResponseOP);
                        };
                        if(!m_pSmtpClient.ReadResponseAsync(readResponseOP)){
                            DataReadFinalResponseCompleted(readResponseOP);
                        }
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pSmtpClient.LogAddException("Exception: " + m_pException.Message,m_pException);
                    SetState(AsyncOP_State.Completed);
                }

                op.Dispose();
            }
Ejemplo n.º 20
0
		/// <summary>
		/// Parses header fields from stream. Stream position stays where header reading ends.
		/// </summary>
		/// <param name="stream">Stream from where to parse.</param>
		public void Parse(SmartStream stream)
		{			
			/* Rfc 2822 2.2 Header Fields
				Header fields are lines composed of a field name, followed by a colon
				(":"), followed by a field body, and terminated by CRLF.  A field
				name MUST be composed of printable US-ASCII characters (i.e.,
				characters that have values between 33 and 126, inclusive), except
				colon.  A field body may be composed of any US-ASCII characters,
				except for CR and LF.  However, a field body may contain CRLF when
				used in header "folding" and  "unfolding" as described in section
				2.2.3.  All field bodies MUST conform to the syntax described in
				sections 3 and 4 of this standard. 
				
			   Rfc 2822 2.2.3 Long Header Fields
				The process of moving from this folded multiple-line representation
				of a header field to its single line representation is called
				"unfolding". Unfolding is accomplished by simply removing any CRLF
				that is immediately followed by WSP.  Each header field should be
				treated in its unfolded form for further syntactic and semantic
				evaluation.
				
				Example:
					Subject: aaaaa<CRLF>
					<TAB or SP>aaaaa<CRLF>
			*/

			m_pHeaderFields.Clear();

            SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[32000],SizeExceededAction.JunkAndThrowException);
            stream.ReadLine(args,false);
            if(args.Error != null){
                throw args.Error;
            }
            string line = args.LineUtf8;

			while(line != null){
				// End of header reached
				if(line == ""){
					break;
				}

				// Store current header line and read next. We need to read 1 header line to ahead,
				// because of multiline header fields.
				string headerField = line; 
				stream.ReadLine(args,false);
                if(args.Error != null){
                    throw args.Error;
                }
                line = args.LineUtf8;

				// See if header field is multiline. See comment above.				
				while(line != null && (line.StartsWith("\t") || line.StartsWith(" "))){
					headerField += line;
					stream.ReadLine(args,false);
                    if(args.Error != null){
                        throw args.Error;
                    }
                    line = args.LineUtf8;
				}

				string[] name_value = headerField.Split(new char[]{':'},2);
				// There must be header field name and value, otherwise invalid header field
				if(name_value.Length == 2){
					Add(name_value[0] + ":",name_value[1].Trim());
				}
			}
		}
Ejemplo n.º 21
0
        /// <summary>
        /// Internal body parsing.
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <param name="mediaType">MIME media type. For example: text/plain.</param>
        /// <param name="stream">Stream from where to read body.</param>
        /// <param name="body">Multipart body instance.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b>, <b>stream</b> or <b>body</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static void ParseInternal(MIME_Entity owner,string mediaType,SmartStream stream,MIME_b_Multipart body)
        {
            if(owner == null){
                throw new ArgumentNullException("owner");
            }
            if(mediaType == null){
                throw new ArgumentNullException("mediaType");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(owner.ContentType == null || owner.ContentType.Param_Boundary == null){
                throw new ParseException("Multipart entity has not required 'boundary' parameter.");
            }
            if(body == null){
                throw new ArgumentNullException("body");
            }

            _MultipartReader multipartReader = new _MultipartReader(stream,owner.ContentType.Param_Boundary);       
            while(multipartReader.Next()){
                MIME_Entity entity = new MIME_Entity();
                entity.Parse(new SmartStream(multipartReader,false),Encoding.UTF8,body.DefaultBodyPartContentType);
                body.m_pBodyParts.Add(entity);
                entity.SetParent(owner);
            }

            body.m_TextPreamble = multipartReader.TextPreamble;
            body.m_TextEpilogue = multipartReader.TextEpilogue;

            body.BodyParts.SetModified(false);
        }
Ejemplo n.º 22
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="stream">Stream from where to read body part.</param>
            /// <param name="boundary">Boundry ID what separates body parts.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>boundary</b> is null reference.</exception>
            public _MultipartReader(SmartStream stream,string boundary)
            {
                if(stream == null){
                    throw new ArgumentNullException("stream");
                }
                if(boundary == null){
                    throw new ArgumentNullException("boundary");
                }

                m_pStream  = stream;
                m_Boundary = boundary;

                m_pReadLineOP   = new SmartStream.ReadLineAsyncOP(new byte[stream.LineBufferSize],SizeExceededAction.ThrowException);
                m_pTextPreamble = new StringBuilder();
                m_pTextEpilogue = new StringBuilder();
            }
Ejemplo n.º 23
0
 /// <summary>
 /// Parses MIME entiry from the specified stream.
 /// </summary>
 /// <param name="stream">Source stream.</param>
 /// <param name="headerEncoding">Header reading encoding. If not sure UTF-8 is recommended.</param>
 /// <param name="defaultContentType">Default content type.</param>
 /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>,<b>headerEncoding</b> or <b>defaultContentType</b> is null reference.</exception>
 internal protected void Parse(SmartStream stream,Encoding headerEncoding,MIME_h_ContentType defaultContentType)
 {
     if(stream == null){
         throw new ArgumentNullException("stream");
     }
     if(headerEncoding == null){
         throw new ArgumentNullException("headerEncoding");
     }
     if(defaultContentType == null){
         throw new ArgumentNullException("defaultContentType");
     }
     
     m_pHeader.Parse(stream,headerEncoding); 
   
     m_pBody = m_pBodyProvider.Parse(this,stream,defaultContentType);
     m_pBody.SetParent(this,false);         
 }
Ejemplo n.º 24
0
		/// <summary>
		/// Parses mime entity from stream.
		/// </summary>
		/// <param name="stream">Data stream from where to read data.</param>
		/// <param name="toBoundary">Entity data is readed to specified boundary.</param>
		/// <returns>Returns false if last entity. Returns true for mulipart entity, if there are more entities.</returns>
		internal bool Parse(SmartStream stream,string toBoundary)
		{
			// Clear header fields
			m_pHeader.Clear();
			m_pHeaderFieldCache.Clear();

			// Parse header
			m_pHeader.Parse(stream);

			// Parse entity and child entities if any (Conent-Type: multipart/xxx...)
            
			// Multipart entity
			if((this.ContentType & MediaType_enum.Multipart) != 0){
				// There must be be boundary ID (rfc 1341 7.2.1  The Content-Type field for multipart entities requires one parameter,
                // "boundary", which is used to specify the encapsulation boundary.)
				string boundaryID = this.ContentType_Boundary;
				if(boundaryID == null){
					// This is invalid message, just skip this mime entity
				}
				else{
					// There is one or more mime entities

                    // Find first boundary start position
                    SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[8000],SizeExceededAction.JunkAndThrowException);
                    stream.ReadLine(args,false);
                    if(args.Error != null){
                        throw args.Error;
                    }
                    string lineString = args.LineUtf8;
				
					while(lineString != null){
						if(lineString.StartsWith("--" + boundaryID)){
							break;
						}
						
                        stream.ReadLine(args,false);
                        if(args.Error != null){
                            throw args.Error;
                        }
                        lineString = args.LineUtf8;
					}
					// This is invalid entity, boundary start not found. Skip that entity.
					if(string.IsNullOrEmpty(lineString)){
						return false;
					}
					
					// Start parsing child entities of this entity
					while(true){					
						// Parse and add child entity
						MimeEntity childEntity = new MimeEntity();					
						this.ChildEntities.Add(childEntity);
				
						// This is last entity, stop parsing
						if(childEntity.Parse(stream,boundaryID) == false){
							break;
						}
						// else{
						// There are more entities, parse them
					}
					
					// This entity is child of mulipart entity.
					// All this entity child entities are parsed,
					// we need to move stream position to next entity start.
					if(!string.IsNullOrEmpty(toBoundary)){
                        stream.ReadLine(args,false);
                        if(args.Error != null){
                            throw args.Error;
                        }
                        lineString = args.LineUtf8;

						while(lineString != null){
							if(lineString.StartsWith("--" + toBoundary)){
								break;
							}
							
							stream.ReadLine(args,false);
                            if(args.Error != null){
                                throw args.Error;
                            }
                            lineString = args.LineUtf8;
						}
						
						// Invalid boundary end, there can't be more entities 
						if(string.IsNullOrEmpty(lineString)){
							return false;
						}
					
						// See if last boundary or there is more. Last boundary ends with --
						if(lineString.EndsWith(toBoundary + "--")){
							return false; 
						}
						// else{
						// There are more entities					
						return true;
					}
				}
			}
			// Singlepart entity.
			else{
                // Boundary is specified, read data to specified boundary.
                if(!string.IsNullOrEmpty(toBoundary)){
                    MemoryStream entityData = new MemoryStream();
                    SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[32000],SizeExceededAction.JunkAndThrowException);

                    // Read entity data while get boundary end tag --boundaryID-- or EOS.
                    while(true){                        
                        stream.ReadLine(readLineOP,false);
                        if(readLineOP.Error != null){
                            throw readLineOP.Error;
                        }
                        // End of stream reached. Normally we should get boundary end tag --boundaryID--, but some x mailers won't add it, so
                        // if we reach EOS, consider boundary closed.
                        if(readLineOP.BytesInBuffer == 0){
                            // Just return data what was readed.
                            m_EncodedData = entityData.ToArray();
                            return false;
                        }
                        // We readed a line.
                        else{
                            // We have boundary start/end tag or just "--" at the beginning of line.
                            if(readLineOP.LineBytesInBuffer >= 2 && readLineOP.Buffer[0] == '-' && readLineOP.Buffer[1] == '-'){
                                string lineString = readLineOP.LineUtf8;
                                // We have boundary end tag, no more boundaries.
                                if(lineString == "--" + toBoundary + "--"){
                                    m_EncodedData = entityData.ToArray();
                                    return false;
                                }
                                // We have new boundary start.
                                else if(lineString == "--" + toBoundary){
                                    m_EncodedData = entityData.ToArray();
                                    return true;
                                }
                                else{
                                    // Just skip
                                }
                            }

                            // Write readed line.
                            entityData.Write(readLineOP.Buffer,0,readLineOP.BytesInBuffer);                    
                        }
                    }
                }
				// Boundary isn't specified, read data to the stream end. 
				else{
                    MemoryStream ms = new MemoryStream();
                    stream.ReadAll(ms);
                    m_EncodedData = ms.ToArray();
				}
			}
			
			return false;
		}
Ejemplo n.º 25
0
        /// <summary>
        /// Completes command reading operation.
        /// </summary>
        /// <param name="op">Operation.</param>
        /// <returns>Returns true if server should start reading next command.</returns>
        private bool ProcessCmd(SmartStream.ReadLineAsyncOP op)
        {
            bool readNextCommand = true;
                        
            try{
                // We are disposed already.
                if(this.IsDisposed){
                    return false;
                }
                // Check errors.
                if(op.Error != null){
                    OnError(op.Error);
                }
                // Remote host shut-down(Socket.ShutDown) socket.
                if(op.BytesInBuffer == 0){
                    LogAddText("The remote host '" + this.RemoteEndPoint.ToString() + "' shut down socket.");
                    Dispose();
                
                    return false;
                }
                                
                string[] cmd_args = Encoding.UTF8.GetString(op.Buffer,0,op.LineBytesInBuffer).Split(new char[]{' '},3);
                if(cmd_args.Length < 2){
                    m_pResponseSender.SendResponseAsync(new IMAP_r_u_ServerStatus("BAD","Error: Command '" + op.LineUtf8 + "' not recognized."));

                    return true;
                }
                string   cmdTag   = cmd_args[0];
                string   cmd      = cmd_args[1].ToUpperInvariant();
                string   args     = cmd_args.Length == 3 ? cmd_args[2] : "";
        
                // Log.
                if(this.Server.Logger != null){
                    // Hide password from log.
                    if(cmd == "LOGIN"){                        
                        this.Server.Logger.AddRead(this.ID,this.AuthenticatedUserIdentity,op.BytesInBuffer,op.LineUtf8.Substring(0,op.LineUtf8.LastIndexOf(' ')) + " <***REMOVED***>",this.LocalEndPoint,this.RemoteEndPoint);
                    }
                    else{
                        this.Server.Logger.AddRead(this.ID,this.AuthenticatedUserIdentity,op.BytesInBuffer,op.LineUtf8,this.LocalEndPoint,this.RemoteEndPoint);
                    }
                }

                if(cmd == "STARTTLS"){                    
                    STARTTLS(cmdTag,args);
                    readNextCommand = false;
                }
                else if(cmd == "LOGIN"){
                    LOGIN(cmdTag,args);
                }
                else if(cmd == "AUTHENTICATE"){
                    AUTHENTICATE(cmdTag,args);
                }
                else if(cmd == "NAMESPACE"){
                    NAMESPACE(cmdTag,args);
                }
                else if(cmd == "LIST"){
                    LIST(cmdTag,args);
                }
                else if(cmd == "CREATE"){
                    CREATE(cmdTag,args);
                }
                else if(cmd == "DELETE"){
                    DELETE(cmdTag,args);
                }
                else if(cmd == "RENAME"){
                    RENAME(cmdTag,args);
                }
                else if(cmd == "LSUB"){
                    LSUB(cmdTag,args);
                }
                else if(cmd == "SUBSCRIBE"){
                    SUBSCRIBE(cmdTag,args);
                }
                else if(cmd == "UNSUBSCRIBE"){
                    UNSUBSCRIBE(cmdTag,args);
                }
                else if(cmd == "STATUS"){
                    STATUS(cmdTag,args);
                }
                else if(cmd == "SELECT"){
                    SELECT(cmdTag,args);
                }
                else if(cmd == "EXAMINE"){
                    EXAMINE(cmdTag,args);
                }
                else if(cmd == "APPEND"){
                    APPEND(cmdTag,args);

                    return false;
                }
                else if(cmd == "GETQUOTAROOT"){
                    GETQUOTAROOT(cmdTag,args);
                }
                else if(cmd == "GETQUOTA"){
                    GETQUOTA(cmdTag,args);
                }
                else if(cmd == "GETACL"){
                    GETACL(cmdTag,args);
                }
                else if(cmd == "SETACL"){
                    SETACL(cmdTag,args);
                }
                else if(cmd == "DELETEACL"){
                    DELETEACL(cmdTag,args);
                }
                else if(cmd == "LISTRIGHTS"){
                    LISTRIGHTS(cmdTag,args);
                }
                else if(cmd == "MYRIGHTS"){
                    MYRIGHTS(cmdTag,args);
                }
                else if(cmd == "ENABLE"){
                    ENABLE(cmdTag,args);
                }
                else if(cmd == "CHECK"){
                    CHECK(cmdTag,args);
                }
                else if(cmd == "CLOSE"){
                    CLOSE(cmdTag,args);
                }
                else if(cmd == "FETCH"){
                    FETCH(false,cmdTag,args);
                }
                else if(cmd == "SEARCH"){
                    SEARCH(false,cmdTag,args);
                }
                else if(cmd == "STORE"){
                    STORE(false,cmdTag,args);
                }
                else if(cmd == "COPY"){
                    COPY(false,cmdTag,args);
                }
                else if(cmd == "UID"){
                    UID(cmdTag,args);
                }
                else if(cmd == "EXPUNGE"){
                    EXPUNGE(cmdTag,args);
                }
                else if(cmd == "IDLE"){
                    readNextCommand = IDLE(cmdTag,args);
                }
                else if(cmd == "CAPABILITY"){
                    CAPABILITY(cmdTag,args);
                }
                else if(cmd == "NOOP"){
                    NOOP(cmdTag,args);
                }
                else if(cmd == "LOGOUT"){
                    LOGOUT(cmdTag,args);
                    readNextCommand = false;
                }
                else{
                    m_BadCommands++;

                    // Maximum allowed bad commands exceeded.
                    if(this.Server.MaxBadCommands != 0 && m_BadCommands > this.Server.MaxBadCommands){
                        WriteLine("* BYE Too many bad commands, closing transmission channel.");
                        Disconnect();

                        return false;
                    }
                   
                    m_pResponseSender.SendResponseAsync(new IMAP_r_ServerStatus(cmdTag,"BAD","Error: Command '" + cmd + "' not recognized."));
                }
             }
             catch(Exception x){
                 OnError(x);
             }

             return readNextCommand;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Parses MIME header from the specified stream.
        /// </summary>
        /// <param name="stream">MIME header stream.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception>
        public void Parse(SmartStream stream)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            Parse(stream,Encoding.UTF8);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Parses MIME entiry from the specified stream.
        /// </summary>
        /// <param name="stream">Source stream.</param>
        /// <param name="defaultContentType">Default content type.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>defaultContentType</b> is null reference.</exception>
        internal void Parse(SmartStream stream,MIME_h_ContentType defaultContentType)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(defaultContentType == null){
                throw new ArgumentNullException("defaultContentType");
            }

            m_pHeader.Parse(stream);
            this.Body = m_pBodyProvider.Parse(this,stream,defaultContentType);
        }
Ejemplo n.º 28
0
            /// <summary>
            /// Is called when incoming SMTP message reading has completed.
            /// </summary>
            /// <param name="op">Asynchronous operation.</param>
            private void MessageReadingCompleted(SmartStream.ReadPeriodTerminatedAsyncOP op)
            {      
                try{
                    if(op.Error != null){
                        if(op.Error is LineSizeExceededException){
                            SendFinalResponse(new SMTP_t_ReplyLine(503,"500 Line too long.",true));
                        }
                        else if(op.Error is DataSizeExceededException){
                            SendFinalResponse(new SMTP_t_ReplyLine(503,"552 Too much mail data.",true));
                        }
                        else{
                            m_pException = op.Error;
                        }

                        m_pSession.OnMessageStoringCanceled();
                    }
                    else{
                        // Log.
                        m_pSession.LogAddRead(op.BytesStored,"Readed " + op.BytesStored + " message bytes.");

                        SMTP_Reply reply = new SMTP_Reply(250,"DATA completed in " + (DateTime.Now - m_StartTime).TotalSeconds.ToString("f2") + " seconds.");

                        reply = m_pSession.OnMessageStoringCompleted(reply);

                        SendFinalResponse(SMTP_t_ReplyLine.Parse(reply.ReplyCode + " " + reply.ReplyLines[0]));
                    }
                }
                catch(Exception x){
                    m_pException = x;       
                }

                // We got some unknown error, we are done.
                if(m_pException != null){
                    SetState(AsyncOP_State.Completed);
                }

                op.Dispose();
            }
Ejemplo n.º 29
0
        /// <summary>
        /// Completes command reading operation.
        /// </summary>
        /// <param name="op">Operation.</param>
        /// <returns>Returns true if server should start reading next command.</returns>
        private bool ProcessCmd(SmartStream.ReadLineAsyncOP op)
        {
            bool readNextCommand = true;
                        
            try{
                // We are already disposed.
                if(this.IsDisposed){
                    return false;
                }
                // Check errors.
                if(op.Error != null){
                    OnError(op.Error);
                }
                // Remote host shut-down(Socket.ShutDown) socket.
                if(op.BytesInBuffer == 0){
                    LogAddText("The remote host '" + this.RemoteEndPoint.ToString() + "' shut down socket.");
                    Dispose();
                
                    return false;
                }

                // Log.
                if(this.Server.Logger != null){
                    this.Server.Logger.AddRead(this.ID,this.AuthenticatedUserIdentity,op.BytesInBuffer,op.LineUtf8,this.LocalEndPoint,this.RemoteEndPoint);
                }

                string[] cmd_args = Encoding.UTF8.GetString(op.Buffer,0,op.LineBytesInBuffer).Split(new char[]{' '},2);
                string   cmd      = cmd_args[0].ToUpperInvariant();
                string   args     = cmd_args.Length == 2 ? cmd_args[1] : "";

                if(cmd == "EHLO"){
                    EHLO(args);
                }
                else if(cmd == "HELO"){
                    HELO(args);
                }
                else if(cmd == "STARTTLS"){
                    STARTTLS(args);
                }
                else if(cmd == "AUTH"){
                    AUTH(args);
                }
                else if(cmd == "MAIL"){
                    MAIL(args);
                }
                else if(cmd == "RCPT"){
                    RCPT(args);
                }
                else if(cmd == "DATA"){                    
                    Cmd_DATA cmdData = new Cmd_DATA();
                    cmdData.CompletedAsync += delegate(object sender,EventArgs<SMTP_Session.Cmd_DATA> e){
                        if(op.Error != null){
                            OnError(op.Error);
                        }

                        cmdData.Dispose();
                        BeginReadCmd();
                    };
                    if(!cmdData.Start(this,args)){
                        if(op.Error != null){
                            OnError(op.Error);
                        }

                        cmdData.Dispose();
                    }
                    else{
                        readNextCommand = false;
                    }
                }
                else if(cmd == "BDAT"){
                    readNextCommand = BDAT(args);
                }
                else if(cmd == "RSET"){
                    RSET(args);
                }
                else if(cmd == "NOOP"){
                     NOOP(args);
                }
                else if(cmd == "QUIT"){
                     QUIT(args);
                     readNextCommand = false;
                }
                else{
                     m_BadCommands++;

                     // Maximum allowed bad commands exceeded.
                     if(this.Server.MaxBadCommands != 0 && m_BadCommands > this.Server.MaxBadCommands){
                         WriteLine("421 Too many bad commands, closing transmission channel.");
                         Disconnect();
                         return false;
                     }
                            
                     WriteLine("502 Error: command '" + cmd + "' not recognized.");
                 }
             }
             catch(Exception x){
                 OnError(x);
             }

             return readNextCommand;
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Parses MIME header from the specified stream.
        /// </summary>
        /// <param name="stream">MIME header stream.</param>
        /// <param name="encoding">Headers fields reading encoding. If not sure, UTF-8 is recommended.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>encoding</b> is null.</exception>
        public void Parse(SmartStream stream,Encoding encoding)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(encoding == null){
                throw new ArgumentNullException("encoding");
            }

            StringBuilder               currentHeader = new StringBuilder();
            SmartStream.ReadLineAsyncOP readLineOP    = new SmartStream.ReadLineAsyncOP(new byte[4*1024*1024],SizeExceededAction.ThrowException);
            while(true){                
                stream.ReadLine(readLineOP,false);
                if(readLineOP.Error != null){
                    throw readLineOP.Error;
                }
                // We reached end of stream.
                else if(readLineOP.BytesInBuffer == 0){
                    if(currentHeader.Length > 0){
                        Add(currentHeader.ToString());
                    }
                    m_IsModified = false;

                    return;
                }
                // We got blank header terminator line.
                else if(readLineOP.LineBytesInBuffer == 0){
                    if(currentHeader.Length > 0){
                        Add(currentHeader.ToString());
                    }
                    m_IsModified = false;

                    return;
                }
                else{
                    string line = encoding.GetString(readLineOP.Buffer,0,readLineOP.BytesInBuffer);
 
                    // New header field starts.
                    if(currentHeader.Length == 0){
                         currentHeader.Append(line);
                    }
                    // Header field continues.
                    else if(char.IsWhiteSpace(line[0])){
                        currentHeader.Append(line);
                    }
                    // Current header field closed, new starts.
                    else{
                        Add(currentHeader.ToString());

                        currentHeader = new StringBuilder();
                        currentHeader.Append(line);
                    }
                }
            }        
        }