Search in sources :

Example 51 with ASN1Exception

use of com.unboundid.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)

Example 52 with ASN1Exception

use of com.unboundid.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class Modification method decode.

/**
 * Decodes the provided ASN.1 sequence as an LDAP modification.
 *
 * @param  modificationSequence  The ASN.1 sequence to decode as an LDAP
 *                               modification.  It must not be {@code null}.
 *
 * @return  The decoded LDAP modification.
 *
 * @throws  LDAPException  If a problem occurs while trying to decode the
 *                         provided ASN.1 sequence as an LDAP modification.
 */
@NotNull()
public static Modification decode(@NotNull final ASN1Sequence modificationSequence) throws LDAPException {
    Validator.ensureNotNull(modificationSequence);
    final ASN1Element[] modificationElements = modificationSequence.elements();
    if (modificationElements.length != 2) {
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MOD_DECODE_INVALID_ELEMENT_COUNT.get(modificationElements.length));
    }
    final int modType;
    try {
        final ASN1Enumerated typeEnumerated = ASN1Enumerated.decodeAsEnumerated(modificationElements[0]);
        modType = typeEnumerated.intValue();
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MOD_DECODE_CANNOT_PARSE_MOD_TYPE.get(StaticUtils.getExceptionMessage(ae)), ae);
    }
    final ASN1Sequence attrSequence;
    try {
        attrSequence = ASN1Sequence.decodeAsSequence(modificationElements[1]);
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MOD_DECODE_CANNOT_PARSE_ATTR.get(StaticUtils.getExceptionMessage(ae)), ae);
    }
    final ASN1Element[] attrElements = attrSequence.elements();
    if (attrElements.length != 2) {
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MOD_DECODE_INVALID_ATTR_ELEMENT_COUNT.get(attrElements.length));
    }
    final String attrName = ASN1OctetString.decodeAsOctetString(attrElements[0]).stringValue();
    final ASN1Set valueSet;
    try {
        valueSet = ASN1Set.decodeAsSet(attrElements[1]);
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MOD_DECODE_CANNOT_PARSE_ATTR_VALUE_SET.get(StaticUtils.getExceptionMessage(ae)), ae);
    }
    final ASN1Element[] valueElements = valueSet.elements();
    final ASN1OctetString[] values = new ASN1OctetString[valueElements.length];
    for (int i = 0; i < values.length; i++) {
        values[i] = ASN1OctetString.decodeAsOctetString(valueElements[i]);
    }
    return new Modification(ModificationType.valueOf(modType), attrName, values);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) ASN1Set(com.unboundid.asn1.ASN1Set) ASN1Enumerated(com.unboundid.asn1.ASN1Enumerated) ASN1Exception(com.unboundid.asn1.ASN1Exception) ASN1Element(com.unboundid.asn1.ASN1Element) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) NotNull(com.unboundid.util.NotNull)

Example 53 with ASN1Exception

use of com.unboundid.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class JNDIConverter method convertControl.

/**
 * Converts the provided JNDI control to an LDAP SDK control.
 *
 * @param  c  The control to be converted.
 *
 * @return  The LDAP SDK control that corresponds to the provided JNDI
 *          control.
 *
 * @throws  NamingException  If a problem is encountered during the conversion
 *                           process.
 */
@Nullable
public static Control convertControl(@Nullable final javax.naming.ldap.Control c) throws NamingException {
    if (c == null) {
        return null;
    }
    final ASN1OctetString value;
    final byte[] valueBytes = c.getEncodedValue();
    if ((valueBytes == null) || (valueBytes.length == 0)) {
        value = null;
    } else {
        try {
            value = ASN1OctetString.decodeAsOctetString(valueBytes);
        } catch (final ASN1Exception ae) {
            throw new NamingException(StaticUtils.getExceptionMessage(ae));
        }
    }
    return new Control(c.getID(), c.isCritical(), value);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Control(com.unboundid.ldap.sdk.Control) BasicControl(javax.naming.ldap.BasicControl) ASN1Exception(com.unboundid.asn1.ASN1Exception) NamingException(javax.naming.NamingException) Nullable(com.unboundid.util.Nullable)

Example 54 with ASN1Exception

use of com.unboundid.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class EndTransactionExtendedResult method decodeOpControls.

/**
 * Decodes the provided ASN.1 element as an update controls sequence.  Each
 * element of the sequence should itself be a sequence containing the message
 * ID associated with the operation in which the control was returned and a
 * sequence of the controls included in the response for that operation.
 *
 * @param  element     The ASN.1 element to be decoded.
 * @param  controlMap  The map into which to place the decoded controls.
 *
 * @throws  LDAPException  If a problem occurs while attempting to decode the
 *                         contents of the provided ASN.1 element.
 */
private static void decodeOpControls(@NotNull final ASN1Element element, @NotNull final Map<Integer, Control[]> controlMap) throws LDAPException {
    final ASN1Sequence ctlsSequence;
    try {
        ctlsSequence = ASN1Sequence.decodeAsSequence(element);
    } catch (final ASN1Exception ae) {
        Debug.debugException(ae);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_END_TXN_RESPONSE_CONTROLS_NOT_SEQUENCE.get(ae), ae);
    }
    for (final ASN1Element e : ctlsSequence.elements()) {
        final ASN1Sequence ctlSequence;
        try {
            ctlSequence = ASN1Sequence.decodeAsSequence(e);
        } catch (final ASN1Exception ae) {
            Debug.debugException(ae);
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_END_TXN_RESPONSE_CONTROL_NOT_SEQUENCE.get(ae), ae);
        }
        final ASN1Element[] ctlSequenceElements = ctlSequence.elements();
        if (ctlSequenceElements.length != 2) {
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_END_TXN_RESPONSE_CONTROL_INVALID_ELEMENT_COUNT.get(ctlSequenceElements.length));
        }
        final int msgID;
        try {
            msgID = ASN1Integer.decodeAsInteger(ctlSequenceElements[0]).intValue();
        } catch (final ASN1Exception ae) {
            Debug.debugException(ae);
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_END_TXN_RESPONSE_CONTROL_MSGID_NOT_INT.get(ae), ae);
        }
        final ASN1Sequence controlsSequence;
        try {
            controlsSequence = ASN1Sequence.decodeAsSequence(ctlSequenceElements[1]);
        } catch (final ASN1Exception ae) {
            Debug.debugException(ae);
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_END_TXN_RESPONSE_CONTROLS_ELEMENT_NOT_SEQUENCE.get(ae), ae);
        }
        final Control[] controls = Control.decodeControls(controlsSequence);
        if (controls.length == 0) {
            continue;
        }
        controlMap.put(msgID, controls);
    }
}
Also used : Control(com.unboundid.ldap.sdk.Control) ASN1Sequence(com.unboundid.asn1.ASN1Sequence) LDAPException(com.unboundid.ldap.sdk.LDAPException) ASN1Exception(com.unboundid.asn1.ASN1Exception) ASN1Element(com.unboundid.asn1.ASN1Element)

Example 55 with ASN1Exception

use of com.unboundid.asn1.ASN1Exception in project ldapsdk by pingidentity.

the class JNDIExtendedRequest method toSDKExtendedRequest.

/**
 * Retrieves an LDAP SDK extended request that is the equivalent of the
 * provided JNDI extended request.
 *
 * @param  r  The JNDI extended request to convert to an LDAP SDK extended
 *            request.
 *
 * @return  The LDAP SDK extended request converted from the provided JNDI
 *          extended request.
 *
 * @throws  NamingException  If a problem occurs while decoding the provided
 *                           JNDI extended request as an SDK extended request.
 */
@Nullable()
public static ExtendedRequest toSDKExtendedRequest(@Nullable final javax.naming.ldap.ExtendedRequest r) throws NamingException {
    if (r == null) {
        return null;
    }
    final ASN1OctetString value;
    final byte[] valueBytes = r.getEncodedValue();
    if (valueBytes == null) {
        value = null;
    } else {
        try {
            value = ASN1OctetString.decodeAsOctetString(valueBytes);
        } catch (final ASN1Exception ae) {
            throw new NamingException(StaticUtils.getExceptionMessage(ae));
        }
    }
    return new ExtendedRequest(r.getID(), value);
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1Exception(com.unboundid.asn1.ASN1Exception) ExtendedRequest(com.unboundid.ldap.sdk.ExtendedRequest) NamingException(javax.naming.NamingException) Nullable(com.unboundid.util.Nullable)

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)8 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)8 NotNull (com.unboundid.util.NotNull)8 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 ArrayList (java.util.ArrayList)4