Search in sources :

Example 16 with FbExceptionBuilder

use of org.firebirdsql.gds.ng.FbExceptionBuilder in project jaybird by FirebirdSQL.

the class WireConnection method socketConnect.

/**
 * Establishes the TCP/IP connection to serverName and portNumber of this
 * Connection
 *
 * @throws SQLTimeoutException
 *         If the connection cannot be established within the connect
 *         timeout (either explicitly set or implied by the OS timeout
 *         of the socket)
 * @throws SQLException
 *         If the connection cannot be established.
 */
public final void socketConnect() throws SQLException {
    try {
        socket = new Socket();
        socket.setTcpNoDelay(true);
        final int connectTimeout = attachProperties.getConnectTimeout();
        final int socketConnectTimeout;
        if (connectTimeout != -1) {
            // connectTimeout is in seconds, need milliseconds
            socketConnectTimeout = (int) TimeUnit.SECONDS.toMillis(connectTimeout);
            // Blocking timeout initially identical to connect timeout
            socket.setSoTimeout(socketConnectTimeout);
        } else {
            // socket connect timeout is not set, so indefinite (0)
            socketConnectTimeout = 0;
            // Blocking timeout to normal socket timeout, 0 if not set
            socket.setSoTimeout(Math.max(attachProperties.getSoTimeout(), 0));
        }
        final int socketBufferSize = attachProperties.getSocketBufferSize();
        if (socketBufferSize != IConnectionProperties.DEFAULT_SOCKET_BUFFER_SIZE) {
            socket.setReceiveBufferSize(socketBufferSize);
            socket.setSendBufferSize(socketBufferSize);
        }
        socket.connect(new InetSocketAddress(getServerName(), getPortNumber()), socketConnectTimeout);
    } catch (SocketTimeoutException ste) {
        throw new FbExceptionBuilder().timeoutException(ISCConstants.isc_network_error).messageParameter(getServerName()).cause(ste).toSQLException();
    } catch (IOException ioex) {
        throw new FbExceptionBuilder().nonTransientConnectionException(ISCConstants.isc_network_error).messageParameter(getServerName()).cause(ioex).toSQLException();
    }
}
Also used : FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) IOException(java.io.IOException)

Example 17 with FbExceptionBuilder

use of org.firebirdsql.gds.ng.FbExceptionBuilder in project jaybird by FirebirdSQL.

the class WireConnection method identify.

/**
 * Performs the connection identification phase of the Wire protocol and
 * returns the FbWireDatabase implementation for the agreed protocol.
 *
 * @return FbWireDatabase
 * @throws SQLTimeoutException
 * @throws SQLException
 */
@Override
public final C identify() throws SQLException {
    try {
        xdrIn = new XdrInputStream(socket.getInputStream());
        xdrOut = new XdrOutputStream(socket.getOutputStream());
        xdrOut.writeInt(op_connect);
        xdrOut.writeInt(op_attach);
        xdrOut.writeInt(CONNECT_VERSION3);
        xdrOut.writeInt(arch_generic);
        xdrOut.writeString(getAttachObjectName(), getEncoding());
        // Count of protocols understood
        xdrOut.writeInt(protocols.getProtocolCount());
        xdrOut.writeBuffer(createUserIdentificationBlock());
        for (ProtocolDescriptor protocol : protocols) {
            // Protocol version
            xdrOut.writeInt(protocol.getVersion());
            // Architecture of client
            xdrOut.writeInt(protocol.getArchitecture());
            // Minimum type
            xdrOut.writeInt(protocol.getMinimumType());
            if (protocol.supportsWireCompression() && attachProperties.isWireCompression()) {
                xdrOut.writeInt(protocol.getMaximumType() | pflag_compress);
            } else {
                // Maximum type
                xdrOut.writeInt(protocol.getMaximumType());
            }
            // Preference weight
            xdrOut.writeInt(protocol.getWeight());
        }
        xdrOut.flush();
        FbWireOperations cryptKeyCallbackWireOperations = null;
        DbCryptCallback dbCryptCallback = null;
        int operation = readNextOperation();
        while (operation == op_crypt_key_callback) {
            if (cryptKeyCallbackWireOperations == null) {
                cryptKeyCallbackWireOperations = getCryptKeyCallbackWireOperations();
            }
            if (dbCryptCallback == null) {
                dbCryptCallback = createDbCryptCallback();
            }
            cryptKeyCallbackWireOperations.handleCryptKeyCallback(dbCryptCallback);
            operation = readNextOperation();
        }
        if (operation == op_accept || operation == op_cond_accept || operation == op_accept_data) {
            FbWireAttachment.AcceptPacket acceptPacket = new FbWireAttachment.AcceptPacket();
            acceptPacket.operation = operation;
            // p_acpt_version - Protocol version
            protocolVersion = xdrIn.readInt();
            // p_acpt_architecture - Architecture for protocol
            protocolArchitecture = xdrIn.readInt();
            // p_acpt_type - Minimum type
            int acceptType = xdrIn.readInt();
            protocolMinimumType = acceptType & ptype_MASK;
            final boolean compress = (acceptType & pflag_compress) != 0;
            if (protocolVersion < 0) {
                protocolVersion = (protocolVersion & FB_PROTOCOL_MASK) | FB_PROTOCOL_FLAG;
            }
            if (operation == op_cond_accept || operation == op_accept_data) {
                byte[] data = acceptPacket.p_acpt_data = xdrIn.readBuffer();
                acceptPacket.p_acpt_plugin = xdrIn.readString(getEncoding());
                final int isAuthenticated = xdrIn.readInt();
                byte[] serverKeys = acceptPacket.p_acpt_keys = xdrIn.readBuffer();
                clientAuthBlock.setServerData(data);
                clientAuthBlock.setAuthComplete(isAuthenticated == 1);
                addServerKeys(serverKeys);
                clientAuthBlock.resetClient(serverKeys);
                clientAuthBlock.switchPlugin(acceptPacket.p_acpt_plugin);
            } else {
                clientAuthBlock.resetClient(null);
            }
            if (compress) {
                xdrOut.enableCompression();
                xdrIn.enableDecompression();
            }
            ProtocolDescriptor descriptor = protocols.getProtocolDescriptor(protocolVersion);
            if (descriptor == null) {
                throw new SQLException(String.format("Unsupported or unexpected protocol version %d connecting to database %s. Supported version(s): %s", protocolVersion, getServerName(), protocols.getProtocolVersions()));
            }
            C connectionHandle = createConnectionHandle(descriptor);
            if (operation == op_cond_accept) {
                connectionHandle.authReceiveResponse(acceptPacket);
            }
            return connectionHandle;
        } else {
            try {
                if (operation == op_response) {
                    // Handle exception from response
                    AbstractWireOperations wireOperations = getDefaultWireOperations();
                    wireOperations.processResponse(wireOperations.processOperation(operation));
                }
            } finally {
                try {
                    close();
                } catch (Exception ex) {
                    log.debug("Ignoring exception on disconnect in connect phase of protocol", ex);
                }
            }
            throw new FbExceptionBuilder().exception(ISCConstants.isc_connect_reject).toFlatSQLException();
        }
    } catch (SocketTimeoutException ste) {
        throw new FbExceptionBuilder().timeoutException(ISCConstants.isc_network_error).messageParameter(getServerName()).cause(ste).toSQLException();
    } catch (IOException ioex) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_network_error).messageParameter(getServerName()).cause(ioex).toSQLException();
    }
}
Also used : SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) XdrOutputStream(org.firebirdsql.gds.impl.wire.XdrOutputStream) IOException(java.io.IOException) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) IOException(java.io.IOException) XdrInputStream(org.firebirdsql.gds.impl.wire.XdrInputStream) DbCryptCallback(org.firebirdsql.gds.ng.dbcrypt.DbCryptCallback)

Example 18 with FbExceptionBuilder

use of org.firebirdsql.gds.ng.FbExceptionBuilder in project jaybird by FirebirdSQL.

the class WireDatabaseConnection method toDbAttachInfo.

@Override
protected DbAttachInfo toDbAttachInfo(IConnectionProperties attachProperties) throws SQLException {
    final DbAttachInfo initialDbAttachInfo = DbAttachInfo.of(attachProperties);
    DbAttachInfo dbAttachInfo = initialDbAttachInfo.hasServerName() ? initialDbAttachInfo : DbAttachInfo.parseConnectString(initialDbAttachInfo.getAttachObjectName());
    if (!dbAttachInfo.hasServerName()) {
        // fallback to localhost (preserves backwards compatibility when serverName/host defaulted to localhost)
        dbAttachInfo = dbAttachInfo.withServerName(PropertyConstants.DEFAULT_SERVER_NAME);
    }
    if (!dbAttachInfo.hasAttachObjectName()) {
        throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(initialDbAttachInfo.getAttachObjectName()).messageParameter("null or empty database name in connection string").toFlatSQLException();
    }
    return dbAttachInfo;
}
Also used : DbAttachInfo(org.firebirdsql.gds.impl.DbAttachInfo) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder)

Example 19 with FbExceptionBuilder

use of org.firebirdsql.gds.ng.FbExceptionBuilder in project jaybird by FirebirdSQL.

the class V10Statement method prepare.

@Override
public void prepare(final String statementText) throws SQLException {
    try {
        synchronized (getSynchronizationObject()) {
            checkTransactionActive(getTransaction());
            final StatementState currentState = getState();
            if (!isPrepareAllowed(currentState)) {
                throw new SQLNonTransientException(String.format("Current statement state (%s) does not allow call to prepare", currentState));
            }
            resetAll();
            final FbWireDatabase db = getDatabase();
            if (currentState == StatementState.NEW) {
                try {
                    sendAllocate();
                    getXdrOut().flush();
                } catch (IOException ex) {
                    switchState(StatementState.ERROR);
                    throw new FbExceptionBuilder().exception(ISCConstants.isc_net_write_err).cause(ex).toSQLException();
                }
                try {
                    processAllocateResponse(db.readGenericResponse(getStatementWarningCallback()));
                } catch (IOException ex) {
                    switchState(StatementState.ERROR);
                    throw new FbExceptionBuilder().exception(ISCConstants.isc_net_read_err).cause(ex).toSQLException();
                }
            } else {
                checkStatementValid();
            }
            try {
                sendPrepare(statementText);
                getXdrOut().flush();
            } catch (IOException ex) {
                switchState(StatementState.ERROR);
                throw new FbExceptionBuilder().exception(ISCConstants.isc_net_write_err).cause(ex).toSQLException();
            }
            try {
                processPrepareResponse(db.readGenericResponse(getStatementWarningCallback()));
            } catch (IOException ex) {
                switchState(StatementState.ERROR);
                throw new FbExceptionBuilder().exception(ISCConstants.isc_net_read_err).cause(ex).toSQLException();
            }
        }
    } catch (SQLException e) {
        exceptionListenerDispatcher.errorOccurred(e);
        throw e;
    }
}
Also used : StatementState(org.firebirdsql.gds.ng.StatementState) SQLNonTransientException(java.sql.SQLNonTransientException) SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) IOException(java.io.IOException)

Example 20 with FbExceptionBuilder

use of org.firebirdsql.gds.ng.FbExceptionBuilder in project jaybird by FirebirdSQL.

the class SrpClient method clientProof.

byte[] clientProof(String user, String password, byte[] authData) throws SQLException {
    if (authData == null || authData.length == 0) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_auth_data).toFlatSQLException();
    }
    if (authData.length > EXPECTED_AUTH_DATA_LENGTH) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_auth_datalength).messageParameter(authData.length).messageParameter(EXPECTED_AUTH_DATA_LENGTH).messageParameter("data").toFlatSQLException();
    }
    final int saltLength = VaxEncoding.iscVaxInteger2(authData, 0);
    if (saltLength > SRP_SALT_SIZE * 2) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_auth_datalength).messageParameter(saltLength).messageParameter(SRP_SALT_SIZE * 2).messageParameter("salt").toFlatSQLException();
    }
    final byte[] salt = Arrays.copyOfRange(authData, 2, saltLength + 2);
    final int keyLength = VaxEncoding.iscVaxInteger2(authData, saltLength + 2);
    final int serverKeyStart = saltLength + 4;
    if (authData.length - serverKeyStart != keyLength) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_auth_datalength).messageParameter(keyLength).messageParameter(authData.length - serverKeyStart).messageParameter("key").toFlatSQLException();
    }
    final String hexServerPublicKey = new String(authData, serverKeyStart, authData.length - serverKeyStart, StandardCharsets.US_ASCII);
    final BigInteger serverPublicKey = new BigInteger(padHexBinary(hexServerPublicKey), 16);
    return clientProof(user.toUpperCase(), password, salt, serverPublicKey);
}
Also used : FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) BigInteger(java.math.BigInteger)

Aggregations

FbExceptionBuilder (org.firebirdsql.gds.ng.FbExceptionBuilder)51 SQLException (java.sql.SQLException)31 IOException (java.io.IOException)27 XdrOutputStream (org.firebirdsql.gds.impl.wire.XdrOutputStream)22 XdrInputStream (org.firebirdsql.gds.impl.wire.XdrInputStream)6 GenericResponse (org.firebirdsql.gds.ng.wire.GenericResponse)6 SQLNonTransientException (java.sql.SQLNonTransientException)4 AbstractWireOperations (org.firebirdsql.gds.ng.wire.AbstractWireOperations)4 Test (org.junit.Test)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 BlobParameterBuffer (org.firebirdsql.gds.BlobParameterBuffer)3 BigInteger (java.math.BigInteger)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SQLNonTransientConnectionException (java.sql.SQLNonTransientConnectionException)2 SQLWarning (java.sql.SQLWarning)2 Cipher (javax.crypto.Cipher)2 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 Encoding (org.firebirdsql.encodings.Encoding)2