Search in sources :

Example 46 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project wildfly-elytron by wildfly-security.

the class Gs2SaslServer method restoreTokenHeader.

/**
 * Recompute and restore the initial context token header for the given token.
 *
 * @param token the initial context token without the token header
 * @return the initial context token with the token header restored
 * @throws ASN1Exception if the mechanism OID cannot be DER encoded
 */
private byte[] restoreTokenHeader(byte[] token) throws ASN1Exception {
    final DEREncoder encoder = new DEREncoder();
    encoder.encodeImplicit(APPLICATION_SPECIFIC_MASK, 0);
    encoder.startSequence();
    try {
        encoder.writeEncoded(mechanism.getDER());
    } catch (GSSException e) {
        throw new ASN1Exception(e);
    }
    encoder.writeEncoded(token);
    encoder.endSequence();
    return encoder.getEncoded();
}
Also used : GSSException(org.ietf.jgss.GSSException) DEREncoder(org.wildfly.security.asn1.DEREncoder) ASN1Exception(org.wildfly.security.asn1.ASN1Exception)

Example 47 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project wildfly-elytron by wildfly-security.

the class AbstractAlgorithmParametersSpiImpl method engineInit.

/**
 * Implementation of the {@code engineInit} method.
 *
 * @param params the encoded parameter specification
 * @throws IOException if decoding failed
 */
protected final void engineInit(final byte[] params) throws IOException {
    final DERDecoder decoder = new DERDecoder(params);
    try {
        parameterSpec = engineDecode(decoder);
        encoded = params;
    } catch (ASN1Exception e) {
        throw log.failedToDecode(e);
    }
}
Also used : ASN1Exception(org.wildfly.security.asn1.ASN1Exception) DERDecoder(org.wildfly.security.asn1.DERDecoder)

Example 48 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class Filter method decode.

/**
 * Decodes the provided ASN.1 element as a search filter.
 *
 * @param  filterElement  The ASN.1 element containing the encoded search
 *                        filter.
 *
 * @return  The decoded search filter.
 *
 * @throws  LDAPException  If the provided ASN.1 element cannot be decoded as
 *                         a search filter.
 */
@NotNull()
public static Filter decode(@NotNull final ASN1Element filterElement) throws LDAPException {
    final byte filterType = filterElement.getType();
    final Filter[] filterComps;
    final Filter notComp;
    final String attrName;
    final ASN1OctetString assertionValue;
    final ASN1OctetString subInitial;
    final ASN1OctetString[] subAny;
    final ASN1OctetString subFinal;
    final String matchingRuleID;
    final boolean dnAttributes;
    switch(filterType) {
        case FILTER_TYPE_AND:
        case FILTER_TYPE_OR:
            notComp = null;
            attrName = null;
            assertionValue = null;
            subInitial = null;
            subAny = NO_SUB_ANY;
            subFinal = null;
            matchingRuleID = null;
            dnAttributes = false;
            final ASN1Set compSet;
            try {
                compSet = ASN1Set.decodeAsSet(filterElement);
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_COMPS.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            final ASN1Element[] compElements = compSet.elements();
            filterComps = new Filter[compElements.length];
            for (int i = 0; i < compElements.length; i++) {
                filterComps[i] = decode(compElements[i]);
            }
            break;
        case FILTER_TYPE_NOT:
            filterComps = NO_FILTERS;
            attrName = null;
            assertionValue = null;
            subInitial = null;
            subAny = NO_SUB_ANY;
            subFinal = null;
            matchingRuleID = null;
            dnAttributes = false;
            final ASN1Element notFilterElement;
            try {
                notFilterElement = ASN1Element.decode(filterElement.getValue());
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_NOT_COMP.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            notComp = decode(notFilterElement);
            break;
        case FILTER_TYPE_EQUALITY:
        case FILTER_TYPE_GREATER_OR_EQUAL:
        case FILTER_TYPE_LESS_OR_EQUAL:
        case FILTER_TYPE_APPROXIMATE_MATCH:
            filterComps = NO_FILTERS;
            notComp = null;
            subInitial = null;
            subAny = NO_SUB_ANY;
            subFinal = null;
            matchingRuleID = null;
            dnAttributes = false;
            final ASN1Sequence avaSequence;
            try {
                avaSequence = ASN1Sequence.decodeAsSequence(filterElement);
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_AVA.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            final ASN1Element[] avaElements = avaSequence.elements();
            if (avaElements.length != 2) {
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_INVALID_AVA_ELEMENT_COUNT.get(avaElements.length));
            }
            attrName = ASN1OctetString.decodeAsOctetString(avaElements[0]).stringValue();
            assertionValue = ASN1OctetString.decodeAsOctetString(avaElements[1]);
            break;
        case FILTER_TYPE_SUBSTRING:
            filterComps = NO_FILTERS;
            notComp = null;
            assertionValue = null;
            matchingRuleID = null;
            dnAttributes = false;
            final ASN1Sequence subFilterSequence;
            try {
                subFilterSequence = ASN1Sequence.decodeAsSequence(filterElement);
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_SUBSTRING.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            final ASN1Element[] subFilterElements = subFilterSequence.elements();
            if (subFilterElements.length != 2) {
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_INVALID_SUBSTR_ASSERTION_COUNT.get(subFilterElements.length));
            }
            attrName = ASN1OctetString.decodeAsOctetString(subFilterElements[0]).stringValue();
            final ASN1Sequence subSequence;
            try {
                subSequence = ASN1Sequence.decodeAsSequence(subFilterElements[1]);
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_SUBSTRING.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            ASN1OctetString tempSubInitial = null;
            ASN1OctetString tempSubFinal = null;
            final ArrayList<ASN1OctetString> subAnyList = new ArrayList<>(1);
            final ASN1Element[] subElements = subSequence.elements();
            for (final ASN1Element subElement : subElements) {
                switch(subElement.getType()) {
                    case SUBSTRING_TYPE_SUBINITIAL:
                        if (tempSubInitial == null) {
                            tempSubInitial = ASN1OctetString.decodeAsOctetString(subElement);
                        } else {
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_MULTIPLE_SUBINITIAL.get());
                        }
                        break;
                    case SUBSTRING_TYPE_SUBANY:
                        subAnyList.add(ASN1OctetString.decodeAsOctetString(subElement));
                        break;
                    case SUBSTRING_TYPE_SUBFINAL:
                        if (tempSubFinal == null) {
                            tempSubFinal = ASN1OctetString.decodeAsOctetString(subElement);
                        } else {
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_MULTIPLE_SUBFINAL.get());
                        }
                        break;
                    default:
                        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_INVALID_SUBSTR_TYPE.get(StaticUtils.toHex(subElement.getType())));
                }
            }
            subInitial = tempSubInitial;
            subAny = subAnyList.toArray(new ASN1OctetString[subAnyList.size()]);
            subFinal = tempSubFinal;
            break;
        case FILTER_TYPE_PRESENCE:
            filterComps = NO_FILTERS;
            notComp = null;
            assertionValue = null;
            subInitial = null;
            subAny = NO_SUB_ANY;
            subFinal = null;
            matchingRuleID = null;
            dnAttributes = false;
            attrName = ASN1OctetString.decodeAsOctetString(filterElement).stringValue();
            break;
        case FILTER_TYPE_EXTENSIBLE_MATCH:
            filterComps = NO_FILTERS;
            notComp = null;
            subInitial = null;
            subAny = NO_SUB_ANY;
            subFinal = null;
            final ASN1Sequence emSequence;
            try {
                emSequence = ASN1Sequence.decodeAsSequence(filterElement);
            } catch (final ASN1Exception ae) {
                Debug.debugException(ae);
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_CANNOT_DECODE_EXTMATCH.get(StaticUtils.getExceptionMessage(ae)), ae);
            }
            String tempAttrName = null;
            ASN1OctetString tempAssertionValue = null;
            String tempMatchingRuleID = null;
            boolean tempDNAttributes = false;
            for (final ASN1Element e : emSequence.elements()) {
                switch(e.getType()) {
                    case EXTENSIBLE_TYPE_ATTRIBUTE_NAME:
                        if (tempAttrName == null) {
                            tempAttrName = ASN1OctetString.decodeAsOctetString(e).stringValue();
                        } else {
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_MULTIPLE_ATTRS.get());
                        }
                        break;
                    case EXTENSIBLE_TYPE_MATCHING_RULE_ID:
                        if (tempMatchingRuleID == null) {
                            tempMatchingRuleID = ASN1OctetString.decodeAsOctetString(e).stringValue();
                        } else {
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_MULTIPLE_MRIDS.get());
                        }
                        break;
                    case EXTENSIBLE_TYPE_MATCH_VALUE:
                        if (tempAssertionValue == null) {
                            tempAssertionValue = ASN1OctetString.decodeAsOctetString(e);
                        } else {
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_MULTIPLE_VALUES.get());
                        }
                        break;
                    case EXTENSIBLE_TYPE_DN_ATTRIBUTES:
                        try {
                            if (tempDNAttributes) {
                                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_MULTIPLE_DNATTRS.get());
                            } else {
                                tempDNAttributes = ASN1Boolean.decodeAsBoolean(e).booleanValue();
                            }
                        } catch (final ASN1Exception ae) {
                            Debug.debugException(ae);
                            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_DNATTRS_NOT_BOOLEAN.get(StaticUtils.getExceptionMessage(ae)), ae);
                        }
                        break;
                    default:
                        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_INVALID_TYPE.get(StaticUtils.toHex(e.getType())));
                }
            }
            if ((tempAttrName == null) && (tempMatchingRuleID == null)) {
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_NO_ATTR_OR_MRID.get());
            }
            if (tempAssertionValue == null) {
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_EXTMATCH_NO_VALUE.get());
            }
            attrName = tempAttrName;
            assertionValue = tempAssertionValue;
            matchingRuleID = tempMatchingRuleID;
            dnAttributes = tempDNAttributes;
            break;
        default:
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_FILTER_ELEMENT_INVALID_TYPE.get(StaticUtils.toHex(filterElement.getType())));
    }
    return new Filter(null, filterType, filterComps, notComp, attrName, assertionValue, subInitial, subAny, subFinal, matchingRuleID, dnAttributes);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Exception(com.unboundid.asn1.ASN1Exception) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1Set(com.unboundid.asn1.ASN1Set) JSONObjectFilter(com.unboundid.ldap.sdk.unboundidds.jsonfilter.JSONObjectFilter) ASN1Element(com.unboundid.asn1.ASN1Element) NotNull(com.unboundid.util.NotNull)

Example 49 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class LDAPConnectionReader method readResponse.

/**
 * Reads a response from the server, blocking if necessary until the response
 * has been received.  This should only be used for connections operating in
 * synchronous mode.
 *
 * @param  messageID  The message ID for the response to be read.  Any
 *                    response read with a different message ID will be
 *                    discarded, unless it is an unsolicited notification in
 *                    which case it will be provided to any registered
 *                    unsolicited notification handler.
 *
 * @return  The response read from the server.
 *
 * @throws  LDAPException  If a problem occurs while reading the response.
 */
@NotNull()
@SuppressWarnings("deprecation")
LDAPResponse readResponse(final int messageID) throws LDAPException {
    while (true) {
        try {
            final LDAPResponse response = LDAPMessage.readLDAPResponseFrom(asn1StreamReader, false, connection.getCachedSchema());
            if (response == null) {
                return new ConnectionClosedResponse(ResultCode.SERVER_DOWN, null);
            }
            connection.setLastCommunicationTime();
            if (response.getMessageID() == messageID) {
                return response;
            }
            if ((response instanceof ExtendedResult) && (response.getMessageID() == 0)) {
                // This is an intermediate response message, so handle it
                // appropriately.
                ExtendedResult extendedResult = (ExtendedResult) response;
                final String oid = extendedResult.getOID();
                if (NoticeOfDisconnectionExtendedResult.NOTICE_OF_DISCONNECTION_RESULT_OID.equals(oid)) {
                    extendedResult = new NoticeOfDisconnectionExtendedResult(extendedResult);
                    connection.setDisconnectInfo(DisconnectType.SERVER_CLOSED_WITH_NOTICE, extendedResult.getDiagnosticMessage(), null);
                } else if (com.unboundid.ldap.sdk.unboundidds.extensions.InteractiveTransactionAbortedExtendedResult.INTERACTIVE_TRANSACTION_ABORTED_RESULT_OID.equals(oid)) {
                    extendedResult = new com.unboundid.ldap.sdk.unboundidds.extensions.InteractiveTransactionAbortedExtendedResult(extendedResult);
                }
                final UnsolicitedNotificationHandler handler = connection.getConnectionOptions().getUnsolicitedNotificationHandler();
                if (handler == null) {
                    if (Debug.debugEnabled(DebugType.LDAP)) {
                        Debug.debug(Level.WARNING, DebugType.LDAP, WARN_READER_UNHANDLED_UNSOLICITED_NOTIFICATION.get(response));
                    }
                } else {
                    handler.handleUnsolicitedNotification(connection, extendedResult);
                }
                continue;
            }
            if (Debug.debugEnabled(DebugType.LDAP)) {
                Debug.debug(Level.WARNING, DebugType.LDAP, WARN_READER_DISCARDING_UNEXPECTED_RESPONSE.get(response, messageID));
            }
        } catch (final LDAPException le) {
            // If the cause was a SocketTimeoutException, then we shouldn't
            // terminate the connection, but we should propagate the failure to
            // the client with the appropriate result.
            final Throwable t = le.getCause();
            if ((t != null) && (t instanceof SocketTimeoutException)) {
                Debug.debugException(Level.FINEST, le);
                throw new LDAPException(ResultCode.TIMEOUT, le.getMessage(), le);
            } else {
                Debug.debugException(le);
            }
            // We should terminate the connection regardless of the type of
            // exception, but might want to customize the debug message.
            final String message;
            Level debugLevel = Level.SEVERE;
            if (t == null) {
                connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, le.getMessage(), t);
                message = le.getMessage();
                debugLevel = Level.WARNING;
            } else if (t instanceof IOException) {
                connection.setDisconnectInfo(DisconnectType.IO_ERROR, le.getMessage(), t);
                message = ERR_READER_CLOSING_DUE_TO_IO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
                debugLevel = Level.WARNING;
            } else if (t instanceof ASN1Exception) {
                connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, le.getMessage(), t);
                message = ERR_READER_CLOSING_DUE_TO_ASN1_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
            } else {
                connection.setDisconnectInfo(DisconnectType.LOCAL_ERROR, le.getMessage(), t);
                message = ERR_READER_CLOSING_DUE_TO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
            }
            Debug.debug(debugLevel, DebugType.LDAP, message, t);
            @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
            if (!autoReconnect) {
                closeRequested = true;
            }
            closeInternal(true, message);
            throw le;
        } catch (final Exception e) {
            Debug.debugException(e);
            // We should terminate the connection regardless of the type of
            // exception, but might want to customize the debug message.
            final String message;
            Level debugLevel = Level.SEVERE;
            if (e instanceof IOException) {
                connection.setDisconnectInfo(DisconnectType.IO_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_IO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
                debugLevel = Level.WARNING;
            } else if (e instanceof ASN1Exception) {
                connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_ASN1_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
            } else {
                connection.setDisconnectInfo(DisconnectType.LOCAL_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
            }
            Debug.debug(debugLevel, DebugType.LDAP, message, e);
            @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
            if (!autoReconnect) {
                closeRequested = true;
            }
            closeInternal(true, message);
            throw new LDAPException(ResultCode.SERVER_DOWN, message, e);
        }
    }
}
Also used : ASN1Exception(com.unboundid.asn1.ASN1Exception) NoticeOfDisconnectionExtendedResult(com.unboundid.ldap.sdk.extensions.NoticeOfDisconnectionExtendedResult) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) ASN1Exception(com.unboundid.asn1.ASN1Exception) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) NoticeOfDisconnectionExtendedResult(com.unboundid.ldap.sdk.extensions.NoticeOfDisconnectionExtendedResult) Level(java.util.logging.Level) LDAPResponse(com.unboundid.ldap.protocol.LDAPResponse) NotNull(com.unboundid.util.NotNull)

Example 50 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class LDAPConnectionReader method run.

/**
 * Operates in a loop, reading data from the server and decoding the
 * responses, and associating them with their corresponding requests.
 */
@Override()
@SuppressWarnings("deprecation")
public void run() {
    boolean reconnect = false;
    thread = Thread.currentThread();
    while (!closeRequested) {
        try {
            final LDAPResponse response;
            try {
                response = LDAPMessage.readLDAPResponseFrom(asn1StreamReader, true, connection.getCachedSchema());
            } catch (final LDAPException le) {
                final Throwable t = le.getCause();
                if ((t != null) && (t instanceof SocketTimeoutException)) {
                    // This is rarely a problem, so we can make the debug message for
                    // this exception only visible at a verbose log level.
                    final SocketTimeoutException ste = (SocketTimeoutException) t;
                    Debug.debugException(Level.FINEST, ste);
                    if (sslSocketFactory != null) {
                        final LDAPConnectionOptions connectionOptions = connection.getConnectionOptions();
                        try {
                            final int responseTimeoutMillis = (int) connectionOptions.getResponseTimeoutMillis();
                            if (responseTimeoutMillis > 0) {
                                InternalSDKHelper.setSoTimeout(connection, responseTimeoutMillis);
                            } else {
                                InternalSDKHelper.setSoTimeout(connection, 0);
                            }
                            final SSLSocket sslSocket;
                            synchronized (sslSocketFactory) {
                                sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, connection.getConnectedAddress(), socket.getPort(), true);
                                sslSocket.startHandshake();
                            }
                            connectionOptions.getSSLSocketVerifier().verifySSLSocket(connection.getConnectedAddress(), socket.getPort(), sslSocket);
                            inputStream = new BufferedInputStream(sslSocket.getInputStream(), DEFAULT_INPUT_BUFFER_SIZE);
                            asn1StreamReader = new ASN1StreamReader(inputStream, connectionOptions.getMaxMessageSize());
                            startTLSOutputStream = sslSocket.getOutputStream();
                            socket = sslSocket;
                            connection.getConnectionInternals(true).setSocket(sslSocket);
                            startTLSSleeper.wakeup();
                        } catch (final Exception e) {
                            Debug.debugException(e);
                            connection.setDisconnectInfo(DisconnectType.SECURITY_PROBLEM, StaticUtils.getExceptionMessage(e), e);
                            startTLSException = e;
                            closeRequested = true;
                            if (thread != null) {
                                thread.setName(thread.getName() + " (closed)");
                                thread = null;
                            }
                            closeInternal(true, StaticUtils.getExceptionMessage(e));
                            startTLSSleeper.wakeup();
                            return;
                        }
                        sslSocketFactory = null;
                    }
                    continue;
                }
                if (closeRequested || connection.closeRequested() || (connection.getDisconnectType() != null)) {
                    // This exception resulted from the connection being closed in a way
                    // that we already knew about.  We don't want to debug it at the
                    // same level as a newly-detected invalidity.
                    closeRequested = true;
                    Debug.debugException(Level.FINEST, le);
                } else {
                    Debug.debugException(le);
                }
                // We should terminate the connection regardless of the type of
                // exception, but might want to customize the debug message.
                final String message;
                Level debugLevel = Level.SEVERE;
                if (t == null) {
                    connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, le.getMessage(), t);
                    message = le.getMessage();
                    debugLevel = Level.WARNING;
                } else if ((t instanceof InterruptedIOException) && socket.isClosed()) {
                    connection.setDisconnectInfo(DisconnectType.SERVER_CLOSED_WITHOUT_NOTICE, le.getMessage(), t);
                    message = ERR_READER_CLOSING_DUE_TO_INTERRUPTED_IO.get(connection.getHostPort());
                    debugLevel = Level.WARNING;
                } else if (t instanceof IOException) {
                    connection.setDisconnectInfo(DisconnectType.IO_ERROR, le.getMessage(), t);
                    message = ERR_READER_CLOSING_DUE_TO_IO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
                    debugLevel = Level.WARNING;
                } else if (t instanceof ASN1Exception) {
                    connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, le.getMessage(), t);
                    message = ERR_READER_CLOSING_DUE_TO_ASN1_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
                } else {
                    connection.setDisconnectInfo(DisconnectType.LOCAL_ERROR, le.getMessage(), t);
                    message = ERR_READER_CLOSING_DUE_TO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(t));
                }
                Debug.debug(debugLevel, DebugType.LDAP, message, t);
                // If the connection is configured to try to auto-reconnect, then set
                // things up to do that.  Otherwise, terminate the connection.
                @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
                if ((!closeRequested) && autoReconnect) {
                    reconnect = true;
                    break;
                } else {
                    closeRequested = true;
                    if (thread != null) {
                        thread.setName(thread.getName() + " (closed)");
                        thread = null;
                    }
                    closeInternal(true, message);
                    return;
                }
            }
            if (response == null) {
                // This should only happen if the socket has been closed.
                connection.setDisconnectInfo(DisconnectType.SERVER_CLOSED_WITHOUT_NOTICE, null, null);
                @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
                if ((!closeRequested) && (!connection.unbindRequestSent()) && autoReconnect) {
                    reconnect = true;
                    break;
                } else {
                    closeRequested = true;
                    if (thread != null) {
                        thread.setName(thread.getName() + " (closed)");
                        thread = null;
                    }
                    closeInternal(true, null);
                    return;
                }
            }
            connection.setLastCommunicationTime();
            Debug.debugLDAPResult(response, connection);
            logResponse(response);
            final ResponseAcceptor responseAcceptor;
            if ((response instanceof SearchResultEntry) || (response instanceof SearchResultReference)) {
                responseAcceptor = acceptorMap.get(response.getMessageID());
            } else if (response instanceof IntermediateResponse) {
                final IntermediateResponse ir = (IntermediateResponse) response;
                responseAcceptor = acceptorMap.get(response.getMessageID());
                IntermediateResponseListener l = null;
                if (responseAcceptor instanceof LDAPRequest) {
                    final LDAPRequest r = (LDAPRequest) responseAcceptor;
                    l = r.getIntermediateResponseListener();
                } else if (responseAcceptor instanceof IntermediateResponseListener) {
                    l = (IntermediateResponseListener) responseAcceptor;
                }
                if (l == null) {
                    Debug.debug(Level.WARNING, DebugType.LDAP, WARN_INTERMEDIATE_RESPONSE_WITH_NO_LISTENER.get(String.valueOf(ir)));
                } else {
                    try {
                        l.intermediateResponseReturned(ir);
                    } catch (final Exception e) {
                        Debug.debugException(e);
                    }
                }
                continue;
            } else {
                responseAcceptor = acceptorMap.remove(response.getMessageID());
            }
            if (responseAcceptor == null) {
                if ((response instanceof ExtendedResult) && (response.getMessageID() == 0)) {
                    // This is an intermediate response message, so handle it
                    // appropriately.
                    ExtendedResult extendedResult = (ExtendedResult) response;
                    final String oid = extendedResult.getOID();
                    if (NoticeOfDisconnectionExtendedResult.NOTICE_OF_DISCONNECTION_RESULT_OID.equals(oid)) {
                        extendedResult = new NoticeOfDisconnectionExtendedResult(extendedResult);
                        connection.setDisconnectInfo(DisconnectType.SERVER_CLOSED_WITH_NOTICE, extendedResult.getDiagnosticMessage(), null);
                    } else if (com.unboundid.ldap.sdk.unboundidds.extensions.InteractiveTransactionAbortedExtendedResult.INTERACTIVE_TRANSACTION_ABORTED_RESULT_OID.equals(oid)) {
                        extendedResult = new com.unboundid.ldap.sdk.unboundidds.extensions.InteractiveTransactionAbortedExtendedResult(extendedResult);
                    }
                    final UnsolicitedNotificationHandler handler = connection.getConnectionOptions().getUnsolicitedNotificationHandler();
                    if (handler == null) {
                        if (Debug.debugEnabled(DebugType.LDAP)) {
                            Debug.debug(Level.WARNING, DebugType.LDAP, WARN_READER_UNHANDLED_UNSOLICITED_NOTIFICATION.get(response));
                        }
                    } else {
                        handler.handleUnsolicitedNotification(connection, extendedResult);
                    }
                    continue;
                }
                if (Debug.debugEnabled(DebugType.LDAP)) {
                    Debug.debug(Level.WARNING, DebugType.LDAP, WARN_READER_NO_ACCEPTOR.get(response));
                }
                continue;
            }
            try {
                responseAcceptor.responseReceived(response);
            } catch (final LDAPException le) {
                Debug.debugException(le);
                Debug.debug(Level.WARNING, DebugType.LDAP, ERR_READER_ACCEPTOR_ERROR.get(String.valueOf(response), connection.getHostPort(), StaticUtils.getExceptionMessage(le)), le);
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            // We should terminate the connection regardless of the type of
            // exception, but might want to customize the debug message.
            final String message;
            Level debugLevel = Level.SEVERE;
            if (e instanceof IOException) {
                connection.setDisconnectInfo(DisconnectType.IO_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_IO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
                debugLevel = Level.WARNING;
            } else if (e instanceof ASN1Exception) {
                connection.setDisconnectInfo(DisconnectType.DECODE_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_ASN1_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
            } else {
                connection.setDisconnectInfo(DisconnectType.LOCAL_ERROR, null, e);
                message = ERR_READER_CLOSING_DUE_TO_EXCEPTION.get(connection.getHostPort(), StaticUtils.getExceptionMessage(e));
            }
            Debug.debug(debugLevel, DebugType.LDAP, message, e);
            // If the connection is configured to try to auto-reconnect, then set
            // things up to do that.  Otherwise, terminate the connection.
            @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
            if (autoReconnect) {
                reconnect = true;
                break;
            } else {
                closeRequested = true;
                if (thread != null) {
                    thread.setName(thread.getName() + " (closed)");
                    thread = null;
                }
                closeInternal(true, message);
                return;
            }
        }
    }
    if (thread != null) {
        thread.setName(constructThreadName(null));
        thread = null;
    }
    if (reconnect && (!connection.closeRequested())) {
        try {
            connection.setNeedsReconnect();
        } catch (final Exception e) {
            Debug.debugException(e);
        }
    } else {
        // Ensure that the connection has properly been closed.
        closeInternal(true, null);
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) SSLSocket(javax.net.ssl.SSLSocket) NoticeOfDisconnectionExtendedResult(com.unboundid.ldap.sdk.extensions.NoticeOfDisconnectionExtendedResult) BufferedInputStream(java.io.BufferedInputStream) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) LDAPResponse(com.unboundid.ldap.protocol.LDAPResponse) ASN1Exception(com.unboundid.asn1.ASN1Exception) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) ASN1Exception(com.unboundid.asn1.ASN1Exception) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) NoticeOfDisconnectionExtendedResult(com.unboundid.ldap.sdk.extensions.NoticeOfDisconnectionExtendedResult) Level(java.util.logging.Level)

Aggregations

IOException (java.io.IOException)18 Asn1Exception (es.gob.jmulticard.asn1.Asn1Exception)16 ASN1Exception (com.unboundid.asn1.ASN1Exception)12 TlvException (es.gob.jmulticard.asn1.TlvException)12 Asn1Exception (sun.security.krb5.Asn1Exception)11 ASN1Element (com.unboundid.asn1.ASN1Element)7 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)7 NotNull (com.unboundid.util.NotNull)7 Iso7816FourCardException (es.gob.jmulticard.card.iso7816four.Iso7816FourCardException)7 CertificateException (java.security.cert.CertificateException)7 X509Certificate (java.security.cert.X509Certificate)7 Asn1Exception (org.kse.utilities.asn1.Asn1Exception)7 ASN1Exception (org.wildfly.security.asn1.ASN1Exception)6 ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)5 Cdf (es.gob.jmulticard.asn1.der.pkcs15.Cdf)5 CryptoCardException (es.gob.jmulticard.card.CryptoCardException)5 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)4 DecoderObject (es.gob.jmulticard.asn1.DecoderObject)4 InvalidCardException (es.gob.jmulticard.card.InvalidCardException)4 DerValue (sun.security.util.DerValue)4