Beispiel #1
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;
        }
Beispiel #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;
        }
        /// <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];
        }
        /// <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;
        }
Beispiel #5
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);
                }
Beispiel #6
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);
        }
Beispiel #7
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[32000],SizeExceededAction.ThrowException);
                m_pTextPreamble = new StringBuilder();
                m_pTextEpilogue = new StringBuilder();
            }
Beispiel #8
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.");
        }
Beispiel #9
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.TypeWithSubtype;
            try{
                if(owner.ContentType != null){
                    mediaType = owner.ContentType.TypeWithSubtype;
                }
            }
            catch{
                // Do nothing, content will be MIME_b_Unknown.
                mediaType = "unknown/unknown";
            }

            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{
                    bodyType = typeof(MIME_b_Unknown);
                }
            }

            return (MIME_b)bodyType.GetMethod("Parse",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy).Invoke(null,new object[]{owner,defaultContentType,stream});
        }
Beispiel #10
0
            /// <summary>
            /// Is called when POP3 server response reading has completed.
            /// </summary>
            /// <param name="op">Asynchronous operation.</param>
            private void AuthReadResponseCompleted(SmartStream.ReadLineAsyncOP op)
            {
                try{
                    // Operation failed.
                    if(op.Error != null){
                        m_pException = op.Error;
                        m_pPop3Client.LogAddException("Exception: " + op.Error.Message,op.Error);
                        SetState(AsyncOP_State.Completed);
                    }
                    // Operation succeeded.
                    else{
                        // Log
                        m_pPop3Client.LogAddRead(op.BytesInBuffer,op.LineUtf8);

                        // Authentication succeeded.
                        if(string.Equals(op.LineUtf8.Split(new char[]{' '},2)[0],"+OK",StringComparison.InvariantCultureIgnoreCase)){
                            // Start filling messages info.
                            POP3_Client.FillMessagesAsyncOP fillOP = new FillMessagesAsyncOP();
                            fillOP.CompletedAsync += delegate(object sender,EventArgs<FillMessagesAsyncOP> e){
                                FillMessagesCompleted(fillOP);
                            };
                            if(!m_pPop3Client.FillMessagesAsync(fillOP)){
                                FillMessagesCompleted(fillOP);
                            }
                        }
                        // Continue authenticating.
                        else if(op.LineUtf8.StartsWith("+")){
                            // + base64Data, we need to decode it.
                            byte[] serverResponse = Convert.FromBase64String(op.LineUtf8.Split(new char[]{' '},2)[1]);

                            byte[] clientResponse = m_pSASL.Continue(serverResponse);

                            // We need just send SASL returned auth-response as base64.
                            byte[] buffer = Encoding.UTF8.GetBytes(Convert.ToBase64String(clientResponse) + "\r\n");

                            // Log
                            m_pPop3Client.LogAddWrite(buffer.Length,Convert.ToBase64String(clientResponse));

                            // Start auth-data sending.
                            m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.AuthCommandSendingCompleted,null);
                        }
                        // Authentication rejected.
                        else{
                            m_pException = new POP3_ClientException(op.LineUtf8);
                            SetState(AsyncOP_State.Completed);
                        }
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                op.Dispose();
            }
Beispiel #11
0
        /// <summary>
        /// Switches session to secure connection.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected or is already secure.</exception>
        protected void SwitchToSecure()
        {
            if(m_IsDisposed){
                throw new ObjectDisposedException("TCP_Client");
            }
            if(!m_IsConnected){
                throw new InvalidOperationException("TCP client is not connected.");
            }
            if(m_IsSecure){
                throw new InvalidOperationException("TCP client is already secure.");
            }

            LogAddText("Switching to SSL.");

            // FIX ME: if ssl switching fails, it closes source stream or otherwise if ssl successful, source stream leaks.

            SslStream sslStream = new SslStream(m_pTcpStream.SourceStream,true,this.RemoteCertificateValidationCallback);
            sslStream.AuthenticateAsClient("dummy");

            // Close old stream, but leave source stream open.
            m_pTcpStream.IsOwner = false;
            m_pTcpStream.Dispose();

            m_IsSecure = true;
            m_pTcpStream = new SmartStream(sslStream,true);
        }
Beispiel #12
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());
                }
            }
        }
        /// <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;
        }
Beispiel #14
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;
        }
        /// <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;
        }
Beispiel #16
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[32000],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);
                    }
                }
            }
        }
Beispiel #17
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);
        }
Beispiel #18
0
            /// <summary>
            /// Is called when POP3 server DELE response reading has completed.
            /// </summary>
            /// <param name="op">Asynchronous operation.</param>
            private void DeleReadResponseCompleted(SmartStream.ReadLineAsyncOP op)
            {
                try{
                    // Operation failed.
                    if(op.Error != null){
                        m_pException = op.Error;
                        m_pPop3Client.LogAddException("Exception: " + op.Error.Message,op.Error);
                        SetState(AsyncOP_State.Completed);
                    }
                    // Operation succeeded.
                    else{
                        // Log
                        m_pPop3Client.LogAddRead(op.BytesInBuffer,op.LineUtf8);

                        // Server returned success response.
                        if(string.Equals(op.LineUtf8.Split(new char[]{' '},2)[0],"+OK",StringComparison.InvariantCultureIgnoreCase)){
                            m_pOwner.m_IsMarkedForDeletion = true;
                            SetState(AsyncOP_State.Completed);
                        }
                        // Server returned error response.
                        else{
                            m_pException = new POP3_ClientException(op.LineUtf8);
                            SetState(AsyncOP_State.Completed);
                        }
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                op.Dispose();
            }
Beispiel #19
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>
        protected internal 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);
        }
Beispiel #20
0
            /// <summary>
            /// Starts reading line.
            /// </summary>
            /// <param name="async">If true then this method can complete asynchronously. If false, this method completed always syncronously.</param>
            /// <param name="stream">Owner SmartStream.</param>
            /// <returns>Returns true if read line completed synchronously, false if asynchronous operation pending.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
            internal bool Start(bool async,SmartStream stream)
            {
                if(stream == null){
                    throw new ArgumentNullException("stream");
                }

                m_pOwner = stream;

                // Clear old data, if any.
                m_IsCompleted   = false;
                m_BytesInBuffer = 0;
                m_LastByte      = -1;
                m_pException    = null;

                m_IsCompletedSync = DoLineReading(async);

                return m_IsCompletedSync;
            }
Beispiel #21
0
        /// <summary>
        /// Is called when POP3 server greeting reading has completed.
        /// </summary>
        /// <param name="op">Asynchronous operation.</param>
        /// <param name="connectCallback">Callback to be called to complete connect operation.</param>
        private void ReadServerGreetingCompleted(SmartStream.ReadLineAsyncOP op,CompleteConnectCallback connectCallback)
        {
            Exception error = null;

            try{
                // Greeting reading failed, we are done.
                if(op.Error != null){
                    error = op.Error;
                }
                // Greeting reading succeded.
                else{
                    string line = op.LineUtf8;

                    // Log.
                    LogAddRead(op.BytesInBuffer,line);

                    // POP3 server accepted connection, get greeting text.
                    if(op.LineUtf8.StartsWith("+OK",StringComparison.InvariantCultureIgnoreCase)){
                        m_GreetingText = line.Substring(3).Trim();

                        // Try to read APOP hash key, if supports APOP.
                        if(line.IndexOf("<") > -1 && line.IndexOf(">") > -1){
                            m_ApopHashKey = line.Substring(line.IndexOf("<"),line.LastIndexOf(">") - line.IndexOf("<") + 1);
                        }
                    }
                    // POP3 server rejected connection.
                    else{
                        error = new POP3_ClientException(line);
                    }
                }
            }
            catch(Exception x){
                error = x;
            }

            // Complete TCP_Client connect operation.
            connectCallback(error);
        }
Beispiel #22
0
        /// <summary>
        /// Reads header from source <b>stream</b> and writes it to stream.
        /// </summary>
        /// <param name="stream">Stream from where to read header.</param>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception>
        public void WriteHeader(Stream stream)
        {
            if(m_IsDisposed){
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            SmartStream reader = new SmartStream(stream,false);
            reader.ReadHeader(this,0,SizeExceededAction.ThrowException);
        }
Beispiel #23
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;
        }
Beispiel #24
0
        /// <summary>
        /// Disconnects connection.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="InvalidOperationException">Is raised when TCP client is not connected.</exception>
        public override void Disconnect()
        {
            if(m_IsDisposed){
                throw new ObjectDisposedException("TCP_Client");
            }
            if(!m_IsConnected){
                throw new InvalidOperationException("TCP client is not connected.");
            }
            m_IsConnected = false;

            m_pLocalEP = null;
            m_pRemoteEP = null;
            m_pTcpStream.Dispose();
            m_IsSecure = false;
            m_pTcpStream = null;

            LogAddText("Disconnected.");
        }