示例#1
0
 /// <summary>
 /// This method is called when TCP client has sucessfully connected.
 /// </summary>
 /// <param name="callback">Callback to be called to complete connect operation.</param>
 protected override void OnConnected(CompleteConnectCallback callback)
 {
     // Read POP3 server greeting response.
     SmartStream.ReadLineAsyncOP readGreetingOP = new SmartStream.ReadLineAsyncOP(new byte[8000],SizeExceededAction.JunkAndThrowException);
     readGreetingOP.Completed += delegate(object s,EventArgs<SmartStream.ReadLineAsyncOP> e){
         ReadServerGreetingCompleted(readGreetingOP,callback);
     };
     if(this.TcpStream.ReadLine(readGreetingOP,true)){
         ReadServerGreetingCompleted(readGreetingOP,callback);
     }
 }
示例#2
0
            /// <summary>
            /// Is called when AUTH command sending has finished.
            /// </summary>
            /// <param name="ar">Asynchronous result.</param>
            private void AuthCommandSendingCompleted(IAsyncResult ar)
            {
                try{
                    m_pPop3Client.TcpStream.EndWrite(ar);

                    // Read POP3 server response.
                    SmartStream.ReadLineAsyncOP op = new SmartStream.ReadLineAsyncOP(new byte[8000],SizeExceededAction.JunkAndThrowException);
                    op.Completed += delegate(object s,EventArgs<SmartStream.ReadLineAsyncOP> e){
                        AuthReadResponseCompleted(op);
                    };
                    if(m_pPop3Client.TcpStream.ReadLine(op,true)){
                        AuthReadResponseCompleted(op);
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }
            }
示例#3
0
        /// <summary>
        /// Reads next continuing FETCH line and stores to fetch reader 'r'.
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">String reader.</param>
        /// <param name="callback">Fetch completion callback.</param>
        /// <returns>Returns true if completed asynchronously or false if completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b> or <b>callback</b> is null reference.</exception>
        private bool ReadNextFetchLine(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[64000],SizeExceededAction.JunkAndThrowException);
            readLineOP.Completed += delegate(object sender,EventArgs<SmartStream.ReadLineAsyncOP> e){
                try{
                    // Read line failed.
                    if(readLineOP.Error != null){
                        callback(this,new EventArgs<Exception>(readLineOP.Error));
                    }
                    else{
                        // Log.
                        imap.LogAddRead(readLineOP.BytesInBuffer,readLineOP.LineUtf8);

                        // Append fetch line to fetch reader.
                        r.AppendString(readLineOP.LineUtf8);

                        ParseDataItems(imap,r,callback);
                    }
                }
                catch(Exception x){
                    callback(this,new EventArgs<Exception>(x));
                }
                finally{
                    readLineOP.Dispose();
                }
            };

            // Read line completed synchronously.
            if(imap.TcpStream.ReadLine(readLineOP,true)){
                try{
                    // Read line failed.
                    if(readLineOP.Error != null){
                        callback(this,new EventArgs<Exception>(readLineOP.Error));

                        return true;
                    }
                    else{
                        // Log.
                        imap.LogAddRead(readLineOP.BytesInBuffer,readLineOP.LineUtf8);

                        // Append fetch line to fetch reader.
                        r.AppendString(readLineOP.LineUtf8);

                        return false;
                    }
                }
                finally{
                    readLineOP.Dispose();
                }
            }

            return true;
        }
示例#4
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();
            }
示例#5
0
        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        /// <exception cref="NotSupportedException">Is raised when reading not supported.</exception>
        public override int Read(byte[] buffer,int offset,int count)
        {
            if(buffer == null){
                throw new ArgumentNullException("buffer");
            }
            if(offset < 0 || offset > buffer.Length){
                throw new ArgumentException("Invalid argument 'offset' value.");
            }
            if(offset + count > buffer.Length){
                throw new ArgumentException("Invalid argument 'count' value.");
            }
            if((m_AccessMode & FileAccess.Read) == 0){
                throw new NotSupportedException();
            }

            while(true){
                // Read next quoted-printable line and decode it.
                if(m_DecodedOffset >= m_DecodedCount){
                    m_DecodedOffset = 0;
                    m_DecodedCount  = 0;
                    SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[32000],SizeExceededAction.ThrowException);
                    m_pStream.ReadLine(readLineOP,false);
                    // IO error reading line.
                    if(readLineOP.Error != null){
                        throw readLineOP.Error;
                    }
                    // We reached end of stream.
                    else if(readLineOP.BytesInBuffer == 0){
                        return 0;
                    }
                    // Decode quoted-printable line.
                    else{
                        // Process bytes.
                        bool softLineBreak = false;
                        int lineLength     = readLineOP.LineBytesInBuffer;
                        for(int i=0;i<readLineOP.LineBytesInBuffer;i++){
                            byte b = readLineOP.Buffer[i];
                            // We have soft line-break.
                            if(b == '=' && i == (lineLength - 1)){
                                softLineBreak = true;
                            }
                            // We should have =XX hex-byte.
                            else if(b == '='){
                                byte b1 = readLineOP.Buffer[++i];
                                byte b2 = readLineOP.Buffer[++i];

                                byte b3 = 0;
                                if(byte.TryParse(new string(new char[]{(char)b1,(char)b2}),System.Globalization.NumberStyles.HexNumber,null,out b3)){
                                    m_pDecodedBuffer[m_DecodedCount++] = b3;
                                }
                                // Not hex number, leave it as it is.
                                else{
                                    m_pDecodedBuffer[m_DecodedCount++] = (byte)'=';
                                    m_pDecodedBuffer[m_DecodedCount++] = b1;
                                    m_pDecodedBuffer[m_DecodedCount++] = b2;
                                }
                            }
                            // Normal char.
                            else{
                                m_pDecodedBuffer[m_DecodedCount++] = b;
                            }
                        }

                        // Add hard line break only if there was one in original data.
                        if(readLineOP.LineBytesInBuffer != readLineOP.BytesInBuffer && !softLineBreak){
                            m_pDecodedBuffer[m_DecodedCount++] = (byte)'\r';
                            m_pDecodedBuffer[m_DecodedCount++] = (byte)'\n';
                        }
                    }
                }

                // We have some decoded data, return it.
                if(m_DecodedOffset < m_DecodedCount){
                    int countToCopy = Math.Min(count,m_DecodedCount - m_DecodedOffset);
                    Array.Copy(m_pDecodedBuffer,m_DecodedOffset,buffer,offset,countToCopy);
                    m_DecodedOffset += countToCopy;

                    return countToCopy;
                }
            }
        }
示例#6
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());
                }
            }
        }
示例#7
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;
        }
示例#8
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);
                    }
                }
            }
        }
示例#9
0
        /// <summary>
        /// Reads and logs specified line from connected host.
        /// </summary>
        /// <returns>Returns readed line.</returns>
        protected string ReadLine()
        {
            SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[32000],SizeExceededAction.JunkAndThrowException);
            this.TcpStream.ReadLine(args,false);
            if(args.Error != null){
                throw args.Error;
            }
            string line = args.LineUtf8;
            if(args.BytesInBuffer > 0){
                LogAddRead(args.BytesInBuffer,line);
            }
            else{
                LogAddText("Remote host closed connection.");
            }

            return line;
        }