Class StandardClient

  • All Implemented Interfaces:
    java.lang.AutoCloseable, Client
    Direct Known Subclasses:
    ReplayClient

    public class StandardClient
    extends java.lang.Object
    implements Client, java.lang.AutoCloseable
    Connection client
    • Field Detail

      • logger

        private static final Logger logger
      • MAX_AUTHENTICATION_SWITCH

        private static final int MAX_AUTHENTICATION_SWITCH
        maximum number of authentication switch requests a server may send during connection
        See Also:
        Constant Field Values
      • exceptionFactory

        protected final ExceptionFactory exceptionFactory
        connection exception factory
      • REDIRECT_PATTERN

        private static final java.util.regex.Pattern REDIRECT_PATTERN
      • socket

        private java.net.Socket socket
        connection socket: the TLS socket once TLS is negotiated, the transport socket before
      • unixSocketTransport

        private boolean unixSocketTransport
        whether the transport is a unix domain socket (a MitM-proof connection method)
      • compressionSequence

        private final MutableByte compressionSequence
      • disablePipeline

        private final boolean disablePipeline
      • context

        protected Context context
        connection context
      • writer

        protected Writer writer
        packet writer
      • closed

        private boolean closed
      • reader

        private Reader reader
      • certFingerprint

        private byte[] certFingerprint
      • socketTimeout

        private int socketTimeout
      • connectDeadlineNs

        private final long connectDeadlineNs
      • redirectConsumer

        private final java.util.function.Consumer<java.lang.String> redirectConsumer
    • Constructor Detail

      • StandardClient

        public StandardClient​(Configuration conf,
                              HostAddress hostAddress,
                              ClosableLock lock,
                              boolean skipPostCommands)
                       throws java.sql.SQLException
        Constructor
        Parameters:
        conf - configuration
        hostAddress - host
        lock - thread locker
        skipPostCommands - must connection post command be skipped
        Throws:
        java.sql.SQLException - if connection fails
    • Method Detail

      • setupConnection

        private void setupConnection​(boolean skipPostCommands)
                              throws java.sql.SQLException,
                                     java.io.IOException
        Throws:
        java.sql.SQLException
        java.io.IOException
      • setupCompression

        private void setupCompression​(java.io.InputStream in,
                                      java.io.OutputStream out,
                                      long clientCapabilities,
                                      long threadId)
      • handleSSLConnection

        private javax.net.ssl.SSLSocket handleSSLConnection​(InitialHandshakePacket handshake,
                                                            long clientCapabilities)
                                                     throws java.sql.SQLException,
                                                            java.io.IOException
        Throws:
        java.sql.SQLException
        java.io.IOException
      • validateServerSslCapability

        private void validateServerSslCapability()
                                          throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • sendSslRequest

        private void sendSslRequest​(InitialHandshakePacket handshake,
                                    long clientCapabilities)
                             throws java.io.IOException
        Throws:
        java.io.IOException
      • createSslSocket

        private javax.net.ssl.SSLSocket createSslSocket​(Configuration conf,
                                                        TlsSocketPlugin socketPlugin,
                                                        javax.net.ssl.TrustManager[] trustManagers)
                                                 throws java.sql.SQLException,
                                                        java.io.IOException
        Throws:
        java.sql.SQLException
        java.io.IOException
      • configureSslSocket

        private void configureSslSocket​(javax.net.ssl.SSLSocket sslSocket,
                                        Configuration conf)
                                 throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • handleSslHandshake

        private void handleSslHandshake​(javax.net.ssl.SSLSocket sslSocket,
                                        javax.net.ssl.TrustManager[] trustManagers)
                                 throws java.io.IOException
        Throws:
        java.io.IOException
      • requiresHostnameVerification

        private boolean requiresHostnameVerification​(SslMode sslMode)
      • verifyHostname

        private void verifyHostname​(javax.net.ssl.SSLSocket sslSocket,
                                    TlsSocketPlugin socketPlugin)
                             throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • configureTimeout

        private void configureTimeout()
                               throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • handleServerHandshake

        private InitialHandshakePacket handleServerHandshake()
                                                      throws java.sql.SQLException,
                                                             java.io.IOException
        Throws:
        java.sql.SQLException
        java.io.IOException
      • throwHandshakeError

        private void throwHandshakeError​(ReadableByteBuf buf)
                                  throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • initializeContext

        private void initializeContext​(InitialHandshakePacket handshake,
                                       long clientCapabilities)
      • handleAuthentication

        private void handleAuthentication​(InitialHandshakePacket handshake,
                                          long clientCapabilities)
                                   throws java.io.IOException,
                                          java.sql.SQLException
        Throws:
        java.io.IOException
        java.sql.SQLException
      • handleConnectionError

        private void handleConnectionError​(java.sql.SQLException e)
                                    throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • handleTimeoutError

        private void handleTimeoutError​(java.net.SocketTimeoutException e)
                                 throws java.sql.SQLTimeoutException
        Throws:
        java.sql.SQLTimeoutException
      • handleIOError

        private void handleIOError​(java.io.IOException e)
                            throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • sendHandshakeResponse

        private void sendHandshakeResponse​(InitialHandshakePacket handshake,
                                           long clientCapabilities,
                                           Credential credential,
                                           java.lang.String authType)
                                    throws java.io.IOException
        Throws:
        java.io.IOException
      • connectDeadlineReached

        static boolean connectDeadlineReached​(long deadlineNs,
                                              int connectTimeout)
        Indicate if the connection phase has exhausted the connectTimeout budget. connectTimeout is applied as a socket timeout during connection, so it bounds each individual read, but not their number: without this check a malicious server can keep a client in the authentication phase forever by sending an endless stream of authentication switch requests.
        Parameters:
        deadlineNs - monotonic deadline (System.nanoTime() based)
        connectTimeout - configured connect timeout, in milliseconds, zero meaning no timeout
        Returns:
        true if connectTimeout is set and the deadline is reached
      • authenticationHandler

        public void authenticationHandler​(Credential credential,
                                          HostAddress hostAddress)
                                   throws java.io.IOException,
                                          java.sql.SQLException
        Parameters:
        credential - credential
        hostAddress - host address
        Throws:
        java.io.IOException - if any socket error occurs
        java.sql.SQLException - if any other kind of issue occurs
      • validateFingerPrint

        private static boolean validateFingerPrint​(AuthenticationPlugin authPlugin,
                                                   byte[] validationHash,
                                                   byte[] fingerPrint,
                                                   Credential credential,
                                                   byte[] seed)
      • redirectByDefault

        private boolean redirectByDefault()
        Without permitRedirect, redirection is followed only on a fully verified TLS connection.
      • redirect

        public void redirect​(java.lang.String redirectUrl)
      • hidePassword

        public static java.lang.String hidePassword​(java.lang.String redirectUrl)
        Mask the password of a redirection url (scheme://user:password@host...) so the credentials a server embeds in redirect_url are not written to the logs.
        Parameters:
        redirectUrl - redirection url
        Returns:
        url with the password component replaced by ***
      • assignStream

        private void assignStream​(java.io.OutputStream out,
                                  java.io.InputStream in,
                                  Configuration conf,
                                  java.lang.Long threadId)
      • destroySocket

        protected void destroySocket()
        Closing socket in case of Connection error after socket creation.
      • handleTimezone

        private void handleTimezone()
                             throws java.sql.SQLException
        load server timezone and ensure this corresponds to client timezone
        Throws:
        java.sql.SQLException - if any socket error.
      • postConnectionQueries

        private void postConnectionQueries()
                                    throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • createSessionVariableQuery

        public java.lang.String createSessionVariableQuery​(Context context)
        Creates a query string for setting session variables based on context and configuration.
        Parameters:
        context - the connection context
        Returns:
        query string for setting session variables or null if no variables need to be set
      • addAutoCommitCommand

        private void addAutoCommitCommand​(Context context,
                                          java.util.List<java.lang.String> commands)
      • isReliableConnectionFlag

        private boolean isReliableConnectionFlag​(Context context)
      • isAutoCommitUpdateRequired

        private boolean isAutoCommitUpdateRequired​(Context context,
                                                   boolean canRelyOnConnectionFlag)
      • addTruncationCommand

        private void addTruncationCommand​(java.util.List<java.lang.String> commands)
      • addSessionTrackingCommand

        private void addSessionTrackingCommand​(Context context,
                                               java.util.List<java.lang.String> commands)
      • addTimeZoneCommand

        private void addTimeZoneCommand​(Context context,
                                        java.util.List<java.lang.String> commands)
      • addFixedOffsetTimeZone

        private void addFixedOffsetTimeZone​(java.time.ZoneId connectionZoneId,
                                            java.util.List<java.lang.String> commands)
      • addTransactionIsolationCommand

        private void addTransactionIsolationCommand​(Context context,
                                                    java.util.List<java.lang.String> commands)
      • addReadOnlyCommand

        private void addReadOnlyCommand​(Context context,
                                        java.util.List<java.lang.String> commands)
      • addCharsetCommand

        private void addCharsetCommand​(Context context,
                                       java.util.List<java.lang.String> commands)
      • isDefaultCharsetSufficient

        private boolean isDefaultCharsetSufficient​(Context context)
      • addCustomSessionVariables

        private void addCustomSessionVariables​(java.util.List<java.lang.String> commands)
      • buildFinalQuery

        private java.lang.String buildFinalQuery​(java.util.List<java.lang.String> commands)
      • setReadOnly

        public void setReadOnly​(boolean readOnly)
                         throws java.sql.SQLException
        Description copied from interface: Client
        Switch to a writer/read-only connection, no effet on mono-connection
        Specified by:
        setReadOnly in interface Client
        Parameters:
        readOnly - must use read-only connection
        Throws:
        java.sql.SQLException - if any error occurs
      • sendQuery

        public int sendQuery​(ClientMessage message)
                      throws java.sql.SQLException
        Send client message to server
        Parameters:
        message - client message
        Returns:
        number of command send
        Throws:
        java.sql.SQLException - if socket error occurs
      • execute

        public java.util.List<Completion> execute​(ClientMessage message,
                                                  boolean canRedo)
                                           throws java.sql.SQLException
        Description copied from interface: Client
        Send client message and read result
        Specified by:
        execute in interface Client
        Parameters:
        message - client message
        canRedo - can client message be redone in case of failover
        Returns:
        results
        Throws:
        java.sql.SQLException - if execution fails
      • execute

        public java.util.List<Completion> execute​(ClientMessage message,
                                                  Statement stmt,
                                                  boolean canRedo)
                                           throws java.sql.SQLException
        Description copied from interface: Client
        Send client message and read result
        Specified by:
        execute in interface Client
        Parameters:
        message - client message
        stmt - statement
        canRedo - can client message be redone in case of failover
        Returns:
        results
        Throws:
        java.sql.SQLException - if execution fails
      • executePipeline

        public java.util.List<Completion> executePipeline​(ClientMessage[] messages,
                                                          Statement stmt,
                                                          int fetchSize,
                                                          long maxRows,
                                                          int resultSetConcurrency,
                                                          int resultSetType,
                                                          boolean closeOnCompletion,
                                                          boolean canRedo)
                                                   throws java.sql.SQLException
        Description copied from interface: Client
        Send client messages pipelining and read result
        Specified by:
        executePipeline in interface Client
        Parameters:
        messages - client message
        stmt - statement
        fetchSize - fetch size
        maxRows - maximum number of rows. 0 = all
        resultSetConcurrency - concurrency
        resultSetType - result-set type
        closeOnCompletion - close statement on completion
        canRedo - can client message be redone in case of failover
        Returns:
        results
        Throws:
        java.sql.SQLException - if any error occurs
      • execute

        public java.util.List<Completion> execute​(ClientMessage message,
                                                  Statement stmt,
                                                  int fetchSize,
                                                  long maxRows,
                                                  int resultSetConcurrency,
                                                  int resultSetType,
                                                  boolean closeOnCompletion,
                                                  boolean canRedo)
                                           throws java.sql.SQLException
        Description copied from interface: Client
        Send client message and read result
        Specified by:
        execute in interface Client
        Parameters:
        message - client message
        stmt - statement
        fetchSize - fetch size
        maxRows - maximum number of rows. 0 = all
        resultSetConcurrency - concurrency
        resultSetType - result-set type
        closeOnCompletion - close statement on completion
        canRedo - can client message be redone in case of failover
        Returns:
        results
        Throws:
        java.sql.SQLException - if any error occurs
      • readResponse

        public java.util.List<Completion> readResponse​(Statement stmt,
                                                       ClientMessage message,
                                                       int fetchSize,
                                                       long maxRows,
                                                       int resultSetConcurrency,
                                                       int resultSetType,
                                                       boolean closeOnCompletion)
                                                throws java.sql.SQLException
        Read server responses for a client message
        Parameters:
        stmt - statement that issue the message
        message - client message sent
        fetchSize - fetch size
        maxRows - maximum number of rows
        resultSetConcurrency - concurrency
        resultSetType - result-set type
        closeOnCompletion - close statement on resultset completion
        Returns:
        list of result
        Throws:
        java.sql.SQLException - if any error occurs
      • readResponse

        public void readResponse​(ClientMessage message)
                          throws java.sql.SQLException
        Read server response
        Parameters:
        message - client message that was sent
        Throws:
        java.sql.SQLException - if any error occurs
      • closePrepare

        public void closePrepare​(Prepare prepare)
                          throws java.sql.SQLException
        Description copied from interface: Client
        Close prepare command
        Specified by:
        closePrepare in interface Client
        Parameters:
        prepare - prepare command
        Throws:
        java.sql.SQLException - if any error occurs
      • readStreamingResults

        public void readStreamingResults​(java.util.List<Completion> completions,
                                         int fetchSize,
                                         long maxRows,
                                         int resultSetConcurrency,
                                         int resultSetType,
                                         boolean closeOnCompletion)
                                  throws java.sql.SQLException
        Description copied from interface: Client
        Read results
        Specified by:
        readStreamingResults in interface Client
        Parameters:
        completions - List that will have the new results
        fetchSize - fetch size
        maxRows - maximum number of rows. 0 = all
        resultSetConcurrency - concurrency
        resultSetType - result-set type
        closeOnCompletion - close statement on completion
        Throws:
        java.sql.SQLException - if any error occurs
      • readResults

        private void readResults​(Statement stmt,
                                 ClientMessage message,
                                 java.util.List<Completion> completions,
                                 int fetchSize,
                                 long maxRows,
                                 int resultSetConcurrency,
                                 int resultSetType,
                                 boolean closeOnCompletion)
                          throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • readPacket

        public Completion readPacket​(ClientMessage message)
                              throws java.sql.SQLException
        Read a MySQL packet from socket
        Parameters:
        message - client message issuing the result
        Returns:
        a mysql result
        Throws:
        java.sql.SQLException - if any error occurs
      • readPacket

        public Completion readPacket​(Statement stmt,
                                     ClientMessage message,
                                     int fetchSize,
                                     long maxRows,
                                     int resultSetConcurrency,
                                     int resultSetType,
                                     boolean closeOnCompletion)
                              throws java.sql.SQLException
        Read server response packet.
        Parameters:
        stmt - current statement (null if internal)
        message - current message
        fetchSize - default fetch size
        maxRows - maximum row number
        resultSetConcurrency - concurrency
        resultSetType - type
        closeOnCompletion - must resultset close statement on completion
        Returns:
        Completion
        Throws:
        java.sql.SQLException - if any exception
        See Also:
        server response packets
      • checkNotClosed

        protected void checkNotClosed()
                               throws java.sql.SQLException
        Throw an exception if client is closed
        Throws:
        java.sql.SQLException - if closed
      • closeSocket

        private void closeSocket()
      • isClosed

        public boolean isClosed()
        Description copied from interface: Client
        Is client closed
        Specified by:
        isClosed in interface Client
        Returns:
        close flag
      • getContext

        public Context getContext()
        Description copied from interface: Client
        Get connection context
        Specified by:
        getContext in interface Client
        Returns:
        connection context
      • abort

        public void abort​(java.util.concurrent.Executor executor)
                   throws java.sql.SQLException
        Description copied from interface: Client
        Abort current connection
        Specified by:
        abort in interface Client
        Parameters:
        executor - executor
        Throws:
        java.sql.SQLException - if any error occurs
      • getSocketTimeout

        public int getSocketTimeout()
        Description copied from interface: Client
        get socket timeout
        Specified by:
        getSocketTimeout in interface Client
        Returns:
        socket timeout
      • setSocketTimeout

        public void setSocketTimeout​(int milliseconds)
                              throws java.sql.SQLException
        Description copied from interface: Client
        Set socket timeout
        Specified by:
        setSocketTimeout in interface Client
        Parameters:
        milliseconds - timeout
        Throws:
        java.sql.SQLException - if any error occurs
      • close

        public void close()
        Description copied from interface: Client
        Close client
        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface Client
      • getSocketIp

        public java.lang.String getSocketIp()
        Description copied from interface: Client
        Get current socket IP or null (for Pipe / unix socket)
        Specified by:
        getSocketIp in interface Client
        Returns:
        Socket current IP
      • isPrimary

        public boolean isPrimary()
        Description copied from interface: Client
        is current client writer or read-only
        Specified by:
        isPrimary in interface Client
        Returns:
        is primary
      • getExceptionFactory

        public ExceptionFactory getExceptionFactory()
        Description copied from interface: Client
        Get connection exception factory
        Specified by:
        getExceptionFactory in interface Client
        Returns:
        connection exception factory
      • getHostAddress

        public HostAddress getHostAddress()
        Description copied from interface: Client
        Get connection host
        Specified by:
        getHostAddress in interface Client
        Returns:
        connection host
      • reset

        public void reset()
        Description copied from interface: Client
        Reset connection
        Specified by:
        reset in interface Client