001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.directory.api.ldap.codec.api;
021
022
023import java.io.InputStream;
024import java.nio.ByteBuffer;
025
026import org.apache.directory.api.asn1.DecoderException;
027import org.apache.directory.api.asn1.ber.Asn1Decoder;
028import org.apache.directory.api.asn1.ber.tlv.TLVStateEnum;
029import org.apache.directory.api.i18n.I18n;
030import org.apache.directory.api.ldap.model.message.Message;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034
035/**
036 * The LdapDecoder decodes ASN.1 BER encoded PDUs into LDAP messages
037 *
038 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
039 */
040public class LdapDecoder
041{
042    /** The logger */
043    private static Logger LOG = LoggerFactory.getLogger( LdapDecoder.class );
044
045    /** A speedup for logger */
046    private static final boolean IS_DEBUG = LOG.isDebugEnabled();
047
048    /** The ASN 1 decoder instance */
049    private Asn1Decoder asn1Decoder;
050
051    /** The name of the LdapSession's attribute for the LDAP container used during the decoding */
052    public static final String MESSAGE_CONTAINER_ATTR = "LDAP-container";
053
054    /** The maximum PDU size, stored into the LDAPSession's attribute */
055    public static final String MAX_PDU_SIZE_ATTR = "LDAP-maxPduSize";
056
057
058    /**
059     * Creates an instance of a Ldap Decoder implementation.
060     */
061    public LdapDecoder()
062    {
063        asn1Decoder = new Asn1Decoder();
064    }
065
066
067    /**
068     * Decodes a PDU from an input stream into a Ldap message container. We can only
069     * decode one complete message.
070     *
071     * @param in The input stream to read and decode PDU bytes from
072     * @return return The decoded message
073     */
074    public Message decode( InputStream in, LdapMessageContainer<MessageDecorator<? extends Message>> container )
075        throws DecoderException
076    {
077        try
078        {
079            int amount;
080
081            while ( in.available() > 0 )
082            {
083                byte[] buf = new byte[in.available()];
084
085                if ( ( amount = in.read( buf ) ) == -1 )
086                {
087                    break;
088                }
089
090                asn1Decoder.decode( ByteBuffer.wrap( buf, 0, amount ), container );
091            }
092        }
093        catch ( Exception e )
094        {
095            String message = I18n.err( I18n.ERR_04060, e.getLocalizedMessage() );
096            LOG.error( message );
097            throw new DecoderException( message, e );
098        }
099
100        if ( container.getState() == TLVStateEnum.PDU_DECODED )
101        {
102            if ( IS_DEBUG )
103            {
104                LOG.debug( "Decoded LdapMessage : " + container );
105            }
106
107            return container.getMessage();
108        }
109        else
110        {
111            LOG.error( I18n.err( I18n.ERR_04062 ) );
112            throw new DecoderException( I18n.err( I18n.ERR_04063 ) );
113        }
114    }
115
116    /**
117     * Decode an incoming buffer into LDAP messages. The result can be 0, 1 or many
118     * LDAP messages, which will be stored into the array the caller has created.
119     * 
120     * @param buffer The incoming byte buffer
121     * @param messageContainer The LdapMessageContainer which will be used to store the
122     * message being decoded. If the message is not fully decoded, the ucrrent state
123     * is stored into this container
124     * @param decodedMessages The list of decoded messages
125     * @throws Exception If the decoding failed
126     *
127    public void decode( ByteBuffer buffer, LdapMessageContainer<MessageDecorator<? extends Message>> messageContainer, List<Message> decodedMessages ) throws DecoderException
128    {
129        buffer.mark();
130
131        while ( buffer.hasRemaining() )
132        {
133            try
134            {
135                if ( IS_DEBUG )
136                {
137                    LOG.debug( "Decoding the PDU : " );
138
139                    int size = buffer.limit();
140                    int position = buffer.position();
141                    int pduLength = size - position;
142
143                    byte[] array = new byte[pduLength];
144
145                    System.arraycopy(buffer.array(), position, array, 0, pduLength);
146
147                    buffer.position( size );
148
149                    if ( array.length == 0 )
150                    {
151                        LOG.debug( "NULL buffer, what the HELL ???" );
152                    }
153                    else
154                    {
155                        LOG.debug( Strings.dumpBytes(array) );
156                    }
157
158                    buffer.reset();
159                }
160
161                asn1Decoder.decode( buffer, messageContainer );
162
163                if ( messageContainer.getState() == TLVStateEnum.PDU_DECODED )
164                {
165                    if ( IS_DEBUG )
166                    {
167                        LOG.debug( "Decoded LdapMessage : " + messageContainer.getMessage() );
168                    }
169
170                    Message message = messageContainer.getMessage();
171
172                    decodedMessages.add( message );
173
174                    messageContainer.clean();
175                }
176            }
177            catch ( DecoderException de )
178            {
179                buffer.clear();
180                messageContainer.clean();
181
182                if ( de instanceof ResponseCarryingException )
183                {
184                    // Transform the DecoderException message to a MessageException
185                    ResponseCarryingMessageException rcme = new ResponseCarryingMessageException( de.getMessage() );
186                    rcme.setResponse( ( ( ResponseCarryingException ) de ).getResponse() );
187
188                    throw rcme;
189                }
190                else
191                {
192                    // TODO : This is certainly not the way we should handle such an exception !
193                    throw new ResponseCarryingException( de.getMessage() );
194                }
195            }
196        }
197    }*/
198}