Search in sources :

Example 6 with MessageDecorator

use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.

the class LdapNetworkConnection method loadSchema.

/**
 * loads schema using the specified schema loader
 *
 * @param loader the {@link SchemaLoader} to be used to load schema
 * @throws LdapException If the schema loading failed
 */
public void loadSchema(SchemaLoader loader) throws LdapException {
    try {
        SchemaManager tmp = new DefaultSchemaManager(loader);
        tmp.loadAllEnabled();
        if (!tmp.getErrors().isEmpty() && loader.isStrict()) {
            String msg = I18n.err(I18n.ERR_03204_ERROR_LOADING_SCHEMA);
            if (LOG.isErrorEnabled()) {
                LOG.error("{} {}", msg, Strings.listToString(tmp.getErrors()));
            }
            throw new LdapException(msg);
        }
        schemaManager = tmp;
        // Change the container's BinaryDetector
        ldapSession.setAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR, new LdapMessageContainer<MessageDecorator<? extends Message>>(codec, new SchemaBinaryAttributeDetector(schemaManager)));
    } catch (LdapException le) {
        throw le;
    } catch (Exception e) {
        LOG.error(I18n.err(I18n.ERR_03205_FAIL_LOAD_SCHEMA), e);
        throw new LdapException(e);
    }
}
Also used : MessageDecorator(org.apache.directory.api.ldap.codec.api.MessageDecorator) Message(org.apache.directory.api.ldap.model.message.Message) DefaultSchemaManager(org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager) SchemaManager(org.apache.directory.api.ldap.model.schema.SchemaManager) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) SchemaBinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.SchemaBinaryAttributeDetector) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) LdapInvalidDnException(org.apache.directory.api.ldap.model.exception.LdapInvalidDnException) InvalidConnectionException(org.apache.directory.ldap.client.api.exception.InvalidConnectionException) LdapOperationException(org.apache.directory.api.ldap.model.exception.LdapOperationException) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) MessageEncoderException(org.apache.directory.api.ldap.codec.api.MessageEncoderException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) DecoderException(org.apache.directory.api.asn1.DecoderException) LdapNoPermissionException(org.apache.directory.api.ldap.model.exception.LdapNoPermissionException) LdapOtherException(org.apache.directory.api.ldap.model.exception.LdapOtherException) ProtocolEncoderException(org.apache.mina.filter.codec.ProtocolEncoderException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) DefaultSchemaManager(org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager)

Example 7 with MessageDecorator

use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.

the class LdapNetworkConnection method connect.

// -------------------------- The methods ---------------------------//
/**
 * {@inheritDoc}
 */
@Override
public boolean connect() throws LdapException {
    if ((ldapSession != null) && connected.get()) {
        // No need to connect if we already have a connected session
        return true;
    }
    // Create the connector if needed
    if (connector == null) {
        createConnector();
    }
    // Build the connection address
    SocketAddress address = new InetSocketAddress(config.getLdapHost(), config.getLdapPort());
    // And create the connection future
    timeout = config.getTimeout();
    long maxRetry = System.currentTimeMillis() + timeout;
    ConnectFuture connectionFuture = null;
    boolean interrupted = false;
    while (maxRetry > System.currentTimeMillis() && !interrupted) {
        connectionFuture = connector.connect(address);
        boolean result = false;
        // Wait until it's established
        try {
            result = connectionFuture.await(timeout);
        } catch (InterruptedException e) {
            connector.dispose();
            connector = null;
            LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
            interrupted = true;
            throw new LdapOtherException(e.getMessage(), e);
        } finally {
            if (result) {
                boolean isConnected = connectionFuture.isConnected();
                if (!isConnected) {
                    Throwable connectionException = connectionFuture.getException();
                    if ((connectionException instanceof ConnectException) || (connectionException instanceof UnresolvedAddressException)) {
                        // We know that there was a permanent error such as "connection refused".
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(I18n.msg(I18n.MSG_03245_CONNECTION_ERROR, connectionFuture.getException().getMessage()));
                        }
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(I18n.msg(I18n.MSG_03244_CONNECTION_RETRYING));
                    }
                    // Wait 500 ms and retry
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        connector = null;
                        LOG.debug(I18n.msg(I18n.MSG_03221_INTERRUPTED_WAITING_FOR_CONNECTION, config.getLdapHost(), config.getLdapPort()), e);
                        interrupted = true;
                        throw new LdapOtherException(e.getMessage(), e);
                    }
                } else {
                    break;
                }
            }
        }
    }
    if (connectionFuture == null) {
        connector.dispose();
        throw new InvalidConnectionException("Cannot connect");
    }
    boolean isConnected = connectionFuture.isConnected();
    if (!isConnected) {
        // disposing connector if not connected
        try {
            close();
        } catch (IOException ioe) {
        // Nothing to do
        }
        Throwable e = connectionFuture.getException();
        if (e != null) {
            StringBuilder message = new StringBuilder("Cannot connect to the server: ");
            // (most of the time no message is associated with this exception)
            if ((e instanceof UnresolvedAddressException) && (e.getMessage() == null)) {
                message.append("Hostname '");
                message.append(config.getLdapHost());
                message.append("' could not be resolved.");
                throw new InvalidConnectionException(message.toString(), e);
            }
            // Default case
            message.append(e.getMessage());
            throw new InvalidConnectionException(message.toString(), e);
        }
        return false;
    }
    // Get the close future for this session
    CloseFuture closeFuture = connectionFuture.getSession().getCloseFuture();
    // Add a listener to close the session in the session.
    closeFuture.addListener(new IoFutureListener<IoFuture>() {

        @Override
        public void operationComplete(IoFuture future) {
            // Process all the waiting operations and cancel them
            LOG.debug(I18n.msg(I18n.MSG_03238_NOD_RECEIVED));
            for (ResponseFuture<?> responseFuture : futureMap.values()) {
                LOG.debug(I18n.msg(I18n.MSG_03235_CLOSING, responseFuture));
                responseFuture.cancel();
                try {
                    if (responseFuture instanceof AddFuture) {
                        ((AddFuture) responseFuture).set(AddNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof BindFuture) {
                        ((BindFuture) responseFuture).set(BindNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof CompareFuture) {
                        ((CompareFuture) responseFuture).set(CompareNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof DeleteFuture) {
                        ((DeleteFuture) responseFuture).set(DeleteNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof ExtendedFuture) {
                        ((ExtendedFuture) responseFuture).set(ExtendedNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof ModifyFuture) {
                        ((ModifyFuture) responseFuture).set(ModifyNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof ModifyDnFuture) {
                        ((ModifyDnFuture) responseFuture).set(ModifyDnNoDResponse.PROTOCOLERROR);
                    } else if (responseFuture instanceof SearchFuture) {
                        ((SearchFuture) responseFuture).set(SearchNoDResponse.PROTOCOLERROR);
                    }
                } catch (InterruptedException e) {
                    LOG.error(I18n.err(I18n.ERR_03202_ERROR_PROCESSING_NOD, responseFuture), e);
                }
                futureMap.remove(messageId.get());
            }
            futureMap.clear();
        }
    });
    // Get back the session
    ldapSession = connectionFuture.getSession();
    connected.set(true);
    // Store the container into the session if we don't have one
    @SuppressWarnings("unchecked") LdapMessageContainer<MessageDecorator<? extends Message>> container = (LdapMessageContainer<MessageDecorator<? extends Message>>) ldapSession.getAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR);
    if (container != null) {
        if ((schemaManager != null) && !(container.getBinaryAttributeDetector() instanceof SchemaBinaryAttributeDetector)) {
            container.setBinaryAttributeDetector(new SchemaBinaryAttributeDetector(schemaManager));
        }
    } else {
        BinaryAttributeDetector atDetector = new DefaultConfigurableBinaryAttributeDetector();
        if (schemaManager != null) {
            atDetector = new SchemaBinaryAttributeDetector(schemaManager);
        }
        ldapSession.setAttribute(LdapDecoder.MESSAGE_CONTAINER_ATTR, new LdapMessageContainer<MessageDecorator<? extends Message>>(codec, atDetector));
    }
    // Initialize the MessageId
    messageId.set(0);
    // And return
    return true;
}
Also used : LdapMessageContainer(org.apache.directory.api.ldap.codec.api.LdapMessageContainer) ModifyFuture(org.apache.directory.ldap.client.api.future.ModifyFuture) Message(org.apache.directory.api.ldap.model.message.Message) InetSocketAddress(java.net.InetSocketAddress) IoFuture(org.apache.mina.core.future.IoFuture) ConnectFuture(org.apache.mina.core.future.ConnectFuture) BindFuture(org.apache.directory.ldap.client.api.future.BindFuture) ModifyDnFuture(org.apache.directory.ldap.client.api.future.ModifyDnFuture) InvalidConnectionException(org.apache.directory.ldap.client.api.exception.InvalidConnectionException) DefaultConfigurableBinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.DefaultConfigurableBinaryAttributeDetector) UnresolvedAddressException(java.nio.channels.UnresolvedAddressException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CompareFuture(org.apache.directory.ldap.client.api.future.CompareFuture) SchemaBinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.SchemaBinaryAttributeDetector) LdapOtherException(org.apache.directory.api.ldap.model.exception.LdapOtherException) ConnectException(java.net.ConnectException) CloseFuture(org.apache.mina.core.future.CloseFuture) ResponseFuture(org.apache.directory.ldap.client.api.future.ResponseFuture) ExtendedFuture(org.apache.directory.ldap.client.api.future.ExtendedFuture) IOException(java.io.IOException) SchemaBinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.SchemaBinaryAttributeDetector) DefaultConfigurableBinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.DefaultConfigurableBinaryAttributeDetector) BinaryAttributeDetector(org.apache.directory.api.ldap.codec.api.BinaryAttributeDetector) DeleteFuture(org.apache.directory.ldap.client.api.future.DeleteFuture) MessageDecorator(org.apache.directory.api.ldap.codec.api.MessageDecorator) AddFuture(org.apache.directory.ldap.client.api.future.AddFuture) SearchFuture(org.apache.directory.ldap.client.api.future.SearchFuture)

Example 8 with MessageDecorator

use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.

the class SearchRequestDecorator method unstackFilters.

/**
 * This method is used to clear the filter's stack for terminated elements. An element
 * is considered as terminated either if :
 *  - it's a final element (ie an element which cannot contains a Filter)
 *  - its current length equals its expected length.
 *
 * @param container The container being decoded
 */
@SuppressWarnings("unchecked")
public void unstackFilters(Asn1Container container) {
    LdapMessageContainer<MessageDecorator<Message>> ldapMessageContainer = (LdapMessageContainer<MessageDecorator<Message>>) container;
    TLV tlv = ldapMessageContainer.getCurrentTLV();
    TLV localParent = tlv.getParent();
    Filter localFilter = terminalFilter;
    // The parent has been completed, so fold it
    while ((localParent != null) && (localParent.getExpectedLength() == 0)) {
        int parentTlvId = localFilter.getParent() != null ? localFilter.getParent().getTlvId() : localFilter.getParentTlvId();
        if (localParent.getId() != parentTlvId) {
            localParent = localParent.getParent();
        } else {
            Filter filterParent = localFilter.getParent();
            // pushed on the stack, so we need to get its parent's parent
            if (localFilter instanceof PresentFilter) {
                if (filterParent == null) {
                    // We don't have parent, get out
                    break;
                }
                filterParent = filterParent.getParent();
            } else {
                filterParent = filterParent.getParent();
            }
            if (filterParent != null) {
                // The parent is a filter ; it will become the new currentFilter
                // and we will loop again.
                localFilter = currentFilter;
                currentFilter = filterParent;
                localParent = localParent.getParent();
            } else {
                // We can stop the recursion, we have reached the searchResult Object
                break;
            }
        }
    }
}
Also used : LdapMessageContainer(org.apache.directory.api.ldap.codec.api.LdapMessageContainer) MessageDecorator(org.apache.directory.api.ldap.codec.api.MessageDecorator) Message(org.apache.directory.api.ldap.model.message.Message) PresentFilter(org.apache.directory.api.ldap.codec.search.PresentFilter) AttributeValueAssertionFilter(org.apache.directory.api.ldap.codec.search.AttributeValueAssertionFilter) AndFilter(org.apache.directory.api.ldap.codec.search.AndFilter) ConnectorFilter(org.apache.directory.api.ldap.codec.search.ConnectorFilter) SubstringFilter(org.apache.directory.api.ldap.codec.search.SubstringFilter) NotFilter(org.apache.directory.api.ldap.codec.search.NotFilter) OrFilter(org.apache.directory.api.ldap.codec.search.OrFilter) PresentFilter(org.apache.directory.api.ldap.codec.search.PresentFilter) ExtensibleMatchFilter(org.apache.directory.api.ldap.codec.search.ExtensibleMatchFilter) Filter(org.apache.directory.api.ldap.codec.search.Filter) TLV(org.apache.directory.api.asn1.ber.tlv.TLV)

Example 9 with MessageDecorator

use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.

the class BindRequestTest method testDecodeBindRequestBadDN.

/**
 * Test the decoding of a BindRequest with Simple authentication and
 * controls
 */
@Test
public void testDecodeBindRequestBadDN() {
    Asn1Decoder ldapDecoder = new Asn1Decoder();
    ByteBuffer stream = ByteBuffer.allocate(0x35);
    stream.put(new byte[] { 0x30, // LDAPMessage ::=SEQUENCE {
    0x33, 0x02, 0x01, // messageID MessageID
    0x01, 0x60, // CHOICE { ..., bindRequest BindRequest, ...
    0x2E, // BindRequest ::= APPLICATION[0] SEQUENCE {
    0x02, 0x01, // version INTEGER (1..127),
    0x03, 0x04, // name LDAPDN,
    0x1F, 'u', 'i', 'd', ':', 'a', 'k', 'a', 'r', 'a', 's', 'u', 'l', 'u', ',', 'd', 'c', '=', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', 'd', 'c', '=', 'c', 'o', 'm', (byte) 0x80, // authentication AuthenticationChoice
    0x08, // ...
    'p', 'a', 's', 's', 'w', 'o', 'r', 'd' });
    stream.flip();
    // Allocate a LdapMessage Container
    LdapMessageContainer<MessageDecorator<? extends Message>> container = new LdapMessageContainer<MessageDecorator<? extends Message>>(codec);
    // Decode the BindRequest PDU
    try {
        ldapDecoder.decode(stream, container);
        BindRequest bindRequest = ((BindRequestDecorator) container.getMessage());
        assertNull(bindRequest.getDn());
        assertEquals("uid:akarasulu,dc=example,dc=com", bindRequest.getName());
    } catch (DecoderException de) {
        assertTrue(de instanceof ResponseCarryingException);
        Message response = ((ResponseCarryingException) de).getResponse();
        assertTrue(response instanceof BindResponseImpl);
        assertEquals(ResultCodeEnum.INVALID_DN_SYNTAX, ((BindResponseImpl) response).getLdapResult().getResultCode());
        return;
    }
}
Also used : LdapMessageContainer(org.apache.directory.api.ldap.codec.api.LdapMessageContainer) DecoderException(org.apache.directory.api.asn1.DecoderException) MessageDecorator(org.apache.directory.api.ldap.codec.api.MessageDecorator) ResponseCarryingException(org.apache.directory.api.ldap.codec.api.ResponseCarryingException) Message(org.apache.directory.api.ldap.model.message.Message) Asn1Decoder(org.apache.directory.api.asn1.ber.Asn1Decoder) BindRequest(org.apache.directory.api.ldap.model.message.BindRequest) BindResponseImpl(org.apache.directory.api.ldap.model.message.BindResponseImpl) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test) AbstractCodecServiceTest(org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest)

Example 10 with MessageDecorator

use of org.apache.directory.api.ldap.codec.api.MessageDecorator in project directory-ldap-api by apache.

the class LdapDecoderTest method testDecodeBadLengthTooSmall.

/**
 * Test the decoding of a PDU with a bad Length. The first TLV has a length
 * of 0x32 when the PDU is 0x33 bytes long.
 */
@Test
public void testDecodeBadLengthTooSmall() {
    Asn1Decoder ldapDecoder = new Asn1Decoder();
    ByteBuffer stream = ByteBuffer.allocate(0x35);
    stream.put(new byte[] { // Length should be 0x33...
    0x30, // LDAPMessage ::=SEQUENCE {
    0x32, 0x02, 0x01, // messageID MessageID
    0x01, 0x60, // CHOICE { ..., bindRequest BindRequest, ...
    0x2E, // BindRequest ::= APPLICATION[0] SEQUENCE {
    0x02, 0x01, // version INTEGER (1..127),
    0x03, 0x04, // name LDAPDN,
    0x1F, 'u', 'i', 'd', '=', 'a', 'k', 'a', 'r', 'a', 's', 'u', 'l', 'u', ',', 'd', 'c', '=', 'e', 'x', 'a', 'm', 'p', 'l', 'e', ',', 'd', 'c', '=', 'c', 'o', 'm', (byte) 0x80, // authentication
    0x08, // ...
    'p', 'a', 's', 's', 'w', 'o', 'r', 'd' });
    stream.flip();
    // Allocate a LdapMessage Container
    LdapMessageContainer<MessageDecorator<? extends Message>> ldapMessageContainer = new LdapMessageContainer<MessageDecorator<? extends Message>>(codec);
    // Decode a BindRequest PDU
    try {
        ldapDecoder.decode(stream, ldapMessageContainer);
    } catch (DecoderException de) {
        assertEquals("ERR_01003_VALUE_LENGTH_ABOVE_EXPECTED_LENGTH The current Value length 48 is above the expected length 47", de.getMessage());
        return;
    }
    fail("Should never reach this point..");
}
Also used : LdapMessageContainer(org.apache.directory.api.ldap.codec.api.LdapMessageContainer) DecoderException(org.apache.directory.api.asn1.DecoderException) MessageDecorator(org.apache.directory.api.ldap.codec.api.MessageDecorator) Message(org.apache.directory.api.ldap.model.message.Message) Asn1Decoder(org.apache.directory.api.asn1.ber.Asn1Decoder) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test) AbstractCodecServiceTest(org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest)

Aggregations

MessageDecorator (org.apache.directory.api.ldap.codec.api.MessageDecorator)11 Message (org.apache.directory.api.ldap.model.message.Message)11 LdapMessageContainer (org.apache.directory.api.ldap.codec.api.LdapMessageContainer)10 ByteBuffer (java.nio.ByteBuffer)8 DecoderException (org.apache.directory.api.asn1.DecoderException)8 AbstractCodecServiceTest (org.apache.directory.api.ldap.codec.osgi.AbstractCodecServiceTest)7 Test (org.junit.Test)7 Asn1Decoder (org.apache.directory.api.asn1.ber.Asn1Decoder)6 BindRequest (org.apache.directory.api.ldap.model.message.BindRequest)3 IOException (java.io.IOException)2 ConnectException (java.net.ConnectException)2 UnresolvedAddressException (java.nio.channels.UnresolvedAddressException)2 ArrayList (java.util.ArrayList)2 SchemaBinaryAttributeDetector (org.apache.directory.api.ldap.codec.api.SchemaBinaryAttributeDetector)2 LdapOtherException (org.apache.directory.api.ldap.model.exception.LdapOtherException)2 InvalidConnectionException (org.apache.directory.ldap.client.api.exception.InvalidConnectionException)2 InetSocketAddress (java.net.InetSocketAddress)1 SocketAddress (java.net.SocketAddress)1 TLV (org.apache.directory.api.asn1.ber.tlv.TLV)1 BinaryAttributeDetector (org.apache.directory.api.ldap.codec.api.BinaryAttributeDetector)1