Search in sources :

Example 21 with FbExceptionBuilder

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

the class V13WireOperations method authReceiveResponse.

@Override
public void authReceiveResponse(FbWireAttachment.AcceptPacket acceptPacket, FbWireOperations.ProcessAttachCallback processAttachCallback) throws SQLException, IOException {
    assert acceptPacket == null || acceptPacket.operation == op_cond_accept : "Unexpected operation in AcceptPacket";
    final XdrInputStream xdrIn = getXdrIn();
    final XdrOutputStream xdrOut = getXdrOut();
    final ClientAuthBlock clientAuthBlock = getClientAuthBlock();
    final Encoding encoding = getEncoding();
    while (true) {
        String pluginName;
        byte[] data;
        if (acceptPacket != null) {
            data = acceptPacket.p_acpt_data;
            pluginName = acceptPacket.p_acpt_plugin;
            addServerKeys(acceptPacket.p_acpt_keys);
            log.debug(String.format("authReceiveResponse: cond_accept data=%d pluginName=%d '%s'", data.length, pluginName != null ? pluginName.length() : null, pluginName));
            // TODO handle compression
            acceptPacket = null;
        } else {
            int operation = readNextOperation();
            switch(operation) {
                case op_trusted_auth:
                    // p_trau_data
                    xdrIn.readBuffer();
                    throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_receiveTrustedAuth_NotSupported).toFlatSQLException();
                case op_cont_auth:
                    // p_data
                    data = xdrIn.readBuffer();
                    // p_name
                    pluginName = xdrIn.readString(encoding);
                    // p_list (ignore?)
                    xdrIn.readBuffer();
                    // p_keys
                    addServerKeys(xdrIn.readBuffer());
                    log.debug(String.format("authReceiveResponse: cont_auth data=%d pluginName=%d '%s'", data.length, pluginName.length(), pluginName));
                    break;
                case op_cond_accept:
                    // Note this is the equivalent of handling the acceptPacket != null above
                    // p_acpt_version
                    xdrIn.readInt();
                    // p_acpt_architecture
                    xdrIn.readInt();
                    // p_acpt_type
                    xdrIn.readInt();
                    // p_acpt_data
                    data = xdrIn.readBuffer();
                    // p_acpt_plugin
                    pluginName = xdrIn.readString(encoding);
                    // p_acpt_authenticated
                    xdrIn.readInt();
                    // p_acpt_keys
                    addServerKeys(xdrIn.readBuffer());
                    log.debug(String.format("authReceiveResponse: cond_accept data=%d pluginName=%d '%s'", data.length, pluginName.length(), pluginName));
                    // TODO handle compression
                    break;
                case op_response:
                    GenericResponse response = (GenericResponse) readOperationResponse(operation, null);
                    boolean wasAuthComplete = clientAuthBlock.isAuthComplete();
                    clientAuthBlock.setAuthComplete(true);
                    processAttachCallback.processAttachResponse(response);
                    addServerKeys(response.getData());
                    WireCrypt wireCrypt = getAttachProperties().getWireCrypt();
                    if (!wasAuthComplete && wireCrypt != WireCrypt.DISABLED) {
                        tryKnownServerKeys();
                    }
                    return;
                default:
                    throw new SQLException(String.format("Unsupported operation code: %d", operation));
            }
        }
        if (pluginName != null && pluginName.length() > 0 && Objects.equals(pluginName, clientAuthBlock.getCurrentPluginName())) {
            pluginName = null;
        }
        if (pluginName != null && pluginName.length() > 0) {
            if (!clientAuthBlock.switchPlugin(pluginName)) {
                break;
            }
        }
        if (!clientAuthBlock.hasPlugin()) {
            break;
        }
        clientAuthBlock.setServerData(data);
        log.debug(String.format("receiveResponse: authenticate(%s)", clientAuthBlock.getCurrentPluginName()));
        clientAuthBlock.authenticate();
        xdrOut.writeInt(op_cont_auth);
        // TODO Move to ClientAuthBlock?
        // p_data
        xdrOut.writeBuffer(clientAuthBlock.getClientData());
        // p_name
        xdrOut.writeString(clientAuthBlock.getCurrentPluginName(), encoding);
        if (clientAuthBlock.isFirstTime()) {
            // p_list
            xdrOut.writeString(clientAuthBlock.getPluginNames(), encoding);
            clientAuthBlock.setFirstTime(false);
        } else {
            // p_list
            xdrOut.writeBuffer(null);
        }
        // p_keys
        xdrOut.writeBuffer(null);
        xdrOut.flush();
    }
    // If we have exited from the cycle, this mean auth failed
    throw new FbExceptionBuilder().exception(ISCConstants.isc_login).toFlatSQLException();
}
Also used : XdrInputStream(org.firebirdsql.gds.impl.wire.XdrInputStream) GenericResponse(org.firebirdsql.gds.ng.wire.GenericResponse) SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) XdrOutputStream(org.firebirdsql.gds.impl.wire.XdrOutputStream) Encoding(org.firebirdsql.encodings.Encoding) WireCrypt(org.firebirdsql.gds.ng.WireCrypt) ClientAuthBlock(org.firebirdsql.gds.ng.wire.auth.ClientAuthBlock)

Example 22 with FbExceptionBuilder

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

the class DbAttachInfo method parseUrlConnectString.

private static DbAttachInfo parseUrlConnectString(String connectString) throws SQLException {
    // Expect host/filename, host:port/filename, ipv4/filename, ipv4:port/filename, [ipv6]/filename or [ipv6]:port/filename
    String server = null;
    String fileName = null;
    Integer port = null;
    int sep = connectString.indexOf('/');
    if (sep == 0 || sep == connectString.length() - 1) {
        throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(connectString).messageParameter("Host separator: '/' at beginning or end").toFlatSQLException();
    } else if (sep > 0) {
        server = connectString.substring(0, sep);
        fileName = connectString.substring(sep + 1);
        if (server.charAt(0) == '[') {
            // ipv6
            int endIpv6Address = server.indexOf(']');
            if (endIpv6Address == -1) {
                throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(connectString).messageParameter("IPv6 address expected, missing closing ']'").toFlatSQLException();
            }
            if (endIpv6Address != server.length() - 1) {
                if (server.charAt(endIpv6Address + 1) == ':') {
                    port = parsePortNumber(connectString, server.substring(endIpv6Address + 2));
                } else {
                    throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(connectString).messageParameter("Unexpected tokens '" + server.substring(endIpv6Address + 1) + "' after IPv6 address").toFlatSQLException();
                }
            }
            server = server.substring(1, endIpv6Address);
        } else {
            // ipv4 or hostname
            int portSep = server.indexOf(':');
            if (portSep == 0 || portSep == server.length() - 1) {
                throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(connectString).messageParameter("Port separator: ':' at beginning or end of: " + server).toFlatSQLException();
            } else if (portSep > 0) {
                String portString = server.substring(portSep + 1);
                port = parsePortNumber(connectString, portString);
                server = server.substring(0, portSep);
            }
        }
    } else if (sep == -1) {
        throw new FbExceptionBuilder().nonTransientConnectionException(JaybirdErrorCodes.jb_invalidConnectionString).messageParameter(connectString).messageParameter("null or empty database name in connection string").toFlatSQLException();
    }
    return new DbAttachInfo(server, port, fileName, connectString);
}
Also used : FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder)

Example 23 with FbExceptionBuilder

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

the class AbstractWireOperations method readStatusVector.

@Override
public final SQLException readStatusVector() throws SQLException {
    boolean debug = log.isDebugEnabled();
    final FbExceptionBuilder builder = new FbExceptionBuilder();
    final XdrInputStream xdrIn = getXdrIn();
    try {
        while (true) {
            int arg = xdrIn.readInt();
            int errorCode;
            switch(arg) {
                case isc_arg_gds:
                    errorCode = xdrIn.readInt();
                    if (debug)
                        log.debug("readStatusVector arg:isc_arg_gds int: " + errorCode);
                    if (errorCode != 0) {
                        builder.exception(errorCode);
                    }
                    break;
                case isc_arg_warning:
                    errorCode = xdrIn.readInt();
                    if (debug)
                        log.debug("readStatusVector arg:isc_arg_warning int: " + errorCode);
                    if (errorCode != 0) {
                        builder.warning(errorCode);
                    }
                    break;
                case isc_arg_interpreted:
                case isc_arg_string:
                    String stringValue = xdrIn.readString(getEncoding());
                    if (debug)
                        log.debug("readStatusVector string: " + stringValue);
                    builder.messageParameter(stringValue);
                    break;
                case isc_arg_sql_state:
                    String sqlState = xdrIn.readString(getEncoding());
                    if (debug)
                        log.debug("readStatusVector sqlstate: " + sqlState);
                    builder.sqlState(sqlState);
                    break;
                case isc_arg_number:
                    int intValue = xdrIn.readInt();
                    if (debug)
                        log.debug("readStatusVector arg:isc_arg_number int: " + intValue);
                    builder.messageParameter(intValue);
                    break;
                case isc_arg_end:
                    if (builder.isEmpty()) {
                        return null;
                    }
                    return builder.toFlatSQLException();
                default:
                    int e = xdrIn.readInt();
                    if (debug)
                        log.debug("readStatusVector arg: " + arg + " int: " + e);
                    builder.messageParameter(e);
                    break;
            }
        }
    } catch (IOException ioe) {
        throw new FbExceptionBuilder().exception(ISCConstants.isc_net_read_err).cause(ioe).toSQLException();
    }
}
Also used : XdrInputStream(org.firebirdsql.gds.impl.wire.XdrInputStream) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) IOException(java.io.IOException)

Example 24 with FbExceptionBuilder

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

the class JnaBlob method open.

@Override
public void open() throws SQLException {
    try {
        if (isOutput() && getBlobId() != NO_BLOB_ID) {
            throw new FbExceptionBuilder().nonTransientException(ISCConstants.isc_segstr_no_op).toSQLException();
        }
        final BlobParameterBuffer blobParameterBuffer = getBlobParameterBuffer();
        final byte[] bpb;
        if (blobParameterBuffer != null) {
            bpb = blobParameterBuffer.toBytesWithType();
        } else {
            bpb = new byte[0];
        }
        synchronized (getSynchronizationObject()) {
            checkDatabaseAttached();
            checkTransactionActive();
            checkBlobClosed();
            final JnaDatabase db = getDatabase();
            if (isOutput()) {
                clientLibrary.isc_create_blob2(statusVector, db.getJnaHandle(), getTransaction().getJnaHandle(), getJnaHandle(), blobId, (short) bpb.length, bpb);
            } else {
                clientLibrary.isc_open_blob2(statusVector, db.getJnaHandle(), getTransaction().getJnaHandle(), getJnaHandle(), blobId, (short) bpb.length, bpb);
            }
            processStatusVector();
            setOpen(true);
            resetEof();
        }
    } catch (SQLException e) {
        exceptionListenerDispatcher.errorOccurred(e);
        throw e;
    }
}
Also used : SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) BlobParameterBuffer(org.firebirdsql.gds.BlobParameterBuffer)

Example 25 with FbExceptionBuilder

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

the class JnaBlob method getSegment.

@Override
public byte[] getSegment(int sizeRequested) throws SQLException {
    try {
        if (sizeRequested <= 0) {
            throw new FbExceptionBuilder().exception(jb_blobGetSegmentNegative).messageParameter(sizeRequested).toSQLException();
        }
        // TODO Honour request for larger sizes by looping?
        sizeRequested = Math.min(sizeRequested, getMaximumSegmentSize());
        final ByteBuffer responseBuffer;
        final ShortByReference actualLength = new ShortByReference();
        synchronized (getSynchronizationObject()) {
            checkDatabaseAttached();
            checkTransactionActive();
            checkBlobOpen();
            responseBuffer = getByteBuffer(sizeRequested);
            clientLibrary.isc_get_segment(statusVector, getJnaHandle(), actualLength, (short) sizeRequested, responseBuffer);
            final int status = statusVector[1].intValue();
            // status 0 means: more to come, isc_segment means: buffer was too small, rest will be returned on next call
            if (!(status == 0 || status == ISCConstants.isc_segment)) {
                if (status == ISCConstants.isc_segstr_eof) {
                    setEof();
                } else {
                    processStatusVector();
                }
            }
        }
        final int actualLengthInt = ((int) actualLength.getValue()) & 0xFFFF;
        final byte[] segment = new byte[actualLengthInt];
        responseBuffer.get(segment);
        return segment;
    } catch (SQLException e) {
        exceptionListenerDispatcher.errorOccurred(e);
        throw e;
    }
}
Also used : ShortByReference(com.sun.jna.ptr.ShortByReference) SQLException(java.sql.SQLException) FbExceptionBuilder(org.firebirdsql.gds.ng.FbExceptionBuilder) ByteBuffer(java.nio.ByteBuffer)

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