예제 #1
0
        public async Task ReceivingHeadersOrDataOnAResetStreamShouldProduceAClosedStreamError(
            bool sendHeaders, bool sendData, bool sendTrailers)
        {
            var inPipe = new BufferedPipe(1024);
            var outPipe = new BufferedPipe(1024);

            var r = await StreamCreator.CreateConnectionAndStream(
                StreamState.Reset, loggerProvider, inPipe, outPipe);

            if (sendHeaders)
            {
                await inPipe.WriteHeaders(r.hEncoder, 1, false, DefaultGetHeaders);
            }
            if (sendData)
            {
                await inPipe.WriteData(1u, 0);
            }
            if (sendTrailers)
            {
                await inPipe.WriteHeaders(r.hEncoder, 1, true, DefaultGetHeaders);
            }
            await outPipe.AssertResetStreamReception(1, ErrorCode.StreamClosed);
        }
예제 #2
0
        private ResSetCollection ReadFile(string filePath, bool gzip)
        {
            ResSetCollection resCollection = new ResSetCollection();
            Stream           stream        = StreamCreator.CreateReader(filePath, gzip);
            ThreadParser     dataParser    = new X2chThreadParser();

            try {
                byte[] buffer = new byte[10240];
                int    readCount = 0, index = 1;

                do
                {
                    // バッファにデータを読み込む
                    readCount = stream.Read(buffer, 0, buffer.Length);
                    int parsed;

                    // 解析してコレクションに格納
                    ICollection collect = dataParser.Parse(buffer, readCount, out parsed);

                    foreach (ResSet resSet in collect)
                    {
                        ResSet res = resSet;
                        res.Index = index++;

                        resCollection.Add(res);
                    }
                } while (readCount != 0);
            }
            finally {
                if (stream != null)
                {
                    stream.Close();
                }
            }

            return(resCollection);
        }
예제 #3
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
                baseStream = StreamCreator.GetStream(Settings);
                //#if !CF && !RT
                //         if (Settings.IncludeSecurityAsserts)
                //            MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                //#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new MySqlException("Resources.UnableToConnectToHost",
                                         (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }
            if (baseStream == null)
            {
                throw new MySqlException("Resources.UnableToConnectToHost",
                                         (int)MySqlErrorCode.UnableToConnectToHost);
            }

            int maxSinglePacket = 255 * 255 * 255;

            stream = new MySqlStream(baseStream, Encoding, false);

            stream.ResetTimeout((int)Settings.ConnectionTimeout * 1000);

            // read off the welcome packet and parse out it's values
            packet = stream.ReadPacket();
            int    protocol      = packet.ReadByte();
            string versionString = packet.ReadString();

            owner.isFabric = versionString.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            version        = DBVersion.Parse(versionString);
            if (!owner.isFabric && !version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException("Resources.ServerTooOld");
            }

            threadId = packet.ReadInteger(4);

            byte[] seedPart1 = packet.ReadStringAsBytes();

            maxSinglePacket = (256 * 256 * 256) - 1;

            // read in Server capabilities if they are provided
            ClientFlags serverCaps = 0;

            if (packet.HasMoreData)
            {
                serverCaps = (ClientFlags)packet.ReadInteger(2);
            }

            /* New protocol with 16 bytes to describe server characteristics */
            owner.ConnectionCharSetIndex = (int)packet.ReadByte();

            serverStatus = (ServerStatusFlags)packet.ReadInteger(2);

            // Since 5.5, high bits of server caps are stored after status.
            // Previously, it was part of reserved always 0x00 13-byte filler.
            uint serverCapsHigh = (uint)packet.ReadInteger(2);

            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            byte[] seedPart2 = packet.ReadStringAsBytes();
            encryptionSeed = new byte[seedPart1.Length + seedPart2.Length];
            seedPart1.CopyTo(encryptionSeed, 0);
            seedPart2.CopyTo(encryptionSeed, seedPart1.Length);

            string authenticationMethod = "";

            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MySql versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);
            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(33);             //character set utf-8
            packet.Write(new byte[23]);

#if !CF && !RT
            if ((serverCaps & ClientFlags.SSL) == 0)
            {
                if ((Settings.SslMode != MySqlSslMode.None) &&
                    (Settings.SslMode != MySqlSslMode.Preferred))
                {
                    // Client requires SSL connections.
                    string message = String.Format("Resources.NoServerSSLSupport",

                                                   Settings.Server);
                    throw new MySqlException(message);
                }
            }
            else if (Settings.SslMode != MySqlSslMode.None)
            {
                stream.SendPacket(packet);
                StartSSL();
                packet.Clear();
                packet.WriteInteger((int)connectionFlags, 4);
                packet.WriteInteger(maxSinglePacket, 4);
                packet.WriteByte(33);                 //character set utf-8
                packet.Write(new byte[23]);
            }
#endif

#if RT
            if (Settings.SslMode != MySqlSslMode.None)
            {
                throw new NotImplementedException("SSL not supported in this WinRT release.");
            }
#endif

            Authenticate(authenticationMethod, false);

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                stream = new MySqlStream(baseStream, Encoding, true);
            }

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            packet.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;
        }
예제 #4
0
        public void Open()
        {
            try
            {
                this.baseStream = StreamCreator.GetStream(this.Settings);
                if (this.Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception inner)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042, inner);
            }
            if (this.baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042);
            }
            this.stream = new MySqlStream(this.baseStream, this.Encoding, false);
            this.stream.ResetTimeout((int)(this.Settings.ConnectionTimeout * 1000u));
            this.packet = this.stream.ReadPacket();
            this.packet.ReadByte();
            string versionString = this.packet.ReadString();

            this.version = DBVersion.Parse(versionString);
            if (!this.version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            this.threadId       = this.packet.ReadInteger(4);
            this.encryptionSeed = this.packet.ReadString();
            int         num         = 16777215;
            ClientFlags clientFlags = (ClientFlags)0uL;

            if (this.packet.HasMoreData)
            {
                clientFlags = (ClientFlags)((long)this.packet.ReadInteger(2));
            }
            this.owner.ConnectionCharSetIndex = (int)this.packet.ReadByte();
            this.serverStatus = (ServerStatusFlags)this.packet.ReadInteger(2);
            uint num2 = (uint)this.packet.ReadInteger(2);

            clientFlags          |= (ClientFlags)(num2 << 16);
            this.packet.Position += 11;
            string str = this.packet.ReadString();

            this.encryptionSeed += str;
            string authMethod;

            if ((clientFlags & ClientFlags.PLUGIN_AUTH) != (ClientFlags)0uL)
            {
                authMethod = this.packet.ReadString();
            }
            else
            {
                authMethod = "mysql_native_password";
            }
            this.SetConnectionFlags(clientFlags);
            this.packet.Clear();
            this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            if ((clientFlags & ClientFlags.SSL) == (ClientFlags)0uL)
            {
                if (this.Settings.SslMode != MySqlSslMode.None && this.Settings.SslMode != MySqlSslMode.Preferred)
                {
                    string msg = string.Format(Resources.NoServerSSLSupport, this.Settings.Server);
                    throw new MySqlException(msg);
                }
            }
            else
            {
                if (this.Settings.SslMode != MySqlSslMode.None)
                {
                    this.stream.SendPacket(this.packet);
                    this.StartSSL();
                    this.packet.Clear();
                    this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
                }
            }
            this.packet.WriteInteger((long)num, 4);
            this.packet.WriteByte(8);
            this.packet.Write(new byte[23]);
            this.Authenticate(authMethod, false);
            if ((this.connectionFlags & ClientFlags.COMPRESS) != (ClientFlags)0uL)
            {
                this.stream = new MySqlStream(this.baseStream, this.Encoding, true);
            }
            this.packet.Version      = this.version;
            this.stream.MaxBlockSize = num;
        }
예제 #5
0
        public override void Open()
        {
            base.Open();

            // connect to one of our specified hosts
            Stream stream;

            try
            {
                if (Settings.Protocol == ConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    stream = str;
                }
                else
                {
                    string pipeName = Settings.PipeName;
                    if (Settings.Protocol != ConnectionProtocol.NamedPipe)
                    {
                        pipeName = null;
                    }
                    StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName);
                    stream = sc.GetStream(Settings.ConnectionTimeout);
                }
            }
            catch (Exception ex)
            {
                throw new MySqlException("Unable to connect to any of the specified MySQL hosts", ex);
            }


            if (stream == null)
            {
                throw new MySqlException("Unable to connect to any of the specified MySQL hosts");
            }

            reader          = new PacketReader(new BufferedStream(stream), this);
            writer          = new PacketWriter(new BufferedStream(stream), this);
            writer.Encoding = encoding;

            // read off the welcome packet and parse out it's values
            reader.OpenPacket();
            protocol = reader.ReadByte();
            string versionString = reader.ReadString();

            version        = DBVersion.Parse(versionString);
            threadId       = (int)reader.ReadInteger(4);
            encryptionSeed = reader.ReadString();

            // starting with 4.0.8, maxSinglePacket should be 0xffffff
            if (version.isAtLeast(4, 0, 8))
            {
                MaxSinglePacket = (256 * 256 * 256) - 1;
            }

            // read in Server capabilities if they are provided
            serverCaps = 0;
            if (reader.HasMoreData)
            {
                serverCaps = (ClientFlags)reader.ReadInteger(2);
            }

            // based on our settings, set our connection flags
            SetConnectionFlags();

            writer.StartPacket(0);
            writer.WriteInteger((int)connectionFlags, version.isAtLeast(4, 1, 0) ? 4 : 2);
            writer.WriteInteger(MaxSinglePacket, version.isAtLeast(4, 1, 0) ? 4 : 3);

            // 4.1.1 included some new server status info
            if (version.isAtLeast(4, 1, 1))
            {
                /* New protocol with 16 bytes to describe server characteristics */
                serverLanguage = reader.ReadInteger(1);
                serverStatus   = (ServerStatusFlags)reader.ReadInteger(2);
                reader.Skip(13);

                string seedPart2 = reader.ReadString();
                encryptionSeed += seedPart2;

                writer.WriteByte(8);
                writer.Write(new byte[23], 0, 23);
            }

            Authenticate();

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                //stream = new CompressedStream( stream, MaxSinglePacket );
                writer          = new PacketWriter(new CompressedStream(new BufferedStream(stream)), this);
                writer.Encoding = encoding;
                reader          = new PacketReader(new CompressedStream(new BufferedStream(stream)), this);
            }

            isOpen = true;
        }
예제 #6
0
        public override void Open()
        {
            base.Open();
            Stream stream;

            try
            {
                if (base.Settings.Protocol == ConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream sharedMemoryStream = new SharedMemoryStream(base.Settings.SharedMemoryName);
                    sharedMemoryStream.Open(base.Settings.ConnectionTimeout);
                    stream = sharedMemoryStream;
                }
                else
                {
                    string pipeName = base.Settings.PipeName;
                    if (base.Settings.Protocol != ConnectionProtocol.NamedPipe)
                    {
                        pipeName = null;
                    }
                    StreamCreator streamCreator = new StreamCreator(base.Settings.Server, base.Settings.Port, pipeName);
                    stream = streamCreator.GetStream((uint)base.Settings.ConnectionTimeout);
                }
                if (stream == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception inner)
            {
                throw new MySqlException(Resources.UnableToConnectToHost, 1042, inner);
            }
            if (stream == null)
            {
                throw new MySqlException("Unable to connect to any of the specified MySQL hosts");
            }
            this.reader          = new PacketReader(new BufferedStream(stream), this);
            this.writer          = new PacketWriter(new BufferedStream(stream), this);
            this.writer.Encoding = this.encoding;
            this.reader.OpenPacket();
            this.protocol = this.reader.ReadByte();
            string versionString = this.reader.ReadString();

            this.version        = DBVersion.Parse(versionString);
            this.threadId       = this.reader.ReadInteger(4);
            this.encryptionSeed = this.reader.ReadString();
            if (this.version.isAtLeast(4, 0, 8))
            {
                this.MaxSinglePacket = 16777215;
            }
            this.serverCaps = (ClientFlags)0;
            if (this.reader.HasMoreData)
            {
                this.serverCaps = (ClientFlags)this.reader.ReadInteger(2);
            }
            this.SetConnectionFlags();
            this.writer.StartPacket(0L);
            this.writer.WriteInteger((long)this.connectionFlags, this.version.isAtLeast(4, 1, 0) ? 4 : 2);
            this.writer.WriteInteger((long)this.MaxSinglePacket, this.version.isAtLeast(4, 1, 0) ? 4 : 3);
            if (this.version.isAtLeast(4, 1, 1))
            {
                this.serverLanguage = this.reader.ReadInteger(1);
                this.serverStatus   = (ServerStatusFlags)this.reader.ReadInteger(2);
                this.reader.Skip(13L);
                string text = this.reader.ReadString();
                this.encryptionSeed += text;
                this.writer.WriteByte(8);
                this.writer.Write(new byte[23], 0, 23);
            }
            this.Authenticate();
            if ((this.connectionFlags & ClientFlags.COMPRESS) != (ClientFlags)0)
            {
                this.writer          = new PacketWriter(new BufferedStream(new CompressedStream(stream)), this);
                this.writer.Encoding = this.encoding;
                this.reader          = new PacketReader(new BufferedStream(new CompressedStream(stream)), this);
            }
            this.isOpen = true;
        }
예제 #7
0
        public void Open()
        {
            // connect to one of our specified hosts
            try
            {
#if !CF
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
#endif
                string pipeName = Settings.PipeName;
                if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                {
                    pipeName = null;
                }
                StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName,
                                                     Settings.Keepalive, this.Version);
#if !CF
                MySqlSecurityPermission.CreatePermissionSet(false).Assert();
#endif
                baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
            }
#endif
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }
            if (baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost);
            }

            int maxSinglePacket = 255 * 255 * 255;
            stream = new MySqlStream(baseStream, Encoding, false);

            stream.ResetTimeout((int)Settings.ConnectionTimeout * 1000);

            // read off the welcome packet and parse out it's values
            packet = stream.ReadPacket();
            int protocol         = packet.ReadByte();
            string versionString = packet.ReadString();
            version = DBVersion.Parse(versionString);
            if (!version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            threadId       = packet.ReadInteger(4);
            encryptionSeed = packet.ReadString();

            maxSinglePacket = (256 * 256 * 256) - 1;

            // read in Server capabilities if they are provided
            ClientFlags serverCaps = 0;
            if (packet.HasMoreData)
            {
                serverCaps = (ClientFlags)packet.ReadInteger(2);
            }

            /* New protocol with 16 bytes to describe server characteristics */
            owner.ConnectionCharSetIndex = (int)packet.ReadByte();

            serverStatus = (ServerStatusFlags)packet.ReadInteger(2);

            // Since 5.5, high bits of server caps are stored after status.
            // Previously, it was part of reserved always 0x00 13-byte filler.
            uint serverCapsHigh = (uint)packet.ReadInteger(2);
            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            string seedPart2 = packet.ReadString();
            encryptionSeed += seedPart2;

            string authenticationMethod = "";
            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);

#if !CF
            if ((serverCaps & ClientFlags.SSL) == 0)
            {
                if ((Settings.SslMode != MySqlSslMode.None) &&
                    (Settings.SslMode != MySqlSslMode.Preferred))
                {
                    // Client requires SSL connections.
                    string message = String.Format(Resources.NoServerSSLSupport,
                                                   Settings.Server);
                    throw new MySqlException(message);
                }
            }
            else if (Settings.SslMode != MySqlSslMode.None)
            {
                stream.SendPacket(packet);
                StartSSL();
                packet.Clear();
                packet.WriteInteger((int)connectionFlags, 4);
            }
#endif

            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(8);
            packet.Write(new byte[23]);

            Authenticate(false);

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                stream = new MySqlStream(baseStream, Encoding, true);
            }

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            packet.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;
        }
예제 #8
0
        public override void Open()
        {
            base.Open();

            // connect to one of our specified hosts
            try
            {
#if !CF
                if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory)
                {
                    SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName);
                    str.Open(Settings.ConnectionTimeout);
                    baseStream = str;
                }
                else
                {
#endif
                string pipeName = Settings.PipeName;
                if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe)
                {
                    pipeName = null;
                }
                StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName);
                baseStream = sc.GetStream(Settings.ConnectionTimeout);
#if !CF
            }
#endif
                if (baseStream == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         (int)MySqlErrorCode.UnableToConnectToHost, ex);
            }

            if (baseStream == null)
            {
                throw new MySqlException("Unable to connect to any of the specified MySQL hosts");
            }

            int maxSinglePacket = 255 * 255 * 255;
            stream = new MySqlStream(baseStream, encoding, false);

            // read off the welcome packet and parse out it's values
            stream.OpenPacket();
            protocol = stream.ReadByte();
            string versionString = stream.ReadString();
            version        = DBVersion.Parse(versionString);
            threadId       = stream.ReadInteger(4);
            encryptionSeed = stream.ReadString();

            if (version.isAtLeast(4, 0, 8))
            {
                maxSinglePacket = (256 * 256 * 256) - 1;
            }

            // read in Server capabilities if they are provided
            serverCaps = 0;
            if (stream.HasMoreData)
            {
                serverCaps = (ClientFlags)stream.ReadInteger(2);
            }
            if (version.isAtLeast(4, 1, 1))
            {
                /* New protocol with 16 bytes to describe server characteristics */
                serverCharSetIndex = stream.ReadInteger(1);

                serverStatus = (ServerStatusFlags)stream.ReadInteger(2);
                stream.SkipBytes(13);
                string seedPart2 = stream.ReadString();
                encryptionSeed += seedPart2;
            }

            // based on our settings, set our connection flags
            SetConnectionFlags();

            stream.StartOutput(0, false);
            stream.WriteInteger((int)connectionFlags,
                                version.isAtLeast(4, 1, 0) ? 4 : 2);

#if !CF
            if (connectionString.UseSSL && (serverCaps & ClientFlags.SSL) != 0)
            {
                stream.Flush();

                StartSSL();

                stream.StartOutput(0, false);
                stream.WriteInteger((int)connectionFlags,
                                    version.isAtLeast(4, 1, 0) ? 4 : 2);
            }
#endif

            stream.WriteInteger(maxSinglePacket,
                                version.isAtLeast(4, 1, 0) ? 4 : 3);

            if (version.isAtLeast(4, 1, 1))
            {
                stream.WriteByte(8);
                stream.Write(new byte[23]);
            }

            Authenticate();

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                stream = new MySqlStream(baseStream, encoding, true);
            }

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            stream.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;

            isOpen = true;
        }
예제 #9
0
        public void Open()
        {
            //try
            //{
            //    this.baseStream = StreamCreator.GetStream(this.Settings);
            //    if (this.Settings.IncludeSecurityAsserts)
            //    {
            //        MySqlSecurityPermission.CreatePermissionSet(false).Assert();
            //    }
            //}
            //catch (SecurityException)
            //{
            //    throw;
            //}
            //catch (Exception inner)
            //{
            //    throw new MySqlException(Resources.UnableToConnectToHost, 1042, inner);
            //}
            //if (this.baseStream == null)
            //{
            //    throw new MySqlException(Resources.UnableToConnectToHost, 1042);
            //}
            //this.stream = new MySqlStream(this.baseStream, this.Encoding, false);
            //this.stream.ResetTimeout((int)(this.Settings.ConnectionTimeout * 1000u));
            //this.packet = this.stream.ReadPacket();
            //this.packet.ReadByte();
            //string text = this.packet.ReadString();
            //this.owner.isFabric = text.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            //this.isEnterprise = text.ToLowerInvariant().Contains("-enterprise-");
            //this.version = DBVersion.Parse(text);
            //if (!this.owner.isFabric && !this.version.isAtLeast(5, 0, 0))
            //{
            //    throw new NotSupportedException(Resources.ServerTooOld);
            //}
            //this.threadId = this.packet.ReadInteger(4);
            //byte[] array = this.packet.ReadStringAsBytes();
            //int num = 16777215;
            //ClientFlags clientFlags = (ClientFlags)0uL;
            //if (this.packet.HasMoreData)
            //{
            //    clientFlags = (ClientFlags)((long)this.packet.ReadInteger(2));
            //}
            //this.owner.ConnectionCharSetIndex = (int)this.packet.ReadByte();
            //this.serverStatus = (ServerStatusFlags)this.packet.ReadInteger(2);
            //uint num2 = (uint)this.packet.ReadInteger(2);
            //clientFlags |= (ClientFlags)(num2 << 16);
            //this.packet.Position += 11;
            //byte[] array2 = this.packet.ReadStringAsBytes();
            //this.encryptionSeed = new byte[array.Length + array2.Length];
            //array.CopyTo(this.encryptionSeed, 0);
            //array2.CopyTo(this.encryptionSeed, array.Length);
            //string authMethod;
            //if ((clientFlags & ClientFlags.PLUGIN_AUTH) != (ClientFlags)0uL)
            //{
            //    authMethod = this.packet.ReadString();
            //}
            //else
            //{
            //    authMethod = "mysql_native_password";
            //}
            //this.SetConnectionFlags(clientFlags);
            //this.packet.Clear();
            //this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            //this.packet.WriteInteger((long)num, 4);
            //this.packet.WriteByte(33);
            //this.packet.Write(new byte[23]);
            //if ((clientFlags & ClientFlags.SSL) == (ClientFlags)0uL)
            //{
            //    if (this.Settings.SslMode != MySqlSslMode.None && this.Settings.SslMode != MySqlSslMode.Preferred)
            //    {
            //        throw new MySqlException(string.Format(Resources.NoServerSSLSupport, this.Settings.Server));
            //    }
            //}
            //else if (this.Settings.SslMode != MySqlSslMode.None)
            //{
            //    this.stream.SendPacket(this.packet);
            //    this.StartSSL();
            //    this.packet.Clear();
            //    this.packet.WriteInteger((long)((int)this.connectionFlags), 4);
            //    this.packet.WriteInteger((long)num, 4);
            //    this.packet.WriteByte(33);
            //    this.packet.Write(new byte[23]);
            //}
            //this.Authenticate(authMethod, false);
            //if ((this.connectionFlags & ClientFlags.COMPRESS) != (ClientFlags)0uL)
            //{
            //    this.stream = new MySqlStream(this.baseStream, this.Encoding, true);
            //}
            //this.packet.Version = this.version;
            //this.stream.MaxBlockSize = num;
            try
            {
                baseStream = StreamCreator.GetStream(Settings);
                if (Settings.IncludeSecurityAsserts)
                {
                    MySqlSecurityPermission.CreatePermissionSet(false).Assert();
                }
            }
            catch (System.Security.SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         1042, ex);
            }
            if (baseStream == null)
            {
                throw new MySqlException(Resources.UnableToConnectToHost,
                                         1042);
            }

            int maxSinglePacket = 255 * 255 * 255;

            stream = new MySqlStream(baseStream, Encoding, false);

            stream.ResetTimeout((int)Settings.ConnectionTimeout * 1000);

            // read off the welcome packet and parse out it's values
            packet = stream.ReadPacket();
            int    protocol      = packet.ReadByte();
            string versionString = packet.ReadString();

            owner.isFabric = versionString.EndsWith("fabric", StringComparison.OrdinalIgnoreCase);
            version        = DBVersion.Parse(versionString);
            if (!owner.isFabric && !version.isAtLeast(5, 0, 0))
            {
                throw new NotSupportedException(Resources.ServerTooOld);
            }
            threadId = packet.ReadInteger(4);

            byte[] array = this.packet.ReadStringAsBytes();

            maxSinglePacket = (256 * 256 * 256) - 1;

            // read in Server capabilities if they are provided
            ClientFlags serverCaps = 0;

            if (packet.HasMoreData)
            {
                serverCaps = (ClientFlags)packet.ReadInteger(2);
            }

            /* New protocol with 16 bytes to describe server characteristics */
            owner.ConnectionCharSetIndex = (int)packet.ReadByte();

            serverStatus = (ServerStatusFlags)packet.ReadInteger(2);

            // Since 5.5, high bits of server caps are stored after status.
            // Previously, it was part of reserved always 0x00 13-byte filler.
            uint serverCapsHigh = (uint)packet.ReadInteger(2);

            serverCaps |= (ClientFlags)(serverCapsHigh << 16);

            packet.Position += 11;
            byte[] array2 = this.packet.ReadStringAsBytes();
            this.encryptionSeed = new byte[array.Length + array2.Length];
            array.CopyTo(this.encryptionSeed, 0);
            array2.CopyTo(this.encryptionSeed, array.Length);

            string authenticationMethod = "";

            if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0)
            {
                authenticationMethod = packet.ReadString();
            }
            else
            {
                // Some MyCat versions like 5.1, don't give name of plugin, default to native password.
                authenticationMethod = "mysql_native_password";
            }

            // based on our settings, set our connection flags
            SetConnectionFlags(serverCaps);

            packet.Clear();
            packet.WriteInteger((int)connectionFlags, 4);

            if ((serverCaps & ClientFlags.SSL) == 0)
            {
                if ((Settings.SslMode != MySqlSslMode.None) &&
                    (Settings.SslMode != MySqlSslMode.Preferred))
                {
                    // Client requires SSL connections.
                    string message = String.Format(Resources.NoServerSSLSupport,
                                                   Settings.Server);
                    throw new MySqlException(message);
                }
            }
            else if (Settings.SslMode != MySqlSslMode.None)
            {
                stream.SendPacket(packet);
                StartSSL();
                packet.Clear();
                packet.WriteInteger((int)connectionFlags, 4);
            }

            packet.WriteInteger(maxSinglePacket, 4);
            packet.WriteByte(8);
            packet.Write(new byte[23]);

            Authenticate(authenticationMethod, false);

            // if we are using compression, then we use our CompressedStream class
            // to hide the ugliness of managing the compression
            if ((connectionFlags & ClientFlags.COMPRESS) != 0)
            {
                stream = new MySqlStream(baseStream, Encoding, true);
            }

            // give our stream the server version we are connected to.
            // We may have some fields that are read differently based
            // on the version of the server we are connected to.
            packet.Version      = version;
            stream.MaxBlockSize = maxSinglePacket;
        }
예제 #10
0
 /// <summary>
 /// Opens the client connection.
 /// </summary>
 public virtual void Open()
 {
   this.stream = StreamCreator.GetStream(server, port, null, 10, new DBVersion(), 60);
 }
예제 #11
0
        public async Task DataShouldBeCorrectlySent(
            bool isServer, int[] dataLength)
        {
            var inPipe  = new BufferedPipe(1024);
            var outPipe = new BufferedPipe(1024);

            var r = await StreamCreator.CreateConnectionAndStream(
                isServer, loggerProvider, inPipe, outPipe);

            var totalToSend = dataLength.Aggregate(0, (sum, n) => sum + n);

            var writeTask = Task.Run(async() =>
            {
                byte nr = 0;
                for (var i = 0; i < dataLength.Length; i++)
                {
                    var toSend        = dataLength[i];
                    var isEndOfStream = i == (dataLength.Length - 1);
                    var buffer        = new byte[toSend];
                    for (var j = 0; j < toSend; j++)
                    {
                        buffer[j] = nr;
                        nr++;
                        if (nr > 122)
                        {
                            nr = 0;
                        }
                    }
                    await r.stream.WriteAsync(
                        new ArraySegment <byte>(buffer), isEndOfStream);
                }
            });

            var data   = new byte[totalToSend];
            var offset = 0;

            for (var i = 0; i < dataLength.Length; i++)
            {
                var fh = await outPipe.ReadFrameHeaderWithTimeout();

                Assert.Equal(FrameType.Data, fh.Type);
                Assert.Equal(1u, fh.StreamId);
                var expectEOS = i == dataLength.Length - 1;
                var gotEOS    = (fh.Flags & (byte)DataFrameFlags.EndOfStream) != 0;
                Assert.Equal(expectEOS, gotEOS);
                Assert.Equal(dataLength[i], fh.Length);

                var part = new byte[fh.Length];
                await outPipe.ReadAllWithTimeout(new ArraySegment <byte>(part));

                Array.Copy(part, 0, data, offset, fh.Length);
                offset += fh.Length;
            }

            var doneTask = await Task.WhenAny(writeTask, Task.Delay(250));

            Assert.True(writeTask == doneTask, "Expected write task to finish");

            // Check if the correct data was received
            var expected = 0;

            for (var j = 0; j < totalToSend; j++)
            {
                Assert.Equal(expected, data[j]);
                expected++;
                if (expected > 122)
                {
                    expected = 0;
                }
            }
        }
예제 #12
0
        public async Task DataFramesWithPaddingShouldBeCorrectlyReceived(
            bool isServer, int nrFrames, byte numPadding, int bytesToSend)
        {
            var inPipe    = new BufferedPipe(10 * 1024);
            var outPipe   = new BufferedPipe(10 * 1024);
            var receiveOk = true;

            var settings = Settings.Default;

            settings.MaxFrameSize      = 100 * 1024;
            settings.InitialWindowSize = int.MaxValue;
            var r = await StreamCreator.CreateConnectionAndStream(
                isServer, loggerProvider, inPipe, outPipe,
                localSettings : settings);

            for (var nrSends = 0; nrSends < nrFrames; nrSends++)
            {
                var buf = new byte[1 + bytesToSend + numPadding];
                buf[0] = numPadding;
                byte nr = 0;
                for (var i = 0; i < bytesToSend; i++)
                {
                    buf[1 + i] = nr;
                    nr++;
                    if (nr > 123)
                    {
                        nr = 0;
                    }
                }
                var fh = new FrameHeader
                {
                    Type     = FrameType.Data,
                    StreamId = 1,
                    Flags    = (byte)DataFrameFlags.Padded,
                    Length   = buf.Length,
                };
                await inPipe.WriteFrameHeaderWithTimeout(fh);

                await inPipe.WriteWithTimeout(new ArraySegment <byte>(buf));
            }

            for (var nrSends = 0; nrSends < nrFrames; nrSends++)
            {
                var buf1 = new byte[bytesToSend];
                await r.stream.ReadAllWithTimeout(new ArraySegment <byte>(buf1));

                var expected = 0;
                for (var j = 0; j < bytesToSend; j++)
                {
                    if (buf1[j] != expected)
                    {
                        receiveOk = false;
                    }
                    expected++;
                    if (expected > 123)
                    {
                        expected = 0;
                    }
                }
            }

            Assert.True(receiveOk, "Expected to receive correct data");
        }
예제 #13
0
        public async Task DataFromDataFramesShouldBeReceived(
            bool isServer, int[] dataLength)
        {
            var inPipe  = new BufferedPipe(1024);
            var outPipe = new BufferedPipe(1024);

            var res = await StreamCreator.CreateConnectionAndStream(
                isServer, loggerProvider, inPipe, outPipe);

            var readTask = res.stream.ReadAllToArrayWithTimeout();

            var totalToSend = dataLength.Aggregate(0, (sum, n) => sum + n);

            byte nr = 0;

            for (var i = 0; i < dataLength.Length; i++)
            {
                var toSend        = dataLength[i];
                var isEndOfStream = i == (dataLength.Length - 1);
                var flags         = isEndOfStream ? DataFrameFlags.EndOfStream : 0;
                var fh            = new FrameHeader
                {
                    Type     = FrameType.Data,
                    StreamId = 1,
                    Flags    = (byte)flags,
                    Length   = toSend,
                };
                await inPipe.WriteFrameHeaderWithTimeout(fh);

                var fdata = new byte[toSend];
                for (var j = 0; j < toSend; j++)
                {
                    fdata[j] = nr;
                    nr++;
                    if (nr > 122)
                    {
                        nr = 0;
                    }
                }
                await inPipe.WriteWithTimeout(new ArraySegment <byte>(fdata));

                // Wait for a short amount of time between DATA frames
                if (!isEndOfStream)
                {
                    await Task.Delay(10);
                }
            }

            var doneTask = await Task.WhenAny(
                readTask, Task.Delay(ReadableStreamTestExtensions.ReadTimeout));

            Assert.True(doneTask == readTask, "Expected read task to complete within timeout");

            byte[] receivedData = await readTask;
            Assert.NotNull(receivedData);
            Assert.Equal(totalToSend, receivedData.Length);
            var expected = 0;

            for (var j = 0; j < totalToSend; j++)
            {
                Assert.Equal(expected, receivedData[j]);
                expected++;
                if (expected > 122)
                {
                    expected = 0;
                }
            }
        }
예제 #14
0
 public virtual void Open()
 {
     this.stream = StreamCreator.GetStream(this.server, this.port, null, 10u, default(DBVersion), 60u);
 }
예제 #15
0
 /// <summary>
 /// Opens the client connection.
 /// </summary>
 public async virtual Task Open()
 {
     this.stream = await StreamCreator.GetStream(server, port, null, 10, new DBVersion(), 60);
 }