void Save(List <string> list, int max)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlTextWriter x = null;

                    try
                    {
                        x = new XmlTextWriter(ms, Encoding.UTF8);
                        if (x == null)
                        {
                            Debug.Assert(false); return;
                        }

                        x.Formatting = Formatting.Indented;

                        x.WriteStartDocument();

                        x.WriteStartElement("RecentFiles");

                        foreach (string filepath in list)
                        {
                            x.WriteStartElement("RecentFile");
                            x.WriteAttributeString("Filepath", filepath);
                            x.WriteEndElement();
                        }

                        x.WriteEndElement();

                        x.WriteEndDocument();

                        x.Flush();

                        using (SmartStream ss = OpenStream(FileMode.Create))
                        {
                            ss.Stream.SetLength(0);

                            ms.Position = 0;

                            byte[] buffer = new byte[1 << 20];
                            for ( ; ;)
                            {
                                int bytes = ms.Read(buffer, 0, buffer.Length);
                                if (bytes == 0)
                                {
                                    break;
                                }
                                ss.Stream.Write(buffer, 0, bytes);
                            }
                        }
                    }
                    finally
                    {
                        if (x != null)
                        {
                            x.Close();
                        }
                    }
                }
            }
Exemplo n.º 2
0
        private void ReadMetadata(EndianReader reader)
        {
            string signature = reader.ReadStringZeroTerm();

            if (signature != Signature)
            {
                throw new Exception($"Signature '{signature}' doesn't match to '{Signature}'");
            }

            SmartStream         webStream = (SmartStream)reader.BaseStream;
            List <WebFileEntry> entries   = new List <WebFileEntry>();
            long headerLength             = reader.ReadInt32();

            while (webStream.Position < headerLength)
            {
                int    offset     = reader.ReadInt32();
                int    length     = reader.ReadInt32();
                int    pathLength = reader.ReadInt32();
                string path       = reader.ReadString(pathLength);

                WebFileEntry entry = new WebFileEntry(webStream, m_filePath, path, offset, length);
                entries.Add(entry);
            }
            Metadata = new WebMetadata(entries);
        }
        /// <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 new static 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);
        }
Exemplo n.º 4
0
        private void ReadScheme()
        {
            using (PartialStream stream = new PartialStream(m_stream, m_offset, m_size))
            {
                using (EndianReader reader = new EndianReader(stream, EndianType.BigEndian))
                {
                    Header.Read(reader);
                }

                long headerSize = stream.Position;
                using (BundleFileReader reader = new BundleFileReader(stream, EndianType.BigEndian, Header.Generation))
                {
                    if (reader.Generation < BundleGeneration.BF_530_x)
                    {
                        using (SmartStream dataStream = ReadPre530Metadata(reader))
                        {
                            ReadPre530Blocks(dataStream);
                        }
                    }
                    else
                    {
                        using (SmartStream dataStream = Read530Metadata(reader, headerSize))
                        {
                            Read530Blocks(dataStream, headerSize);
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        private SmartStream ReadPre530Metadata(BundleFileReader reader)
        {
            switch (Header.Type)
            {
            case BundleType.UnityRaw:
            {
                Metadata.Read(reader);
                return(m_stream.CreateReference());
            }

            case BundleType.UnityWeb:
            {
                // read only last chunk. wtf?
                ChunkInfo chunkInfo = Header.ChunkInfos[Header.ChunkInfos.Count - 1];
                using (SmartStream stream = SmartStream.CreateMemory(new byte[chunkInfo.DecompressedSize]))
                {
                    SevenZipHelper.DecompressLZMASizeStream(reader.BaseStream, chunkInfo.CompressedSize, stream);
                    using (BundleFileReader decompressReader = new BundleFileReader(stream, reader.EndianType, reader.Generation))
                    {
                        Metadata.Read(decompressReader);
                    }
                    return(stream.CreateReference());
                }
            }

            default:
                throw new NotSupportedException($"Bundle type {Header.Type} isn't supported before 530 generation");
            }
        }
Exemplo n.º 6
0
        public static WebFile Read(SmartStream stream, string webPath)
        {
            WebFile web = new WebFile(webPath);

            web.Read(stream);
            return(web);
        }
Exemplo n.º 7
0
 private void Read(SmartStream stream)
 {
     using (EndianReader reader = new EndianReader(stream, EndianType.LittleEndian, stream.Position))
     {
         ReadMetadata(reader);
     }
 }
Exemplo n.º 8
0
        internal static WebFileScheme ReadScheme(SmartStream stream, long offset, long size, string filePath, string fileName)
        {
            WebFileScheme scheme = new WebFileScheme(stream, offset, size, filePath, fileName);

            scheme.ReadScheme();
            scheme.ProcessEntries();
            return(scheme);
        }
Exemplo n.º 9
0
        private SerializedFileScheme(SmartStream stream, long offset, long size, string filePath, string fileName, TransferInstructionFlags flags) :
            base(stream, offset, size, filePath, fileName)
        {
            Flags = flags;

            Header   = new SerializedFileHeader(Name);
            Metadata = new SerializedFileMetadata(Name);
        }
Exemplo n.º 10
0
 public SerializedFileScheme(SmartStream stream, string filePath, string name) :
     base(stream, filePath)
 {
     if (string.IsNullOrEmpty(name))
     {
         throw new ArgumentNullException(nameof(filePath));
     }
     Name = name;
 }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
        internal bool Start(SmartStream stream)
        {
            // TODO: Clear old data, if any.
            m_IsCompleted   = false;
            m_BytesInBuffer = 0;
            m_pException    = null;

            return(DoLineReading());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Parses mime message from stream.
        /// </summary>
        /// <param name="stream">Mime message stream.</param>
        /// <returns></returns>
        public static Mime Parse(Stream stream)
        {
            Mime mime = new Mime();

            using (var ss = new SmartStream(stream, false))
                mime.MainEntity.Parse(ss, null);

            return(mime);
        }
Exemplo n.º 14
0
        public static Stream BuildUrlEncodedData(IDictionary formData, Encoding encoding = null)
        {
            AssertUtil.ArgumentNotNull(formData, nameof(formData));

            encoding = encoding == null ? Encoding.UTF8 : encoding;

            var stream = new MemoryStream();

            using (var writer = new SmartStream(stream, false))
            {
                writer.Encoding = encoding;

                bool firstKeyValue = true;
                foreach (var key in formData.Keys)
                {
                    if (!(key is string))
                    {
                        throw new ArgumentException("Key isnot typeof string.");
                    }

                    if (string.IsNullOrWhiteSpace((string)key))
                    {
                        throw new ArgumentException("Key cannot be null or empty.");
                    }

                    if (formData[key] is IEnumerable)
                    {
                        foreach (var value in (IEnumerable)formData[key])
                        {
                            if (!firstKeyValue)
                            {
                                writer.Write("&");
                            }

                            firstKeyValue = false;
                            writer.Write($"{HttpUtility.UrlEncode(((string)key).Trim())}={HttpUtility.UrlEncode(value?.ToString())}");
                        }
                    }
                    else
                    {
                        if (!firstKeyValue)
                        {
                            writer.Write("&");
                        }

                        firstKeyValue = false;
                        writer.Write($"{HttpUtility.UrlEncode(((string)key).Trim())}={HttpUtility.UrlEncode(formData[key]?.ToString())}");
                    }
                }

                writer.Flush();
            }

            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Connects to the specified remote end point.
        /// </summary>
        /// <param name="localEP">Local IP end point to use. Value null means that system will allocate it.</param>
        /// <param name="remoteEP">Remote IP end point to connect.</param>
        /// <param name="ssl">Specifies if connection switches to SSL affter connect.</param>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this method is accessed.</exception>
        /// <exception cref="InvalidOperationException">Is raised when client is already connected.</exception>
        /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null reference.</exception>
        public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl)
        {
            ThrowIfObjectDisposed();

            AssertUtil.ArgumentNotNull(remoteEP, nameof(remoteEP));


            lock (this)
            {
                ThrowIfConnected();

                // Create socket.
                if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
                {
                    this.Socket                = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    this.Socket.SendTimeout    = m_ReadWriteTimeout;
                    this.Socket.ReceiveTimeout = m_ReadWriteTimeout;
                }
                else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    this.Socket                = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    this.Socket.SendTimeout    = m_ReadWriteTimeout;
                    this.Socket.ReceiveTimeout = m_ReadWriteTimeout;
                }

                // Bind socket to the specified end point.
                if (localEP != null)
                {
                    this.Socket.Bind(localEP);
                }


                LogAddText($"Connecting to {remoteEP}.");

                this.Socket.Connect(remoteEP);

                LogAddText($"Connected, localEP='{this.Socket.LocalEndPoint}', remoteEP='{this.Socket.RemoteEndPoint}'.");


                m_ID          = ObjectId.NewId();
                m_IsConnected = true;
                m_ConnectTime = DateTime.Now;
                m_pLocalEP    = (IPEndPoint)this.Socket.LocalEndPoint;
                m_pRemoteEP   = (IPEndPoint)this.Socket.RemoteEndPoint;
                m_pTcpStream  = new SmartStream(new NetworkStream(this.Socket, true), true);

                // Start SSL handshake.
                if (ssl)
                {
                    SwitchToSecure();
                }

                OnConnected();
            }
        }
Exemplo n.º 16
0
 private SmartStream ReadBrotli(EndianReader reader)
 {
     using (SmartStream stream = SmartStream.CreateMemory())
     {
         using (BrotliInputStream brotliStream = new BrotliInputStream(reader.BaseStream))
         {
             brotliStream.CopyTo(stream);
         }
         return(stream.CreateReference());
     }
 }
Exemplo n.º 17
0
 public static SerializedFileScheme LoadScheme(string filePath, string fileName, TransferInstructionFlags flags)
 {
     if (!FileMultiStream.Exists(filePath))
     {
         throw new Exception($"Serialized file at path '{filePath}' doesn't exist");
     }
     using (SmartStream fileStream = SmartStream.OpenRead(filePath))
     {
         return(ReadScheme(fileStream, 0, fileStream.Length, filePath, fileName, flags));
     }
 }
Exemplo n.º 18
0
 private SmartStream ReadGZip(EndianReader reader)
 {
     using (SmartStream stream = SmartStream.CreateMemory())
     {
         using (GZipStream gzipStream = new GZipStream(reader.BaseStream, CompressionMode.Decompress))
         {
             gzipStream.CopyTo(stream);
         }
         return(stream.CreateReference());
     }
 }
Exemplo n.º 19
0
        private void Load()
        {
            if (!FileUtils.Exists(m_filePath))
            {
                throw new Exception($"BundleFile at path '{m_filePath}' doesn't exist");
            }

            using (SmartStream stream = SmartStream.OpenRead(m_filePath))
            {
                Read(stream);
            }
        }
Exemplo n.º 20
0
        public static BundleFileScheme LoadScheme(string filePath)
        {
            if (!FileUtils.Exists(filePath))
            {
                throw new Exception($"Bundle file at path '{filePath}' doesn't exist");
            }
            string fileName = Path.GetFileNameWithoutExtension(filePath);

            using (SmartStream stream = SmartStream.OpenRead(filePath))
            {
                return(ReadScheme(stream, 0, stream.Length, filePath, fileName));
            }
        }
Exemplo n.º 21
0
        /// <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];
        }
Exemplo n.º 22
0
        public override void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }

            if (!m_IsTerminated)
            {
                try
                { Disconnect(); }
                catch (Exception ex)
                {
                    string dummy = ex.Message;
                }
            }

            // We must call disposed event before we release events.
            try
            { OnDisposed(); }
            catch (Exception ex)
            {
                string dummy = ex.Message;
            }

            this.IsDisposed = true;

            m_pTags.Clear();
            m_pTags        = null;
            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.Dispose();
            }
            m_pRawTcpStream = null;

            // Release events.
            this.IdleTimeout = null;
            this.Disonnected = null;
            this.Error       = null;
            this.Disposed    = null;
        }
Exemplo n.º 23
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);
            Body = m_pBodyProvider.Parse(this, stream, ContentType ?? defaultContentType);
        }
Exemplo n.º 24
0
        /// <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[Workaround.Definitions.MaxStreamLineLength];
            m_pEncodedBuffer = new byte[78];
            line_buf         = new byte[Workaround.Definitions.MaxStreamLineLength];
        }
        /// <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;

            try
            {
                //_socket.Shutdown(SocketShutdown.Both);//Stop coms
                m_pTcpStream.Dispose();
            }
            catch (Exception)
            {
            }

            m_pTcpStream = null;
            m_pTags      = null;

            // Release events.
            IdleTimeout = null;
            Disonnected = null;
            Disposed    = null;
        }
        /// <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;
        }
Exemplo n.º 27
0
        private void ReadGZip(EndianReader reader)
        {
            using (SmartStream stream = SmartStream.CreateMemory())
            {
                using (GZipStream gzipStream = new GZipStream(reader.BaseStream, CompressionMode.Decompress))
                {
                    gzipStream.CopyTo(stream);
                    stream.Position = 0;
                }

                string           name  = Path.GetFileName(m_filePath);
                ArchiveFileEntry entry = new ArchiveFileEntry(stream, m_filePath, name, 0, stream.Length);
                Metadata = new ArchiveMetadata(entry);
            }
        }
Exemplo n.º 28
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 client is not connected.</exception>
        public override void Disconnect()
        {
            ThrowIfObjectDisposed();
            ThrowIfNotConnected();

            m_IsConnected        = false;
            m_IsSecureConnection = false;

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

            LogAddText("Disconnected.");
        }
Exemplo n.º 29
0
        private void ReadBrotli(EndianReader reader)
        {
            using (SmartStream stream = SmartStream.CreateMemory())
            {
                using (BrotliInputStream brotliStream = new BrotliInputStream(reader.BaseStream))
                {
                    brotliStream.CopyStream(stream);
                    stream.Position = 0;
                }

                string           name  = Path.GetFileName(m_filePath);
                ArchiveFileEntry entry = new ArchiveFileEntry(stream, m_filePath, name, 0, stream.Length);
                Metadata = new ArchiveMetadata(entry);
            }
        }
Exemplo n.º 30
0
 private void Read(SmartStream stream)
 {
     using (EndianReader reader = new EndianReader(stream, stream.Position, EndianType.BigEndian))
     {
         long position = reader.BaseStream.Position;
         Header.Read(reader);
         if (Header.Generation < BundleGeneration.BF_530_x)
         {
             ReadPre530Metadata(reader);
         }
         else
         {
             Read530Metadata(reader, position);
         }
     }
 }
Exemplo n.º 31
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 new static 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_Video retVal = new MIME_b_Video(mediaType);

            Net_Utils.StreamCopy(stream, retVal.EncodedStream, Workaround.Definitions.MaxStreamLineLength);

            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 new static 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_MultipartAlternative retVal = new MIME_b_MultipartAlternative(owner.ContentType);
            ParseInternal(owner, mediaType, stream, retVal);

            return retVal;
        }
Exemplo n.º 33
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;

            try
            {
                //_socket.Shutdown(SocketShutdown.Both);//Stop coms
                m_pTcpStream.Dispose();
            }
            catch (Exception)
            {
                                
            }
            
            m_pTcpStream = null;
            m_pTags = null;

            // Release events.
            IdleTimeout = null;
            Disonnected = null;
            Disposed = null;
        }
Exemplo n.º 34
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner stream.</param>
            /// <param name="storeStream">Stream where to store readed data.</param>
            /// <param name="count">Number of bytes to read from source stream.</param>
            /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param>
            /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> or <b>storeStream</b> is null reference.</exception>
            /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
            public ReadToStreamAsyncOperation(SmartStream owner,Stream storeStream,long count,AsyncCallback callback,object asyncState)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }
                if(storeStream == null){
                    throw new ArgumentNullException("storeStream");
                }
                if(count < 0){
                    throw new ArgumentException("Argument 'count' must be >= 0.");
                }

                m_pOwner             = owner;
                m_pStoreStream       = storeStream;
                m_Count              = count;
                m_pAsyncCallback     = callback;
                m_pAsyncState        = asyncState;

                m_pAsyncWaitHandle = new AutoResetEvent(false);

                if(m_Count == 0){
                    Completed();
                }
                else{
                    DoDataReading();
                }
            }
Exemplo n.º 35
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();
        }
Exemplo n.º 36
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), body.DefaultBodyPartContentType);
                body.m_pBodyParts.Add(entity);
                entity.SetParent(owner);
            }

            body.m_TextPreamble = multipartReader.TextPreamble;
            body.m_TextEpilogue = multipartReader.TextEpilogue;
        }
Exemplo n.º 37
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;

            // Check errors.
            if (op.Error != null)
            {
                OnError(op.Error);
            }

            try
            {
                if (IsDisposed)
                {
                    return false;
                }

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

                string[] cmd_args =
                    Encoding.UTF8.GetString(op.Buffer, 0, op.LineBytesInBuffer).Split(new[] {' '}, 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")
                {
                    readNextCommand = DATA(args);
                }
                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 (Server.MaxBadCommands != 0 && m_BadCommands > 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;
        }
Exemplo n.º 38
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 connection is already secure or when SSL certificate is not specified.</exception>
        public void SwitchToSecure()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException("TCP_ServerSession");
            }
            if (m_IsSecure)
            {
                throw new InvalidOperationException("Session is already SSL/TLS.");
            }
            if (m_pCertificate == null)
            {
                throw new InvalidOperationException("There is no certificate specified.");
            }

            // 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);
            sslStream.AuthenticateAsServer(m_pCertificate);

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

            m_IsSecure = true;
            m_pTcpStream = new SmartStream(sslStream, true);
        }
Exemplo n.º 39
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>stream</b> is null reference.</exception>
        /// <exception cref="ParseException">Is raised when any parsing errors.</exception>
        protected static 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");
            }

            throw new NotImplementedException("Body provider class does not implement required Parse method.");
        }
        /// <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[Workaround.Definitions.MaxStreamLineLength],
                                                                               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[] {':'}, 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());
                }
            }
        }
Exemplo n.º 41
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;
            string mediaTypeWithParams = defaultContentType.ToString().Split(':')[1].TrimStart(' ');
            if (owner.ContentType != null)
            {
                mediaType = owner.ContentType.TypeWithSubype;
                mediaTypeWithParams = owner.ContentType.ToString().Split(':')[1].TrimStart(' ');
            }

            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",
                                   BindingFlags.Static | BindingFlags.NonPublic |
                                   BindingFlags.FlattenHierarchy).Invoke(null,
                                                                         new object[] { owner, mediaTypeWithParams, stream });
        }
Exemplo n.º 42
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);
            Body = m_pBodyProvider.Parse(this, stream, ContentType??defaultContentType);
        }
Exemplo n.º 43
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 (!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,
                                                RemoteCertificateValidationCallback);
            sslStream.AuthenticateAsClient("");

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

            m_IsSecure = true;
            m_pTcpStream = new SmartStream(sslStream, true);
        }
Exemplo n.º 44
0
        /// <summary>
        /// Connects to the specified remote end point.
        /// </summary>
        /// <param name="localEP">Local IP end point to use for connet.</param>
        /// <param name="remoteEP">Remote IP end point where to connect.</param>
        /// <param name="ssl">Specifies if connects to SSL end point.</param>
        /// <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 already connected.</exception>
        /// <exception cref="ArgumentNullException">Is raised when <b>remoteEP</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        public void Connect(IPEndPoint localEP, IPEndPoint remoteEP, bool ssl, int timeout)
        {
            Debug.Print("TCP client connect");
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException("TCP_Client");
            }
            if (IsConnected)
            {
                throw new InvalidOperationException("TCP client is already connected.");
            }
            if (remoteEP == null)
            {
                throw new ArgumentNullException("remoteEP");
            }

            if (Socket != null && Socket.Connected)
            {
                Socket.Disconnect(false);
                Socket.Shutdown(SocketShutdown.Both);
            }

            Socket = null;
            if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
            {
                Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            else if (remoteEP.AddressFamily == AddressFamily.InterNetworkV6)
            {
                Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
            }
            else
            {
                throw new ArgumentException("Remote end point has invalid AddressFamily.");
            }

            try
            {
                Socket.SendTimeout = timeout;
                Socket.ReceiveTimeout = timeout;

                if (localEP != null)
                {
                    Socket.Bind(localEP);
                }

                LogAddText("Connecting to " + remoteEP + ".");
                Socket.Connect(remoteEP);

                m_IsConnected = true;
                m_ID = Guid.NewGuid().ToString();
                m_ConnectTime = DateTime.Now;
                m_pLocalEP = (IPEndPoint) Socket.LocalEndPoint;
                m_pRemoteEP = (IPEndPoint) Socket.RemoteEndPoint;
                m_pTcpStream = new SmartStream(new NetworkStream(Socket, true), true);

                LogAddText("Connected, localEP='" + m_pLocalEP + "'; remoteEP='" + remoteEP + "'.");

                if (ssl)
                {
                    SwitchToSecure();
                }
            }
            catch (Exception x)
            {
                LogAddException("Exception: " + x.Message, x);

                // Switching to secure failed.
                if (IsConnected)
                {
                    Disconnect();
                }
                    // Bind or connect failed.
                else
                {
                    Socket.Close();
                }

                OnError(x);

                throw x;
            }

            OnConnected();
        }
Exemplo n.º 45
0
        /// <summary>
        /// Initializes session. This method is called from TCP_Server when new session created.
        /// </summary>
        /// <param name="server">Owner TCP server.</param>
        /// <param name="socket">Connected socket.</param>
        /// <param name="hostName">Local host name.</param>
        /// <param name="ssl">Specifies if session should switch to SSL.</param>
        /// <param name="certificate">SSL certificate.</param>
        internal void Init(object server,
                           Socket socket,
                           string hostName,
                           bool ssl,
                           X509Certificate certificate)
        {
            // NOTE: We may not raise any event here !
            _socket = socket;
            m_pServer = server;
            m_LocalHostName = hostName;
            m_ID = Guid.NewGuid().ToString();
            m_ConnectTime = DateTime.Now;
            m_pLocalEP = (IPEndPoint) socket.LocalEndPoint;
            m_pRemoteEP = (IPEndPoint) socket.RemoteEndPoint;
            m_pCertificate = certificate;

            socket.ReceiveBufferSize = Workaround.Definitions.MaxStreamLineLength;
            socket.SendBufferSize = Workaround.Definitions.MaxStreamLineLength;
            socket.ReceiveTimeout = 30000;
            socket.SendTimeout = 10000;//10 sec

            if (ssl)
            {
                SwitchToSecure();
            }
            else
            {
                m_pTcpStream = new SmartStream(new NetworkStream(socket, true), true);
            }
        }
Exemplo n.º 46
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)
        {
            //TODO: ���� ��������� �������! �������� ����! �� ��� ���� �������� � utf8 �����

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

            var headers = new List<KeyValuePair<string, byte[]>>();
            var currentMemStream = new MemoryStream();
            SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[Workaround.Definitions.MaxStreamLineLength],
                                                                                     SizeExceededAction.
                                                                                         ThrowException);
            while (true)
            {
                stream.ReadLine(readLineOP, false);
                if (readLineOP.Error != null)
                {
                    throw readLineOP.Error;
                }
                // We reached end of stream.
                if (readLineOP.BytesInBuffer == 0)
                {
                    if (currentMemStream.Length > 0)
                    {
                        AddToBinaryDict(headers, currentMemStream);
                    }
                    m_IsModified = false;

                    break;
                }
                // We got blank header terminator line.
                if (readLineOP.LineBytesInBuffer == 0)
                {
                    if (currentMemStream.Length > 0)
                    {
                        AddToBinaryDict(headers, currentMemStream);
                    }
                    m_IsModified = false;

                    break;
                }

                string line = Encoding.UTF8.GetString(readLineOP.Buffer, 0, readLineOP.BytesInBuffer);
                var realBuffer = new List<byte>();

                if ((line.StartsWith("From: \"") || line.StartsWith("To: \"")) && !line.EndsWith(">\r\n"))
                {
                    var tmpArr = new byte[readLineOP.BytesInBuffer];
                    Array.Copy(readLineOP.Buffer, 0, tmpArr, 0, readLineOP.BytesInBuffer);
                    realBuffer.AddRange(tmpArr);
                    do
                    {
                        stream.ReadLine(readLineOP, false);

                        if (readLineOP.LineBytesInBuffer == 0)
                            break;

                        line = Encoding.UTF8.GetString(readLineOP.Buffer, 0, readLineOP.BytesInBuffer);

                        tmpArr = new byte[readLineOP.BytesInBuffer];
                        Array.Copy(readLineOP.Buffer, 0, tmpArr, 0, readLineOP.BytesInBuffer);
                        realBuffer.AddRange(tmpArr);

                    } while (!line.EndsWith(">\r\n"));

                    if (realBuffer.Count > 0)
                    {
                        line = Encoding.UTF8.GetString(realBuffer.ToArray());
                    }
                }
                

                // New header field starts.
                if (currentMemStream.Length == 0)
                {
                    currentMemStream.Write(readLineOP.Buffer, 0, readLineOP.BytesInBuffer);
                }
                // Header field continues.
                else if (char.IsWhiteSpace(line[0]))
                {
                    currentMemStream.Write(readLineOP.Buffer, 0, readLineOP.BytesInBuffer);
                }
                // Current header field closed, new starts.
                else
                {
                    AddToBinaryDict(headers, currentMemStream);

                    currentMemStream = new MemoryStream();
                    if (realBuffer.Count > 0)
                        currentMemStream.Write(realBuffer.ToArray(), 0, realBuffer.Count);
                    else
                        currentMemStream.Write(readLineOP.Buffer, 0, readLineOP.BytesInBuffer);
                }
            }
            //Process dictionary
            //Find content type
            var contentTypeHeader = 
                headers
                    .Where(x => x.Value != null)
                    .Where(x => "content-type".Equals(x.Key, StringComparison.OrdinalIgnoreCase))
                    .Select(x => Encoding.UTF8.GetString(x.Value))
                    .SingleOrDefault();
            var encoding = Encoding.UTF8;
            if (contentTypeHeader != null)
            {
                var mime = MIME_h_ContentType.Parse(contentTypeHeader);
                if (!string.IsNullOrEmpty(mime.Param_Charset))
                {
                    encoding = EncodingTools.GetEncodingByCodepageName(mime.Param_Charset) ?? Encoding.UTF8;
                }
                else
                {
                    //Join headers
                    var subjectRaw =
                        headers
                            .Where(x => x.Value != null)
                            .Where(x => "subject".Equals(x.Key, StringComparison.OrdinalIgnoreCase))
                            .Select(x => x.Value)
                            .SingleOrDefault();
                    //Try to detect hueristic
                    encoding = subjectRaw != null ? EncodingTools.DetectInputCodepage(subjectRaw) : Encoding.UTF8;
                }
            }

            foreach (var keyValuePair in headers)
            {
                Add(encoding.GetString(keyValuePair.Value));
            }
        }
Exemplo n.º 47
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[Workaround.Definitions.MaxStreamLineLength],
                                                                SizeExceededAction.ThrowException);
                m_pTextPreamble = new StringBuilder();
                m_pTextEpilogue = new StringBuilder();
            }
Exemplo n.º 48
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner stream.</param>
            /// <param name="terminator">Data terminator.</param>
            /// <param name="storeStream">Stream where to store readed header.</param>
            /// <param name="maxCount">Maximum number of bytes to read. Value 0 means not limited.</param>
            /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param>
            /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param>
            /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>,<b>terminator</b> or <b>storeStream</b> is null reference.</exception>
            public ReadToTerminatorAsyncOperation(SmartStream owner,string terminator,Stream storeStream,long maxCount,SizeExceededAction exceededAction,AsyncCallback callback,object asyncState)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }
                if(terminator == null){
                    throw new ArgumentNullException("terminator");
                }
                if(storeStream == null){
                    throw new ArgumentNullException("storeStream");
                }
                if(maxCount < 0){
                    throw new ArgumentException("Argument 'maxCount' must be >= 0.");
                }

                m_pOwner             = owner;
                m_Terminator         = terminator;
                m_pTerminatorBytes   = Encoding.ASCII.GetBytes(terminator);
                m_pStoreStream       = storeStream;
                m_MaxCount           = maxCount;
                m_SizeExceededAction = exceededAction;
                m_pAsyncCallback     = callback;
                m_pAsyncState        = asyncState;

                m_pAsyncWaitHandle = new AutoResetEvent(false);

                m_pLineBuffer = new byte[32000];

                // Start reading data.
                #pragma warning disable
                m_pOwner.BeginReadLine(m_pLineBuffer,0,m_pLineBuffer.Length - 2,m_SizeExceededAction,new AsyncCallback(this.ReadLine_Completed),null);
                #pragma warning restore
            }
Exemplo n.º 49
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner stream.</param>
            /// <param name="buffer">Buffer where to store data.</param>
            /// <param name="offset">The location in <b>buffer</b> to begin storing the data.</param>
            /// <param name="maxCount">Maximum number of bytes to read.</param>
            /// <param name="exceededAction">Specifies how this method behaves when maximum line size exceeded.</param>
            /// <param name="callback">The AsyncCallback delegate that is executed when asynchronous operation completes.</param>
            /// <param name="asyncState">User-defined object that qualifies or contains information about an asynchronous operation.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b>,<b>buffer</b> is null reference.</exception>
            /// <exception cref="ArgumentOutOfRangeException">Is raised when any of the arguments has out of valid range.</exception>
            public ReadLineAsyncOperation(SmartStream owner,byte[] buffer,int offset,int maxCount,SizeExceededAction exceededAction,AsyncCallback callback,object asyncState)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }
                if(buffer == null){
                    throw new ArgumentNullException("buffer");
                }
                if(offset < 0){
                    throw new ArgumentOutOfRangeException("offset","Argument 'offset' value must be >= 0.");
                }
                if(offset > buffer.Length){
                    throw new ArgumentOutOfRangeException("offset","Argument 'offset' value must be < buffer.Length.");
                }
                if(maxCount < 0){
                    throw new ArgumentOutOfRangeException("maxCount","Argument 'maxCount' value must be >= 0.");
                }
                if(offset + maxCount > buffer.Length){
                    throw new ArgumentOutOfRangeException("maxCount","Argument 'maxCount' is bigger than than argument 'buffer' can store.");
                }

                m_pOwner             = owner;
                m_pBuffer            = buffer;
                m_OffsetInBuffer     = offset;
                m_MaxCount           = maxCount;
                m_SizeExceededAction = exceededAction;
                m_pAsyncCallback     = callback;
                m_pAsyncState        = asyncState;

                m_pAsyncWaitHandle = new AutoResetEvent(false);

                DoLineReading();
            }
Exemplo n.º 50
0
        /// <summary>
        /// Gets files and directories in the current server directory.
        /// </summary>
        /// <param name="path">Directory or file name which listing to get. Value null means current directory will be listed.</param>
        /// <returns>Returns current working directory listing.</returns>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
        /// <exception cref="InvalidOperationException">Is raised when FTP client is not connected or FTP data connection has active read/write operation.</exception>
        /// <exception cref="FTP_ClientException">Is raised when FTP server returns error.</exception>
        public FTP_ListItem[] GetList(string path)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
            if (!IsConnected)
            {
                throw new InvalidOperationException("You must connect first.");
            }
            if (m_pDataConnection.IsActive)
            {
                throw new InvalidOperationException(
                    "There is already active read/write operation on data connection.");
            }

            List<FTP_ListItem> retVal = new List<FTP_ListItem>();

            // Set transfer mode
            SetTransferType(TransferType.Binary);

            if (m_TransferMode == FTP_TransferMode.Passive)
            {
                Pasv();
            }
            else
            {
                Port();
            }

            // If FTP server supports MLSD command, use it to get directory listing.
            // MLSD is standard way to get dir listing, while LIST command isn't any strict standard.
            bool mlsdSupported = false;
            foreach (string feature in m_pExtCapabilities)
            {
                if (feature.ToLower().StartsWith("mlsd"))
                {
                    mlsdSupported = true;
                    break;
                }
            }

            #region MLSD

            if (mlsdSupported)
            {
                if (string.IsNullOrEmpty(path))
                {
                    WriteLine("MLSD");
                }
                else
                {
                    WriteLine("MLSD " + path);
                }

                string[] response = ReadResponse();
                if (!response[0].StartsWith("1"))
                {
                    throw new FTP_ClientException(response[0]);
                }

                MemoryStream ms = new MemoryStream();
                m_pDataConnection.ReadAll(ms);

                response = ReadResponse();
                if (!response[0].StartsWith("2"))
                {
                    throw new FTP_ClientException(response[0]);
                }

                byte[] lineBuffer = new byte[8000];
                ms.Position = 0;
                SmartStream mlsdStream = new SmartStream(ms, true);
                while (true)
                {
                    SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(lineBuffer,
                                                                                       SizeExceededAction.
                                                                                           JunkAndThrowException);
                    mlsdStream.ReadLine(args, false);
                    if (args.Error != null)
                    {
                        throw args.Error;
                    }
                    string line = args.LineUtf8;

                    // We reached end of stream, we readed whole list sucessfully.
                    if (line == null)
                    {
                        break;
                    }
                    else
                    {
                        string[] parameters = line.Substring(0, line.LastIndexOf(';')).Split(';');
                        string name = line.Substring(line.LastIndexOf(';') + 1).Trim();

                        string type = "";
                        long size = 0;
                        DateTime modified = DateTime.MinValue;
                        foreach (string parameter in parameters)
                        {
                            string[] name_value = parameter.Split('=');
                            if (name_value[0].ToLower() == "type")
                            {
                                type = name_value[1].ToLower();
                            }
                            else if (name_value[0].ToLower() == "size")
                            {
                                size = Convert.ToInt32(name_value[1]);
                            }
                            else if (name_value[0].ToLower() == "modify")
                            {
                                modified = DateTime.ParseExact(name_value[1],
                                                               "yyyyMMddHHmmss",
                                                               DateTimeFormatInfo.InvariantInfo);
                            }
                            else
                            {
                                // Other options won't interest us, skip them.
                            }
                        }

                        if (type == "dir")
                        {
                            retVal.Add(new FTP_ListItem(name, 0, modified, true));
                        }
                        else if (type == "file")
                        {
                            retVal.Add(new FTP_ListItem(name, size, modified, false));
                        }
                    }
                }
            }

                #endregion

                #region LIST

            else
            {
                if (string.IsNullOrEmpty(path))
                {
                    WriteLine("LIST");
                }
                else
                {
                    WriteLine("LIST " + path);
                }

                string[] response = ReadResponse();
                if (!response[0].StartsWith("1"))
                {
                    throw new FTP_ClientException(response[0]);
                }

                MemoryStream ms = new MemoryStream();
                m_pDataConnection.ReadAll(ms);

                response = ReadResponse();
                if (!response[0].StartsWith("2"))
                {
                    throw new FTP_ClientException(response[0]);
                }

                ms.Position = 0;
                SmartStream listStream = new SmartStream(ms, true);
                SmartStream.ReadLineAsyncOP args = new SmartStream.ReadLineAsyncOP(new byte[8000],
                                                                                   SizeExceededAction.
                                                                                       JunkAndThrowException);
                listStream.ReadLine(args, false);
                if (args.Error != null)
                {
                    throw args.Error;
                }
                string line = args.LineUtf8;

                string listingType = "unix";
                // Dedect listing.
                if (line != null)
                {
                    try
                    {
                        StringReader r = new StringReader(line);
                        DateTime modified = DateTime.ParseExact(r.ReadWord() + " " + r.ReadWord(),
                                                                new[] {"MM-dd-yy hh:mmtt"},
                                                                DateTimeFormatInfo.InvariantInfo,
                                                                DateTimeStyles.None);
                        listingType = "win";
                    }
                    catch {}
                }

                string[] winDateFormats = new[] {"M-d-yy h:mmtt"};
                string[] unixFormats = new[] {"MMM d H:mm", "MMM d yyyy"};

                byte[] lineBuffer = new byte[8000];
                while (line != null)
                {
                    // Windows listing.                 
                    if (listingType == "win")
                    {
                        // MM-dd-yy hh:mm <DIR> directoryName
                        // MM-dd-yy hh:mm size  fileName

                        StringReader r = new StringReader(line);
                        // Read date
                        DateTime modified = DateTime.ParseExact(r.ReadWord() + " " + r.ReadWord(),
                                                                winDateFormats,
                                                                DateTimeFormatInfo.InvariantInfo,
                                                                DateTimeStyles.None);

                        r.ReadToFirstChar();
                        // We have directory.
                        if (r.StartsWith("<dir>", false))
                        {
                            r.ReadSpecifiedLength(5);
                            r.ReadToFirstChar();

                            retVal.Add(new FTP_ListItem(r.ReadToEnd(), 0, modified, true));
                        }
                            // We have file
                        else
                        {
                            // Read file size
                            long size = Convert.ToInt64(r.ReadWord());
                            r.ReadToFirstChar();

                            retVal.Add(new FTP_ListItem(r.ReadToEnd(), size, modified, false));
                        }
                    }
                        // Unix listing
                    else
                    {
                        // "d"directoryAtttributes xx xx xx 0 MMM d HH:mm/yyyy directoryName
                        // fileAtttributes xx xx xx fileSize MMM d HH:mm/yyyy fileName

                        StringReader r = new StringReader(line);
                        string attributes = r.ReadWord();
                        r.ReadWord();
                        r.ReadWord();
                        r.ReadWord();
                        long size = Convert.ToInt64(r.ReadWord());
                        DateTime modified =
                            DateTime.ParseExact(r.ReadWord() + " " + r.ReadWord() + " " + r.ReadWord(),
                                                unixFormats,
                                                DateTimeFormatInfo.InvariantInfo,
                                                DateTimeStyles.None);
                        r.ReadToFirstChar();
                        string name = r.ReadToEnd();
                        if (name != "." && name != "..")
                        {
                            if (attributes.StartsWith("d"))
                            {
                                retVal.Add(new FTP_ListItem(name, 0, modified, true));
                            }
                            else
                            {
                                retVal.Add(new FTP_ListItem(name, size, modified, false));
                            }
                        }
                    }

                    listStream.ReadLine(args, false);
                    if (args.Error != null)
                    {
                        throw args.Error;
                    }
                    line = args.LineUtf8;
                }
            }

            #endregion

            return retVal.ToArray();
        }
        /// <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 new static 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_MessageRfc822 retVal = new MIME_b_MessageRfc822();
            if (owner.ContentTransferEncoding != null && owner.ContentTransferEncoding.Equals("base64", StringComparison.OrdinalIgnoreCase))
            {
                Stream decodedDataStream = new MemoryStream();
                using (StreamReader reader = new StreamReader(stream))
                {
                    byte[] decoded = Convert.FromBase64String(reader.ReadToEnd());
                    decodedDataStream.Write(decoded, 0, decoded.Length);
                    decodedDataStream.Seek(0, SeekOrigin.Begin);
                }

                //Create base64 decoder
                stream = new SmartStream(decodedDataStream,true);

            }
            retVal.m_pMessage = Mail_Message.ParseFromStream(stream);

            return retVal;
        }
Exemplo n.º 52
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="stream">Source stream. Reading starts from stream current location.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
            public WritePeriodTerminatedAsyncOP(Stream stream)
            {
                if(stream == null){
                    throw new ArgumentNullException("stream");
                }

                m_pStream = new SmartStream(stream,false);
            }
Exemplo n.º 53
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 ((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 = 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();
                        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[Workaround.Definitions.MaxStreamLineLength],
                                                                                             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;
        }
Exemplo n.º 54
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="owner">Owner stream.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            public BufferReadAsyncOP(SmartStream owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pOwner = owner;
            }