Example #1
0
        private void Negotiate(MySqlStream channel)
        {
            var body = channel.ReadPacket();
            HandshakeInitializationPacket handshakePacket = new HandshakeInitializationPacket();

            handshakePacket.FromBytes(body);
            ConnectionId = handshakePacket.ThreadId;

            _logger.LogInformation("Handshake initialization packet received, prepare the client authentication packet to send");

            ClientAuthenticationPacket clientAuth = new ClientAuthenticationPacket();

            clientAuth.CharsetNumber = CharsetNumber;
            clientAuth.UserName      = UserName;
            clientAuth.Password      = Password;
            clientAuth.DatabaseName  = DefaultSchema;
            clientAuth.ScrumbleBuff  = handshakePacket.EncryptionSeed;

            var clientAuthPkgBody = clientAuth.ToBytes();

            channel.SendPacket(clientAuthPkgBody);
            _logger.LogInformation("Client Authentication Packet is sent out.");

            channel.ReadPacket();
        }
        public void Connect()
        {
            var endpoint = new IPEndPoint(IPAddress.Parse(config.host), config.port);

            socket.Connect(endpoint);

            byte[] buffer = new byte[512];
            int    count  = socket.Receive(buffer);

            if (count < 512)
            {
                writer.Rewrite();
                parser.LoadNewBuffer(buffer, count);
                handshake = new HandshakePacket();
                handshake.ParsePacket(parser);
                this.threadId = handshake.threadId;
                byte[] token = MakeToken(config.password, GetScrollbleBuffer(handshake.scrambleBuff1, handshake.scrambleBuff2));
                writer.IncrementPacketNumber();

                //------------------------------------------
                authPacket = new ClientAuthenticationPacket();
                authPacket.SetValues(config.user, token, config.database, handshake.protocol41);
                authPacket.WritePacket(writer);

                byte[] sendBuff    = writer.ToArray();
                byte[] receiveBuff = new byte[512];
                int    sendNum     = socket.Send(sendBuff);
                int    receiveNum  = socket.Receive(receiveBuff);

                parser.LoadNewBuffer(receiveBuff, receiveNum);
                if (receiveBuff[4] == 255)
                {
                    ErrPacket errPacket = new ErrPacket();
                    errPacket.ParsePacket(parser);
                    return;
                }
                else
                {
                    OkPacket okPacket = new OkPacket(handshake.protocol41);
                    okPacket.ParsePacket(parser);
                }
                writer.Rewrite();
                GetMaxAllowedPacket();
                if (MAX_ALLOWED_PACKET > 0)
                {
                    writer.SetMaxAllowedPacket(MAX_ALLOWED_PACKET);
                }
            }
        }