Search in sources :

Example 1 with OkPacket

use of com.mysql.cj.protocol.a.result.OkPacket in project ABC by RuiPinto96274.

the class NativeProtocol method readServerStatusForResultSets.

@SuppressWarnings("unchecked")
public final <T> T readServerStatusForResultSets(NativePacketPayload rowPacket, boolean saveOldStatus) {
    T result = null;
    if (rowPacket.isEOFPacket()) {
        // read EOF packet
        // skip the packet signature header
        rowPacket.setPosition(1);
        this.warningCount = (int) rowPacket.readInteger(IntegerDataType.INT2);
        if (this.warningCount > 0) {
            // this is a 'latch', it's reset by sendCommand()
            this.hadWarnings = true;
        }
        this.serverSession.setStatusFlags((int) rowPacket.readInteger(IntegerDataType.INT2), saveOldStatus);
        checkTransactionState();
    } else {
        // read OK packet
        OkPacket ok = OkPacket.parse(rowPacket, this.serverSession.getCharsetSettings().getErrorMessageEncoding());
        result = (T) ok;
        this.serverSession.setStatusFlags(ok.getStatusFlags(), saveOldStatus);
        this.serverSession.getServerSessionStateController().setSessionStateChanges(ok.getSessionStateChanges());
        checkTransactionState();
        this.warningCount = ok.getWarningCount();
        if (this.warningCount > 0) {
            // this is a 'latch', it's reset by sendCommand()
            this.hadWarnings = true;
        }
    }
    return result;
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket)

Example 2 with OkPacket

use of com.mysql.cj.protocol.a.result.OkPacket in project ABC by RuiPinto96274.

the class TextResultsetReader method read.

@Override
public Resultset read(int maxRows, boolean streamResults, NativePacketPayload resultPacket, ColumnDefinition metadata, ProtocolEntityFactory<Resultset, NativePacketPayload> resultSetFactory) throws IOException {
    Resultset rs = null;
    // try {
    long columnCount = resultPacket.readInteger(IntegerDataType.INT_LENENC);
    if (columnCount > 0) {
        // Build a result set with rows.
        // Read in the column information
        ColumnDefinition cdef = this.protocol.read(ColumnDefinition.class, new ColumnDefinitionFactory(columnCount, metadata));
        // There is no EOF packet after fields when CLIENT_DEPRECATE_EOF is set
        if (!this.protocol.getServerSession().isEOFDeprecated()) {
            this.protocol.skipPacket();
        // this.protocol.readServerStatusForResultSets(this.protocol.readPacket(this.protocol.getReusablePacket()), true);
        }
        ResultsetRows rows = null;
        if (!streamResults) {
            TextRowFactory trf = new TextRowFactory(this.protocol, cdef, resultSetFactory.getResultSetConcurrency(), false);
            ArrayList<ResultsetRow> rowList = new ArrayList<>();
            ResultsetRow row = this.protocol.read(ResultsetRow.class, trf);
            while (row != null) {
                if ((maxRows == -1) || (rowList.size() < maxRows)) {
                    rowList.add(row);
                }
                row = this.protocol.read(ResultsetRow.class, trf);
            }
            rows = new ResultsetRowsStatic(rowList, cdef);
        } else {
            rows = new ResultsetRowsStreaming<>(this.protocol, cdef, false, resultSetFactory);
            this.protocol.setStreamingData(rows);
        }
        /*
             * Build ResultSet from ResultsetRows
             */
        rs = resultSetFactory.createFromProtocolEntity(rows);
    } else {
        // check for file request
        if (columnCount == NativePacketPayload.NULL_LENGTH) {
            String charEncoding = this.protocol.getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue();
            String fileName = resultPacket.readString(StringSelfDataType.STRING_TERM, this.protocol.getServerSession().getCharsetSettings().doesPlatformDbCharsetMatches() ? charEncoding : null);
            resultPacket = this.protocol.sendFileToServer(fileName);
        }
        /*
             * Build ResultSet with no ResultsetRows
             */
        // read and parse OK packet
        // oldStatus set in sendCommand()
        OkPacket ok = this.protocol.readServerStatusForResultSets(resultPacket, false);
        rs = resultSetFactory.createFromProtocolEntity(ok);
    }
    return rs;
// } catch (IOException ioEx) {
// throw SQLError.createCommunicationsException(this.protocol.getConnection(), this.protocol.getPacketSentTimeHolder().getLastPacketSentTime(),
// this.protocol.getPacketReceivedTimeHolder().getLastPacketReceivedTime(), ioEx, this.protocol.getExceptionInterceptor());
// }
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket) ArrayList(java.util.ArrayList) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) Resultset(com.mysql.cj.protocol.Resultset)

Example 3 with OkPacket

use of com.mysql.cj.protocol.a.result.OkPacket in project JavaSegundasQuintas by ecteruel.

the class NativeProtocol method readServerStatusForResultSets.

@SuppressWarnings("unchecked")
public final <T> T readServerStatusForResultSets(NativePacketPayload rowPacket, boolean saveOldStatus) {
    T result = null;
    if (rowPacket.isEOFPacket()) {
        // read EOF packet
        // skip the packet signature header
        rowPacket.setPosition(1);
        this.warningCount = (int) rowPacket.readInteger(IntegerDataType.INT2);
        if (this.warningCount > 0) {
            // this is a 'latch', it's reset by sendCommand()
            this.hadWarnings = true;
        }
        this.serverSession.setStatusFlags((int) rowPacket.readInteger(IntegerDataType.INT2), saveOldStatus);
        checkTransactionState();
    } else {
        // read OK packet
        OkPacket ok = OkPacket.parse(rowPacket, this.serverSession.getCharsetSettings().getErrorMessageEncoding());
        result = (T) ok;
        this.serverSession.setStatusFlags(ok.getStatusFlags(), saveOldStatus);
        this.serverSession.getServerSessionStateController().setSessionStateChanges(ok.getSessionStateChanges());
        checkTransactionState();
        this.warningCount = ok.getWarningCount();
        if (this.warningCount > 0) {
            // this is a 'latch', it's reset by sendCommand()
            this.hadWarnings = true;
        }
    }
    return result;
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket)

Example 4 with OkPacket

use of com.mysql.cj.protocol.a.result.OkPacket in project JavaSegundasQuintas by ecteruel.

the class BinaryResultsetReader method read.

@Override
public Resultset read(int maxRows, boolean streamResults, NativePacketPayload resultPacket, ColumnDefinition metadata, ProtocolEntityFactory<Resultset, NativePacketPayload> resultSetFactory) throws IOException {
    Resultset rs = null;
    // try {
    long columnCount = resultPacket.readInteger(IntegerDataType.INT_LENENC);
    if (columnCount > 0) {
        // Build a result set with rows.
        // Read in the column information
        ColumnDefinition cdef = this.protocol.read(ColumnDefinition.class, new MergingColumnDefinitionFactory(columnCount, metadata));
        boolean isCursorPossible = this.protocol.getPropertySet().getBooleanProperty(PropertyKey.useCursorFetch).getValue() && resultSetFactory.getResultSetType() == Type.FORWARD_ONLY && resultSetFactory.getFetchSize() > 0;
        // If CLIENT_DEPRECATE_EOF is set, there is no way to tell which one, OK or ResultsetRow, is the next packet, so it should be read with a special caching method.
        if (isCursorPossible || !this.protocol.getServerSession().isEOFDeprecated()) {
            // Read the next packet but leave it in the reader cache. In case it's not the OK or EOF one it will be read again by ResultSet factories.
            NativePacketPayload rowPacket = this.protocol.probeMessage(this.protocol.getReusablePacket());
            this.protocol.checkErrorMessage(rowPacket);
            if (rowPacket.isResultSetOKPacket() || rowPacket.isEOFPacket()) {
                // Consume the OK/EOF packet from the reader cache and read the status flags from it;
                // The SERVER_STATUS_CURSOR_EXISTS flag should indicate the cursor state in this case.
                rowPacket = this.protocol.readMessage(this.protocol.getReusablePacket());
                this.protocol.readServerStatusForResultSets(rowPacket, true);
            } else {
                // If it's not an OK/EOF then the cursor is not created and this recent packet is a row.
                // Retain the packet in the reader cache.
                isCursorPossible = false;
            }
        }
        ResultsetRows rows = null;
        if (isCursorPossible && this.protocol.getServerSession().cursorExists()) {
            rows = new ResultsetRowsCursor(this.protocol, cdef);
        } else if (!streamResults) {
            BinaryRowFactory brf = new BinaryRowFactory(this.protocol, cdef, resultSetFactory.getResultSetConcurrency(), false);
            ArrayList<ResultsetRow> rowList = new ArrayList<>();
            ResultsetRow row = this.protocol.read(ResultsetRow.class, brf);
            while (row != null) {
                if ((maxRows == -1) || (rowList.size() < maxRows)) {
                    rowList.add(row);
                }
                row = this.protocol.read(ResultsetRow.class, brf);
            }
            rows = new ResultsetRowsStatic(rowList, cdef);
        } else {
            rows = new ResultsetRowsStreaming<>(this.protocol, cdef, true, resultSetFactory);
            this.protocol.setStreamingData(rows);
        }
        /*
             * Build ResultSet from ResultsetRows
             */
        rs = resultSetFactory.createFromProtocolEntity(rows);
    } else {
        // check for file request
        if (columnCount == NativePacketPayload.NULL_LENGTH) {
            String charEncoding = this.protocol.getPropertySet().getStringProperty(PropertyKey.characterEncoding).getValue();
            String fileName = resultPacket.readString(StringSelfDataType.STRING_TERM, this.protocol.getServerSession().getCharsetSettings().doesPlatformDbCharsetMatches() ? null : charEncoding);
            resultPacket = this.protocol.sendFileToServer(fileName);
        }
        /*
             * Build ResultSet with no ResultsetRows
             */
        // read and parse OK packet
        // oldStatus set in sendCommand()
        OkPacket ok = this.protocol.readServerStatusForResultSets(resultPacket, false);
        rs = resultSetFactory.createFromProtocolEntity(ok);
    }
    return rs;
}
Also used : OkPacket(com.mysql.cj.protocol.a.result.OkPacket) ArrayList(java.util.ArrayList) ResultsetRows(com.mysql.cj.protocol.ResultsetRows) ResultsetRowsStreaming(com.mysql.cj.protocol.a.result.ResultsetRowsStreaming) ColumnDefinition(com.mysql.cj.protocol.ColumnDefinition) ResultsetRow(com.mysql.cj.protocol.ResultsetRow) ResultsetRowsCursor(com.mysql.cj.protocol.a.result.ResultsetRowsCursor) ResultsetRowsStatic(com.mysql.cj.protocol.a.result.ResultsetRowsStatic) Resultset(com.mysql.cj.protocol.Resultset)

Example 5 with OkPacket

use of com.mysql.cj.protocol.a.result.OkPacket in project aws-mysql-jdbc by awslabs.

the class NativeAuthenticationProvider method proceedHandshakeWithPluggableAuthentication.

/**
 * Performs an authentication handshake to authorize connection to a given database as a given MySQL user.
 * This can happen upon initial connection to the server, after receiving Auth Challenge Packet, or
 * at any moment during the connection life-time via a Change User request.
 *
 * This method will use registered authentication plugins as requested by the server.
 *
 * @param challenge
 *            the Auth Challenge Packet received from server if
 *            this method is used during the initial connection.
 *            Otherwise null.
 */
private void proceedHandshakeWithPluggableAuthentication(final NativePacketPayload challenge) {
    ServerSession serverSession = this.protocol.getServerSession();
    if (this.authenticationPlugins == null) {
        loadAuthenticationPlugins();
    }
    boolean forChangeUser = true;
    if (challenge != null) {
        this.serverDefaultAuthenticationPluginName = challenge.readString(StringSelfDataType.STRING_TERM, "ASCII");
        forChangeUser = false;
    }
    serverSession.getCharsetSettings().configurePreHandshake(forChangeUser);
    /*
         * Select the initial plugin:
         * Choose the client-side default authentication plugin, if explicitely specified, otherwise choose the server-side default authentication plugin.
         */
    String pluginName;
    if (this.clientDefaultAuthenticationPluginExplicitelySet) {
        pluginName = this.clientDefaultAuthenticationPluginName;
    } else {
        pluginName = this.serverDefaultAuthenticationPluginName != null ? this.serverDefaultAuthenticationPluginName : this.clientDefaultAuthenticationPluginName;
    }
    AuthenticationPlugin<NativePacketPayload> plugin = getAuthenticationPlugin(pluginName);
    if (plugin == null) {
        /* Use default if there is no plugin for pluginName. */
        pluginName = this.clientDefaultAuthenticationPluginName;
        plugin = getAuthenticationPlugin(pluginName);
    }
    boolean skipPassword = false;
    if (pluginName.equals(Sha256PasswordPlugin.PLUGIN_NAME) && !pluginName.equals(this.clientDefaultAuthenticationPluginName) && !this.protocol.getSocketConnection().isSSLEstablished() && this.propertySet.getStringProperty(PropertyKey.serverRSAPublicKeyFile).getValue() == null && !this.propertySet.getBooleanProperty(PropertyKey.allowPublicKeyRetrieval).getValue()) {
        /*
             * Fall back to client default if plugin is 'sha256_password' but required conditions for this to work aren't met.
             * If client default is other than 'sha256_password', this will result in an immediate authentication switch request, allowing for other plugins to
             * authenticate successfully. If client default is 'sha256_password' then the authentication will fail as expected. In both cases user's password
             * won't be sent to avoid subjecting it to lesser security levels.
             */
        plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
        skipPassword = true;
    }
    checkConfidentiality(plugin);
    // Servers not affected by Bug#70865 expect the Change User Request containing a correct answer to seed sent by the server during the initial handshake,
    // thus we reuse it here. Servers affected by Bug#70865 will just ignore it and send the Auth Switch.
    NativePacketPayload fromServer = new NativePacketPayload(StringUtils.getBytes(this.seed));
    String sourceOfAuthData = this.serverDefaultAuthenticationPluginName;
    NativePacketPayload lastSent = null;
    NativePacketPayload lastReceived = challenge;
    ArrayList<NativePacketPayload> toServer = new ArrayList<>();
    boolean firstPacket = true;
    // MFA authentication factor
    int mfaNthFactor = 1;
    /* Max iterations number */
    int counter = 100;
    while (0 < counter--) {
        /*
             * call plugin
             */
        plugin.setAuthenticationParameters(this.username, skipPassword ? null : getNthFactorPassword(mfaNthFactor));
        plugin.setSourceOfAuthData(sourceOfAuthData);
        plugin.nextAuthenticationStep(fromServer, toServer);
        /*
             * send response to server
             */
        if (firstPacket) {
            NativePacketPayload authData = toServer.isEmpty() ? new NativePacketPayload(0) : toServer.get(0);
            if (forChangeUser) {
                // write COM_CHANGE_USER Packet
                lastSent = createChangeUserPacket(serverSession, plugin.getProtocolPluginName(), authData);
                this.protocol.send(lastSent, lastSent.getPosition());
            } else {
                // write HandshakeResponse packet
                lastSent = createHandshakeResponsePacket(serverSession, plugin.getProtocolPluginName(), authData);
                this.protocol.send(lastSent, lastSent.getPosition());
            }
            firstPacket = false;
        } else if (!toServer.isEmpty()) {
            // write AuthSwitchResponse packet or raw packet(s)
            toServer.forEach(b -> this.protocol.send(b, b.getPayloadLength()));
        }
        /*
             * read packet from server
             */
        lastReceived = this.protocol.checkErrorMessage();
        if (lastReceived.isOKPacket()) {
            // read OK packet
            OkPacket ok = OkPacket.parse(lastReceived, null);
            serverSession.setStatusFlags(ok.getStatusFlags(), true);
            serverSession.getServerSessionStateController().setSessionStateChanges(ok.getSessionStateChanges());
            // authentication complete
            plugin.destroy();
            break;
        } else if (lastReceived.isAuthMethodSwitchRequestPacket()) {
            // read AuthSwitchRequest Packet
            skipPassword = false;
            pluginName = lastReceived.readString(StringSelfDataType.STRING_TERM, "ASCII");
            if (plugin.getProtocolPluginName().equals(pluginName)) {
                // just reset the current one
                plugin.reset();
            } else {
                // get new plugin
                plugin.destroy();
                plugin = getAuthenticationPlugin(pluginName);
                if (plugin == null) {
                    throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { pluginName }), getExceptionInterceptor());
                }
            }
            checkConfidentiality(plugin);
            fromServer = new NativePacketPayload(lastReceived.readBytes(StringSelfDataType.STRING_EOF));
        } else if (lastReceived.isAuthNextFactorPacket()) {
            // authentication not done yet, there's another MFA iteration
            mfaNthFactor++;
            skipPassword = false;
            pluginName = lastReceived.readString(StringSelfDataType.STRING_TERM, "ASCII");
            if (plugin.getProtocolPluginName().equals(pluginName)) {
                // just reset the current one
                plugin.reset();
            } else {
                // get new plugin
                plugin.destroy();
                plugin = getAuthenticationPlugin(pluginName);
                if (plugin == null) {
                    throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { pluginName }), getExceptionInterceptor());
                }
            }
            checkConfidentiality(plugin);
            fromServer = new NativePacketPayload(lastReceived.readBytes(StringSelfDataType.STRING_EOF));
        } else {
            // read raw (from AuthMoreData) packet
            if (!this.protocol.versionMeetsMinimum(5, 5, 16)) {
                lastReceived.setPosition(lastReceived.getPosition() - 1);
            }
            fromServer = new NativePacketPayload(lastReceived.readBytes(StringSelfDataType.STRING_EOF));
        }
        sourceOfAuthData = pluginName;
    }
    if (counter == 0) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("CommunicationsException.TooManyAuthenticationPluginNegotiations"), getExceptionInterceptor());
    }
    this.protocol.afterHandshake();
    if (!this.useConnectWithDb) {
        this.protocol.changeDatabase(this.database);
    }
}
Also used : StringSelfDataType(com.mysql.cj.protocol.a.NativeConstants.StringSelfDataType) ExceptionFactory(com.mysql.cj.exceptions.ExceptionFactory) StringLengthDataType(com.mysql.cj.protocol.a.NativeConstants.StringLengthDataType) HashMap(java.util.HashMap) MysqlNativePasswordPlugin(com.mysql.cj.protocol.a.authentication.MysqlNativePasswordPlugin) UnableToConnectException(com.mysql.cj.exceptions.UnableToConnectException) UsernameCallback(com.mysql.cj.callback.UsernameCallback) ArrayList(java.util.ArrayList) Constants(com.mysql.cj.Constants) AuthenticationPlugin(com.mysql.cj.protocol.AuthenticationPlugin) Protocol(com.mysql.cj.protocol.Protocol) AuthenticationProvider(com.mysql.cj.protocol.AuthenticationProvider) CachingSha2PasswordPlugin(com.mysql.cj.protocol.a.authentication.CachingSha2PasswordPlugin) Sha256PasswordPlugin(com.mysql.cj.protocol.a.authentication.Sha256PasswordPlugin) Map(java.util.Map) SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) LinkedList(java.util.LinkedList) RuntimeProperty(com.mysql.cj.conf.RuntimeProperty) AuthenticationKerberosClient(com.mysql.cj.protocol.a.authentication.AuthenticationKerberosClient) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) PropertySet(com.mysql.cj.conf.PropertySet) ServerSession(com.mysql.cj.protocol.ServerSession) Messages(com.mysql.cj.Messages) AuthenticationLdapSaslClientPlugin(com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin) MysqlCallbackHandler(com.mysql.cj.callback.MysqlCallbackHandler) AuthenticationOciClient(com.mysql.cj.protocol.a.authentication.AuthenticationOciClient) AwsIamAuthenticationTokenHelper(com.mysql.cj.protocol.a.authentication.AwsIamAuthenticationTokenHelper) MysqlOldPasswordPlugin(com.mysql.cj.protocol.a.authentication.MysqlOldPasswordPlugin) OkPacket(com.mysql.cj.protocol.a.result.OkPacket) List(java.util.List) IntegerDataType(com.mysql.cj.protocol.a.NativeConstants.IntegerDataType) ExceptionInterceptor(com.mysql.cj.exceptions.ExceptionInterceptor) StringUtils(com.mysql.cj.util.StringUtils) MysqlClearPasswordPlugin(com.mysql.cj.protocol.a.authentication.MysqlClearPasswordPlugin) AwsIamClearAuthenticationPlugin(com.mysql.cj.protocol.a.authentication.AwsIamClearAuthenticationPlugin) Collections(java.util.Collections) PropertyKey(com.mysql.cj.conf.PropertyKey) AwsIamAuthenticationPlugin(com.mysql.cj.protocol.a.authentication.AwsIamAuthenticationPlugin) ServerSession(com.mysql.cj.protocol.ServerSession) OkPacket(com.mysql.cj.protocol.a.result.OkPacket) ArrayList(java.util.ArrayList) WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException)

Aggregations

OkPacket (com.mysql.cj.protocol.a.result.OkPacket)12 ArrayList (java.util.ArrayList)9 ColumnDefinition (com.mysql.cj.protocol.ColumnDefinition)6 Resultset (com.mysql.cj.protocol.Resultset)6 ResultsetRow (com.mysql.cj.protocol.ResultsetRow)6 ResultsetRows (com.mysql.cj.protocol.ResultsetRows)6 ResultsetRowsStatic (com.mysql.cj.protocol.a.result.ResultsetRowsStatic)6 WrongArgumentException (com.mysql.cj.exceptions.WrongArgumentException)3 ServerSession (com.mysql.cj.protocol.ServerSession)3 ResultsetRowsCursor (com.mysql.cj.protocol.a.result.ResultsetRowsCursor)3 ResultsetRowsStreaming (com.mysql.cj.protocol.a.result.ResultsetRowsStreaming)3 Constants (com.mysql.cj.Constants)1 Messages (com.mysql.cj.Messages)1 MysqlCallbackHandler (com.mysql.cj.callback.MysqlCallbackHandler)1 UsernameCallback (com.mysql.cj.callback.UsernameCallback)1 SslMode (com.mysql.cj.conf.PropertyDefinitions.SslMode)1 PropertyKey (com.mysql.cj.conf.PropertyKey)1 PropertySet (com.mysql.cj.conf.PropertySet)1 RuntimeProperty (com.mysql.cj.conf.RuntimeProperty)1 ExceptionFactory (com.mysql.cj.exceptions.ExceptionFactory)1