Exemple #1
0
 internal CloseEventArgs(PayloadData data)
     : base(Opcode.CLOSE, data)
 {
     _code = getCodeFrom (data);
       _reason = getReasonFrom (data);
       _clean = false;
 }
 internal CloseEventArgs(PayloadData payload)
 {
     var data = payload.ApplicationData;
       _code = getCodeFrom (data);
       _reason = getReasonFrom (data);
       _clean = false;
 }
    internal CloseEventArgs ()
    {
      _payloadData = new PayloadData ();
      _rawData = _payloadData.ApplicationData;

      _code = (ushort) CloseStatusCode.NoStatusCode;
      _reason = String.Empty;
    }
        public static OkPayload Create(PayloadData payload)
        {
            var reader = new ByteArrayReader(payload.ArraySegment);
            reader.ReadByte(Signature);
            var affectedRowCount = checked((int) reader.ReadLengthEncodedInteger());
            var lastInsertId = checked((long) reader.ReadLengthEncodedInteger());
            var serverStatus = (ServerStatus) reader.ReadUInt16();
            var warningCount = (int) reader.ReadUInt16();

            return new OkPayload(affectedRowCount, lastInsertId, serverStatus, warningCount);
        }
    internal CloseEventArgs (PayloadData payload)
    {
      var data = payload.ApplicationData;
      var len = data.Length;
      _code = len > 1
              ? data.SubArray (0, 2).ToUInt16 (ByteOrder.Big)
              : (ushort) CloseStatusCode.NoStatusCode;

      _reason = len > 2
                ? Encoding.UTF8.GetString (data.SubArray (2, len - 2))
                : String.Empty;
    }
    internal CloseEventArgs (PayloadData payloadData)
    {
      _payloadData = payloadData;
      _rawData = payloadData.ApplicationData;

      var len = _rawData.Length;
      _code = len > 1
              ? _rawData.SubArray (0, 2).ToUInt16 (ByteOrder.Big)
              : (ushort) CloseStatusCode.NoStatus;

      _reason = len > 2
                ? _rawData.SubArray (2, len - 2).UTF8Decode ()
                : String.Empty;
    }
Exemple #7
0
        public CloseEventArgs(PayloadData data)
            : base(Opcode.CLOSE, data)
        {
            _code = (ushort)CloseStatusCode.NO_STATUS_CODE;
            _reason = String.Empty;
            _wasClean = false;

            if (data.Length >= 2)
                _code = Ext.To<ushort>(Ext.SubArray(data.ToBytes(), 0, 2), ByteOrder.BIG);

            if (data.Length > 2)
            {
                var buffer = Ext.SubArray(data.ToBytes(), 2, (int)(data.Length - 2));
                _reason = Encoding.UTF8.GetString(buffer);
            }
        }
        public virtual async Task <DbDataReader> ExecuteReaderAsync(string commandText, MySqlParameterCollection parameterCollection,
                                                                    CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (m_command.RegisterCancel(cancellationToken))
            {
                m_command.Connection.Session.StartQuerying(m_command);
                m_command.LastInsertedId = -1;
                var statementPreparerOptions = StatementPreparerOptions.None;
                if (m_command.Connection.AllowUserVariables || m_command.CommandType == CommandType.StoredProcedure)
                {
                    statementPreparerOptions |= StatementPreparerOptions.AllowUserVariables;
                }
                if (m_command.Connection.OldGuids)
                {
                    statementPreparerOptions |= StatementPreparerOptions.OldGuids;
                }
                if (m_command.CommandType == CommandType.StoredProcedure)
                {
                    statementPreparerOptions |= StatementPreparerOptions.AllowOutputParameters;
                }
                var preparer = new MySqlStatementPreparer(commandText, parameterCollection, statementPreparerOptions);
                var payload  = new PayloadData(preparer.ParseAndBindParameters());
                try
                {
                    await m_command.Connection.Session.SendAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);

                    return(await MySqlDataReader.CreateAsync(m_command, behavior, ioBehavior).ConfigureAwait(false));
                }
                catch (MySqlException ex) when(ex.Number == (int)MySqlErrorCode.QueryInterrupted && cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException(cancellationToken);
                }
                catch (Exception ex) when(payload.ArraySegment.Count > 4_194_304 && (ex is SocketException || ex is IOException || ex is MySqlProtocolException))
                {
                    // the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet
                    // use "decimal megabytes" (to round up) when creating the exception message
                    int megabytes = payload.ArraySegment.Count / 1_000_000;

                    throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex);
                }
            }
        }
    // Update is called once per frame
    void Update()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            if (Input.GetKey(KeyCode.Escape))
            {
                Application.Quit();
            }
        }

        if (offline && Time.time - lastChange >= dataSpeed)
        {
            currentIndex++;
            PayloadData pd = new PayloadData();
            if (currentIndex >= baseMotorSpeeds.Length)
            {
                currentIndex = 0;
            }
            if (baseMotor != null)
            {
                pd.base_motor_speed = baseMotorSpeeds[currentIndex];
            }
            if (armMotor != null)
            {
                pd.arm_motor_speed = armSpeed[currentIndex];
            }
            if (liftMotor != null)
            {
                pd.lift_motor_speed = liftSpeed[currentIndex];
            }
            if (battery != null)
            {
                pd.battery = batteryValue[currentIndex];
            }
            lastChange = Time.time;
            lastData   = pd;
        }

        if (lastData != null)
        {
            setSensorValues(lastData);
        }
    }
Exemple #10
0
        internal void Stop(byte [] data, bool send)
        {
            lock (_sync) {
                _state = ServerState.ShuttingDown;

                var payload      = new PayloadData(data);
                var args         = new CloseEventArgs(payload);
                var frameAsBytes =
                    send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null;

                foreach (var host in _hosts.Values)
                {
                    host.Sessions.Stop(args, frameAsBytes);
                }

                _hosts.Clear();
                _state = ServerState.Stop;
            }
        }
Exemple #11
0
        private async Task <PayloadData> SendEncryptedPasswordAsync(
            AuthenticationMethodSwitchRequestPayload switchRequest,
            string rsaPublicKey,
            ConnectionSettings cs,
            IOBehavior ioBehavior,
            CancellationToken cancellationToken)
        {
            // load the RSA public key
            RSA rsa;

            try
            {
                rsa = Utility.DecodeX509PublicKey(rsaPublicKey);
            }
            catch (Exception ex)
            {
                throw new MySqlException("Couldn't load server's RSA public key; try using a secure connection instead.", ex);
            }

            // add NUL terminator to password
            var passwordBytes = Encoding.UTF8.GetBytes(cs.Password);

            Array.Resize(ref passwordBytes, passwordBytes.Length + 1);

            using (rsa)
            {
                // XOR the password bytes with the challenge
                AuthPluginData = Utility.TrimZeroByte(switchRequest.Data);
                for (var i = 0; i < passwordBytes.Length; i++)
                {
                    passwordBytes[i] ^= AuthPluginData[i % AuthPluginData.Length];
                }

                // encrypt with RSA public key
                var padding           = switchRequest.Name == "caching_sha2_password" ? RSAEncryptionPadding.Pkcs1 : RSAEncryptionPadding.OaepSHA1;
                var encryptedPassword = rsa.Encrypt(passwordBytes, padding);
                var payload           = new PayloadData(encryptedPassword);
                await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                return(await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false));
            }
        }
Exemple #12
0
        public static InitialHandshakePayload Create(PayloadData payload)
        {
            var reader = new ByteArrayReader(payload.ArraySegment);

            reader.ReadByte(c_protocolVersion);
            var    serverVersion  = reader.ReadNullTerminatedByteString();
            var    connectionId   = reader.ReadInt32();
            var    authPluginData = reader.ReadByteString(8);
            string authPluginName = null;

            reader.ReadByte(0);
            var protocolCapabilities = (ProtocolCapabilities)reader.ReadUInt16();

            if (reader.BytesRemaining > 0)
            {
                var charSet             = (CharacterSet)reader.ReadByte();
                var status              = (ServerStatus)reader.ReadInt16();
                var capabilityFlagsHigh = reader.ReadUInt16();
                protocolCapabilities |= (ProtocolCapabilities)(capabilityFlagsHigh << 16);
                var authPluginDataLength = reader.ReadByte();
                var unused = reader.ReadByteString(10);
                if ((protocolCapabilities & ProtocolCapabilities.SecureConnection) != 0)
                {
                    var authPluginData2 = reader.ReadByteString(Math.Max(13, authPluginDataLength - 8));
                    var concatenated    = new byte[authPluginData.Length + authPluginData2.Length];
                    Buffer.BlockCopy(authPluginData, 0, concatenated, 0, authPluginData.Length);
                    Buffer.BlockCopy(authPluginData2, 0, concatenated, authPluginData.Length, authPluginData2.Length);
                    authPluginData = concatenated;
                }
                if ((protocolCapabilities & ProtocolCapabilities.PluginAuth) != 0)
                {
                    authPluginName = Encoding.UTF8.GetString(reader.ReadNullOrEofTerminatedByteString());
                }
            }

            if (reader.BytesRemaining != 0)
            {
                throw new FormatException("Extra bytes at end of payload.");
            }

            return(new InitialHandshakePayload(protocolCapabilities, serverVersion, connectionId, authPluginData, authPluginName));
        }
Exemple #13
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Command.Length != 0)
            {
                hash ^= Command.GetHashCode();
            }
            if (SeqId != 0L)
            {
                hash ^= SeqId.GetHashCode();
            }
            if (ErrorCode != 0)
            {
                hash ^= ErrorCode.GetHashCode();
            }
            if (PayloadData.Length != 0)
            {
                hash ^= PayloadData.GetHashCode();
            }
            if (ErrorMsg.Length != 0)
            {
                hash ^= ErrorMsg.GetHashCode();
            }
            if (ErrorData.Length != 0)
            {
                hash ^= ErrorData.GetHashCode();
            }
            if (SubBiz.Length != 0)
            {
                hash ^= SubBiz.GetHashCode();
            }
            if (KlinkPushId != 0L)
            {
                hash ^= KlinkPushId.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public byte[] ToArray()
        {
            using (var buff = new MemoryStream())
            {
                var header = (int)Fin;
                header = (header << 1) + (int)Rsv2;
                header = (header << 1) + (int)Rsv3;
                header = (header << 1) + (int)Rsv4;
                header = (header << 4) + (int)Opcode;
                header = (header << 1) + (int)Mask;
                header = (header << 7) + (int)PayloadLength;
                buff.Write(((ushort)header).InternalToByteArray(ByteOrder.Big), 0, 2);

                if (PayloadLength > 125)
                {
                    buff.Write(ExtendedPayloadLength, 0, PayloadLength == 126 ? 2 : 8);
                }

                if (Mask == Mask.On)
                {
                    buff.Write(MaskingKey, 0, 4);
                }

                if (PayloadLength > 0)
                {
                    var bytes = PayloadData.ToArray();
                    if (PayloadLength < 127)
                    {
                        buff.Write(bytes, 0, bytes.Length);
                    }
                    else
                    {
                        buff.WriteBytes(bytes, 1024);
                    }
                }

                buff.Close();
                var a = buff.ToArray();
                return(a);
            }
        }
Exemple #15
0
        // Continues a conversation with the server by sending a reply to a packet received with 'Receive' or 'ReceiveReply'.
        public ValueTask <int> SendReplyAsync(PayloadData payload, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            ValueTask <int> task;

            try
            {
                VerifyConnected();
                task = m_payloadHandler.WritePayloadAsync(payload.ArraySegment, ioBehavior);
            }
            catch (Exception ex)
            {
                task = ValueTaskExtensions.FromException <int>(ex);
            }

            if (task.IsCompletedSuccessfully)
            {
                return(task);
            }

            return(new ValueTask <int>(task.AsTask().ContinueWith(TryAsyncContinuation, cancellationToken, TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)));
        }
Exemple #16
0
        public static AuthenticationMethodSwitchRequestPayload Create(PayloadData payload)
        {
            var reader = new ByteArrayReader(payload.ArraySegment);

            reader.ReadByte(Signature);
            string name;

            byte[] data;
            if (payload.ArraySegment.Count == 1)
            {
                // if the packet is just the header byte (0xFE), it's an "Old Authentication Method Switch Request Packet"
                // (possibly sent by a server that doesn't support CLIENT_PLUGIN_AUTH)
                name = "mysql_old_password";
                data = new byte[0];
            }
            else
            {
                name = Encoding.UTF8.GetString(reader.ReadNullTerminatedByteString());
                data = reader.ReadByteArray(reader.BytesRemaining);
            }
            return(new AuthenticationMethodSwitchRequestPayload(name, data));
        }
Exemple #17
0
        private PayloadData TryAsyncContinuation(Task <ArraySegment <byte> > task)
        {
            if (task.IsFaulted)
            {
                SetFailed();
            }
            ArraySegment <byte> bytes;

            try
            {
                bytes = task.GetAwaiter().GetResult();
            }
            catch (MySqlException ex) when(ex.Number == (int)MySqlErrorCode.CommandTimeoutExpired)
            {
                HandleTimeout();
                throw;
            }
            var payload = new PayloadData(bytes);

            payload.ThrowIfError();
            return(payload);
        }
        public static ErrorPayload Create(PayloadData payload)
        {
            var reader = new ByteArrayReader(payload.ArraySegment);

            reader.ReadByte(Signature);

            var    errorCode = reader.ReadUInt16();
            var    stateMarker = Encoding.ASCII.GetString(reader.ReadByteString(1));
            string state, message;

            if (stateMarker == "#")
            {
                state   = Encoding.ASCII.GetString(reader.ReadByteString(5));
                message = Encoding.UTF8.GetString(reader.ReadByteString(payload.ArraySegment.Count - 9));
            }
            else
            {
                state   = "HY000";
                message = stateMarker + Encoding.UTF8.GetString(reader.ReadByteString(payload.ArraySegment.Count - 4));
            }
            return(new ErrorPayload(errorCode, state, message));
        }
        internal void Stop(byte [] data, bool send)
        {
            lock (_sync)
            {
                _state = ServerState.SHUTDOWN;

                var payload      = new PayloadData(data);
                var args         = new CloseEventArgs(payload);
                var frameAsBytes = send
                         ? WsFrame.CreateCloseFrame(Mask.UNMASK, payload).ToByteArray()
                         : null;

                foreach (var host in _serviceHosts.Values)
                {
                    host.Sessions.Stop(args, frameAsBytes);
                }

                _serviceHosts.Clear();

                _state = ServerState.STOP;
            }
        }
Exemple #20
0
        public virtual async Task <DbDataReader> ExecuteReaderAsync(string commandText, MyCatParameterCollection parameterCollection,
                                                                    CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            m_command.VerifyValid();
            var connection = m_command.Connection;

            connection.HasActiveReader = true;

            MyCatDataReader reader = null;

            try
            {
                m_command.LastInsertedId = -1;
                var statementPreparerOptions = StatementPreparerOptions.None;
                if (connection.AllowUserVariables || m_command.CommandType == CommandType.StoredProcedure)
                {
                    statementPreparerOptions |= StatementPreparerOptions.AllowUserVariables;
                }
                if (connection.OldGuids)
                {
                    statementPreparerOptions |= StatementPreparerOptions.OldGuids;
                }
                var preparer = new MyCatStatementPreparer(commandText, parameterCollection, statementPreparerOptions);
                var payload  = new PayloadData(preparer.ParseAndBindParameters());
                await connection.Session.SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                reader = await MyCatDataReader.CreateAsync(m_command, behavior, ioBehavior, cancellationToken).ConfigureAwait(false);

                return(reader);
            }
            finally
            {
                if (reader == null)
                {
                    // received an error from MySQL and never created an active reader
                    connection.HasActiveReader = false;
                }
            }
        }
Exemple #21
0
        protected override async Task <DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
        {
            VerifyValid();
            Connection.HasActiveReader = true;

            MySqlDataReader reader = null;

            try
            {
                LastInsertedId = -1;
                var connection = (MySqlConnection)DbConnection;
                var statementPreparerOptions = StatementPreparerOptions.None;
                if (connection.AllowUserVariables)
                {
                    statementPreparerOptions |= StatementPreparerOptions.AllowUserVariables;
                }
                if (connection.OldGuids)
                {
                    statementPreparerOptions |= StatementPreparerOptions.OldGuids;
                }
                var preparer = new MySqlStatementPreparer(CommandText, m_parameterCollection, statementPreparerOptions);
                preparer.BindParameters();
                var payload = new PayloadData(new ArraySegment <byte>(Payload.CreateEofStringPayload(CommandKind.Query, preparer.PreparedSql)));
                await Session.SendAsync(payload, cancellationToken).ConfigureAwait(false);

                reader = await MySqlDataReader.CreateAsync(this, behavior, cancellationToken).ConfigureAwait(false);

                return(reader);
            }
            finally
            {
                if (reader == null)
                {
                    // received an error from MySQL and never created an active reader
                    Connection.HasActiveReader = false;
                }
            }
        }
Exemple #22
0
        private void stop(PayloadData payloadData, bool send)
        {
            var bytes = send
                                                        ? WebSocketFrame.CreateCloseFrame(payloadData, false).ToArray()
                                                        : null;

            lock (_sync)
            {
                _state = ServerState.ShuttingDown;

#if NETCF
                _sweepTimer.Stop();
#else
                _sweepTimer.Enabled = _clean;
#endif
                foreach (var session in _sessions.Values.ToList())
                {
                    session.Context.WebSocket.Close(payloadData, bytes);
                }

                _state = ServerState.Stop;
            }
        }
        private async Task ResetConnectionAsync(CancellationToken cancellationToken)
        {
            if (m_session.ServerVersion.Version.CompareTo(ServerVersions.SupportsResetConnection) >= 0)
            {
                await m_session.SendAsync(ResetConnectionPayload.Create(), cancellationToken).ConfigureAwait(false);

                var payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);

                OkPayload.Create(payload);
            }
            else
            {
                // optimistically hash the password with the challenge from the initial handshake (supported by MariaDB; doesn't appear to be supported by MySQL)
                var hashedPassword = AuthenticationUtility.HashPassword(m_session.AuthPluginData, 0, m_connectionStringBuilder.Password);
                var payload        = ChangeUserPayload.Create(m_connectionStringBuilder.UserID, hashedPassword, m_database);
                await m_session.SendAsync(payload, cancellationToken).ConfigureAwait(false);

                payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);

                if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
                {
                    // if the server didn't support the hashed password; rehash with the new challenge
                    var switchRequest = AuthenticationMethodSwitchRequestPayload.Create(payload);
                    if (switchRequest.Name != "mysql_native_password")
                    {
                        throw new NotSupportedException("Only 'mysql_native_password' authentication method is supported.");
                    }
                    hashedPassword = AuthenticationUtility.HashPassword(switchRequest.Data, 0, m_connectionStringBuilder.Password);
                    payload        = new PayloadData(new ArraySegment <byte>(hashedPassword));
                    await m_session.SendReplyAsync(payload, cancellationToken).ConfigureAwait(false);

                    payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);
                }
                OkPayload.Create(payload);
            }
        }
    public void setSensorValues(PayloadData data)
    {
        //Debug.Log("Base: " + data.base_motor_speed);
        //Debug.Log("Arm: " + data.arm_motor_speed);
        //Debug.Log("Lift: " + data.lift_motor_speed);
        // Debug.Log("Battery: " + data.battery);

        if (baseMotor != null)
        {
            baseMotor.value = data.base_motor_speed;
        }
        if (armMotor != null)
        {
            armMotor.value = data.arm_motor_speed;
        }
        if (liftMotor != null)
        {
            liftMotor.value = data.lift_motor_speed;
        }
        if (battery != null)
        {
            battery.value = data.battery;
        }
    }
        private bool ReadAsyncRemainder(PayloadData payload)
        {
            if (EofPayload.IsEof(payload))
            {
                var eof = EofPayload.Create(payload);
                m_state = eof.ServerStatus.HasFlag(ServerStatus.MoreResultsExist) ? State.HasMoreData : State.NoMoreData;
                return(false);
            }

            var reader = new ByteArrayReader(payload.ArraySegment);

            for (var column = 0; column < m_dataOffsets.Length; column++)
            {
                var length = checked ((int)ReadFieldLength(reader));
                m_dataLengths[column] = length == -1 ? 0 : length;
                m_dataOffsets[column] = length == -1 ? -1 : reader.Offset;
                reader.Offset        += m_dataLengths[column];
            }

            m_currentRow = payload.ArraySegment.Array;

            m_state = State.ReadingRows;
            return(true);
        }
 public FieldErrorEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
        private void close(PayloadData payload, bool send, bool wait)
        {
            lock (_forConn)
            {
                if (_readyState == WebSocketState.Closing || _readyState == WebSocketState.Closed)
                {
                    return;
                }

                _readyState = WebSocketState.Closing;
            }

            var e = new CloseEventArgs(payload);
            e.WasClean =
              closeHandshake(
                  send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
                  wait ? 1000 : 0,
                  closeServerResources);

            _readyState = WebSocketState.Closed;
            try
            {
                OnClose.Emit(this, e);
            }
            catch (Exception ex)
            {
                error("An exception has occurred while OnClose.", ex);
            }
        }
Exemple #28
0
 private void closeAsync(PayloadData payload, bool send, bool wait)
 {
     Action<PayloadData, bool, bool> closer = close;
       closer.BeginInvoke (payload, send, wait, ar => closer.EndInvoke (ar), null);
 }
Exemple #29
0
 public RetractBinStatusEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
        public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
        {
            Reset();

            try
            {
                while (true)
                {
                    var payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                    var firstByte = payload.HeaderByte;
                    if (firstByte == OkPayload.Signature)
                    {
                        var ok = OkPayload.Create(payload.Span, Session.SupportsDeprecateEof, Session.SupportsSessionTrack);
                        RecordsAffected = (RecordsAffected ?? 0) + ok.AffectedRowCount;
                        LastInsertId    = unchecked ((long)ok.LastInsertId);
                        WarningCount    = ok.WarningCount;
                        if (ok.NewSchema is object)
                        {
                            Connection.Session.DatabaseOverride = ok.NewSchema;
                        }
                        ColumnDefinitions = null;
                        ColumnTypes       = null;
                        State             = (ok.ServerStatus & ServerStatus.MoreResultsExist) == 0
                                                        ? ResultSetState.NoMoreData
                                                        : ResultSetState.HasMoreData;
                        if (State == ResultSetState.NoMoreData)
                        {
                            break;
                        }
                    }
                    else if (firstByte == LocalInfilePayload.Signature)
                    {
                        try
                        {
                            if (!Connection.AllowLoadLocalInfile)
                            {
                                throw new NotSupportedException("To use LOAD DATA LOCAL INFILE, set AllowLoadLocalInfile=true in the connection string. See https://fl.vu/mysql-load-data");
                            }
                            var localInfile = LocalInfilePayload.Create(payload.Span);
                            if (!IsHostVerified(Connection) &&
                                !localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal))
                            {
                                throw new NotSupportedException("Use SourceStream or SslMode >= VerifyCA for LOAD DATA LOCAL INFILE. See https://fl.vu/mysql-load-data");
                            }

                            using var stream = localInfile.FileName.StartsWith(MySqlBulkLoader.StreamPrefix, StringComparison.Ordinal) ?
                                               MySqlBulkLoader.GetAndRemoveStream(localInfile.FileName) :
                                               File.OpenRead(localInfile.FileName);
                            var readBuffer = new byte[65536];
                            int byteCount;
                            while ((byteCount = await stream.ReadAsync(readBuffer, 0, readBuffer.Length).ConfigureAwait(false)) > 0)
                            {
                                payload = new PayloadData(new ArraySegment <byte>(readBuffer, 0, byteCount));
                                await Session.SendReplyAsync(payload, ioBehavior, CancellationToken.None).ConfigureAwait(false);
                            }
                        }
                        catch (Exception ex)
                        {
                            // store the exception, to be thrown after reading the response packet from the server
                            ReadResultSetHeaderException = new MySqlException("Error during LOAD DATA LOCAL INFILE", ex);
                        }

                        await Session.SendReplyAsync(EmptyPayload.Instance, ioBehavior, CancellationToken.None).ConfigureAwait(false);
                    }
                    else
                    {
                        int ReadColumnCount(ReadOnlySpan <byte> span)
                        {
                            var reader       = new ByteArrayReader(span);
                            var columnCount_ = (int)reader.ReadLengthEncodedInteger();

                            if (reader.BytesRemaining != 0)
                            {
                                throw new MySqlException("Unexpected data at end of column_count packet; see https://github.com/mysql-net/MySqlConnector/issues/324");
                            }
                            return(columnCount_);
                        }
                        var columnCount = ReadColumnCount(payload.Span);

                        // reserve adequate space to hold a copy of all column definitions (but note that this can be resized below if we guess too small)
                        Utility.Resize(ref m_columnDefinitionPayloads, columnCount * 96);

                        ColumnDefinitions = new ColumnDefinitionPayload[columnCount];
                        ColumnTypes       = new MySqlDbType[columnCount];

                        for (var column = 0; column < ColumnDefinitions.Length; column++)
                        {
                            payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                            var payloadLength = payload.Span.Length;

                            // 'Session.ReceiveReplyAsync' reuses a shared buffer; make a copy so that the column definitions can always be safely read at any future point
                            if (m_columnDefinitionPayloadUsedBytes + payloadLength > m_columnDefinitionPayloads.Count)
                            {
                                Utility.Resize(ref m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes + payloadLength);
                            }
                            payload.Span.CopyTo(m_columnDefinitionPayloads.Array.AsSpan().Slice(m_columnDefinitionPayloadUsedBytes));

                            var columnDefinition = ColumnDefinitionPayload.Create(new ResizableArraySegment <byte>(m_columnDefinitionPayloads, m_columnDefinitionPayloadUsedBytes, payloadLength));
                            ColumnDefinitions[column]           = columnDefinition;
                            ColumnTypes[column]                 = TypeMapper.ConvertToMySqlDbType(columnDefinition, treatTinyAsBoolean: Connection.TreatTinyAsBoolean, guidFormat: Connection.GuidFormat);
                            m_columnDefinitionPayloadUsedBytes += payloadLength;
                        }

                        if (!Session.SupportsDeprecateEof)
                        {
                            payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);

                            EofPayload.Create(payload.Span);
                        }

                        if (ColumnDefinitions.Length == (Command?.OutParameters?.Count + 1) && ColumnDefinitions[0].Name == SingleCommandPayloadCreator.OutParameterSentinelColumnName)
                        {
                            ContainsCommandParameters = true;
                        }
                        LastInsertId = -1;
                        WarningCount = 0;
                        State        = ResultSetState.ReadResultSetHeader;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ReadResultSetHeaderException = ex;
            }
            finally
            {
                BufferState = State;
            }
        }
Exemple #31
0
        private void close(ushort code, string reason)
        {
            var data = new List<byte>(Ext.ToBytes(code, ByteOrder.BIG));
            if (!Ext.IsNullOrEmpty(reason))
            {
                var buffer = Encoding.UTF8.GetBytes(reason);
                data.AddRange(buffer);
            }

            var payloadData = new PayloadData(data.ToArray());
            if (payloadData.Length > 125)
            {
                var msg = "A Close frame must have a payload length of 125 bytes or less.";
                onError(msg);
                return;
            }

            close(payloadData);
        }
Exemple #32
0
 private static ushort getCodeFrom(PayloadData data)
 {
     var appData = data.ApplicationData;
       return appData.Length >= 2
      ? appData.SubArray (0, 2).To<ushort> (ByteOrder.BIG)
      : (ushort) CloseStatusCode.NO_STATUS_CODE;
 }
Exemple #33
0
 public TrackDetectedEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
        private void close(PayloadData payload, bool send, bool wait)
        {
            lock (_forClose)
              {
            if (_readyState == WebSocketState.CLOSING || _readyState == WebSocketState.CLOSED)
              return;

            _readyState = WebSocketState.CLOSING;
              }

              _logger.Trace ("Start closing handshake.");

              var args = new CloseEventArgs (payload);
              args.WasClean = _client
                    ? close (
                        send ? WsFrame.CreateCloseFrame (Mask.MASK, payload).ToByteArray () : null,
                        wait ? 5000 : 0,
                        closeClientResources)
                    : close (
                        send ? WsFrame.CreateCloseFrame (Mask.UNMASK, payload).ToByteArray () : null,
                        wait ? 1000 : 0,
                        closeServerResources);

              _readyState = WebSocketState.CLOSED;
              OnClose.Emit (this, args);

              _logger.Trace ("End closing handshake.");
        }
Exemple #35
0
 internal virtual void  SetPayloadData(System.String field, int numFieldInstancesToSkip, byte[] data, int offset, int length)
 {
     fieldToData[field] = new PayloadData(numFieldInstancesToSkip, data, offset, length);
 }
    private IEnumerable <DestinationData> getAvailableDestinations(RocketData rocket, PayloadData payload)
    {
        if (rocket == null || payload == null)
        {
            return(Enumerable.Empty <DestinationData>());
        }
        int excessRocketPower = rocket.power - payload.weight;

        return(registry.destinations
               .Where(destination => payload.validDestinations.Contains(destination))
               .OrderBy(arg => arg.requiredPower));
    }
Exemple #37
0
 private WsFrame createFrame(Fin fin, Opcode opcode, PayloadData payloadData)
 {
     return _isClient
            ? new WsFrame(fin, opcode, payloadData)
            : new WsFrame(fin, opcode, Mask.UNMASK, payloadData);
 }
Exemple #38
0
 private void pong(PayloadData data)
 {
     var frame = createFrame(Fin.FINAL, Opcode.PONG, data);
     send(frame);
 }
Exemple #39
0
 private void pong(string data)
 {
     var payloadData = new PayloadData(data);
     pong(payloadData);
 }
 public MediaAutoRetractedEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
 internal MessageEventArgs(Opcode opcode, PayloadData payload)
 {
     _opcode = opcode;
       _rawData = payload.ApplicationData;
       _data = convertToString (opcode, _rawData);
 }
Exemple #42
0
        private static WsFrame createFrame(
      Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool client)
        {
            var mask = client ? Mask.MASK : Mask.UNMASK;
              var frame = new WsFrame (fin, opcode, mask, payloadData, compressed);

              return frame;
        }
Exemple #43
0
        private static string getReasonFrom(PayloadData data)
        {
            var appData = data.ApplicationData;
              var appDataLen = appData.Length;
              if (appDataLen <= 2)
            return String.Empty;

              var reason = appData.SubArray (2, appDataLen - 2);
              return Encoding.UTF8.GetString (reason);
        }
Exemple #44
0
        private void close(PayloadData data)
        {
            _logger.Debug ("Is this thread background?: " + Thread.CurrentThread.IsBackground);

              var sent = false;
              CloseEventArgs args = null;
              lock (_forClose)
              {
            if (_readyState == WebSocketState.CLOSING || _readyState == WebSocketState.CLOSED)
              return;

            var current = _readyState;
            _readyState = WebSocketState.CLOSING;

            args = new CloseEventArgs (data);
            if (current == WebSocketState.CONNECTING)
            {
              if (!_client)
              {
            close (HttpStatusCode.BadRequest);
            return;
              }
            }
            else
            {
              if (!data.ContainsReservedCloseStatusCode)
            sent = send (createControlFrame (Opcode.CLOSE, data, _client));
            }
              }

              var received = Thread.CurrentThread.IsBackground ||
                     (_exitReceiving != null && _exitReceiving.WaitOne (5 * 1000));

              var released = closeResources ();
              args.WasClean = sent && received && released;
              _logger.Debug ("Was clean?: " + args.WasClean);

              _readyState = WebSocketState.CLOSED;
              OnClose.Emit (this, args);

              _logger.Trace ("Exit close method.");
        }
            static Row?ScanRowAsyncRemainder(ResultSet this_, PayloadData payload, Row?row_)
            {
                if (payload.HeaderByte == EofPayload.Signature)
                {
                    var span = payload.Span;
                    if (this_.Session.SupportsDeprecateEof && OkPayload.IsOk(span, this_.Session.SupportsDeprecateEof))
                    {
                        var ok = OkPayload.Create(span, this_.Session.SupportsDeprecateEof, this_.Session.SupportsSessionTrack);
                        this_.BufferState = (ok.ServerStatus & ServerStatus.MoreResultsExist) == 0 ? ResultSetState.NoMoreData : ResultSetState.HasMoreData;
                        return(null);
                    }
                    if (!this_.Session.SupportsDeprecateEof && EofPayload.IsEof(payload))
                    {
                        var eof = EofPayload.Create(span);
                        this_.BufferState = (eof.ServerStatus & ServerStatus.MoreResultsExist) == 0 ? ResultSetState.NoMoreData : ResultSetState.HasMoreData;
                        return(null);
                    }
                }

                if (row_ is null)
                {
                    bool isBinaryRow = false;
                    if (payload.HeaderByte == 0 && !this_.Connection.IgnorePrepare)
                    {
                        // this might be a binary row, but it might also be a text row whose first column is zero bytes long; try reading
                        // the row as a series of length-encoded values (the text format) to see if this might plausibly be a text row
                        var isTextRow   = false;
                        var reader      = new ByteArrayReader(payload.Span);
                        var columnCount = 0;
                        while (reader.BytesRemaining > 0)
                        {
                            int length;
                            var firstByte = reader.ReadByte();
                            if (firstByte == 0xFB)
                            {
                                // NULL
                                length = 0;
                            }
                            else if (firstByte == 0xFC)
                            {
                                // two-byte length-encoded integer
                                if (reader.BytesRemaining < 2)
                                {
                                    break;
                                }
                                length = unchecked ((int)reader.ReadFixedLengthUInt32(2));
                            }
                            else if (firstByte == 0xFD)
                            {
                                // three-byte length-encoded integer
                                if (reader.BytesRemaining < 3)
                                {
                                    break;
                                }
                                length = unchecked ((int)reader.ReadFixedLengthUInt32(3));
                            }
                            else if (firstByte == 0xFE)
                            {
                                // eight-byte length-encoded integer
                                if (reader.BytesRemaining < 8)
                                {
                                    break;
                                }
                                length = checked ((int)reader.ReadFixedLengthUInt64(8));
                            }
                            else if (firstByte == 0xFF)
                            {
                                // invalid length prefix
                                break;
                            }
                            else
                            {
                                // single-byte length
                                length = firstByte;
                            }

                            if (reader.BytesRemaining < length)
                            {
                                break;
                            }
                            reader.Offset += length;
                            columnCount++;

                            if (columnCount == this_.ColumnDefinitions !.Length)
                            {
                                // if we used up all the bytes reading exactly 'ColumnDefinitions' length-encoded columns, then assume this is a text row
                                if (reader.BytesRemaining == 0)
                                {
                                    isTextRow = true;
                                }
                                break;
                            }
                        }

                        isBinaryRow = !isTextRow;
                    }
                    row_ = isBinaryRow ? (Row) new BinaryRow(this_) : new TextRow(this_);
                }
                row_.SetData(payload.Memory);
                this_.m_hasRows   = true;
                this_.BufferState = ResultSetState.ReadingRows;
                return(row_);
            }
Exemple #46
0
			internal virtual void  SetPayloadData(System.String field, byte[] data, int offset, int length)
			{
				fieldToData[field] = new PayloadData(0, data, offset, length);
			}
 internal CloseEventArgs ()
 {
   _code = (ushort) CloseStatusCode.NoStatus;
   _payloadData = PayloadData.Empty;
 }
Exemple #48
0
			internal virtual void  SetPayloadData(System.String field, int numFieldInstancesToSkip, byte[] data, int offset, int length)
			{
				fieldToData[field] = new PayloadData(numFieldInstancesToSkip, data, offset, length);
			}
Exemple #49
0
        private void close(PayloadData payload, bool send, bool wait)
        {
            lock (_forConn) {
            if (_readyState == WebSocketState.Closing || _readyState == WebSocketState.Closed) {
              _logger.Info ("Closing the WebSocket connection has already been done.");
              return;
            }

            _readyState = WebSocketState.Closing;
              }

              _logger.Trace ("Start closing handshake.");

              var args = new CloseEventArgs (payload);
              args.WasClean =
            _client
            ? closeHandshake (
            send ? WsFrame.CreateCloseFrame (Mask.Mask, payload).ToByteArray () : null,
            wait ? 5000 : 0,
            closeClientResources)
            : closeHandshake (
            send ? WsFrame.CreateCloseFrame (Mask.Unmask, payload).ToByteArray () : null,
            wait ? 1000 : 0,
            closeServerResources);

              _logger.Trace ("End closing handshake.");

              _readyState = WebSocketState.Closed;
              try {
            OnClose.Emit (this, args);
              }
              catch (Exception ex) {
            _logger.Fatal (ex.ToString ());
            error ("An exception has occurred while OnClose.");
              }
        }
Exemple #50
0
 private void closeHandshake(PayloadData data)
 {
     var args = new CloseEventArgs(data);
     var frame = createFrame(Fin.FINAL, Opcode.CLOSE, data);
     send(frame);
     onClose(args);
 }
Exemple #51
0
 internal virtual void  SetPayloadData(System.String field, byte[] data, int offset, int length)
 {
     fieldToData[field] = new PayloadData(0, data, offset, length);
 }
        internal void Stop(byte [] data, bool send)
        {
            lock (_sync) {
            _state = ServerState.ShuttingDown;

            var payload = new PayloadData (data);
            var args = new CloseEventArgs (payload);
            var frameAsBytes = send
                         ? WsFrame.CreateCloseFrame (Mask.Unmask, payload).ToByteArray ()
                         : null;

            foreach (var host in _hosts.Values)
              host.Sessions.Stop (args, frameAsBytes);

            _hosts.Clear ();
            _state = ServerState.Stop;
              }
        }
Exemple #53
0
 public CardActionEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
 internal MessageEventArgs(Opcode opcode, PayloadData data)
 {
     _opcode = opcode;
       _rawData = data.ApplicationData;
 }
Exemple #55
0
 public MediaPresentedUnsolicitedEvent(string RequestId, PayloadData Payload)
     : base(RequestId, Payload)
 {
 }
Exemple #56
0
 private void pong(PayloadData data)
 {
     var frame = createControlFrame (Opcode.PONG, data, _client);
       send (frame);
 }
Exemple #57
0
        private void close(PayloadData data)
        {
            #if DEBUG
              Console.WriteLine("WS: Info@close: Current thread IsBackground?: {0}", Thread.CurrentThread.IsBackground);
              #endif
              lock(_forClose)
              {
            // Whether the closing handshake has been started already?
            if (_readyState == WsState.CLOSING || _readyState == WsState.CLOSED)
              return;

            // Whether the closing handshake on server is started before the connection has been established?
            if (_readyState == WsState.CONNECTING && !_client)
            {
              sendResponseHandshake(HttpStatusCode.BadRequest);
              onClose(new CloseEventArgs(data));

              return;
            }

            _readyState = WsState.CLOSING;
              }

              // Whether a payload data contains the close status code which must not be set for send?
              if (data.ContainsReservedCloseStatusCode)
              {
            onClose(new CloseEventArgs(data));
            return;
              }

              closeHandshake(data);
              #if DEBUG
              Console.WriteLine("WS: Info@close: Exit close method.");
              #endif
        }
Exemple #58
0
        private static WsFrame createControlFrame(Opcode opcode, PayloadData payloadData, bool client)
        {
            var mask = client ? Mask.MASK : Mask.UNMASK;
              var frame = new WsFrame (Fin.FINAL, opcode, mask, payloadData);

              return frame;
        }
 private int minPayloadDestinationPower(PayloadData payload)
 {
     return(payload.validDestinations.Min(arg => arg.requiredPower));
 }
Exemple #60
0
        private void closeHandshake(PayloadData data)
        {
            var args = new CloseEventArgs(data);
              var frame = createControlFrame(Opcode.CLOSE, data, _client);
              if (send(frame))
            args.WasClean = true;

              onClose(args);
        }